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
3295ba22f98c3a11cea53dbdf79b6c4b6f961acd
a0968ddd21d34765caff5888b5de2c0e116d9142
/codeforces/1251/C.cpp
39dc37eb6be45ca00afc0811606901805ba78b9d
[]
no_license
AmneetSinghh/Codeforces-feb_2021
b07d1dd41257c313f7325afcc6c522f5dd389198
b2ce45e944cc80b42f478890b18ffa89b433f353
refs/heads/master
2023-03-25T00:25:11.559794
2021-02-18T12:12:00
2021-03-03T18:48:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
C.cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; string s,s1,s2; while(t--) { s1=""; s2=""; cin>>s; for(int i=0;i<s.length();i++) { if(s[i]%2==0) s1+=s[i]; else s2+=s[i]; } //cout<<s<<" "<<s1<<" "<<s2<<endl; merge(s1.begin(),s1.end(),s2.begin(),s2.end(),s.begin()); cout<<s<<"\n"; } return 0; }
1bed8b7c88b3e535489def399f1b5757af22e7fe
0882ed3c9e1078a8f69a1fc720d2c05c9289dd23
/src/test/OpenEXRTest/testOptimizedInterleavePatterns.cpp
155be2bb906e8f1d7e4c3b8db00879bb562f7be3
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
AcademySoftwareFoundation/openexr
846500ee441cc7b60d717ca4377050c55949ecde
1ee0ffec3a499ac8bae1ad7e5eff60571d1d83de
refs/heads/main
2023-09-01T11:33:55.842765
2023-08-31T20:30:32
2023-08-31T20:30:32
3,533,348
782
281
BSD-3-Clause
2023-09-14T20:59:10
2012-02-24T06:30:00
C
UTF-8
C++
false
false
21,139
cpp
testOptimizedInterleavePatterns.cpp
// // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) Weta Digital, Ltd and Contributors to the OpenEXR Project. // #ifdef NDEBUG # undef NDEBUG #endif #include "ImfChannelList.h" #include "ImfCompression.h" #include "ImfFrameBuffer.h" #include "ImfInputFile.h" #include "ImfOutputFile.h" #include "ImfStandardAttributes.h" #include <IlmThread.h> #include <ImathBox.h> #include <algorithm> #include <assert.h> #include <iostream> #include <limits> #include <stdlib.h> #include <vector> #include "random.h" #include "tmpDir.h" namespace IMF = OPENEXR_IMF_NAMESPACE; using namespace IMF; using namespace std; using namespace IMATH_NAMESPACE; using namespace ILMTHREAD_NAMESPACE; namespace { using OPENEXR_IMF_NAMESPACE::FLOAT; using OPENEXR_IMF_NAMESPACE::UINT; std::string filename; vector<char> writingBuffer; // buffer as file was written vector<char> readingBuffer; // buffer containing new image (and filled channels?) vector<char> preReadBuffer; // buffer as it was before reading - unread, unfilled channels should be unchanged int gOptimisedReads = 0; int gSuccesses = 0; int gFailures = 0; // // @todo Needs a description of what this is used for. // // struct Schema { const char* _name; // name of this scheme const char* const* _active; // channels to be read const char* const* _passive; // channels to be ignored (keep in buffer passed to inputfile, should not be overwritten) int _banks; const char* const* _views; // list of views to write, or NULL const PixelType* _types; // NULL for all HALF, otherwise per-channel type vector<string> views () const { const char* const* v = _views; vector<string> svec; while (*v != NULL) { svec.push_back (*v); v++; } return svec; } }; const char* rgb[] = {"R", "G", "B", NULL}; const char* rgba[] = {"R", "G", "B", "A", NULL}; const char* bgr[] = {"B", "G", "R", NULL}; const char* abgr[] = {"A", "B", "G", "R", NULL}; const char* alpha[] = {"A", NULL}; const char* redalpha[] = {"R", "A", NULL}; const char* rgbrightrgb[] = { "R", "G", "B", "right.R", "right.G", "right.B", NULL}; const char* rgbleftrgb[] = {"R", "G", "B", "left.R", "left.G", "left.B", NULL}; const char* rgbarightrgba[] = { "R", "G", "B", "A", "right.R", "right.G", "right.B", "right.A", NULL}; const char* rgbaleftrgba[] = { "R", "G", "B", "A", "left.R", "left.G", "left.B", "left.A", NULL}; const char* rgbrightrgba[] = { "R", "G", "B", "right.R", "right.G", "right.B", "right.A", NULL}; const char* rgbleftrgba[] = { "R", "G", "B", "left.R", "left.G", "left.B", "left.A", NULL}; const char* rgbarightrgb[] = { "R", "G", "B", "A", "right.R", "right.G", "right.B", NULL}; const char* rgbaleftrgb[] = { "R", "G", "B", "A", "left.R", "left.G", "left.B", NULL}; const char* rightrgba[] = {"right.R", "right.G", "right.B", "right.A", NULL}; const char* leftrgba[] = {"left.R", "left.G", "left.B", "left.A", NULL}; const char* rightrgb[] = {"right.R", "right.G", "right.B", NULL}; const char* leftrgb[] = {"left.R", "left.G", "left.B", NULL}; const char* threeview[] = { "R", "G", "B", "A", "left.R", "left.G", "left.B", "left.A", "right.R", "right.G", "right.B", "right.A", NULL}; const char* trees[] = {"rimu", "pohutukawa", "manuka", "kauri", NULL}; const char* treesandbirds[] = { "kiwi", "rimu", "pohutukawa", "kakapu", "kauri", "manuka", "moa", "fantail", NULL}; const char* lefthero[] = {"left", "right", NULL}; const char* righthero[] = {"right", "left", NULL}; const char* centrehero[] = {"centre", "left", "right", NULL}; const PixelType four_floats[] = { IMF::FLOAT, IMF::FLOAT, IMF::FLOAT, IMF::FLOAT}; const PixelType hhhfff[] = { IMF::HALF, IMF::HALF, IMF::HALF, IMF::FLOAT, IMF::FLOAT, IMF::FLOAT}; const PixelType hhhhffff[] = { IMF::HALF, IMF::HALF, IMF::HALF, IMF::HALF, IMF::FLOAT, IMF::FLOAT, IMF::FLOAT, IMF::FLOAT}; Schema Schemes[] = { {"RGBHalf", rgb, NULL, 1, NULL, NULL}, {"RGBAHalf", rgba, NULL, 1, NULL, NULL}, {"ABGRHalf", abgr, NULL, 1, NULL, NULL}, {"RGBFloat", rgb, NULL, 1, NULL, four_floats}, {"BGRHalf", bgr, NULL, 1, NULL, NULL}, {"RGBLeftRGB", rgbleftrgb, NULL, 1, righthero, NULL}, {"RGBRightRGB", rgbrightrgb, NULL, 1, lefthero, NULL}, {"RGBALeftRGBA", rgbaleftrgba, NULL, 1, righthero, NULL}, {"RGBARightRGBA", rgbarightrgba, NULL, 1, lefthero, NULL}, {"LeftRGB", leftrgb, NULL, 1, NULL, NULL}, {"RightRGB", rightrgb, NULL, 1, NULL, NULL}, {"LeftRGBA", leftrgba, NULL, 1, NULL, NULL}, {"RightRGBA", rightrgba, NULL, 1, NULL, NULL}, {"TripleView", threeview, NULL, 1, centrehero, NULL}, {"Trees", trees, NULL, 1, NULL, NULL}, {"TreesAndBirds", treesandbirds, NULL, 1, NULL, NULL}, {"RGBLeftRGBA", rgbleftrgba, NULL, 1, righthero, NULL}, {"RGBRightRGBA", rgbrightrgba, NULL, 1, lefthero, NULL}, {"RGBALeftRGB", rgbaleftrgb, NULL, 1, righthero, NULL}, {"RGBARightRGB", rgbarightrgb, NULL, 1, lefthero, NULL}, {"TwinRGBLeftRGB", rgbleftrgb, NULL, 2, righthero, NULL}, {"TwinRGBRightRGB", rgbrightrgb, NULL, 2, lefthero, NULL}, {"TwinRGBALeftRGBA", rgbaleftrgba, NULL, 2, righthero, NULL}, {"TwinRGBARightRGBA", rgbarightrgba, NULL, 2, lefthero, NULL}, {"TripleTripleView", threeview, NULL, 3, centrehero, NULL}, {"Alpha", alpha, NULL, 1, NULL, NULL}, {"RedAlpha", redalpha, NULL, 1, NULL, NULL}, {"RG+BA", rgba, NULL, 2, NULL, NULL}, //interleave only RG, then BA {"RGBpassiveA", rgb, alpha, 1, NULL, NULL}, //interleave only RG, then BA {"RGBpassiveleftRGB", rgb, leftrgb, 1, NULL, NULL}, {"RGBFloatA", rgba, NULL, 1, NULL, hhhfff}, {"RGBFloatLeftRGB", rgbleftrgb, NULL, 1, righthero, hhhfff}, {"RGBAFloatLeftRGBA", rgbaleftrgba, NULL, 1, righthero, hhhhffff}, {"RGBApassiverightRGBA", rgba, rightrgba, 1, NULL, NULL}, {"BanksOfTreesAndBirds", treesandbirds, NULL, 2, NULL, NULL}, {NULL, NULL, NULL, 0, NULL, NULL}}; template <class T> inline T alignToFour (T input) { while ((intptr_t (input) & 3) != 0) { input++; } return input; } bool compare ( const FrameBuffer& asRead, const FrameBuffer& asWritten, const Box2i& dataWindow, bool nonfatal) { for (FrameBuffer::ConstIterator i = asRead.begin (); i != asRead.end (); i++) { FrameBuffer::ConstIterator p = asWritten.find (i.name ()); for (int y = dataWindow.min.y; y <= dataWindow.max.y; y++) { for (int x = dataWindow.min.x; x <= dataWindow.max.x; x++) { // // extract value read back from file // intptr_t base = reinterpret_cast<intptr_t> (i.slice ().base); char* ptr = reinterpret_cast<char*> ( base + i.slice ().yStride * intptr_t (y) + i.slice ().xStride * intptr_t (x)); half readHalf; switch (i.slice ().type) { case IMF::FLOAT: assert (alignToFour (ptr) == ptr); readHalf = half (*(float*) ptr); break; case IMF::HALF: readHalf = half (*(half*) ptr); break; case IMF::UINT: continue; // can't very well check this default: cout << "don't know about that\n"; exit (1); } half writtenHalf; if (p != asWritten.end ()) { intptr_t base = reinterpret_cast<intptr_t> (p.slice ().base); char* ptr = reinterpret_cast<char*> ( base + p.slice ().yStride * intptr_t (y) + p.slice ().xStride * intptr_t (x)); switch (p.slice ().type) { case IMF::FLOAT: assert (alignToFour (ptr) == ptr); writtenHalf = half (*(float*) ptr); break; case IMF::HALF: writtenHalf = half (*(half*) ptr); break; case IMF::UINT: continue; default: cout << "don't know about that\n"; exit (1); } } else { writtenHalf = half (i.slice ().fillValue); } if (writtenHalf.bits () != readHalf.bits ()) { if (nonfatal) { return false; } else { cout << "\n\nerror reading back channel " << i.name () << " pixel " << x << ',' << y << " got " << readHalf << " expected " << writtenHalf << endl; assert (writtenHalf.bits () == readHalf.bits ()); exit (1); } } } } } return true; } // // allocate readingBuffer or writingBuffer, setting up a framebuffer to point to the right thing // ChannelList setupBuffer ( const Header& hdr, // header to grab datawindow from const char* const* channels, // NULL terminated list of channels to write const char* const* passivechannels, // NULL terminated list of channels to write const PixelType* pt, // type of each channel, or NULL for all HALF FrameBuffer& buf, // buffer to fill with pointers to channel FrameBuffer& prereadbuf, // channels which aren't being read - indexes into the preread buffer FrameBuffer& postreadbuf, // channels which aren't being read - indexes into the postread buffer int banks, // number of banks - channels within each bank are interleaved, banks are scanline interleaved bool writing, // true if should allocate bool allowNonfinite // true if the buffer is allowed to create infinity or NaN values ) { Box2i dw = hdr.dataWindow (); // // how many channels in total // int activechans = 0; int bytes_per_pixel = 0; bool has32BitValue = false; while (channels[activechans] != NULL) { if (pt == NULL) { bytes_per_pixel += 2; } else { switch (pt[activechans]) { case IMF::HALF: bytes_per_pixel += 2; break; case IMF::FLOAT: case IMF::UINT: // some architectures (e.g arm7) cannot write 32 bit values // to addresses which aren't aligned to 32 bit addresses // so bump to next multiple of four bytes_per_pixel = alignToFour (bytes_per_pixel); bytes_per_pixel += 4; has32BitValue = true; break; default: cout << "Unexpected PixelType?\n"; exit (1); } } activechans++; } int passivechans = 0; while (passivechannels != NULL && passivechannels[passivechans] != NULL) { if (pt == NULL) { bytes_per_pixel += 2; } else { switch (pt[passivechans + activechans]) { case IMF::HALF: bytes_per_pixel += 2; break; case IMF::FLOAT: case IMF::UINT: bytes_per_pixel = alignToFour (bytes_per_pixel); bytes_per_pixel += 4; has32BitValue = true; break; default: cout << "Unexpected PixelType?\n"; exit (1); } } passivechans++; } if (has32BitValue) { bytes_per_pixel = alignToFour (bytes_per_pixel); } int chans = activechans + passivechans; int bytes_per_bank = bytes_per_pixel / banks; int samples = (hdr.dataWindow ().max.x + 1 - hdr.dataWindow ().min.x) * (hdr.dataWindow ().max.y + 1 - hdr.dataWindow ().min.y) * chans; int size = samples * bytes_per_pixel; if (writing) { writingBuffer.resize (size); } else { readingBuffer.resize (size); } const char* write_ptr = writing ? &writingBuffer[0] : &readingBuffer[0]; // fill with random halfs, casting to floats for float channels int chan = 0; for (int i = 0; i < samples; i++) { half v; // generate a random finite half // if the value is to be cast to a float, ensure the value is not infinity // or NaN, since the value is not guaranteed to round trip from half to float // and back again with bit-identical precision do { unsigned short int values = random_int (std::numeric_limits<unsigned short>::max ()); v.setBits (values); } while(!( (v-v)==0 || allowNonfinite )); if (pt == NULL || pt[chan] == IMF::HALF) { *(half*) write_ptr = half (v); write_ptr += 2; } else { write_ptr = alignToFour (write_ptr); *(float*) write_ptr = float (v); write_ptr += 4; } chan++; if (chan == chans) { chan = 0; } } if (!writing) { //take a copy of the buffer as it was before being read preReadBuffer = readingBuffer; } char* offset = NULL; ChannelList chanlist; int bytes_per_row = bytes_per_pixel * (dw.max.x + 1 - dw.min.x); int bytes_per_bank_row = bytes_per_row / banks; int first_pixel_index = bytes_per_row * dw.min.y + bytes_per_bank * dw.min.x; for (int i = 0; i < chans; i++) { PixelType type = pt == NULL ? IMF::HALF : pt[i]; if (i < activechans && writing) { chanlist.insert (channels[i], type); } if (i % (chans / banks) == 0) { // // set offset pointer to beginning of bank // int bank = i / (chans / banks); offset = (writing ? &writingBuffer[0] : &readingBuffer[0]) + bank * bytes_per_bank_row - first_pixel_index; } if (type == FLOAT || type == UINT) { offset = alignToFour (offset); } if (i < activechans) { buf.insert ( channels[i], Slice ( type, offset, bytes_per_bank, bytes_per_row, 1, 1, 100 + i)); } else { if (!writing) { postreadbuf.insert ( passivechannels[i - activechans], Slice ( type, offset, bytes_per_bank, bytes_per_row, 1, 1, 0.4)); char* pre_offset = offset - &readingBuffer[0] + &preReadBuffer[0]; prereadbuf.insert ( passivechannels[i - activechans], Slice ( type, pre_offset, bytes_per_bank, bytes_per_row, 1, 1, 0.4)); } } switch (type) { case IMF::HALF: offset += 2; break; case IMF::FLOAT: offset += 4; break; default: cout << "Unexpected Pixel Type\n"; exit (1); } } return chanlist; } Box2i writefile (Schema& scheme, FrameBuffer& buf, bool tiny , bool allowNonfinite) { const int height = 128; const int width = 128; Header hdr (width, height, 1); //min values in range [-100,100] hdr.dataWindow ().min.x = random_int (201) - 100; hdr.dataWindow ().min.y = random_int (201) - 100; // in tiny mode, make image up to 14*14 pixels (less than two SSE instructions) if (tiny) { hdr.dataWindow ().max.x = hdr.dataWindow ().min.x + 1 + random_int (14); hdr.dataWindow ().max.y = hdr.dataWindow ().min.y + 1 + random_int (14); } else { // in normal mode, make chunky images hdr.dataWindow ().max.x = hdr.dataWindow ().min.x + 64 + random_int (400); hdr.dataWindow ().max.y = hdr.dataWindow ().min.y + 64 + random_int (400); } hdr.compression () = ZIPS_COMPRESSION; FrameBuffer dummy1, dummy2; hdr.channels () = setupBuffer ( hdr, scheme._active, scheme._passive, scheme._types, buf, dummy1, dummy2, scheme._banks, true, allowNonfinite); if (scheme._views) { addMultiView (hdr, scheme.views ()); } remove (filename.c_str ()); OutputFile f (filename.c_str (), hdr); f.setFrameBuffer (buf); f.writePixels (hdr.dataWindow ().max.y - hdr.dataWindow ().min.y + 1); return hdr.dataWindow (); } bool readfile ( Schema scheme, FrameBuffer& buf, ///< list of channels to read: index to readingBuffer FrameBuffer& preread, ///< list of channels to skip: index to preReadBuffer FrameBuffer& postread, ///< list of channels to skip: index to readingBuffer) bool allowNonfinite) { InputFile infile (filename.c_str ()); setupBuffer ( infile.header (), scheme._active, scheme._passive, scheme._types, buf, preread, postread, scheme._banks, false, allowNonfinite); infile.setFrameBuffer (buf); cout.flush (); infile.readPixels ( infile.header ().dataWindow ().min.y, infile.header ().dataWindow ().max.y); return infile.isOptimizationEnabled (); } void test (Schema writeScheme, Schema readScheme, bool nonfatal, bool tiny) { ostringstream q; q << writeScheme._name << " read as " << readScheme._name << "..."; cout << left << setw (53) << q.str (); FrameBuffer writeFrameBuf; // only allow NaN and infinity values if file is read and written as half float // (otherwise casting between half and float may cause different bit patterns) bool allowNonfinite = (writeScheme._types == nullptr && readScheme._types==nullptr); Box2i dw = writefile (writeScheme, writeFrameBuf, tiny , allowNonfinite); FrameBuffer readFrameBuf; FrameBuffer preReadFrameBuf; FrameBuffer postReadFrameBuf; cout.flush (); bool opt = readfile (readScheme, readFrameBuf, preReadFrameBuf, postReadFrameBuf,allowNonfinite); if (compare (readFrameBuf, writeFrameBuf, dw, nonfatal) && compare (preReadFrameBuf, postReadFrameBuf, dw, nonfatal)) { cout << " OK "; if (opt) { cout << "OPTIMISED "; gOptimisedReads++; } cout << "\n"; gSuccesses++; } else { cout << " FAIL" << endl; gFailures++; } remove (filename.c_str ()); } void runtests (bool nonfatal, bool tiny) { random_reseed (1); int i = 0; int skipped = 0; gFailures = 0; gSuccesses = 0; gOptimisedReads = 0; while (Schemes[i]._name != NULL) { int j = 0; while (Schemes[j]._name != NULL) { cout << right << setw (2) << i << ',' << right << setw (2) << j << ": "; cout.flush (); if (nonfatal) { cout << " skipping " << Schemes[i]._name << ',' << Schemes[j]._name << ": known to crash\n"; skipped++; } else { test (Schemes[i], Schemes[j], nonfatal, tiny); } j++; } i++; } cout << gFailures << '/' << (gSuccesses + gFailures) << " runs failed\n"; cout << skipped << " tests skipped (assumed to be bad)\n"; cout << gOptimisedReads << '/' << gSuccesses << " optimised\n"; if (gFailures > 0) { cout << " TESTS FAILED\n"; assert (false); } } } // namespace void testOptimizedInterleavePatterns (const std::string& tempDir) { filename = tempDir + "imf_test_interleave_patterns.exr"; cout << "Testing SSE optimisation with different interleave patterns (large images) ... " << endl; runtests (false, false); cout << "Testing SSE optimisation with different interleave patterns (tiny images) ... " << endl; runtests (false, true); cout << "ok\n" << endl; }
2d6b25f83b2b43db7018af9a5ca6157f659f47c0
d74a438f4db67ddf80e80788b47646d2e8492f7b
/NeuralNetwork/nnfileinput.h
c86bd25b363efb263c4d66d0d25a2eba6b79b472
[]
no_license
David-Estevez/NeuralNetwork
035598ac604e72546eeed79de179ebab7df542fc
bb073eca995154fd25cfdf25122c8c48cc1b75aa
refs/heads/main
2016-09-05T23:22:48.353747
2012-12-13T22:20:04
2012-12-13T22:20:04
6,280,631
1
0
null
null
null
null
UTF-8
C++
false
false
5,367
h
nnfileinput.h
/*! \file nninput.h * \brief File support for NeuralNetwork data input. * * Loads the data for the input, weights and training examples from * different files. * * \author David Estévez Fernández ( http://github.com/David-Estevez ) * \date Nov 18th, 2012 * */ #ifndef NNFILEINPUT_H #define NNFILEINPUT_H #include <fstream> #include <vector> #include <cstdlib> #include "nninput.h" #include "neuralnetwork.h" #include "matrix.h" /*! \class NNFileInput * \brief File support for data input to NeuralNetwork. * * Loads the data for the input, weights and training examples from * different files. * * \todo Document new functions. */ class NNFileInput : public NNInput { public: //-- Constructors: //--------------------------------------------------------------------------- /*! * \brief Default constructor */ NNFileInput() {} /*! * \brief Creates a file input interface and connects it to a NeuralNetwork. * * \param nn NeuralNetwork to connect to. */ NNFileInput(NeuralNetwork& nn): NNInput(nn) { } /*! * \brief Creates a file input interface and connects it to a NeuralNetwork and NNTrainer. * * \param nn NeuralNetwork to connect to. * \param traininModule NNTrainer to connect to. */ NNFileInput(NeuralNetwork& nn, NNTrainer& trainingModule): NNInput(nn) { this->trainingModule = &trainingModule; } //-- Connectivity: //--------------------------------------------------------------------------- void connectToTrainingModule( NNTrainer& trainingModule) { this->trainingModule = &trainingModule; } //-- Load data from files: //--------------------------------------------------------------------------- /*! * \brief Loads the input data of the NeuralNetwork from a file, and sends it * to the network. */ virtual void loadWeights(); /*! * \brief Loads the weights of the NeuralNetwork from a file, and sends them * to the network. * * \todo If dimensions are nonconsistent, it stills tries to load the data. */ virtual void loadTrainingExamples(); /*! * \brief Loads the training examples data for the NeuralNetwork from a file, * and sends it to the network. */ virtual void loadInput(); //-- Store the files path: //--------------------------------------------------------------------------- /*! * \brief Adds one path containing weight matrix data. * * \param filePath String containing the path to the file. */ void addWeightsFile( const std::string filePath); /*! * \brief Selects the path containing the nth weight matrix data. * * \param filePath String containing the path to the file. * \param n Index of path to change. */ void setWeightsFile( const std::string filePath, const int n); /*! * \brief Selects the path containing the input data. * * The input data can be loaded from a file containing a row vector (all data * in a row, separed by spaces), a column vector (each number in a row) or as * a Matrix, that will be converted to a vector. * * \param filePath String containing the path to the file. * */ void setInputFile( const std::string filePath); /*! * \brief Selects the path containing the training set data. * * \param filePath String containing the path to the file. * * \todo This may have to change after training of the network is implemented. */ void addTrainingSetFile( const std::string filePath); /*! * \brief Selects the path containing the nth training set data. * * \param filePath String containing the path to the file. * \param n Index of path to change. */ void setTrainingSetFile( const std::string filePath, const int n); //! \todo Document this: std::vector<std::string> getWeightsFile( ) {return weightsFile; } std::string getInputFile() {return inputFile; } std::vector<std::string> getTrainingSetFile() { return trainingSetFile;} private: //-- Variables storing files path: //--------------------------------------------------------------------------- /*! \var std::vector<std::string> weightsFile * \brief Vector containing the paths to the files containing the NeuralNetwork * weights. */ std::vector<std::string> weightsFile; /*! \var std::string inputFile * \brief String containing the path to the input file. */ std::string inputFile; /*! \var std::vector<std::string> trainingSetFile * \brief Vector containing the paths to the training set data. */ std::vector<std::string> trainingSetFile; //-- Pointer to the training module to use the training examples: //-------------------------------------------------------------------------------- NNTrainer *trainingModule; //-- Load a matrix from a file: //-------------------------------------------------------------------------- /*! * \brief Loads a new Matrix from a file. * * \warning Matrices created with this function have to be deallocated later. * * \param filePath String containing the path to the file. */ Matrix* loadMatrix( const std::string filePath); }; #endif // NNFILEINPUT_H
99b7d45cc64bbf33db0f64bee5a875f50d2ee666
f75c62b9227f8459e2807fde3279b2a5e56e6e64
/CHr39/icoFoam/0.2/Co
cde12b3421bb5ddb26f17e5791dd8d4a069e8670
[]
no_license
kohoman/mstAdvComp.sp21
a718a930d693030e0abf05f451cdee50a6fca5f0
30307c3ff3c3e1e2c1dabf611e550f2c426d5d8d
refs/heads/main
2023-04-22T08:27:11.181441
2021-05-03T19:57:22
2021-05-03T19:57:22
338,087,447
1
0
null
null
null
null
UTF-8
C++
false
false
4,852
Co
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.2"; object Co; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField nonuniform List<scalar> 400 ( 0.00028479 0.000728841 0.00228469 0.00490826 0.00791924 0.0109435 0.0136589 0.0158076 0.0171979 0.0177064 0.0177064 0.0172802 0.0159421 0.0137969 0.0110357 0.00793629 0.00485353 0.00219414 0.000681975 0.000313588 0.000683913 0.00433482 0.0105169 0.0179062 0.0256464 0.0329574 0.039168 0.0437431 0.0462983 0.0466115 0.0465292 0.0463987 0.0439903 0.0394726 0.033209 0.025756 0.0178443 0.0103308 0.00413467 0.000615876 0.00224275 0.0107876 0.0221955 0.0345889 0.0466424 0.0572834 0.0656602 0.0711433 0.0733281 0.0720451 0.0718102 0.0733975 0.0714983 0.0661825 0.0577932 0.0469632 0.0346192 0.0219626 0.0104555 0.00204831 0.00514555 0.0194484 0.036682 0.0542397 0.0703495 0.0837062 0.093374 0.0987418 0.0994975 0.0956226 0.0951681 0.0995472 0.0993002 0.094283 0.0846894 0.0711018 0.0545425 0.0365078 0.0190081 0.00483342 0.00901597 0.0302398 0.0538788 0.0767438 0.0966997 0.112286 0.122567 0.127039 0.125561 0.118329 0.117527 0.1256 0.127952 0.124139 0.114102 0.0982659 0.0776547 0.0539919 0.0297879 0.00858727 0.0138129 0.0431703 0.0738385 0.102166 0.125765 0.143125 0.153413 0.156317 0.151934 0.14072 0.139332 0.151916 0.157746 0.156005 0.14628 0.128718 0.104225 0.0746471 0.0429218 0.0133092 0.019546 0.0583094 0.0966684 0.130594 0.157578 0.176202 0.185858 0.186533 0.178634 0.162909 0.160541 0.178404 0.188596 0.189862 0.181319 0.162686 0.134577 0.0988085 0.0586455 0.0190733 0.0262712 0.075779 0.122484 0.16205 0.192011 0.211224 0.219485 0.217205 0.205186 0.184499 0.180576 0.204426 0.2199 0.225243 0.218976 0.20019 0.168966 0.126853 0.0772922 0.0260262 0.0340895 0.0957487 0.151375 0.196409 0.228649 0.24749 0.253358 0.247261 0.230493 0.204478 0.198245 0.22867 0.250364 0.261036 0.258466 0.240867 0.207448 0.159132 0.0992783 0.0343873 0.0431584 0.118443 0.183376 0.233314 0.266661 0.283717 0.285845 0.274864 0.252672 0.221074 0.211637 0.249 0.277814 0.295245 0.298205 0.283734 0.249713 0.195893 0.125089 0.0444586 0.0537255 0.144169 0.218425 0.272054 0.304606 0.317816 0.314386 0.297196 0.268863 0.231579 0.218012 0.262301 0.29897 0.324715 0.335495 0.326874 0.294829 0.237136 0.155262 0.0566524 0.0661998 0.173353 0.256275 0.31134 0.340134 0.346575 0.335201 0.310207 0.275013 0.232169 0.213706 0.264331 0.309235 0.344817 0.366123 0.366995 0.340853 0.282381 0.190343 0.0715484 0.0812829 0.20657 0.296274 0.348892 0.369496 0.365206 0.342924 0.308351 0.265693 0.21775 0.194075 0.24966 0.302544 0.349169 0.383903 0.398831 0.384214 0.330238 0.230785 0.089998 0.100189 0.244463 0.336813 0.380625 0.386736 0.366689 0.330172 0.284353 0.234004 0.181933 0.153525 0.211726 0.271377 0.329455 0.380212 0.414359 0.418751 0.377578 0.276639 0.113287 0.124937 0.287229 0.374003 0.399102 0.382382 0.340918 0.287131 0.229135 0.171702 0.117222 0.0856986 0.14316 0.207065 0.275547 0.343684 0.401882 0.434221 0.417941 0.326681 0.14329 0.158415 0.332753 0.398647 0.390729 0.341558 0.273794 0.201401 0.136483 0.092428 0.058419 0.0303574 0.0692532 0.11139 0.17619 0.260372 0.345205 0.414187 0.438533 0.376026 0.18219 0.20303 0.371087 0.389938 0.331304 0.259764 0.227831 0.224473 0.21893 0.207844 0.188429 0.167928 0.195199 0.213821 0.226268 0.235962 0.260572 0.333513 0.415037 0.410373 0.230422 0.254506 0.370143 0.318129 0.284096 0.304334 0.327408 0.347753 0.361749 0.3671 0.36214 0.351332 0.365739 0.369193 0.363011 0.349224 0.331487 0.315899 0.341791 0.393338 0.27959 0.270207 0.318666 0.341717 0.400663 0.457549 0.504547 0.540344 0.565214 0.579709 0.584135 0.581489 0.584999 0.578232 0.56078 0.531798 0.490571 0.438115 0.381908 0.34417 0.282174 0.270207 0.491557 0.627326 0.71212 0.766517 0.801915 0.825056 0.839856 0.848502 0.852126 0.852126 0.851147 0.845374 0.8339 0.814742 0.784032 0.734484 0.652672 0.514208 0.282174 ) ; boundaryField { movingWall { type zeroGradient; } fixedWalls { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
3b3bffd2bb819fc72c3f986cdaad77285b8eafcd
2307db20bbea63dae055ea9b9f73c6a0f812dacc
/StarPatterns/StarSquare.cpp
842335075513e1b5d01ceb348ccd9dba5dd16f85
[]
no_license
NeelayRaj/CPPNotes
4801d9d12b921f31059602e30b6abe98dc6b6a52
86582041dcb9a5666613bd05db43449e8d6df786
refs/heads/main
2023-08-16T12:17:32.697524
2021-10-11T12:55:28
2021-10-11T12:55:28
406,369,664
0
0
null
null
null
null
UTF-8
C++
false
false
478
cpp
StarSquare.cpp
#include<iostream> using namespace std; int main() { int n; cout<<"Enter a Number "; cin>>n; for(int i = 0; i < n;i++) { for(int j = 1; j<n-i; j++) cout<<" "; for(int j = 1; j<=2*i+1;j++) cout<<"* "; cout<<endl; } for(int i = 1; i <= n-1;i++) { for(int j = 1; j<i+1; j++) cout<<" "; for(int j = 1; j<=2*(n-i)-1;j++) cout<<"* "; cout<<endl; } return 0; }
ac7cf5400cfd10e66d05983c8d4333aaea7ee5f9
752d76cfc60356c1fd7b416a1c33f222eb0c0438
/Year-2021/03-Mar/TestSockAndStruct/TestSrv/dialogsrv.h
9ef675d80a877c227480f0386487340d827014e6
[]
no_license
YYZYHS/Study-Documents-2021
55e59ef924b4215b4f98780eb20daf3ddbbbebbb
fa84b8968ba96f07e70d378fbd4ec140846a3f82
refs/heads/main
2023-03-21T05:50:22.397173
2021-03-09T07:44:33
2021-03-09T07:44:33
337,659,754
0
0
null
null
null
null
UTF-8
C++
false
false
992
h
dialogsrv.h
#ifndef DIALOGSRV_H #define DIALOGSRV_H #include <QDialog> #include <QtNetwork> #include <QStringList> #include <QList> #include "clientjobs.h" namespace Ui { class DialogSrv; } //结构体 struct NetData { unsigned int length; unsigned int n1; double d1; double d2; char name[32]; //这里数组可以,注意如果是指针指向堆空间,堆里数据要自己copy }; class DialogSrv : public QDialog { Q_OBJECT public: explicit DialogSrv(QWidget *parent = 0); ~DialogSrv(); private slots: void on_pushButtonListen_clicked(); //两个信号的槽函数 void onNewConnection(); // void DeleteOneClient(QString strIPAndPort); void on_pushButtonStop_clicked(); void on_pushButtonSend_clicked(); private: Ui::DialogSrv *ui; //server QTcpServer *m_pTCPSrv; //保存客户列表 QStringList m_listIPAndPorts; //IP_Port QList<ClientJobs*> m_listClients;//客户端 }; #endif // DIALOGSRV_H
ebf2ead247a386590ec85de901440b54ff25f7ed
202b96b76fc7e3270b7a4eec77d6e1fd7d080b12
/modules/scope/scope_document_listener.h
3eaa672a7e8e604a03097febdaf554ea0e17efbd
[]
no_license
prestocore/browser
4a28dc7521137475a1be72a6fbb19bbe15ca9763
8c5977d18f4ed8aea10547829127d52bc612a725
refs/heads/master
2016-08-09T12:55:21.058966
1995-06-22T00:00:00
1995-06-22T00:00:00
51,481,663
98
66
null
null
null
null
UTF-8
C++
false
false
1,448
h
scope_document_listener.h
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef OP_SCOPE_DOCUMENT_LISTENER_H #define OP_SCOPE_DOCUMENT_LISTENER_H #if defined(SCOPE_DOCUMENT_MANAGER) || defined(SCOPE_PROFILER) #include "modules/dochand/docman.h" class OpScopeDocumentListener { public: /** * Arguments for OnAboutToLoadDocument. The contents copy the parameters * of DocumentManager::OpenURL. */ struct AboutToLoadDocumentArgs { DocumentManager::OpenURLOptions options; URL_Rep *url; URL_Rep *referrer_url; BOOL check_if_expired; BOOL reload; }; // AboutToLoadDocumentArgs /** * Check if document listener is enabled. If it isn't, the caller * does not need to send events. * * @return TRUE if enabled, FALSE if disabled. */ static BOOL IsEnabled(); /** * Call this when a document is about to be loaded. (Not when it * has finished loading). * * @param docman The DocumentManager that is about to be loaded. * @param args Arguments to DocumentManager::OpenURL. See OnLoadDocumentArgs. */ static OP_STATUS OnAboutToLoadDocument(DocumentManager *docman, const AboutToLoadDocumentArgs &args); }; // OpScopeDocumentListener #endif // SCOPE_DOCUMENT_MANAGER || SCOPE_PROFILER #endif // OP_SCOPE_DOCUMENT_LISTENER_H
67010c4971cfdc8b32baaecc0a4ad409385d9779
402bc4cddb7b06f1217e8e855c80e72032c8ea4f
/Lab_3_1/Lab_3_1.ino
41482f209356519c96b9498adf89b1193e156d19
[]
no_license
QuentinTorg/Pitt_Mechatronics
55eb2b9c9006ef2310f1a23e9f2184f32811cbd6
9abfc1237404c0471aa5e06fb31d5bd134e6d965
refs/heads/master
2021-01-10T16:08:15.150097
2016-04-30T01:44:04
2016-04-30T01:44:04
49,481,386
0
0
null
null
null
null
UTF-8
C++
false
false
1,664
ino
Lab_3_1.ino
/////////// hardware /////////////// /* When running, disconnect arduino from computer. Could cause power error on computer Set power supply somewhere between 7.5 and 10 volts. Start at 7.5 and go up if stepper doesn't work Power supply should only be connected to arduino Vin, NOT VCC!!!!!!!!! *** to reverse the motor's direction, switch motor wire1 with motor wire2 pin9 --> Hbridge M1 Enable pin2 --> Hbridge M1 Forward pin3 --> Hbridge M1 Reverse power supply ground --> Hbridge ground power supply Positive --> Hbridge Motor Power IN power supply Positive --> Arduino Vin Arduino Vcc --> Hbridge +5V Arduino Ground --> Hbridge Ground Arduino Vcc --> Potentiometer outer pin1 Arduino Ground --> Potentiometer outer pin2 pinA0 --> Potentiometer middle pin *** Motor wire1 --> Hbridge M1 output pin Motor wire2 --> Hbridge M1 output pin *** */ // Software byte motor_enable_pin = 9; byte motor_direction_pin_1 = 3; byte motor_direction_pin_2 = 2; byte sensor_pin = A0; void setup() { // Set pinmode of each output pin pinMode(motor_enable_pin, OUTPUT); pinMode(motor_direction_pin_1, OUTPUT); pinMode(motor_direction_pin_2, OUTPUT); } void loop() { // calculate setpoint in number of steps using float_map function drive_motor(map((float)analogRead(sensor_pin), 0, 1023, -255, 255)); } void drive_motor(int motor_output) { // write duty cycle for the motor analogWrite(motor_enable_pin, abs(motor_output)); // write direction pins for motor digitalWrite(motor_direction_pin_1, (motor_output >= 0 ? 0 : 1)); digitalWrite(motor_direction_pin_2, !(motor_output >= 0 ? 0 : 1)); }
773276a2d048585beb6b283983809a08e5c30b11
20805224c698e9260cc5b9f3f51a3290fafec386
/plt/op_svr/src/frame/global_serv.cpp
a000970cfa9f9be87f98dbc3531965c67368efe0
[]
no_license
jyqiu1216/bob
bacd14472a3b5f19b52fbf9747c1e2d5b0f29ee2
5a58c17deaa953a48df512c29ed1557276ef3608
refs/heads/master
2020-06-18T17:56:26.416382
2017-01-03T01:16:49
2017-01-03T01:16:49
74,750,647
0
0
null
null
null
null
GB18030
C++
false
false
8,930
cpp
global_serv.cpp
#include "global_serv.h" #include "statistic.h" #include "curl/curl.h" #include "aws_table_include.h" #include "conf_base.h" #include <string> #include <sstream> #include "warning_mgr.h" #include "game_command.h" // 静态变量定义 CTseLogger* CGlobalServ::m_poServLog = NULL; CTseLogger* CGlobalServ::m_poReqLog = NULL; CTseLogger* CGlobalServ::m_poRegLog = NULL; CTseLogger* CGlobalServ::m_poStatLog = NULL; CConf* CGlobalServ::m_poConf = NULL; CSessionMgr* CGlobalServ::m_poSessionMgr = NULL; CTaskQueue* CGlobalServ::m_poTaskQueue = NULL; CQueryNetIO* CGlobalServ::m_poQueryNetIO = NULL; CSearchNetIO* CGlobalServ::m_poSearchNetIO = NULL; CTaskProcess* CGlobalServ::m_poTaskProcess = NULL; CDownMgr* CGlobalServ::m_poDownMgr = NULL; CZkRegConf* CGlobalServ::m_poZkConf = NULL; CZkRegClient* CGlobalServ::m_poZkRegClient = NULL; TUINT32 CGlobalServ::m_udwDownReqSeq = 1; pthread_mutex_t CGlobalServ::m_mtxDownReqSeq = PTHREAD_MUTEX_INITIALIZER; TUINT32 CGlobalServ::GenerateHsReqSeq() { TUINT32 udwSeq = 0; pthread_mutex_lock(&m_mtxDownReqSeq); m_udwDownReqSeq++; if (m_udwDownReqSeq < 100000) { m_udwDownReqSeq = 100000; } udwSeq = m_udwDownReqSeq; pthread_mutex_unlock(&m_mtxDownReqSeq); return udwSeq; } int CGlobalServ::InitAwsTable(const TCHAR *pszProjectPrefix) { TbAl_member::Init("../tblxml/al_member.xml", pszProjectPrefix); } int CGlobalServ::Init() { // 初始化日志对象 INIT_LOG_MODULE("../conf/serv_log.conf"); config_ret = 0; DEFINE_LOG(serv_log, "serv_log"); DEFINE_LOG(reg_log, "reg_log"); DEFINE_LOG(req_log, "req_log"); DEFINE_LOG(stat_log, "stat_log"); m_poServLog = serv_log; m_poReqLog = req_log; m_poRegLog = reg_log; m_poStatLog = stat_log; // ---------------------公共tool初始化-------------------------------- // curl curl_global_init(CURL_GLOBAL_ALL); // ----------------------初始化配置文件-------------------------------- m_poConf = new CConf(); if (0 != m_poConf->Init("../conf/serv_info.conf")) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init conf failed!")); return -1; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init conf success!")); if (0 != CConfBase::Init("../conf/module.conf", m_poConf->m_szModuleName)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init project.conf failed!")); return -2; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init project.conf success!")); // 初始化zk相关配置 m_poZkConf = new CZkRegConf(); if (0 != m_poZkConf->Init("../conf/serv_info.conf", "../conf/module.conf")) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init zk_conf failed!")); return -3; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init zk_conf success!")); //初始化aws_tables InitAwsTable(CConfBase::GetString("tbxml_project").c_str()); TSE_LOG_INFO(m_poServLog, ("GlobalServ inittable success!")); // 初始化ZK客户端 m_poZkRegClient = new CZkRegClient(); if (0 != m_poZkRegClient->Init(m_poRegLog, m_poZkConf)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ Init zk_reg_client failed")); return -4; } TSE_LOG_INFO(m_poServLog, ("GlobalServ Init zk_reg_client succ")); // 初始化命令字信息 CClientCmd *poClientCmd = CClientCmd::GetInstance(); if (0 != poClientCmd->Init()) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init client cmd info failed!")); return -17; } // ----------------------初始化队列相关-------------------------------- // 初始化队列信息 m_poTaskQueue = new CTaskQueue(); if (0 != m_poTaskQueue->Init(CConfBase::GetInt("queue_size"))) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init task queue failed! [queue_size=%u]", CConfBase::GetInt("queue_size"))); return -5; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init task_queue success!")); // 初始化Session管理器 m_poSessionMgr = CSessionMgr::Instance(); if (0 != m_poSessionMgr->Init(CConfBase::GetInt("queue_size"), m_poServLog)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init session_mgr failed!")); return -6; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init session_mgr success!")); // ----------------------初始化线程相关-------------------------------- // 初始化网络IO——对上游 m_poQueryNetIO = new CQueryNetIO(); if (0 != m_poQueryNetIO->Init(m_poServLog, m_poTaskQueue)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init query_net_io failed!")); return -7; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init query_net_io success!")); // 初始化网络IO——对下游 m_poSearchNetIO = new CSearchNetIO(); if (0 != m_poSearchNetIO->Init(m_poConf, m_poServLog, m_poTaskQueue)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init search_net_io failed!")); return -8; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init search_net_io success!")); // 初始化zk下游管理线程 m_poDownMgr = CDownMgr::Instance(); if (0 != m_poDownMgr->zk_Init(m_poRegLog, m_poSearchNetIO->m_pLongConn, m_poZkConf)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init down_mgr failed!")); return -9; } TSE_LOG_INFO(m_poServLog, ("GlobalServ init down_mgr success!")); // 初始化工作线程 m_poTaskProcess = new CTaskProcess[CConfBase::GetInt("work_thread_num")]; for (TINT32 dwIdx = 0; dwIdx < CConfBase::GetInt("work_thread_num"); dwIdx++) { if (0 != m_poTaskProcess[dwIdx].Init(m_poConf, m_poSearchNetIO->m_pLongConn, m_poQueryNetIO->m_pLongConn, m_poTaskQueue, m_poServLog, m_poReqLog)) { TSE_LOG_ERROR(m_poServLog, ("GlobalServ init %uth task process failed!", dwIdx)); return -10; } } TSE_LOG_INFO(m_poServLog, ("GlobalServ init task_process success!")); // 初始化告警上报 CWarningMgr::GetInstance()->Init(m_poServLog); TSE_LOG_INFO(m_poServLog, ("GlobalServ init warning mgr success!")); // statistic CStatistic *pstStatistic = CStatistic::Instance(); pstStatistic->Init(m_poStatLog, m_poConf); // ----------------------end-------------------------------- TSE_LOG_INFO(m_poServLog, ("GlobalServ init all success!")); return 0; } int CGlobalServ::Uninit() { // do nothing return 0; } int CGlobalServ::Start() { pthread_t thread_id = 0; // 创建统计线程 if (pthread_create(&thread_id, NULL, CStatistic::Start, CStatistic::Instance()) != 0) { TSE_LOG_ERROR(m_poServLog, ("create statistic thread failed! Error[%s]", strerror(errno))); return -1; } TSE_LOG_INFO(m_poServLog, ("create statistic thread success!")); // 创建工作线程 for (TINT32 dwIdx = 0; dwIdx < CConfBase::GetInt("work_thread_num"); dwIdx++) { if (pthread_create(&thread_id, NULL, CTaskProcess::Start, &m_poTaskProcess[dwIdx]) != 0) { TSE_LOG_ERROR(m_poServLog, ("create task process thread failed! [idx=%u] Error[%s]", dwIdx, strerror(errno))); return -2; } } TSE_LOG_INFO(m_poServLog, ("create task_process thread success!")); // 创建zk下游管理线程 if (pthread_create(&thread_id, NULL, CDownMgr::zk_StartPull, CDownMgr::Instance()) != 0) { TSE_LOG_ERROR(m_poServLog, ("create down manager thread failed! Error[%s]", strerror(errno))); return -3; } if (pthread_create(&thread_id, NULL, CDownMgr::zk_StartCheck, CDownMgr::Instance()) != 0) { TSE_LOG_ERROR(m_poServLog, ("create down manager thread failed! Error[%s]", strerror(errno))); return -3; } // 创建网络线程-下游 if (pthread_create(&thread_id, NULL, CSearchNetIO::RoutineNetIO, m_poSearchNetIO) != 0) { TSE_LOG_ERROR(m_poServLog, ("create search_net_io thread failed! Error[%s]", strerror(errno))); return -4; } TSE_LOG_INFO(m_poServLog, ("create search_net_io thread success!")); // 创建网络线程-上游——此线程提供对外服务,最后进行延时启动 sleep(2); if (pthread_create(&thread_id, NULL, CQueryNetIO::RoutineNetIO, m_poQueryNetIO) != 0) { TSE_LOG_ERROR(m_poServLog, ("create query_net_io thread failed! Error[%s]", strerror(errno))); return -5; } TSE_LOG_INFO(m_poServLog, ("create query_net_io thread success!")); // 启动注册线程 m_poZkRegClient->Start(); TSE_LOG_INFO(m_poServLog, ("GlobalServ start all thread success!")); return 0; } int CGlobalServ::StopNet() { // 停止query线程的接收请求端口 m_poQueryNetIO->CloseListenSocket(); curl_global_cleanup(); return 0; }
84533ebd24d5beb85e60f92e5f7383cc6027fd7b
96d1adb78c70bbfe35158bcea5a5496eab0ef8e6
/src/Server/Store/SpaceshipHullStore.hpp
1860527606c4179221bf814fb92a5304c86952cc
[ "MIT" ]
permissive
paulbacelar/Erewhon-Game
2ff8d05d7b69b91892c8faa9cc07302becfee548
3b8a268331f1c417cf6cc36dabbddf237b001365
refs/heads/master
2021-04-26T23:44:39.772077
2018-04-16T06:26:15
2018-04-16T06:26:15
123,847,980
0
0
null
2018-03-05T01:33:35
2018-03-05T01:33:34
null
UTF-8
C++
false
false
1,222
hpp
SpaceshipHullStore.hpp
// Copyright (C) 2018 Jérôme Leclercq // This file is part of the "Erewhon Server" project // For conditions of distribution and use, see copyright notice in LICENSE #pragma once #ifndef EREWHON_SERVER_SPACESHIPHULLSTORE_HPP #define EREWHON_SERVER_SPACESHIPHULLSTORE_HPP #include <Server/DatabaseStore.hpp> #include <NDK/Entity.hpp> #include <string> #include <vector> namespace ewn { class Database; class DatabaseResult; class SpaceshipHullStore final : public DatabaseStore { public: inline SpaceshipHullStore(); ~SpaceshipHullStore() = default; inline std::size_t GetEntryCollisionMeshId(std::size_t entryId) const; inline std::size_t GetEntryVisualMeshId(std::size_t entryId) const; inline bool IsEntryLoaded(std::size_t entryId) const; private: bool FillStore(ServerApplication* app, DatabaseResult& result) override; struct HullInfo { std::size_t collisionMeshId; std::size_t visualMeshId; std::string name; std::string description; bool doesExist = false; bool isLoaded = false; }; std::vector<HullInfo> m_hullInfos; bool m_isLoaded; }; } #include <Server/Store/SpaceshipHullStore.inl> #endif // EREWHON_SERVER_SPACESHIPHULLSTORE_HPP
d99080be1be15e12f081692af34e1686e37b6f18
943548ce22e7e8afef7f9aed6bf3e97e8f74df1c
/Source/Runtime/Constructor.h
72bdef9860e343c440e965e2bc0d2b8ec4c536e7
[ "MIT" ]
permissive
alix00083/CPP-Reflection
42da1768c0868db96b902681c1eb938b1319034f
e55882bb8da0728f6a993f3e5c0b18838564e438
refs/heads/master
2022-01-12T22:37:11.703496
2019-05-03T12:03:24
2019-05-03T12:03:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
h
Constructor.h
/* ---------------------------------------------------------------------------- ** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved. ** ** Constructor.h ** --------------------------------------------------------------------------*/ #pragma once #include <memory> #include "MetaContainer.h" #include "Invokable.h" #include "Type.h" #include "ConstructorInvoker.h" namespace ursine { namespace meta { class Variant; class Argument; class Constructor : public MetaContainer , public Invokable { public: Constructor(void); Constructor(const Constructor &rhs); Constructor(const Constructor &&rhs) noexcept; Constructor( Type classType, InvokableSignature signature, ConstructorInvokerBase *invoker, bool isDynamic ); Constructor &operator=(const Constructor &&rhs); static const Constructor &Invalid(void); Type GetClassType(void) const; bool IsValid(void) const; bool IsDynamic(void) const; Variant InvokeVariadic(const ArgumentList &arguments) const; template<typename ...Args> Variant Invoke(Args &&...args) const; private: bool m_isDynamic; Type m_classType; std::shared_ptr<ConstructorInvokerBase> m_invoker; }; } } #include "Variant.h" #include "Argument.h" namespace ursine { namespace meta { template<typename ...Args> Variant Constructor::Invoke(Args &&...args) const { ArgumentList arguments{ std::forward<Args>(args)... }; return InvokeVariadic(arguments); } } }
cd4a4b21857d82098f00005f49288239933865be
d215271a6a0682c870b04ea614fd19db6f27b5c6
/USER/missionInfo.hpp
0ffc4608bb75fd17f26b3aba5e9c50dac0e083a1
[]
no_license
gruppe-adler/CO_OperationHomecoming_II.Majan
202816e23f6ff30a03735f9daa6d71af137a25b6
317af1425f4a603bd3d522050b842d30c8af720e
refs/heads/main
2023-03-01T03:24:26.904192
2021-01-30T17:57:39
2021-01-30T17:57:39
329,733,413
0
0
null
null
null
null
UTF-8
C++
false
false
5,898
hpp
missionInfo.hpp
/* * Legt allgemeine Information über die Mission fest. */ author = "nomisum für Gruppe Adler"; // Missionsersteller onLoadName = "Operation Homecoming II"; // Name der Mission onLoadMission = ""; // Beschreibung der Mission (wird im Ladebildschirm unterhalb des Ladebildes angezeigt) loadScreen = "data\loading.paa"; // Ladebild overviewPicture = ""; // Bild, das in der Missionsauswahl angezeigt wird overviewText = ""; // Text, der in der Missionsauswahl angezeigt wird #include "..\node_modules\grad-leaveNotes\grad_leaveNotes.hpp" class CfgSFX { sounds[] = {}; class sfxsound10 { name = "music1"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\music1.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound11 { name = "music2"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\music2.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound12 { name = "kunduznews"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\kunduznews.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound13 { name = "SanginnewsBBC"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\SanginnewsBBC.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound14 { name = "prayer2"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\prayer2.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound16 { name = "ISISpropoganda"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\ISISpropoganda.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound18 { name = "arab_talking"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\arab_talking.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound19 { name = "arabicsong1"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\arabicsong1.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class sfxsound20 { name = "arabicsong2"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\arabicsong2.ogg",35,1,150,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; class piss { name = "piss"; sounds[]={sfxsound}; sfxsound[]={"USER\sound\piss.ogg",10,1,50,1,1,1,0}; empty[]= {"",0,0,0,0,0,0,0}; }; }; class CfgVehicles { class sfxsound // class name to be used with createSoundSource { sound = "sfxsound"; // reference to CfgSFX class }; class sfxsound2 // class name to be used with createSoundSource { sound = "sfxsound2"; // reference to CfgSFX class }; class sfxsound3 // class name to be used with createSoundSource { sound = "sfxsound3"; // reference to CfgSFX class }; class sfxsound4 // class name to be used with createSoundSource { sound = "sfxsound4"; // reference to CfgSFX class }; class sfxsound5 // class name to be used with createSoundSource { sound = "sfxsound5"; // reference to CfgSFX class }; class sfxsound6 // class name to be used with createSoundSource { sound = "sfxsound6"; // reference to CfgSFX class }; class sfxsound7 // class name to be used with createSoundSource { sound = "sfxsound7"; // reference to CfgSFX class }; class sfxsound8 // class name to be used with createSoundSource { sound = "sfxsound8"; // reference to CfgSFX class }; class sfxsound9 // class name to be used with createSoundSource { sound = "sfxsound9"; // reference to CfgSFX class }; class sfxsound10 // class name to be used with createSoundSource { sound = "sfxsound10"; // reference to CfgSFX class }; class sfxsound11 // class name to be used with createSoundSource { sound = "sfxsound11"; // reference to CfgSFX class }; class sfxsound12 // class name to be used with createSoundSource { sound = "sfxsound12"; // reference to CfgSFX class }; class sfxsound13 // class name to be used with createSoundSource { sound = "sfxsound13"; // reference to CfgSFX class }; class sfxsound14 // class name to be used with createSoundSource { sound = "sfxsound14"; // reference to CfgSFX class }; class sfxsound15 // class name to be used with createSoundSource { sound = "sfxsound15"; // reference to CfgSFX class }; class sfxsound16 // class name to be used with createSoundSource { sound = "sfxsound16"; // reference to CfgSFX class }; class sfxsound17 // class name to be used with createSoundSource { sound = "sfxsound17"; // reference to CfgSFX class }; class sfxsound18 // class name to be used with createSoundSource { sound = "sfxsound18"; // reference to CfgSFX class }; class sfxsound19 // class name to be used with createSoundSource { sound = "sfxsound19"; // reference to CfgSFX class }; class sfxsound20 // class name to be used with createSoundSource { sound = "sfxsound20"; // reference to CfgSFX class }; class piss // class name to be used with createSoundSource { sound = "piss"; // reference to CfgSFX class }; };
60b2dbe29b145e91818d317571a3d27154c1a27d
4b1305bcde2dc6d33186309fd28a52564334f338
/untitled12/untitled12/logger.cpp
54eb289cf4abaa0ea44cfd64e2654ae283954bd3
[]
no_license
BrandDebiel/LogExample
95e222878e09b4544d66c667fb8883a240f60ace
54703f6f99b1ecd4b9d4d476ca669f78f4ecf88a
refs/heads/master
2020-03-14T17:53:38.065342
2018-05-01T15:38:27
2018-05-01T15:38:27
131,730,597
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
cpp
logger.cpp
#include "logger.h" Logger* Logger::instance = 0; Logger::Logger() { } Logger* Logger::getInstance() { if (instance == 0) { instance = new Logger(); } return instance; } void Logger::logMessage() { qDebug() << "Message OK"; } void Logger::messageHandler(QtMsgType type,const QString & str) { const char * msg = str.toStdString().c_str(); QString messageString; QDateTime dateTime; dateTime = QDateTime::currentDateTime(); messageString.append(dateTime.toString("yyyy-MM-dd hh:mm:ss:zzz")); messageString.append(" "); switch (type) { case QtDebugMsg: messageString.append(QString("DEBUG : %1").arg(msg)); break; case QtWarningMsg: messageString.append(QString("WARNING : %1").arg(msg)); break; case QtCriticalMsg: messageString.append(QString("CRITICAL : %1").arg(msg)); break; case QtInfoMsg: messageString.append(QString("INFO : %1").arg(msg)); break; case QtFatalMsg: messageString.append(QString("FATAL : %1").arg(msg)); abort(); } QFile outFile("log"); outFile.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream ts(&outFile); ts << messageString << endl; if(m_textEditorEnabled) { m_textEditor->appendPlainText(messageString); } } void Logger::setTextEdit(QPlainTextEdit *textEditor) { m_textEditor = textEditor; m_textEditorEnabled = true; }
e11647775caa66da61cd9c0f3c711fa4f051984c
4cdadf94219c512b31ca03c13c69f49ada5f5e40
/sea-server/contract_object.cpp
72601d2ae2b1a5b47480f7a81bc06e42add5f9bd
[]
no_license
lache/lo
c7fbf5af2d6b96ea10001923c79cf5ae75a166ee
98423f676957862837ed294f964447547da72847
refs/heads/master
2023-05-11T08:12:08.970610
2023-05-08T16:01:03
2023-05-08T16:01:03
134,514,309
4
0
null
2023-03-07T02:52:48
2018-05-23T04:41:01
C
UTF-8
C++
false
false
58
cpp
contract_object.cpp
#include "precompiled.hpp" #include "contract_object.hpp"
2f7800013d6f36a54e8324d842bd19c9f6f55a66
c89c682aa9ad1eda06608f161617469a02d94e00
/uva_41695.cpp
cbf7ba01a89a51de68383b699769d9101f615225
[]
no_license
jeremyhuang3627/Online-Judge
a32fc775ddb78fdafb90f41478a15638bc2e28b7
a875e6f735ac814d662ad6de8e1d06648c138670
refs/heads/master
2021-01-10T21:00:10.410788
2014-09-29T01:21:21
2014-09-29T01:21:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
uva_41695.cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <cstring> using namespace std; int a,b,n,m; void topo(int num,vector<int> &ans,vector<int> adj[],vector<bool> &v) { for(int i=0;i<adj[num].size();i++){ if(!v[adj[num][i]]){ topo(adj[num][i],ans,adj,v); } } v[num] = true; ans.push_back(num); } int main() { cin >> n >> m; while(n!=0 || m!=0){ vector<int> adj[105]; vector<bool> v (105); for(int i=0;i<m;i++){ cin >> a >> b; adj[b].push_back(a); } vector<int> ans; for(int i=1;i<=n;i++){ if(!v[i]) { topo(i,ans,adj,v); } } for(int i=0;i<ans.size();i++){ cout << ans[i] << " "; } cout << endl; cin >> n >> m; } return 0; }
25aee53a4b82bd527dd843f28f3295d493f53e5c
f293d1da56d8b1689d39b48a1d05362bd36baef4
/Corners/Harris.cpp
e6c20321275ff77ef2737b8d7c8c0ec94f1acec1
[]
no_license
aa6588/RIT
6521a089a13dbe2dd159dda2c0d6dab354475286
dae9f999c816e7ea8a4972ebecf2e17637bde336
refs/heads/main
2023-03-15T22:14:13.192409
2021-03-07T04:25:34
2021-03-07T04:25:34
345,256,549
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
cpp
Harris.cpp
/** Implementation file for finding corner features using Harris * * \file ipcv/corners/Harris.cpp * \author Carl Salvaggio, Ph.D. (salvaggio@cis.rit.edu) * \edited: Andrea Avendano (aa6588@rit.edu) * \date 7 Nov 2020 */ #include "Corners.h" #include "opencv2/imgproc.hpp" #include <iostream> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> using namespace std; namespace ipcv { /** Apply the Harris corner detector to a color image * * \param[in] src source cv::Mat of CV_8UC3 * \param[out] dst destination cv:Mat of CV_32FC1 * \param[in] sigma standard deviation of the Gaussian blur kernel * \param[in] k free parameter in the equation * dst = (lambda1)(lambda2) - k(lambda1 + lambda2)^2 */ bool Harris(const cv::Mat &src, cv::Mat &dst, const float sigma, const float k) { cv::Mat src_gray; cv::cvtColor(src, src_gray, cv::COLOR_BGR2GRAY); dst.create(src_gray.size(), CV_32FC1); // dst.create(src.size(),CV_8UC1); // Compute derivatives cv::Mat Ix; cv::Mat Iy; Ix.create(src_gray.size(), CV_32FC1); Iy.create(src_gray.size(), CV_32FC1); // Horizontal and Vertical Gradients cv::Mat kernelH; kernelH.create(3, 3, CV_32FC1); kernelH = 0; kernelH.at<float>(0, 0) = -1; kernelH.at<float>(0, 2) = 1; kernelH.at<float>(1, 0) = -1; kernelH.at<float>(1, 2) = 1; kernelH.at<float>(2, 0) = -1; kernelH.at<float>(2, 2) = 1; kernelH /= 1; cv::Mat kernelV; kernelV.create(3, 3, CV_32FC1); kernelV = 0; kernelV.at<float>(0, 0) = -1; kernelV.at<float>(2, 0) = 1; kernelV.at<float>(0, 1) = -1; kernelV.at<float>(2, 1) = 1; kernelV.at<float>(0, 2) = -1; kernelV.at<float>(2, 2) = 1; kernelV /= 1; cv::filter2D(src_gray, Ix, CV_32FC1, kernelH); cv::filter2D(src_gray, Iy, CV_32FC1, kernelV); // Create Hessian Matrix cv::Mat A; cv::Mat B; cv::Mat C; A.create(Ix.size(), CV_32FC1); B.create(Iy.size(), CV_32FC1); C.create(Ix.size(), CV_32FC1); A = Ix.mul(Ix); B = Iy.mul(Iy); C = Ix.mul(Iy); // Gaussian blur the matrix cv::GaussianBlur(A, A, cv::Size(0, 0), sigma, 0); cv::GaussianBlur(B, B, cv::Size(0, 0), sigma, 0); cv::GaussianBlur(C, C, cv::Size(0, 0), sigma, 0); // Compute the Harris response cv::Mat R; R.create(A.size(), CV_32FC1); for (int r = 0; r < Ix.rows; r++) { for (int c = 0; c < Ix.cols; c++) { float eigenA; float eigenB; float eigenC; eigenA = A.at<float>(r, c); eigenB = B.at<float>(r, c); eigenC = C.at<float>(r, c); float det = eigenA * eigenB - eigenC * eigenC; float trace = eigenA + eigenB; R.at<float>(r, c) = det - k * trace * trace; } } // output image, filter out corners to be 1 pixel cv::Mat dst2; R.copyTo(dst2); for (int row = 2; row < dst2.rows - 2; row++) { for (int col = 2; col < dst2.cols - 2; col++) { cv::Mat neighborhood(dst2, cv::Range(col - 2, col + 2), cv::Range(row - 2, row + 2)); double max; double min; cv::minMaxLoc(neighborhood, &min, &max); if (neighborhood.at<float>(2, 2) == max && neighborhood.at<float>(2, 2) > 0) { dst.at<float>(row, col) = 255; } } } dst.convertTo(dst, CV_8UC1); return true; } } // namespace ipcv
00376a0f652b3723f58d7079020b6d43145d462f
863167020d3cc5a0bd4c10c242ba17ca005642ed
/3D Project/VGUI/UIText.cpp
9b46e54f085dc873695688ff63f77f10af451922
[]
no_license
ThaiNhatMinh/LightEngine
b19ce380a82df58e6843a82e505912359fd50df1
465b18062d1c2a894d8ad2de0a5527fde2a54271
refs/heads/v2.0
2021-10-10T12:20:50.745137
2018-11-04T18:33:36
2018-11-04T18:33:36
92,942,691
2
3
null
2018-11-04T18:33:37
2017-05-31T12:10:54
C++
UTF-8
C++
false
false
2,061
cpp
UIText.cpp
#include <pch.h> UIText::UIText() { } void UIText::OnInit(VGUI *pVGUI) { m_UIShader = pVGUI->GetShader(); m_Font = pVGUI->GetFont("Default"); } void UIText::Render() { float x = m_Pos.x; float y = m_Pos.y; if (m_Text.size() == 0) return; for (size_t i = 0; i<m_Text.size(); i++) { m_Meshs[i].Mesh.VAO.Bind(); // Render glyph texture over quad //glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_Meshs[i].texID); m_UIShader->SetUniform("tex", 0); m_UIShader->SetUniform("isText", 1); m_UIShader->SetUniform("objColor", vec3(1.0f)); m_UIShader->SetUniform("Translate", m_Pos + m_Meshs[i].Pos); // Render quad glDrawArrays(GL_TRIANGLES, 0, 6); } } const string & UIText::GetText() const { return m_Text; } void UIText::SetText(const string & text) { m_Text = text; UpdateInternalData(); } void UIText::UpdateInternalData() { if (m_Text.size() == 0) return; float x = 0;// m_Pos.x; float y = 0;// m_Pos.y; m_Meshs.clear(); //m_Meshs.resize(m_Text.size()); for (std::size_t i = 0; i<m_Text.size(); i++) { TextRenderInfo tr; FTFont::FontChar* ch = m_Font->GetChar(m_Text[i]); float xpos = x + ch->Bearing[0]; float ypos = y - (ch->size[1] - ch->Bearing[1]); GLfloat w = ch->size[0]; GLfloat h = ch->size[1]; // Update VBO for each character GLfloat vertices[6][4] = { { 0, h, 0.0, 0.0 }, { 0, 0, 0.0, 1.0 }, { w, 0, 1.0, 1.0 }, { 0, h, 0.0, 0.0 }, { w, 0, 1.0, 1.0 }, { w, h, 1.0, 0.0 } }; // Render glyph texture over quad tr.texID = ch->iTextureID; // Update content of VBO memory tr.Mesh.VBO.Bind(); tr.Mesh.VBO.SetData(sizeof(vertices), vertices, GL_STATIC_DRAW); tr.Mesh.VBO.UnBind(); tr.Pos = vec2(xpos, ypos); x += (ch->advance >> 6); // Bitshift by 6 to get value in pixels (2^6 = 64) m_Meshs.push_back(std::move(tr)); } } UIText::TextRenderInfo::TextRenderInfo(TextRenderInfo && other):Mesh(std::move(other.Mesh)),texID(other.texID),Pos(other.Pos) { }
d08efd4148fbd12e711a2f5fb3be245515ebc17d
cfc99437b085afa7304ed5a4eab2a90072c7e50e
/pintools/source/tools/ChildProcess/fork_probed2.cpp
7eff92adee91e385715ea2a1ded329037a764dd3
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
moraispgsi/pin-bootstrap
95498b63f88c311e4fe446259214266130aece3f
7315b4e1709f63f018781456f9c745fc6f020f22
refs/heads/master
2021-09-07T18:09:11.568374
2018-02-27T05:16:32
2018-02-27T05:16:32
122,972,429
0
1
MIT
2018-02-26T14:31:18
2018-02-26T13:17:08
C++
UTF-8
C++
false
false
4,286
cpp
fork_probed2.cpp
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include "pin.H" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; /* ===================================================================== */ KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "fork_probed2.out", "specify file name"); ofstream Out; void (*free_memory_ptr)(void) = NULL; /* ===================================================================== */ INT32 Usage() { cerr << "This pin tool tests probe replacement.\n" "\n"; cerr << KNOB_BASE::StringKnobSummary(); cerr << endl; return -1; } pid_t activeProcessId = 0; pid_t parentPid = 0; void BeforeFork(UINT32 childPid, void *data) { parentPid = PIN_GetPid(); Out << "TOOL: Before fork.." << endl; } void AfterForkInParent(UINT32 childPid, void *data) { activeProcessId = PIN_GetPid(); Out << "TOOL: After fork in parent." << endl; } void AfterForkInChild(UINT32 childPid, void *data) { activeProcessId = PIN_GetPid(); Out << "TOOL: After fork in child." << endl; ASSERTX(NULL != free_memory_ptr); free_memory_ptr(); } BOOL FollowChild(CHILD_PROCESS childProcess, VOID * userData) { if (PIN_GetPid() == parentPid) { Out << "TOOL: At follow child callback in parent process." << endl; } else { Out << "TOOL: At follow child callback in child process." << endl; } // Pin replaces vfork with fork. In this case the global variable // activeProcessId will receive the right value if (activeProcessId != PIN_GetPid()) { fprintf(stderr, "vfork works incorrectly with -follow_execv\n"); exit(-1); } return TRUE; } VOID Image(IMG img, VOID* arg) { if (IMG_IsMainExecutable(img)) { RTN free_memory_rtn = RTN_FindByName(img, "free_memory"); ASSERTX(RTN_Valid(free_memory_rtn)); free_memory_ptr = (void(*)(void))RTN_Address(free_memory_rtn); } } int main(int argc, CHAR *argv[]) { PIN_InitSymbols(); if( PIN_Init(argc,argv) ) { return Usage(); } string outFileName = KnobOutputFile.Value() + string("_") + decstr(PIN_GetPid()); Out.open(outFileName.c_str(), ios_base::app); if (!Out.is_open()) { cerr << "Can't open file " << outFileName << endl; exit(-1); } cerr << "Open file " << outFileName << endl; IMG_AddInstrumentFunction(Image, NULL); PIN_AddForkFunctionProbed(FPOINT_BEFORE, BeforeFork, 0); PIN_AddForkFunctionProbed(FPOINT_AFTER_IN_CHILD, AfterForkInChild, 0); PIN_AddForkFunctionProbed(FPOINT_AFTER_IN_PARENT, AfterForkInParent, 0); PIN_AddFollowChildProcessFunction(FollowChild, 0); PIN_StartProgramProbed(); return 0; }
9d607a26bb562741d18442bc167c3180cd283dbd
3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c
/unpassed/2305.cpp
d021f96d41b33aa930e769a28c9c443695536424
[]
no_license
usherfu/zoj
4af6de9798bcb0ffa9dbb7f773b903f630e06617
8bb41d209b54292d6f596c5be55babd781610a52
refs/heads/master
2021-05-28T11:21:55.965737
2009-12-15T07:58:33
2009-12-15T07:58:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
807
cpp
2305.cpp
#include<iostream> using namespace std; // wrong answer long long A, B, C, K; long long egcd(long long a, long long b, long long &x, long long &y){ if(b == 0){ x = 1, y = 0; return a; } long long d = egcd(b, a % b, x, y); long long t = x; x = y; y = t - a / b * y; return d; } long long fun(){ long long M = 1, d; long long x, y; M <<= K; K = (B - A + M) % M; d = egcd(M, C, x, y); if(K % d != 0) return -1; y *= (K / d); return y; } int readIn(){ scanf("%lld%lld%lld%lld", &A, &B, &C, &K); return int(A + B + C + K); } int main(){ long long t; while(readIn() > 0){ t = fun(); if(t < 0){ printf("FOREVER\n"); } else { printf("%lld\n", t); } } return 0; }
e2ccd8f32776f124b147f0f22719768b1a90f034
3575a37fe45bd7babbf3dce1cceadb158a9a4990
/main.cpp
ccb741ab7d848c896370e0ff61fe86b7870a01e7
[]
no_license
KarinaGanieva-sl/Quick_sort_hamlet
0c8816deefc1b36c2278876ac6d8a847af75fec4
0c6a77c1216b01e2238db3e3aff4fdb58d838d96
refs/heads/main
2022-12-26T01:31:47.680355
2020-10-08T00:48:51
2020-10-08T00:48:51
302,193,165
0
0
null
null
null
null
UTF-8
C++
false
false
2,262
cpp
main.cpp
#include <iostream> #include <cassert> #include <sys\stat.h> #include <fstream> #include <cmath> #include "quick_sort.h" #include "tests.h" using namespace std; char** readText(char* filename, int &length) { assert(filename != NULL); assert(isfinite(length)); string str = ""; ifstream file(filename, ifstream::in); if(!file) { cerr << "Can't open input file"; exit(-1); } int ind = 0; char** text = new char*[50]; while (ind < 50 && getline(file, str)) { text[ind] = new char[strlen(str.c_str())]; if(!strcpy(text[ind], str.c_str())) { cerr << "Can't convert c_str to char *"; exit(-1); } ind++; } file.close(); length = ind; return text; } void writeText(string filename, char** text, size_t length) { assert(text); assert(isfinite(length)); ofstream fout; fout.open(filename); if(!fout) { cerr << "Can't open output file"; exit(-1); } for(size_t i = 0; i < length; ++i) fout << text[i] << '\n'; fout.close(); } void test_all() { test_quick_sort(); test_quick_sort_rev(); } char** init_text_copy(char** text, size_t length) { assert(text); assert(isfinite(length)); char** text_copy = new char*[length]; for(size_t i = 0; i < length; ++i) text_copy[i] = text[i]; return text_copy; } int main(int argc, char * argv[]) { if(argc != 2) { cout << "Wrong number of input arguments. Check if you entered input filename!"; return 1; } int length = 0; char** text = readText(argv[1], length); char** copy_1 = init_text_copy(text, length); quick_sort(copy_1, length); writeText("../output.txt", copy_1, length); for(size_t i = 0; i < length; ++i) delete[] copy_1[i]; delete[] copy_1; char** copy_2 = init_text_copy(text, length); quick_sort_rev(copy_2, length); writeText("../output_rev.txt", copy_2, length); for(size_t i = 0; i < length; ++i) delete[] copy_2[i]; delete[] copy_2; writeText("../output_origin.txt", text, length); for(size_t i = 0; i < length; ++i) delete[] text[i]; delete[] text; return 0; }
257f785140f19aba4924240e927b54006cb0d135
5f97e1d56411a2feb7c8261780e7ef3e94cff37b
/Program/Apue.h
7a0f2ab9b3f2c87193baa6d5fc572de31c431c61
[]
no_license
jammgit/LearnPlatformBaseQt
165d8ec2960a5cbec6149ac2784f1a8815ab38b9
8bf5a5d659ee5df8546d22b70865401dccd021de
refs/heads/master
2021-01-17T18:07:47.406842
2016-07-07T16:27:56
2016-07-07T16:27:56
56,146,621
4
0
null
null
null
null
UTF-8
C++
false
false
825
h
Apue.h
/* * 作者:江伟霖 * 时间:2016/04/15 * 邮箱:269337654@qq.com or adalinors@gmail.com * 描述:功能函数声明头文件 */ #ifndef APUE_H #define APUE_H #include <unistd.h> #include <fcntl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <stdio.h> #include <signal.h> #include <assert.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <vector> #include <string> extern int sig_pipefd[2]; int gSetNonblocking(int fd); void gAddfd(int epollfd, int fd, bool oneshoot = false); void gSigHandler(int sig); void gAddSig(int sig, void (*handler)(int), bool restart = true); void gRemovefd(int epollfd, int fd); void gResetOneshot(int epollfd, int sockfd); std::vector<std::string> gSplitMsgPack(const char *text, char conver = '\\', char splitc = '_'); #endif
bdecb546b122b77e2b9f84508102d9776685b6e0
c16f1735f2adeb9a3adba82a7dad48e09d103717
/src/Utils.h
e844f40ecb79c7d18aa2e8e49bb128e7253dc38c
[]
no_license
mtstnt/proyek-akhir-sd
95f692c06ce5b91af3f39d375ac332b28a8bf48b
78cc83bd0f9026a68158125a21a6e8ef8d83a28f
refs/heads/master
2023-02-08T07:53:22.042767
2020-12-23T12:28:23
2020-12-23T12:28:23
313,807,162
0
1
null
2020-12-22T14:18:44
2020-11-18T02:59:26
C++
UTF-8
C++
false
false
716
h
Utils.h
#pragma once #include "Includes.h" namespace Utils { template <class T> class IterableStack : public std::stack<T> { public: const T& get(int i) { return this->c[i]; } }; inline std::vector<std::string> split(std::string str) { std::vector<std::string> splitResults; std::string word; for (int i = 0; i <= str.length(); i++) { if (str[i] == ' ' || i == str.length()) { splitResults.push_back(word); word.clear(); } else { word += str[i]; } } return splitResults; } inline bool isDistinct(Directory* dir, std::string name) { auto& ref = dir->getChildren(); for (Node* n : ref) { if (n->getName() == name) { return false; } } return true; } }
4508e662201ad4a64993fe110381ba547991f344
5e57a3e3c8e31f074da384c091271598b7b357e5
/src/test_encoding.cpp
9bc4e4de8cc3fa71f8669d08d4ef03b7df0023f2
[]
no_license
Jitesh7/pylon-utils
1fde62f0e33b921b136f606004918a6b7b67ed19
63e42fb5e22207ba587a7669638f279345a8cc7d
refs/heads/master
2020-03-16T15:27:27.637341
2017-07-07T22:01:48
2017-07-07T22:01:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,571
cpp
test_encoding.cpp
#include "basler_utils.h" #include "basler_opencv_utils.h" #include "image_utils.h" #include "Profile.h" #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <unistd.h> using namespace Pylon; class OutputFileWrapper { public: FILE* fp; OutputFileWrapper(const char* filename) { fp = fopen(filename, "wb"); } ~OutputFileWrapper() { fflush(fp); fsync(fileno(fp)); // make sure writes go to disk for benchmarking! fclose(fp); } }; void write_png(const char* filename, const IImage& image) { OutputFileWrapper w(filename); EPixelType ptype = image.GetPixelType(); size_t stride = image.GetWidth() * BitPerPixel(ptype) / 8 + image.GetPaddingX(); png_pixel_format format = ( SamplesPerPixel(ptype) == 3 ? PNG_PIXEL_FORMAT_RGB : PNG_PIXEL_FORMAT_GRAY ); write_png(w.fp, format, 1, image.GetWidth(), image.GetHeight(), stride, (const uint8_t*)image.GetBuffer()); } int main(int argc, char** argv) { PylonInitialize(); try { CPylonImage p_yuv; CPylonImage p_bayer; if (!(load_image_raw("../images/debug_YCbCr422_8.pylon_raw", p_yuv) && load_image_raw("../images/debug_BayerBG8.pylon_raw", p_bayer))) { std::cout << "error loading image!\n"; exit(1); } uint32_t width = p_yuv.GetWidth(); uint32_t height = p_yuv.GetHeight(); if (p_bayer.GetWidth() != width || p_bayer.GetHeight() != height) { std::cout << "size mismatch!\n"; exit(1); } std::cout << "loaded YUV & Bayer input images with size " << width << "x" << height << "\n"; PROFILE("wrote ycbr422.jpg") { OutputFileWrapper wrapper("ycbr422.jpg"); ycbcr422_to_jpeg(wrapper.fp, 100, width, height, 2*width + p_yuv.GetPaddingX(), (const uint8_t*)p_yuv.GetBuffer()); } CImageFormatConverter fc; fc.OutputPixelFormat = PixelType_RGB8packed; CPylonImage p_yuv2rgb; PROFILE("converted YUV -> RGB") { fc.Convert(p_yuv2rgb, p_yuv); } PROFILE("wrote ycbr422.png via libpng") { write_png("ycbr422.png", p_yuv2rgb); } CPylonImage p_bayer2 = CPylonImage::Create(PixelType_Mono8, width, height); CPylonImage p_bayer3 = CPylonImage::Create(PixelType_Mono8, width, height); PROFILE ("wrote bayerBG8_raw.png") { write_png("bayerBG8_raw.png", p_bayer); } PROFILE("de-interleaved bayer data") { bayer_deinterleave(width, height, (const uint8_t*)p_bayer.GetBuffer(), width, (uint8_t*)p_bayer2.GetBuffer(), width); } PROFILE("wrote bayerBG8_raw2.png") { write_png("bayerBG8_raw2.png", p_bayer2); } PROFILE("re-interleaved bayer data (same as orig)") { bayer_interleave(width, height, (const uint8_t*)p_bayer2.GetBuffer(), width, (uint8_t*)p_bayer3.GetBuffer(), width); } PROFILE("wrote bayerBG8_raw3.png") { write_png("bayerBG8_raw3.png", p_bayer3); } CPylonImage p_bayer2rgb; PROFILE("used Pylon to convert Bayer -> RGB") { fc.Convert(p_bayer2rgb, p_bayer); } PROFILE("wrote bayerBG8_p.png") { write_png("bayerBG8_p.png", p_bayer2rgb); } cv::Mat cv_bayer2rgb_cv; PROFILE("used OpenCV to convert Bayer -> RGB") { cv::cvtColor(pylon_to_cv(p_bayer), cv_bayer2rgb_cv, CV_BayerBG2RGB); } PROFILE ("wrote bayerBG8_cv.png") { cv::imwrite("bayerBG8_cv.png", cv_bayer2rgb_cv); sync(); // my write_png calls fsync() for benchmarking purposes, opencv doesn't } } catch (GenericException& e) { std::cerr << "error: " << e.GetDescription() << "\n"; return 1; } return 0; }
2f277f7db238336a186ba8816c88ef944bf31b52
f67cb6b3aae6c5ecd9aae9d58ca4b326b982a135
/old/CIS 150/Labs/Lab 10/Chap11/fraction.h
94875b067926a1183c491711b7ad931e3c1e8701
[]
no_license
watsont/old_archive_classes
2782696afa83a7a6330b00fbcc9dcbe585a81bf3
aaa70e3886e2bfd75430754042a697d7cd7f18d1
refs/heads/master
2021-01-21T02:36:04.782580
2014-07-12T15:25:32
2014-07-12T15:25:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
978
h
fraction.h
// Header file Fraction.h declares class Fraction. class Fraction { public: Fraction Add(Fraction frac1) const; // Pre: frac1 and self have been initialized. // Post: self + frac1 is returned. Fraction Sub(Fraction frac1) const; // Pre: frac1 and self have been initialized. // Post: self - frac1 is returned. Fraction Mult(Fraction frac1) const; // Pre: frac1 and self have been initialized. // Post: self * frac1 is returned. Fraction Div(Fraction frac1) const; // Pre: frac1 and self have been initialized. // Post: self / frac1 is returned. int NumIs() const; // Pre: frac1 has been initialized. // Post: Numerator of frac1 is returned. int DenomIs() const; // Pre: frac1 has been initialized. // Post: Denominator of frac1 is returned. void Set(int num, int denom); // Post: self has been set to num / denom. private: int numerator; int denominator; };
d8e89d849d9b178f4ee0106f8c681a9735c10293
c5e0f75b747fbe606c7da1bbe0d2259906f00070
/addons/UtilityClasses/ColorDistanceMetric.cpp
789c1666b3b0483accdf8b94f726618b9b4e7e55
[]
no_license
HaikuArchives/ArtPaint
61a8be16c34a612c2d392468f65f6a0fe334bc17
cb39f1aaad119f0fdda99dcc54bb03d5776ba1dc
refs/heads/master
2023-08-17T08:47:32.203643
2023-07-23T00:52:13
2023-08-14T12:47:27
11,695,045
29
26
null
2023-09-14T06:16:04
2013-07-26T21:18:41
C++
UTF-8
C++
false
false
1,173
cpp
ColorDistanceMetric.cpp
/* * Copyright 2003, Heikki Suhonen * Distributed under the terms of the MIT License. * * Authors: * Heikki Suhonen <heikki.suhonen@gmail.com> * */ #include <math.h> #include "ColorDistanceMetric.h" BLocker ColorDistanceMetric::ctr_dtr_locker("ColorDistanceMetric::ctr_dtr_locker"); float* ColorDistanceMetric::sqrt_table = NULL; int* ColorDistanceMetric::sqr_table = NULL; int ColorDistanceMetric::instance_counter = 0; ColorDistanceMetric::ColorDistanceMetric() { ctr_dtr_locker.Lock(); instance_counter++; if (sqrt_table == NULL) { sqrt_table = new float[196608]; // 3*(256^2) float x=0; for (int32 i=0;i<196608;i++) { sqrt_table[i] = sqrt(x); x++; } sqr_table = new int[513]; // -256 to -1, 0, 1 to 256 for (int32 i=0;i<513;i++) { sqr_table[i] = (i-256)*(i-256); } sqr_table = &sqr_table[256]; } ctr_dtr_locker.Unlock(); } ColorDistanceMetric::~ColorDistanceMetric() { ctr_dtr_locker.Lock(); instance_counter--; if ((instance_counter == 0) && (sqrt_table != NULL)) { delete[] sqrt_table; sqrt_table = NULL; sqr_table = &sqr_table[-256]; delete[] sqr_table; sqr_table = NULL; } ctr_dtr_locker.Unlock(); }
34a399ba5450f217264a0ce8c839db5452a04615
3589a833a0d518328bc9d1ff070363df0b842fbc
/第3章 程序的流程控制(算法)描述——语句/3.3 7,P58.cpp
9a4665786d24121c6842dcd3575043bc7f3778cb
[]
no_license
crowds01/C-lianxi
cd76f8fef04f24c35150d688f31bd5fdf1adfc46
9a54d6d1b52fbe85066131e9c0182216da3a6ad3
refs/heads/master
2020-09-01T07:04:21.300785
2019-11-19T07:54:43
2019-11-19T07:54:43
218,902,240
0
0
null
null
null
null
GB18030
C++
false
false
1,038
cpp
3.3 7,P58.cpp
/*从键盘输入一个星期的某一天(0:星期天;1:星期一;......;6:星期六),然后输出其对应的英语单词。 解:用if语句来实现*/ #include <iostream> using namespace std; int main() { int day; cin >> day; if (day == 0) cout << "Sunday"; else if (day == 1) cout << "Monday"; else if (day == 2) cout << "Tuesday"; else if (day == 3) cout << "Wednesday"; else if (day == 4) cout << "Thursday"; else if (day == 5) cout << "Friday"; else if (day == 6) cout << "Saturday"; else cout << "Input error";//防止输入无效内容 cout << endl; return 0; } //用switch语句来实现 //int main() //{ // int day; // cin >> day; // switch (day) // { // case 0:cout << "Sunday"; break; // case 1:cout << "Monday"; break; // case 2:cout << "Tuesday"; break; // case 3:cout << "Wednesday"; break; // case 4:cout << "Thursday"; break; // case 5:cout << "Friday"; break; // case 6:cout << "Saturday"; break; // default:cout << "Input error"; // } // cout << endl; // return 0; //}
0981f45abed65a9fd5b1d30c50a253b796360c75
87b48673f6e33d16cde1e17b587c3a142fe1193c
/question_13.cpp
4bd54184d91be6e3392451fc19fabee2467055ea
[]
no_license
theabhishekgupta/College_workPlace
b7821c1528343d553c3230bc07ba0910d22452f7
85b7ecbafae7e608058bc2e25c7996a9413af04b
refs/heads/main
2023-06-09T17:43:49.301112
2021-06-27T10:53:52
2021-06-27T10:53:52
380,661,163
0
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
question_13.cpp
/*Write a program to find the size of a file*/ #include <bits/stdc++.h> using namespace std; long int findSize(char file_name[]) { FILE* fp = fopen(file_name, "r"); if (fp == NULL) { printf("File Not Found!\n"); return -1; } fseek(fp,0L,SEEK_END); long int res = ftell(fp); fclose(fp); return res; } int main() { char text[100]; fstream file; file.open("abhi.txt",ios::out); if(!file) { cout<<"Error in creating file!!!"; return 0; } cout<<"File created successfully."<<endl; cout << "\n\n\t\t---Write text to be written on file---\n\n" << endl; cin.getline(text, sizeof(text)); file << text << endl; file.close(); char file_name[] = {"abhi.txt" }; long int res = findSize(file_name); if (res != -1) printf("\n\n\n\n\n\t\t----Size of the file is %ld bytes---\n", res); return 0; }
c8c38eb29a7691325f0f6e3f43bb732f365c8e1b
3c62339b05995815527a2329ef3612d33755d4cc
/department_student/department_student/generation.cpp
2506dcb0f57574ede5ddf6fb6e8c3caca0f863d5
[]
no_license
laizhiping/department_student
8bd5f507bbfd04897d475c7871654d497dee4794
c8fb57fa56cf7c2ca5268e82ec9158792504282d
refs/heads/master
2021-07-09T14:52:01.816410
2017-10-11T02:46:58
2017-10-11T02:46:58
106,142,258
0
0
null
null
null
null
GB18030
C++
false
false
6,630
cpp
generation.cpp
#include <iostream>//赖志平 #include <cstdlib> #include <fstream> #include <ctime> #include <string> #include <set> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" #define N 20 #define M 300 using namespace std; using namespace rapidjson; struct Department{ string department_no; int member_limit; string event_schedules[20]; string tags[20]; int accept_members; }department[N]; struct Student{ string student_no; string applications_department[5]; string free_time[20]; string tags[20]; int join_departments; }student[M]; /*string generateTime()//产生随机的时间段 { int tmp; string temp; char c[10]; string week[7] = { "Mon", "Tues", "Thur", "Wed", "Fri", "Sat", "Sun" }; tmp = rand() % 7; string temp1 = ""; temp1 = temp1 + week[tmp] + "."; tmp = 6 + rand() % 19;//产生6~24的随机数 int t = 1 + rand() % 4;//产生活动时长,1~4小时 _itoa(tmp, c, 10); temp = c; temp1 = temp1 + temp + ":00~"; tmp = tmp + t; _itoa(tmp, c, 10); temp = c; temp1 = temp1 + temp + ":00"; return temp1; } */ void generateTime(string* tim)//产生随机的时间段 { int tmp; string week[7] = { "Mon.", "Tues.", "Thur.", "Wed.", "Fri.", "Sat.", "Sun." }; char c[10]; int tt = rand()%8;//产生一星期中有空的天数 if (tt == 0) return; int t = 0; set<string>ss; for(int i = 0; i < tt;i++) { tmp = rand() % 7; ss.insert(week[tmp]); } set<string>::iterator it; for (it = ss.begin(); it != ss.end(); it++) { string temp1 = ""; string temp; temp1 =temp1 + *it; tmp = 6+rand() % 18;//产生一天中初始时间点(6-23之间) _itoa(tmp, c, 10); temp = c; temp1 = temp1 + temp + ":00~"; while (tmp<24) { tmp = tmp + 1+rand() % 5;//生成结束时间 if (tmp>24) break; _itoa(tmp, c, 10); temp = c; temp1 = temp1 + temp + ":00"; tim[t++] = temp1; temp1 = ""; tmp = tmp + 1+ rand() % 16;//生成一天内下一次初始时间点 if (tmp >= 24) break; _itoa(tmp, c, 10); temp = c; temp1 = temp1 + *it+ temp + ":00~"; } } } string generateTags()//产生随机的tags { //srand((unsigned)time(NULL)); string tag[20] = { "study", "film", "English", "music", "reading", "chess", "football", "dance", "programming", "basketball", "table tennisy", "volleyball", "badminton", "run", "tour", "climb", "compute games", "swim", "chat", "eat" }; int tmp = rand() % 20; return tag[tmp]; } int main() { int tmp; char c[10]; set <string> strset; srand((unsigned)time(NULL)); Document doc; doc.SetObject(); Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器 Value temp_string; Value stu(kArrayType); for (int i = 0; i < M; i++) { Value obj(kObjectType); Value free_time_array(kArrayType); generateTime(student[i].free_time); int t = 0; while (student[i].free_time[t] != ""&&t < 20) { temp_string.SetString(StringRef(student[i].free_time[t].c_str())); free_time_array.PushBack(temp_string, allocator); t++; } /* int k = rand() % 11; for (int j = 0; j < k; j++) { student[i].free_time[j] = generateTime(); temp_string.SetString(StringRef(student[i].free_time[j].c_str())); free_time_array.PushBack(temp_string, allocator); } */ obj.AddMember("free_time", free_time_array, allocator); tmp = 1 + rand() % 20; _itoa(i + 1, c, 10); string temp = c; if (i < 10) student[i].student_no = "03150200" + temp; else if (i < 100) student[i].student_no = "0315020" + temp; else student[i].student_no = "031502" + temp; temp_string.SetString(StringRef(student[i].student_no.c_str())); obj.AddMember("student_no", temp_string, allocator); Value applications_department_array(kArrayType); int k = 1 + rand() % 5; for (int j = 0; j < k; j++) { tmp = rand() % 20 + 1; _itoa(tmp, c, 10); string temp = c; if (tmp < 10) { string s = ""; s = "D00" + temp; student[i].applications_department[j] = s; } else { string s = ""; s = s + "D0" + temp; student[i].applications_department[j] = s; } temp_string.SetString(StringRef(student[i].applications_department[j].c_str())); applications_department_array.PushBack(temp_string, allocator); } obj.AddMember("applications_department", applications_department_array, allocator); Value tag_array(kArrayType); tmp = 0 + rand() % 7; for (int j = 0; j < tmp; j++) { student[i].tags[j] = generateTags(); temp_string.SetString(StringRef(student[i].tags[j].c_str())); tag_array.PushBack(temp_string, allocator); } obj.AddMember("tags", tag_array, allocator); stu.PushBack(obj, allocator); } doc.AddMember("students",stu, allocator); Value dep(kArrayType); for (int i = 0; i < N; i++) { Value obj(kObjectType); Value event_schedules_array(kArrayType); generateTime(department[i].event_schedules); int t = 0; while (department[i].event_schedules[t] != ""&&t < 20) { temp_string.SetString(StringRef(department[i].event_schedules[t].c_str())); event_schedules_array.PushBack(temp_string, allocator); t++; } /* int k = rand() % 8; for (int j = 0; j < k; j++) { department[i].event_schedules[j] = generateTime(); temp_string.SetString(StringRef(department[i].event_schedules[j].c_str())); event_schedules_array.PushBack(temp_string, allocator); }*/ obj.AddMember("event_schedules", event_schedules_array, allocator); department[i].member_limit = 10 + rand() % 6; obj.AddMember("member_limit", department[i].member_limit, allocator); _itoa(i + 1, c, 10); string temp = c; if (i < 10) { string s = ""; s = "D00" + temp; department[i].department_no = s; } else { string s = ""; s = s + "D0" + temp; department[i].department_no = s; } temp_string.SetString(StringRef(department[i].department_no.c_str())); obj.AddMember("department_no",temp_string, allocator); Value tag_array(kArrayType); tmp = 1 + rand() % 10; for (int j = 0; j < tmp; j++) { department[i].tags[j] = generateTags(); temp_string.SetString(StringRef(department[i].tags[j].c_str())); tag_array.PushBack(temp_string, allocator); } obj.AddMember("tag", tag_array, allocator); dep.PushBack(obj, allocator); } doc.AddMember("departments", dep, allocator); StringBuffer buffer; PrettyWriter<StringBuffer> pretty_writer(buffer); //PrettyWriter是格式化的json,如果是Writer则是换行空格压缩后的json doc.Accept(pretty_writer); //输出到文件 ofstream ffout; ffout.open("generate.txt"); ffout << buffer.GetString(); ffout.close(); return 0; }
96e21429ae0e6a9e01e0b5c15638b6036497ade3
e061b2fd7e517cd1db7d8916041feb37310b67b3
/src/Window.hpp
02f56dd8325fc418c7e840ece74152f23cff64ba
[]
no_license
Kevin-Escobedo/ShinyCounter
99d40bf685fc7952ea167c7a455c09f536db6364
e7e29e8c0a12eab475be7b36ee79d1759cfcbd3c
refs/heads/master
2021-12-05T22:03:58.990806
2021-08-11T21:44:03
2021-08-11T21:44:03
182,899,073
0
0
null
null
null
null
UTF-8
C++
false
false
825
hpp
Window.hpp
#ifndef WINDOW_HPP #define WINDOW_HPP #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/System/Vector2.hpp> #include <SFML/Window/Event.hpp> #include <iostream> class Window { public: sf::RenderWindow screen; private: sf::Vector2u dimensions; const char* name; const unsigned int FRAMERATE = 60; public: Window(const char* title, const unsigned int x, const unsigned int y); Window(const char* title, const sf::Vector2u& screenDimensions); Window(const Window& w); Window& operator =(const Window& w); sf::Vector2u getDimensions(); ~Window(); friend std::ostream& operator <<(std::ostream& os, const Window& w); void setDimensions(const unsigned int x, const unsigned int y); void setDimensions(const sf::Vector2u& screenDimensions); }; #endif /* WINDOW_HPP */
c3cc6224338ad7f27ccb400ba302609b1a962adc
1269bd766f03c4e6387a2d2fe76bcf697018f0f0
/src/clstepcore/STEPcomplex.h
c589c8c0c05ed39a689000b36b3a6adc89e683fe
[ "BSD-3-Clause" ]
permissive
starseeker/stepcode_updates
8bcb95425cafd7888d76e002a1e2ecc97f285a79
7fca581e63def7d851044f25706df1411a715304
refs/heads/master
2023-07-13T19:02:03.231568
2021-06-27T18:07:28
2021-06-27T18:07:28
392,814,301
0
0
null
null
null
null
UTF-8
C++
false
false
3,497
h
STEPcomplex.h
#ifndef STEPCOMPLEX_H #define STEPCOMPLEX_H #include <sc_export.h> #include <errordesc.h> #include <sdai.h> #include <baseType.h> #include <ExpDict.h> #include <Registry.h> #include <list> /* attr's for SC's are created with a pointer to their data. * STEPcomplex_attr_data_list is used to store the pointers for * deletion. this list is composed of attrData_t's, which track * types for ease of deletion */ typedef struct { PrimitiveType type; union { SDAI_Integer * i; SDAI_String * str; SDAI_Binary * bin; SDAI_Real * r; SDAI_BOOLEAN * b; SDAI_LOGICAL * l; SDAI_Application_instance ** ai; SDAI_Enum * e; SDAI_Select * s; STEPaggregate * a; }; } attrData_t; typedef std::list< attrData_t > STEPcomplex_attr_data_list; typedef STEPcomplex_attr_data_list::iterator STEPcomplex_attr_data_iter; /** FIXME are inverse attr's initialized for STEPcomplex? */ class SC_CORE_EXPORT STEPcomplex : public SDAI_Application_instance { public: //TODO should this _really_ be public?! STEPcomplex * sc; STEPcomplex * head; Registry * _registry; int visited; ///< used when reading (or as you wish?) #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable: 4251 ) #endif STEPcomplex_attr_data_list _attr_data_list; ///< attrs are created with a pointer to data; this stores them for deletion #ifdef _MSC_VER #pragma warning( pop ) #endif public: STEPcomplex( Registry * registry, int fileid ); STEPcomplex( Registry * registry, const std::string ** names, int fileid, const char * schnm = 0 ); STEPcomplex( Registry * registry, const char ** names, int fileid, const char * schnm = 0 ); virtual ~STEPcomplex(); int EntityExists( const char * name, const char * currSch = 0 ); STEPcomplex * EntityPart( const char * name, const char * currSch = 0 ); virtual const EntityDescriptor * IsA( const EntityDescriptor * ) const; virtual Severity ValidLevel( ErrorDescriptor * error, InstMgrBase * im, int clearError = 1 ); // READ virtual Severity STEPread( int id, int addFileId, class InstMgrBase * instance_set, istream & in = cin, const char * currSch = NULL, bool useTechCor = true, bool strict = true ); virtual void STEPread_error( char c, int index, istream & in, const char * schnm ); // WRITE virtual void STEPwrite( ostream & out = cout, const char * currSch = NULL, int writeComment = 1 ); virtual const char * STEPwrite( std::string & buf, const char * currSch = NULL ); SDAI_Application_instance * Replicate(); virtual void WriteExtMapEntities( ostream & out = cout, const char * currSch = NULL ); virtual const char * WriteExtMapEntities( std::string & buf, const char * currSch = NULL ); virtual void AppendEntity( STEPcomplex * stepc ); protected: virtual void CopyAs( SDAI_Application_instance * se ); void BuildAttrs( const char * s ); void AddEntityPart( const char * name ); void AssignDerives(); void Initialize( const char ** names, const char * schnm ); }; #endif
3cc9c4164fca66aeb0bf863a3ba2a655259d42b1
1abd9f9eb7741c3cc8423462fc513aca68fc037e
/test/test_common.cpp
620b6a54a598dcfe998f715466a449b7103e3278
[]
no_license
andijcr/tsar_lib
1c9d711658a3c44ba8059d2f8c43e0795f59a81b
05ed6e7b0802f6e0091873fea71eb76c7d857d4e
refs/heads/master
2021-01-10T14:30:54.038474
2016-02-19T14:14:17
2016-02-19T14:15:28
52,005,173
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
test_common.cpp
// // Created by andrea on 15/09/15. // #ifndef PRODUCERS_CONSUMERS_TEST_COMMON_H #define PRODUCERS_CONSUMERS_TEST_COMMON_H #define CATCH_CONFIG_COLOUR_NONE #define CATCH_CONFIG_MAIN #include "catch.hpp" #endif //PRODUCERS_CONSUMERS_TEST_COMMON_H
cb08b1d4e82799ea21fe2bcc2ff87744043e5b1b
06810247a5fe519f3521adcc031b9a65011b485e
/No/2016.cpp
1365ee60bf3ccb2bd0049ca300e5c97980bde782
[]
no_license
yjhmelody/hdoj
ce036b7573200a4b075f4d8815595e5afc904887
4fabb95b2cb42c984ad5f0e7e8cc9680110c1b0c
refs/heads/master
2020-02-26T13:31:30.066347
2016-11-22T14:21:39
2016-11-22T14:21:39
68,513,913
0
0
null
2016-11-21T09:21:58
2016-09-18T10:21:50
C++
UTF-8
C++
false
false
595
cpp
2016.cpp
#include<stdio.h> int main() { int i,j,k,n,a[101],min,temp; while(~scanf("%d",&n)) { if(n==0) break; for(i=0;i<n;++i) scanf("%d",&a[i]); k=a[0]; min=0; for(i=1;i<n;++i) if(k>=a[i]) { k=a[i]; min=i; } temp=a[0]; a[0]=a[min]; a[min]=temp; for(i=0;i<n-1;i++) printf("%d ",a[i]); printf("%d\n",a[i]); } return 0; }
da0ef11e2e05597c1162d9f811a0265bcb07d46e
abc1ba19d957e0f1fc0e8777527a967256c3d208
/TP3/client_src/Client.h
ff9e49dd7b87992c42cd45b4672aea3a44776387
[]
no_license
JulianBiancardi/Taller1-75.42
cd40105ce99513f81a3e3e75f05ae3e15ce2fdd2
c1bd0f82531dd2e97e06200a3413749730a93781
refs/heads/main
2023-04-03T06:34:37.542113
2021-04-17T18:19:39
2021-04-17T18:19:39
356,372,369
0
0
null
null
null
null
UTF-8
C++
false
false
543
h
Client.h
#ifndef __CLIENT_H__ #define __CLIENT_H__ // ---------------------------------------------------------------------------- #include <stddef.h> #include <string> #include "../common_src/Socket.h" // ---------------------------------------------------------------------------- class Client { private: Socket socket; public: Client(const std::string& host, const std::string& port); void send(); void recv(); ~Client(); }; // ---------------------------------------------------------------------------- #endif // __CLIENT_H__
24fd45482f8f2d9e212b2243e5e14b23657d1eb1
0248d4d628a064eca0a97ce8aaf06c634676e82c
/code/CGraphRGBY.cpp
dd792e541a74cd04e65bdfa25b8f04cb309ac698
[]
no_license
kenichi-yasui/Background-subtraction-method
bf3807fcf13f6fdddf01eaaaf83e32da3a9b0401
aa2a15eae784dce623ad7347d25d62a77dcab471
refs/heads/master
2022-09-27T16:33:58.264117
2020-06-06T15:40:24
2020-06-06T15:40:24
270,005,920
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
11,546
cpp
CGraphRGBY.cpp
#include <math.h> #include "resource.h" #include "CGraphRGBY.h" /* #define GRAPH_POINT 30 #define GRAPH_START_X 400 #define GRAPH_START_Y 400 */ #define GRAPH_END_X m_GraphStartX+m_Graph_Point*10 #define GRAPH_END_Y m_GraphStartY-m_Graph_Point*10 #define LOG_START 1 #define LOG_STOP 0 CGraphRGBY *g_pCGraph; CGraphRGBY::CGraphRGBY(int MaxX,int MaxY) { m_X=0; m_Y=0; ZeroMemory(m_exR,10); ZeroMemory(m_exG,10); ZeroMemory(m_exB,10); ZeroMemory(m_exV,10); ZeroMemory(m_exY,10); ZeroMemory(m_exYGosa,10); m_exNo=-1; m_FlagLogSave=0;//ログ保存するかどうか m_LogFileP=NULL; g_pCGraph=this; m_MaxX=MaxX; m_MaxY=MaxY; m_hDlg=NULL; #ifdef RADIO_BUTTON_ON m_RadioFlag=IDC_MPEG_G; #endif } void CGraphRGBY::Reset(void) { ZeroMemory(m_exR,10); ZeroMemory(m_exG,10); ZeroMemory(m_exB,10); ZeroMemory(m_exV,10); ZeroMemory(m_exY,10); ZeroMemory(m_exYGosa,10); m_exNo=-1; m_FlagLogSave=0;//ログ保存するかどうか if(m_LogFileP) fclose(m_LogFileP); m_LogFileP=NULL; } /****************** PrintRGB RGB変化を表示 ******************/ void CGraphRGBY::PrintRGB(HDC hdc,CReadBmp *Bmp,int RGBPaintX,int RGBPaintY, int GraphStartX,int GraphStartY,int Graph_Point) { //下策 if(hdc==NULL) { HDC hDdc; if(m_hDlg==NULL) return; hDdc=GetDC(m_hDlg); PrintRGB(hDdc,Bmp,RGBPaintX,RGBPaintY, GraphStartX,GraphStartY,Graph_Point); ReleaseDC(m_hDlg,hDdc); return; } int x=m_X,y=m_Y; SetPrintXY( RGBPaintX, RGBPaintY, GraphStartX, GraphStartY, Graph_Point); char str[256]; sprintf(str,"座標(%003d , %003d)",x,y); int Height=Bmp->getHeight(); TextOut(hdc,m_RGBPaintX, m_RGBPaintY+GYOU*2,str,strlen(str)); ChangeExRGB(Bmp); BackGraphDraw(hdc); sprintf(str,"exNo : %003d",m_exNo); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*9,str,strlen(str)); if(m_FlagLogSave) { sprintf(str,"ログ保存中。",m_exNo); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*10,str,strlen(str)); } else //下作 { sprintf(str," ",m_exNo); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*10,str,strlen(str)); } sprintf(str,"R : %003d",m_exR[m_exNo]); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*3,str,strlen(str)); sprintf(str,"G : %003d",m_exG[m_exNo]); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*4,str,strlen(str)); sprintf(str,"B : %003d",m_exB[m_exNo]); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*5,str,strlen(str)); sprintf(str,"Y : %003d",m_exY[m_exNo]); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*6,str,strlen(str)); sprintf(str,"V : %003d",m_exV[m_exNo]); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*7,str,strlen(str)); sprintf(str,"Y : %003d",m_exYGosa[m_exNo]); TextOut(hdc,m_RGBPaintX,m_RGBPaintY+GYOU*8,str,strlen(str)); int PenStartX=80+m_RGBPaintX,LastY; HPEN hPen, hOldPen,hPenBack; /* hPen = CreatePen(PS_SOLID, 3, RGB(0,0, 0)); hOldPen = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, x-5,y, NULL); LineTo(hdc, x+5,y); MoveToEx(hdc, x,y+5, NULL); LineTo(hdc, x,y-5); DeleteObject(hPen); */ //Back hPenBack = CreatePen(PS_SOLID, GYOU-4, RGB(100,100, 100)); hOldPen = (HPEN)SelectObject(hdc, hPenBack); LastY=m_RGBPaintY+GYOU*3+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, 255+PenStartX, LastY); LastY=m_RGBPaintY+GYOU*4+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, 255+PenStartX, LastY); LastY=m_RGBPaintY+GYOU*5+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, 255+PenStartX, LastY); LastY=m_RGBPaintY+GYOU*6+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, 255+PenStartX, LastY); LastY=m_RGBPaintY+GYOU*7+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, 255+PenStartX, LastY); LastY=m_RGBPaintY+GYOU*8+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, 255+PenStartX, LastY); //赤ペン先生 hPen = CreatePen(PS_SOLID, GYOU-7, RGB(255,0, 0)); SelectObject(hdc, hPen); LastY=m_RGBPaintY+GYOU*3+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, m_exR[m_exNo]+PenStartX, LastY); DeleteObject(hPen); //緑 hPen = CreatePen(PS_SOLID, GYOU-7, RGB(0,255, 0)); SelectObject(hdc, hPen); LastY=m_RGBPaintY+GYOU*4+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, m_exG[m_exNo]+PenStartX, LastY); DeleteObject(hPen); //青 hPen = CreatePen(PS_SOLID, GYOU-7, RGB(0,0, 255)); SelectObject(hdc, hPen); LastY=m_RGBPaintY+GYOU*5+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, m_exB[m_exNo]+PenStartX, LastY); DeleteObject(hPen); //輝度 hPen = CreatePen(PS_SOLID, GYOU-7, RGB(255,255, 255)); (HPEN)SelectObject(hdc, hPen); LastY=m_RGBPaintY+GYOU*6+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, m_exY[m_exNo]+PenStartX, LastY); DeleteObject(hPen); hPen = CreatePen(PS_SOLID, GYOU-7, RGB(255,255, 0)); (HPEN)SelectObject(hdc, hPen); LastY=m_RGBPaintY+GYOU*7+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, m_exV[m_exNo]+PenStartX, LastY); DeleteObject(hPen); hPen = CreatePen(PS_SOLID, GYOU-7, RGB(230,230, 230)); (HPEN)SelectObject(hdc, hPen); LastY=m_RGBPaintY+GYOU*8+8; MoveToEx(hdc, PenStartX, LastY, NULL); LineTo(hdc, m_exYGosa[m_exNo]+PenStartX, LastY); DeleteObject(hPen); /////////////// hPen = CreatePen(PS_SOLID, 1, RGB(255,0, 0)); (HPEN)SelectObject(hdc, hPen); PaintGraph(hdc,m_exR); DeleteObject(hPen); hPen = CreatePen(PS_SOLID, 1, RGB(0,255, 0)); (HPEN)SelectObject(hdc, hPen); PaintGraph(hdc,m_exG); DeleteObject(hPen); hPen = CreatePen(PS_SOLID, 1, RGB(0,0,255)); (HPEN)SelectObject(hdc, hPen); PaintGraph(hdc,m_exB); DeleteObject(hPen); hPen = CreatePen(PS_SOLID, 1, RGB(255,255, 255)); (HPEN)SelectObject(hdc, hPen); PaintGraph(hdc,m_exY); DeleteObject(hPen); hPen = CreatePen(PS_SOLID, 1, RGB(255,255, 0)); (HPEN)SelectObject(hdc, hPen); PaintGraph(hdc,m_exV); hPen = CreatePen(PS_SOLID, 1, RGB(230,230, 230)); (HPEN)SelectObject(hdc, hPen); PaintGraph(hdc,m_exYGosa); SelectObject(hdc, hOldPen); } bool CGraphRGBY::setXY(int x,int y) { if(m_MaxX<=x || x<0) return false; else if(m_MaxY<=y || y<0) return false; m_Y=y; m_X=x; return true; } void CGraphRGBY::PaintGraph(HDC hdc,unsigned int *p) { int i; int no; for(i=0;i<9;i++) { no=( (m_exNo-i)<0 ? (m_exNo-i)+10 : m_exNo-i ); MoveToEx(hdc, m_GraphStartX+m_Graph_Point*i, m_GraphStartY-p[no], NULL); no=( (no-1)<0 ? no-1+10 : no-1); LineTo(hdc, m_GraphStartX+m_Graph_Point*(i+1), m_GraphStartY-p[no]); } } //グラフ void CGraphRGBY::BackGraphDraw(HDC hdc) { HBRUSH hBrush, hOldBrush; HPEN hPen, hOldPen; hBrush = CreateSolidBrush(RGB(100,100,100)); hOldBrush = (HBRUSH)SelectObject(hdc, hBrush); Rectangle(hdc, m_GraphStartX-20, m_GraphStartY+20, GRAPH_END_X+20,GRAPH_END_Y-20); SelectObject(hdc, hOldBrush); DeleteObject(hBrush); // グラフ hPen = CreatePen(PS_SOLID, 10, RGB(0,0, 0)); hOldPen = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, m_GraphStartX, m_GraphStartY, NULL); LineTo(hdc, m_GraphStartX,GRAPH_END_Y); MoveToEx(hdc, m_GraphStartX, m_GraphStartY, NULL); LineTo(hdc, GRAPH_END_X,m_GraphStartY); DeleteObject(hPen); SelectObject(hdc, hOldPen); } void CGraphRGBY::ChangeExRGB(CReadBmp *Bmp) { unsigned char R,G,B,Y,ex_Y; int V; int x=m_X,y=Bmp->getHeight()-m_Y; Bmp->getRGB(x,y,&R,&G,&B); Y=Bmp->getYIQ(x,y,0); ex_Y=m_exY[m_exNo]; double s_data=(m_exR[m_exNo]-R)*(m_exR[m_exNo]-R)+ (m_exG[m_exNo]-G) * (m_exG[m_exNo]-G) + (m_exB[m_exNo]-B)*(m_exB[m_exNo]-B); V=sqrt(s_data); // V=sqrt( (m_exR[m_exNo]-R)*(m_exR[m_exNo]-R)+ (m_exG[m_exNo]-G) * (m_exG[m_exNo]-G) + (m_exB[m_exNo]-B)*(m_exB[m_exNo]-B) ); m_exNo++; if(m_exNo>=10) m_exNo=0; m_exR[m_exNo]=R; m_exG[m_exNo]=G; m_exB[m_exNo]=B; m_exY[m_exNo]=Y; m_exV[m_exNo]=V; m_exYGosa[m_exNo]=abs(ex_Y-Y); //ログ保存 switch(m_FlagLogSave) { case LOG_START: fprintf(m_LogFileP,"%d\t",m_exR[m_exNo]); fprintf(m_LogFileP,"%d\t",m_exG[m_exNo]); fprintf(m_LogFileP,"%d\t",m_exB[m_exNo]); fprintf(m_LogFileP,"%d\t",m_exY[m_exNo]); fprintf(m_LogFileP,"%d\t",m_exV[m_exNo]); fprintf(m_LogFileP,"%d\t",m_exYGosa[m_exNo]); fprintf(m_LogFileP,"\n"); break; case LOG_STOP: if(m_LogFileP!=NULL) { fclose(m_LogFileP); m_LogFileP=NULL; } break; } } void CGraphRGBY::setHWnd(HWND hWnd) { m_hDlg=hWnd; } BOOL CALLBACK CtlCamDlgProc(HWND hDlg,UINT msg,WPARAM wp,LPARAM lp) { static char Buf[MAX_PATH]; char *FNameP; switch(msg) { //ダイヤログ版のWM_CREATEみたいなもん WM_CREATEはこないのでキヲツケロ case WM_INITDIALOG: g_pCGraph->setHWnd(hDlg); ZeroMemory(Buf,MAX_PATH); GetCurrentDirectory(MAX_PATH,Buf); strcat(Buf,"\\Log.txt"); SetDlgItemText(hDlg,ID_SAVE_PASS,Buf); #ifdef RADIO_BUTTON_ON IsDlgButtonChecked(hDlg,g_pCGraph->getRadioFlag()); #endif break; case WM_COMMAND: ///ボタンなどのメッセージ switch(LOWORD(wp)) { case IDC_LOG_SAVE_PASS_GET: FNameP=FileSave(hDlg,"色成分ログ保存先指定","txt"); if(!FNameP) break; strcpy(Buf,FNameP); SetDlgItemText(hDlg,ID_SAVE_PASS,Buf); if(g_pCGraph->m_FlagLogSave==LOG_START) { g_pCGraph->m_FlagLogSave=LOG_STOP; } break; case IDC_LOG_START: g_pCGraph->m_LogFileP=fopen(Buf,"w"); if(!g_pCGraph->m_LogFileP) { MessageBox(hDlg,"ファイルが開けませんでした。","Error",MB_OK); break; } fprintf(g_pCGraph->m_LogFileP,"R\tG\tB\tY\tV\tY(誤差)\n"); g_pCGraph->m_FlagLogSave=LOG_START; //ログ保存スタート break; case IDC_LOG_STOP: g_pCGraph->m_FlagLogSave=LOG_STOP; //ログ保存ストップ break; case IDCANCEL: g_pCGraph->setHWnd(NULL); EndDialog(hDlg,IDCANCEL); return TRUE; #ifdef RADIO_BUTTON_ON case IDC_DETECT_G: case IDC_MPEG_G: case IDC_BACK_G: g_pCGraph->SetRadioFlag(LOWORD(wp)); break; #endif } return FALSE; } return FALSE; } void CGraphRGBY::CreateDlg(HWND hWnd,LPCTSTR DlgStr) { if(m_hDlg) return; HINSTANCE hInst = (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE); DialogBox(hInst,DlgStr,NULL,CtlCamDlgProc); } /***************************** FileSave ファイルを保存関数 引数  hWnd windowハンドル Str ファイルを保存するダイアログボックスのタイトル FileType ファイル形式(例,"txt",",mpeg") *****************************/ char *FileSave(HWND hWnd,const char *Str,const char *FileType) { DWORD dwSize = 0L; OPENFILENAME ofn; char szFileTitle[512]; char szFilter[512]; static char szFile[512]; int len; sprintf(szFilter,"%s(*.%s)",FileType,FileType); len=strlen(szFilter)+1; sprintf(&szFilter[len],"*.%s",FileType); memset(&ofn, 0, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hWnd; // ofn.lpstrFilter = "txt(*.txt)\0All files(*.*)\0*.*\0\0"; ofn.lpstrFilter = szFilter; ofn.lpstrFile = szFile; ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFile = sizeof(szFile); ofn.nMaxFileTitle = sizeof(szFileTitle); ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; // ofn.lpstrDefExt = "txt"; ofn.lpstrDefExt = FileType; ofn.lpstrTitle = Str; if(GetSaveFileName(&ofn) == 0) return NULL; return szFile; } int CGraphRGBY::getRadioFlag(void) { return m_RadioFlag; } void CGraphRGBY::SetPrintXY(int RGBPaintX,int RGBPaintY, int GraphStartX,int GraphStartY,int Graph_Point) { m_RGBPaintX=RGBPaintX; m_RGBPaintY=RGBPaintY; m_GraphStartX=GraphStartX; m_GraphStartY=GraphStartY; m_Graph_Point=Graph_Point; }
a64191c1041992cf96840ba55989f133b3881deb
c563ddccbe259546dc6c94e43160c51795a0b58b
/src/Status.cpp
d215cb86f7d3c32495d4a0deb697dfbf2887979f
[ "BSD-3-Clause" ]
permissive
dublet/KARR
c910e63bff632c2350705e02722c22a8b42c7a46
4b14090b34dab4d8be4e28814cb4d58cd34639ac
refs/heads/master
2021-03-12T21:24:07.273119
2015-07-30T07:18:46
2015-07-30T07:18:46
16,044,024
0
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
Status.cpp
#include "Status.h" using namespace KARR; Status Status::_instance = Status(); Status::Status() { _speed = 0; _rpm = 0; _fuelLevel = 0; _engineTemp = 0; } Status::~Status() { } Status &Status::instance() { return _instance; } const unsigned int Status::getRpm() { return _rpm.load(); } const unsigned short Status::getSpeed() { return _speed.load(); } const unsigned int Status::getFuelLevel() { return _fuelLevel.load(); } const unsigned short Status::getEngineTemp() { return _engineTemp.load(); } void Status::setRpm(unsigned int newRpm) { _rpm.store(newRpm); } void Status::setSpeed(unsigned short newSpeed) { _speed.store(newSpeed); } void Status::setFuelLevel(unsigned int newFuelLevel) { _fuelLevel.store(newFuelLevel); } void Status::setEngineTemp(unsigned short newEngineTemp) { _engineTemp.store(newEngineTemp); }
dc07859416bc6262aaf6a0df693c9b32b95f3379
7a5b8cbd29cb5aeba1080e79f8efb0f9f44aa2dd
/hero.cpp
f41b5a4b32107169feb59dc8095e6637034e3436
[]
no_license
playNekk/Zemsta-Kaski
3c713c21736aba1a66eb11a793f3cec6e54ddb9e
e239cd2248d98f693c41d4084a266ebc3743a4f9
refs/heads/master
2022-10-27T03:58:48.954746
2022-10-19T15:02:15
2022-10-19T15:02:15
269,136,499
1
0
null
null
null
null
UTF-8
C++
false
false
6,487
cpp
hero.cpp
#include "hero.h" Hero::Hero(AnimationSet *animSet){ const string HERO_ANIM_UP = "Up"; const string HERO_ANIM_DOWN = "Down"; const string HERO_ANIM_LEFT = "Left"; const string HERO_ANIM_RIGHT = "Right"; const string HERO_ANIM_IDLE_UP = "idleUp"; const string HERO_ANIM_IDLE_DOWN = "idleDown"; const string HERO_ANIM_IDLE_LEFT = "idleLeft"; const string HERO_ANIM_IDLE_RIGHT = "idleRight"; const string HERO_SLASH_ANIM_UP = "slashUp"; const string HERO_SLASH_ANIM_DOWN = "slashDown"; const string HERO_SLASH_ANIM_LEFT = "slashLeft"; const string HERO_SLASH_ANIM_RIGHT = "slashRight"; const string HERO_ANIM_DIE = "die"; const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; const int DIR_UP = 0, DIR_DOWN = 1, DIR_LEFT = 2, DIR_RIGHT = 3, DIR_NONE = -1; this->animSet = animSet; type = "hero"; //ustawianie x = Window::ScreenWidth / 2; y = Window::ScreenHeight / 2; moveSpeed = 0; moveSpeedMax = 80; hp = hpMax = 20; damage = 0; collisionBoxW = 20; collisionBoxH = 24; collisionBoxYOffset = -20; direction = DIR_DOWN; changeAnimation(HERO_STATE_IDLE, true); updateCollisionBox(); } void Hero::update(){ const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; if (hp < 1 && state != HERO_STATE_DEAD){ changeAnimation(HERO_STATE_DEAD, true); moving = false; die(); } updateCollisionBox(); updateMovement(); updateCollisions(); updateHitBox(); updateDamages(); updateAnimation(); updateInvincibleTimer(); } void Hero::slash(){ const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; if (hp > 0 && (state == HERO_STATE_MOVE || state == HERO_STATE_IDLE)) { moving = false; frameTimer = 0; changeAnimation(HERO_STATE_SLASH, true); } } void Hero::die(){ const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; moving = false; changeAnimation(HERO_STATE_DEAD, true); } void Hero::revive(){ const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; hp = hpMax; changeAnimation(HERO_STATE_IDLE, true); moving = false; x = Window::ScreenWidth / 2; y = Window::ScreenHeight / 2; slideAmount = 0; } void Hero::changeAnimation(int newState, bool resetFrameToBeginning){ const string HERO_ANIM_UP = "Up"; const string HERO_ANIM_DOWN = "Down"; const string HERO_ANIM_LEFT = "Left"; const string HERO_ANIM_RIGHT = "Right"; const string HERO_ANIM_IDLE_UP = "idleUp"; const string HERO_ANIM_IDLE_DOWN = "idleDown"; const string HERO_ANIM_IDLE_LEFT = "idleLeft"; const string HERO_ANIM_IDLE_RIGHT = "idleRight"; const string HERO_SLASH_ANIM_UP = "slashUp"; const string HERO_SLASH_ANIM_DOWN = "slashDown"; const string HERO_SLASH_ANIM_LEFT = "slashLeft"; const string HERO_SLASH_ANIM_RIGHT = "slashRight"; const string HERO_ANIM_DIE = "die"; const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; state = newState; const int DIR_UP = 0, DIR_DOWN = 1, DIR_LEFT = 2, DIR_RIGHT = 3, DIR_NONE = -1; if (state == HERO_STATE_IDLE){ if (direction == DIR_DOWN) currentAnim = animSet->getAnimation(HERO_ANIM_IDLE_DOWN); else if (direction == DIR_UP) currentAnim = animSet->getAnimation(HERO_ANIM_IDLE_UP); else if (direction == DIR_LEFT) currentAnim = animSet->getAnimation(HERO_ANIM_IDLE_LEFT); else if (direction == DIR_RIGHT) currentAnim = animSet->getAnimation(HERO_ANIM_IDLE_RIGHT); } else if (state == HERO_STATE_MOVE){ if (direction == DIR_DOWN) currentAnim = animSet->getAnimation(HERO_ANIM_DOWN); else if (direction == DIR_UP) currentAnim = animSet->getAnimation(HERO_ANIM_UP); else if (direction == DIR_LEFT) currentAnim = animSet->getAnimation(HERO_ANIM_LEFT); else if (direction == DIR_RIGHT) currentAnim = animSet->getAnimation(HERO_ANIM_RIGHT); } else if (state == HERO_STATE_SLASH){ if (direction == DIR_DOWN) currentAnim = animSet->getAnimation(HERO_SLASH_ANIM_DOWN); else if (direction == DIR_UP) currentAnim = animSet->getAnimation(HERO_SLASH_ANIM_UP); else if (direction == DIR_LEFT) currentAnim = animSet->getAnimation(HERO_SLASH_ANIM_LEFT); else if (direction == DIR_RIGHT) currentAnim = animSet->getAnimation(HERO_SLASH_ANIM_RIGHT); } else if (state == HERO_STATE_DEAD){ currentAnim = animSet->getAnimation(HERO_ANIM_DIE); } if (resetFrameToBeginning) currentFrame = currentAnim->getFrame(0); else currentFrame = currentAnim->getFrame(currentFrame->frameNumber); } void Hero::updateAnimation(){ const int HERO_STATE_IDLE = 0; const int HERO_STATE_MOVE = 1; const int HERO_STATE_SLASH = 2; const int HERO_STATE_DEAD = 4; if (currentFrame == NULL || currentAnim == NULL) return; if (state == HERO_STATE_MOVE && !moving){ changeAnimation(HERO_STATE_IDLE, true); } if (state != HERO_STATE_MOVE && moving){ changeAnimation(HERO_STATE_MOVE, true); } frameTimer += TimeController::timeController.dT; if (frameTimer >= currentFrame->duration) { if (currentFrame->frameNumber == currentAnim->getEndFrameNumber()){ if (state == HERO_STATE_SLASH){ changeAnimation(HERO_STATE_MOVE, true); } else if (state == HERO_STATE_DEAD && hp > 0){ changeAnimation(HERO_STATE_MOVE, true); } else{ currentFrame = currentAnim->getFrame(0); } } else { currentFrame = currentAnim->getNextFrame(currentFrame); } frameTimer = 0; } } void Hero::updateDamages(){ if (active && hp > 0 && invincibleTimer <= 0){ for (auto entity = Entity::entities.begin(); entity != Entity::entities.end(); entity++){ if ((*entity)->active && (*entity)->type == "enemy"){ LivingEntity* enemy = (LivingEntity*)(*entity); if (enemy->damage > 0 && Entity::checkCollision(collisionBox, enemy->hitBox)){ enemy->hitLanded(this); hp -= enemy->damage; if (hp > 0){ invincibleTimer = 0.3; } slideAngle = Entity::angleBetweenTwoEntities((*entity), this); slideAmount = 200; } } } } }
7044a56586113a5383fd8bc34d34e5a7c12ba0d8
7ada00cd38c2c9359085e2111fa72c264e062998
/src/services/alloc/AllocTracker.cpp
34a7bb01fbbacaf48cb1eba013a2a54b7b14233a
[ "BSD-3-Clause" ]
permissive
rblake-llnl/Caliper
8dd5c367a6480aec5a7ae0be5a972ad79a9749a9
f958f45f5cf2dccc4529f2b27d8628981a60b012
refs/heads/master
2020-09-09T02:19:43.923958
2019-11-11T20:51:11
2019-11-11T20:51:11
221,316,681
0
0
NOASSERTION
2019-11-12T21:35:25
2019-11-12T21:35:24
null
UTF-8
C++
false
false
17,180
cpp
AllocTracker.cpp
// Copyright (c) 2019, Lawrence Livermore National Security, LLC. // See top-level LICENSE file for details. #include "caliper/Caliper.h" #include "caliper/AllocTracker.h" #include "caliper/SnapshotRecord.h" #include "caliper/common/Attribute.h" #include "caliper/MemoryPool.h" #include <cstring> #include <mutex> #include <iostream> using namespace cali; using namespace DataTracker; namespace cali { extern Attribute alloc_label_attr; extern Attribute alloc_fn_attr; Node *tree_entry_alloc; Node *tree_entry_free; void init_alloc_tree_entries(Caliper *c) { tree_entry_alloc = c->make_tree_entry(alloc_fn_attr, Variant(CALI_TYPE_STRING, "alloc", 6)); tree_entry_free = c->make_tree_entry(alloc_fn_attr, Variant(CALI_TYPE_STRING, "free", 5)); } } extern cali_id_t cali_alloc_fn_attr_id; extern cali_id_t cali_alloc_label_attr_id; extern cali_id_t cali_alloc_uid_attr_id; extern cali_id_t cali_alloc_addr_attr_id; extern cali_id_t cali_alloc_elem_size_attr_id; extern cali_id_t cali_alloc_num_elems_attr_id; extern cali_id_t cali_alloc_total_size_attr_id; extern cali_id_t cali_alloc_same_size_count_attr_id; const Allocation Allocation::invalid(-1, "INVALID", 0, 0, nullptr, 0); const std::string AllocTracker::cali_alloc("Caliper Alloc"); const std::string AllocTracker::cali_free("Caliper Free"); size_t Allocation::num_bytes(const size_t elem_size, const size_t dimensions[], const size_t num_dimensions) { return elem_size*num_elems(dimensions, num_dimensions); } size_t Allocation::num_elems(const size_t dimensions[], const size_t num_dimensions) { size_t ret = 1; for(int i=0; i<num_dimensions; i++) ret *= dimensions[i]; return ret; } Allocation::Allocation(const uint64_t uid, const std::string &label, const uint64_t start_address, const size_t elem_size, const size_t dimensions[], const size_t num_dimensions) : m_uid(uid), m_label(label), m_start_address(start_address), m_elem_size(elem_size), m_dimensions(new size_t[num_dimensions]), m_num_elems(num_elems(dimensions, num_dimensions)), m_bytes(num_bytes(elem_size, dimensions, num_dimensions)), m_end_address(start_address + m_bytes), m_num_dimensions(num_dimensions), m_index_ret(new size_t[num_dimensions]) { for(int i=0; i<num_dimensions; i++) m_dimensions[i] = dimensions[i]; } Allocation::Allocation(const Allocation &other) : m_uid(other.m_uid), m_label(other.m_label), m_start_address(other.m_start_address), m_elem_size(other.m_elem_size), m_dimensions(new size_t[other.m_num_dimensions]), m_num_elems(other.m_num_elems), m_bytes(other.m_bytes), m_end_address(other.m_end_address), m_num_dimensions(other.m_num_dimensions), m_index_ret(new size_t[m_num_dimensions]) { std::memcpy(m_dimensions, other.m_dimensions, m_num_dimensions*sizeof(size_t)); std::memcpy(m_index_ret, other.m_index_ret, m_num_dimensions*sizeof(size_t)); } Allocation::~Allocation() { delete[] m_dimensions; delete[] m_index_ret; } bool Allocation::contains(uint64_t address) { return m_start_address <= address && m_end_address > address; } size_t Allocation::index_1D(uint64_t address) { return (address - m_start_address) / m_elem_size; } const size_t * Allocation::index_ND(uint64_t address) { size_t offset = index_1D(address); size_t d; for (d = 0; d<m_num_dimensions-1; d++) { m_index_ret[d] = offset % m_dimensions[d]; offset = offset / m_dimensions[d]; } m_index_ret[d] = offset; return m_index_ret; } struct AllocTracker::AllocTree { std::mutex process_mutex; static thread_local std::mutex thread_mutex; enum HAND { LEFT = -1, NA = 0, RIGHT = 1 }; struct AllocNode { Allocation *allocation; AllocNode *parent; AllocNode *left; AllocNode *right; HAND handedness; uint64_t key; bool tracked; AllocNode(Allocation *allocation, AllocNode *parent, AllocNode *left, AllocNode *right, HAND handedness, bool tracked = true) : allocation(allocation), parent(parent), left(left), right(right), handedness(handedness), key(allocation->m_start_address), tracked(tracked) { } ~AllocNode() { delete allocation; } AllocNode* insert(Allocation *allocation) { if (allocation->m_start_address < key) { if (left) return left->insert(allocation); else { AllocNode *newNode = new AllocNode(allocation, this, nullptr, nullptr, LEFT); left = newNode; return newNode; } } else if (allocation->m_start_address > key) { if (right) return right->insert(allocation); else { AllocNode *newNode = new AllocNode(allocation, this, nullptr, nullptr, RIGHT); right = newNode; return newNode; } } else { // Duplicate allocation, replace this one delete this->allocation; this->allocation = allocation; return this; } } AllocNode* find_allocation_containing(uint64_t address) { if (address < key) { if (left) return left->find_allocation_containing(address); else return nullptr; } else { // if (allocation.start_address >= key) { if (allocation->contains(address)) return this; else if (right) return right->find_allocation_containing(address); else return nullptr; } } AllocNode* findMin() { if (left) return left->findMin(); return this; } AllocNode* findMax() { if (right) return right->findMax(); return this; } }; // AllocNode AllocNode *m_root; std::atomic<uint64_t> m_active_bytes; std::map<uint64_t, AllocNode*> m_alloc_map; std::map<uint64_t,uint64_t> m_count_for_size; AllocTree(AllocNode *root = nullptr) : m_root(root), m_active_bytes(0) { } uint64_t count_for_size(uint64_t size) { return m_count_for_size[size]; } void rotate_left(AllocNode *node) { if (node->left) { node->left->parent = node->parent; node->left->handedness = RIGHT; } AllocNode *npp = node->parent->parent; HAND np_hand = node->parent->handedness; node->parent->parent = node; node->parent->handedness = LEFT; node->parent->right = node->left; node->left = node->parent; node->parent = npp; node->handedness = (npp ? np_hand : NA); } void rotate_right(AllocNode *node) { if (node->right) { node->right->parent = node->parent; node->right->handedness = LEFT; } AllocNode *npp = node->parent->parent; HAND np_hand = node->parent->handedness; node->parent->parent = node; node->parent->handedness = RIGHT; node->parent->left = node->right; node->right = node->parent; node->parent = npp; node->handedness = (npp ? np_hand : NA); } void splay(AllocNode *node) { while (node->parent) { if (node->parent->parent == nullptr) { // Case: single zig if (node->handedness == RIGHT) { // Case zig left rotate_left(node); } else if (node->handedness == LEFT) { // Case zig right rotate_right(node); } } else if (node->handedness == RIGHT && node->parent->handedness == RIGHT) { // Case zig zig left rotate_left(node); rotate_left(node); } else if (node->handedness == LEFT && node->parent->handedness == LEFT) { // Case zig zig right rotate_right(node); rotate_right(node); } else if (node->handedness == RIGHT && node->parent->handedness == LEFT) { // Case zig zag left rotate_left(node); rotate_right(node); } else if (node->handedness == LEFT && node->parent->handedness == RIGHT) { // Case zig zag right rotate_right(node); rotate_left(node); } } // Splayed, root is now node m_root = node; } AllocNode* insert(Allocation *allocation, bool track_range) { std::unique_lock<std::mutex> thread_lock(thread_mutex, std::try_to_lock); if(!thread_lock.owns_lock()){ std::cerr << "Thread Lock Failed!" << std::endl; return nullptr; } std::unique_lock<std::mutex> process_lock(process_mutex); if (!track_range) { AllocNode *newNode = new AllocNode(allocation, nullptr, nullptr, nullptr, NA, false); m_active_bytes += allocation->m_bytes; m_alloc_map[allocation->m_start_address] = newNode; m_count_for_size[allocation->m_bytes]++; return newNode; } if (m_root == nullptr) { m_root = new AllocNode(allocation, nullptr, nullptr, nullptr, NA, true); } else { AllocNode *newNode = m_root->insert(allocation); splay(newNode); } m_active_bytes += allocation->m_bytes; m_alloc_map[m_root->key] = m_root; m_count_for_size[allocation->m_bytes]++; return m_root; } Allocation remove(uint64_t start_address) { std::unique_lock<std::mutex> thread_lock(thread_mutex, std::try_to_lock); if(!thread_lock.owns_lock()){ std::cerr << "Thread Lock Failed!" << std::endl; return Allocation::invalid; } std::unique_lock<std::mutex> process_lock(process_mutex); AllocNode *node = m_alloc_map[start_address]; if (node) { m_active_bytes -= node->allocation->m_bytes; m_count_for_size[node->allocation->m_bytes]--; if (!node->tracked) { Allocation ret(*node->allocation); delete node; m_alloc_map.erase(start_address); return ret; } else { splay(node); AllocTree leftTree(node->left); if (leftTree.m_root) { leftTree.m_root->parent = nullptr; leftTree.m_root->handedness = NA; AllocNode *lMax = leftTree.m_root->findMax(); leftTree.splay(lMax); m_root = lMax; m_root->right = node->right; if (m_root->right) m_root->right->parent = m_root; } else if (node->right) { m_root = node->right; m_root->parent = nullptr; m_root->handedness = NA; } else { m_root = nullptr; } Allocation ret = *(node->allocation); delete node; m_alloc_map.erase(start_address); return ret; } } return Allocation::invalid; } AllocNode* get_allocation_at(uint64_t address) { if (m_alloc_map.find(address) == m_alloc_map.end()) { return nullptr; } else { return m_alloc_map[address]; } } AllocNode* find_allocation_containing(uint64_t address) { std::unique_lock<std::mutex> thread_lock(thread_mutex, std::try_to_lock); if(!thread_lock.owns_lock()){ return nullptr; } std::unique_lock<std::mutex> process_lock(process_mutex); if (m_root == nullptr) { // Nothing to find here return nullptr; } AllocNode *node = m_root->find_allocation_containing(address); if (node) { splay(node); return node; } return nullptr; } }; thread_local std::mutex AllocTracker::AllocTree::thread_mutex; AllocTracker::AllocTracker(bool record_snapshots, bool track_ranges) : m_record_snapshots(record_snapshots), m_track_ranges(track_ranges), alloc_tree(new AllocTree(nullptr)) { } AllocTracker::~AllocTracker() { // TODO: delete all allocations } void AllocTracker::set_record_snapshots(bool record_snapshots) { m_record_snapshots = record_snapshots; } void AllocTracker::set_track_ranges(bool track_ranges) { m_track_ranges = track_ranges; } uint64_t AllocTracker::get_active_bytes() { return alloc_tree->m_active_bytes; } std::atomic<uint64_t> allocation_id(0); void AllocTracker::add_allocation(const std::string &label, const uint64_t addr, const size_t elem_size, const size_t dimensions[], const size_t num_dimensions, const std::string fn_name, bool record_snapshot, bool track_range, bool count_same_sized_allocs) { // Create allocation and update tracking info Allocation *a = new Allocation(allocation_id++, label, addr, elem_size, dimensions, num_dimensions); AllocTree::AllocNode *newNode = alloc_tree->insert(a, track_range && m_track_ranges); if (!m_record_snapshots || !record_snapshot) return; Caliper c = Caliper(); // Record snapshot cali_id_t attrs[] = { cali_alloc_addr_attr_id, cali_alloc_elem_size_attr_id, cali_alloc_num_elems_attr_id, cali_alloc_total_size_attr_id, cali_alloc_same_size_count_attr_id, cali_alloc_label_attr_id }; Variant data[] = { Variant(a->m_start_address), Variant(cali_make_variant_from_uint(a->m_elem_size)), Variant(cali_make_variant_from_uint(a->m_num_elems)), Variant(cali_make_variant_from_uint(a->m_bytes)), Variant(cali_make_variant_from_uint(alloc_tree->count_for_size(a->m_bytes))), Variant(cali_make_variant_from_uint(a->m_uid)) }; // TODO: When string type are available, add string labels here SnapshotRecord trigger_info(0, nullptr, 6, attrs, data); c.push_snapshot(CALI_SCOPE_PROCESS | CALI_SCOPE_THREAD, &trigger_info); } Allocation AllocTracker::remove_allocation(uint64_t address, const std::string fn_name, bool record_snapshot) { Allocation removed = alloc_tree->remove(address); if (!m_record_snapshots || !record_snapshot || !removed.isValid()) return removed; Caliper c = Caliper(); cali_id_t attrs[] = { cali_alloc_addr_attr_id, cali_alloc_elem_size_attr_id, cali_alloc_num_elems_attr_id, cali_alloc_total_size_attr_id, cali_alloc_same_size_count_attr_id, cali_alloc_uid_attr_id }; Variant data[] = { Variant(removed.m_start_address), Variant(cali_make_variant_from_uint(removed.m_elem_size)), Variant(cali_make_variant_from_uint(removed.m_num_elems)), Variant(cali_make_variant_from_uint(removed.m_bytes)), Variant(cali_make_variant_from_uint(alloc_tree->count_for_size(removed.m_bytes))), Variant(cali_make_variant_from_uint(removed.m_uid)) }; // TODO: When string type are available, add string labels here SnapshotRecord trigger_info(0, nullptr, 6, attrs, data); c.push_snapshot(CALI_SCOPE_PROCESS | CALI_SCOPE_THREAD, &trigger_info); return removed; } Allocation *AllocTracker::get_allocation_at(uint64_t address) { if (AllocTree::AllocNode *node = alloc_tree->get_allocation_at(address)) return node->allocation; else return nullptr; } Allocation *AllocTracker::find_allocation_containing(uint64_t address) { if (AllocTree::AllocNode *node = alloc_tree->find_allocation_containing(address)) return node->allocation; else return nullptr; }
f68a15ba0377e18f12db0d95150afe0d0949644d
ef3cff2c1f2bb992eaa97a604c02792c1b8aa0e0
/Die.h
349678b77dca92631ca09186fe7821e0ff204dcc
[]
no_license
jpugliesi/PA6
676d0b7ec55d5d7829b014e4a30d3464acabcb14
8465281f2ac449a5d47f9bff9d6da8e734fadb95
refs/heads/master
2021-01-18T13:55:20.091711
2014-05-02T01:02:40
2014-05-02T01:02:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
242
h
Die.h
//Die.h #ifndef DIE_H #define DIE_H class Die{ private: int numSides; //number of sides on the die public: //constructors Die(); ~Die(); //functions int rollDie(); //generates and returns random value between 1 and 6 }; #endif
ec719cb94810f4db5af65127b903e6783329cb74
67ed24f7e68014e3dbe8970ca759301f670dc885
/win10.19042/SysWOW64/ir50_qc.dll.cpp
5bbd733855b463f21afeb79f6a542ac5a378b949
[]
no_license
nil-ref/dll-exports
d010bd77a00048e52875d2a739ea6a0576c82839
42ccc11589b2eb91b1aa82261455df8ee88fa40c
refs/heads/main
2023-04-20T21:28:05.295797
2021-05-07T14:06:23
2021-05-07T14:06:23
401,055,938
1
0
null
2021-08-29T14:00:50
2021-08-29T14:00:49
null
UTF-8
C++
false
false
980
cpp
ir50_qc.dll.cpp
#pragma comment(linker, "/export:AllocInstanceData=\"C:\\Windows\\SysWOW64\\ir50_qc.AllocInstanceData\"") #pragma comment(linker, "/export:Compress=\"C:\\Windows\\SysWOW64\\ir50_qc.Compress\"") #pragma comment(linker, "/export:CompressBegin=\"C:\\Windows\\SysWOW64\\ir50_qc.CompressBegin\"") #pragma comment(linker, "/export:CompressEnd=\"C:\\Windows\\SysWOW64\\ir50_qc.CompressEnd\"") #pragma comment(linker, "/export:CompressFramesInfo=\"C:\\Windows\\SysWOW64\\ir50_qc.CompressFramesInfo\"") #pragma comment(linker, "/export:CompressQuery=\"C:\\Windows\\SysWOW64\\ir50_qc.CompressQuery\"") #pragma comment(linker, "/export:DllMain=\"C:\\Windows\\SysWOW64\\ir50_qc.DllMain\"") #pragma comment(linker, "/export:FreeInstanceData=\"C:\\Windows\\SysWOW64\\ir50_qc.FreeInstanceData\"") #pragma comment(linker, "/export:SetCPUID=\"C:\\Windows\\SysWOW64\\ir50_qc.SetCPUID\"") #pragma comment(linker, "/export:SetScalability=\"C:\\Windows\\SysWOW64\\ir50_qc.SetScalability\"")
07c8f2f8f2d884a0bb8788a256e72fcee7cddde0
e71551968ccc826f536c13ce5ef68e7f6d3c2b83
/src/IHM/Process/VerticesLoadingProcess.h
c88bfbf55ad77e01a3df354ff1955f35c24b0443
[]
no_license
FCHcap/Cubator
2c77cc3ec4db06c2f26d81acd2ef2cc4e06a75c6
cfac8d3e8b86c9c5a43e7f5dd1ac01b0cb4edca6
refs/heads/master
2020-04-11T07:19:36.865124
2018-06-14T09:31:39
2018-06-14T09:31:39
30,690,083
0
0
null
null
null
null
UTF-8
C++
false
false
649
h
VerticesLoadingProcess.h
#ifndef VERTICESLOADINGPROCESS_H #define VERTICESLOADINGPROCESS_H // QT #include <QPen> #include <QGraphicsItemGroup> #include <QGraphicsEllipseItem> // CUBATOR #include <DefaultProcess.h> #include <DVertexList.h> #include <Messages.h> #include <GraphicsPointXYZItem.h> class VerticesLoadingProcess : public DefaultProcess { Q_OBJECT public: VerticesLoadingProcess(); void setVertices(DVertexList & vertices, const bool displayDepth); public slots: void run(); signals: void verticesItemUpdated(QGraphicsItemGroup *); protected: DVertexList * _vertices; bool _displayDepth; }; #endif // VERTICESLOADINGPROCESS_H
68445407e6ce6a2cf9cb9f6a7f5de77edfd6eceb
9b3fd39f5d45a901a4e1c92735b20da8cc2310d1
/prj/inc/LStack.hpp
7a261c24324048ec496a37abf78ea09311a24386
[]
no_license
marcinochman1993/ADT-stack-queue
03fc15a611ba9487505860304be523a263d26188
ec660b5ed1e786df6beb0962bab81fe0ac6417e9
refs/heads/master
2021-01-02T08:57:06.056723
2014-06-11T06:56:44
2014-06-11T06:56:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
881
hpp
LStack.hpp
#ifndef LSTACK_HPP #define LSTACK_HPP #include <list> /*! * \brief Klasa reprezentująca stos zaimplementowany na podstawie listy */ template<typename Type> class LStack { public: /*! * \brief Sprawdza czy stos jest pusty. */ bool isEmpty() const { return m_list.empty(); } /*! * \brief Pozwala pobrać rozmiar stosu. */ unsigned int size() const { return m_list.size(); } /*! * \brief Odkłada na stos element. */ void push(const Type& element) { m_list.push_front(element); } /*! * \brief Sciąga ze stosu element zwracając go. * */ Type pop(); private: /*! * \brief Lista przechowująca dane. */ std::list<Type> m_list; }; template<typename Type> Type LStack<Type>::pop() { if(isEmpty()) throw "Stack is empty"; Type front = m_list.front(); m_list.pop_front(); return front; } #endif
f101c23838de4200738b4c6f532faf2f0e795ad5
9ed1564e46c1d6f7bfb2138e328d3c6d0cb4931c
/source/plugin/factory/pluginfactory.cpp
bbd2d897075fea5e04712a2b570f2e071936ccbf
[]
no_license
ww4u/mct-t4
c66a399fd2f4d281d1aa1cb6db1aded7edf781f1
b4ff50ce2947e7d69972d500633aec991cd13c57
refs/heads/master
2022-12-14T22:36:39.047386
2019-08-05T04:32:15
2019-08-05T04:32:15
296,253,721
0
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
pluginfactory.cpp
#include "pluginfactory.h" #include "../t4/t4.h" #include "../h2/h2.h" #define PLUGIN_MRX_T4_NAME "mrx-t4" #define PLUGIN_MRX_H2_NAME "mrx-h2" //! factory XPlugin *PluginFactory::createPlugin( const QString &name, const QString &addr ) { if ( str_is( name, PLUGIN_MRX_T4_NAME) ) { return new MRX_T4( ); } // else if ( str_is( name, PLUGIN_MRX_H2_NAME) ) // { return new MRX_H2(); } else { return NULL; } } PluginFactory::PluginFactory() { }
6a42be9e22ca56d166458968b2bf39be7bea202c
336b2a1c9d848b1b66ada397f4007344f32b45a0
/Framework/Math/Inc/Matrix3x3.h
9fd7ca60f56a4a21151038a576b22ea781ec71ab
[ "MIT" ]
permissive
xnylhsa/SingularityEngine
73edd6caca12584b0634ccca5a4922a558330c23
5d1c93f95889423cff7ba0e0cb06f10ab8ac019c
refs/heads/master
2023-03-23T11:57:22.600377
2021-03-17T14:04:41
2021-03-17T14:04:41
328,586,360
1
0
null
null
null
null
UTF-8
C++
false
false
3,898
h
Matrix3x3.h
#ifndef INCLUDED_MATH_MATRIX_3X3_H #define INCLUDED_MATH_MATRIX_3X3_H #include "Common.h" #include "SimpleFloatingPointMath.h" #include "MathForwards.h" namespace SingularityEngine::Math { struct Matrix3x3 { float _11, _12, _13; float _21, _22, _23; float _31, _32, _33; Matrix3x3() : _11(1.0f), _12(0.0f), _13(0.0f), _21(0.0f), _22(1.0f), _23(0.0f), _31(0.0f), _32(0.0f), _33(1.0f) {} Matrix3x3( float _11, float _12, float _13, float _21, float _22, float _23, float _31, float _32, float _33) :_11(_11), _12(_12), _13(_13), _21(_21), _22(_22), _23(_23), _31(_31), _32(_32), _33(_33) {} static Matrix3x3 Zero() { return Matrix3x3(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); } static Matrix3x3 Identity() { return Matrix3x3(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); }; static Matrix3x3 Translation(float x, float y) { return Matrix3x3(1.0f, 0.0f, x, 0.0f, 1.0f, y, 0.0f, 0.0f, 1.0f); }; static Matrix3x3 Rotation(float rad) { return Matrix3x3 ( cosf(rad), -sinf(rad), 0.0f, sinf(rad), cosf(rad), 0.0f, 0.0f, 0.0f, 1.0f ) ; } static Matrix3x3 Shear(float a) { return Matrix3x3(1.0f, a, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); } static Matrix3x3 Scale(float sx, float sy) { return Matrix3x3(sx, 0.0f, 0.0f, 0.0f, sy, 0.0f, 0.0f, 0.0f, 1.0f); } static Matrix3x3 Scale(float s) { return Matrix3x3(s, 0.0f, 0.0f, 0.0f, s, 0.0f, 0.0f, 0.0f, 1.0f); } inline Matrix3x3 operator-(); inline Matrix3x3 operator+(const Matrix3x3& right) const; inline Matrix3x3 operator-(const Matrix3x3& right) const; inline Matrix3x3 operator*(float scaler) const; inline Matrix3x3 operator*(const Matrix3x3& right) const; inline Matrix3x3 operator/(float scaler) const; inline Matrix3x3& operator+=(const Matrix3x3& right); }; inline Matrix3x3 Matrix3x3::operator-() { return Matrix3x3( -(_11), -(_12), -(_13), -(_21), -(_22), -(_23), -(_31), -(_32), -(_33)); } inline Matrix3x3 Matrix3x3::operator+(const Matrix3x3& right) const { return Matrix3x3( _11 + right._11, _12 + right._12, _13 + right._13, _21 + right._21, _22 + right._22, _23 + right._23, _31 + right._31, _32 + right._32, _33 + right._33 ); } inline Matrix3x3 Matrix3x3::operator-(const Matrix3x3& right) const { return Matrix3x3( _11 - right._11, _12 - right._12, _13 - right._13, _21 - right._21, _22 - right._22, _23 - right._23, _31 - right._31, _32 - right._32, _33 - right._33 ); } inline Matrix3x3 Matrix3x3::operator*(float scaler) const { return Matrix3x3( _11 * scaler, _12 * scaler, _13 * scaler, _21 * scaler, _22 * scaler, _23 * scaler, _31 * scaler, _32 * scaler, _33 * scaler ); } inline Matrix3x3 Matrix3x3::operator*(const Matrix3x3& right) const { return Matrix3x3( _11 * right._11 + _12 * right._21 + _13 * right._31, _11 * right._12 + _12 * right._22 + _13 * right._32, _11 * right._13 + _12 * right._23 + _13 * right._33, _21 * right._11 + _22 * right._21 + _23 * right._31, _22 * right._12 + _22 * right._22 + _23 * right._32, _23 * right._13 + _22 * right._23 + _23 * right._33, _31 * right._11 + _32 * right._21 + _33 * right._31, _32 * right._12 + _32 * right._22 + _33 * right._32, _33 * right._13 + _32 * right._23 + _33 * right._33 ); } inline Matrix3x3 Matrix3x3::operator/(float scaler) const { ASSERT(scaler != 0, "[MATH::Matrix3x3] Error Divide By Zero"); return Matrix3x3( _11 / scaler, _12 / scaler, _13 / scaler, _21 / scaler, _22 / scaler, _23 / scaler, _31 / scaler, _32 / scaler, _33 / scaler ); } inline Matrix3x3& Matrix3x3::operator+=(const Matrix3x3& right) { _11 += right._11; _12 += right._12; _13 += right._13; _21 += right._21; _22 += right._22; _23 += right._23; _31 += right._31; _32 += right._32; _33 += right._33; return *this; } } #endif
48137c382a853edb8bccceabcda649ba205711d0
39ab815dfdbab9628ede8ec3b4aedb5da3fd456a
/aql/benchmark/lib_20/class_5.cpp
bd923702ccd1091ce8abf1f9f6467f01ad3bdc2e
[ "MIT" ]
permissive
menify/sandbox
c03b1bf24c1527b47eb473f1acc433f17bfb1d4f
32166c71044f0d5b414335b2b6559adc571f568c
refs/heads/master
2016-09-05T21:46:53.369065
2015-04-20T06:35:27
2015-04-20T06:35:27
25,891,580
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
class_5.cpp
#include "class_5.h" #include "class_4.h" #include "class_6.h" #include "class_8.h" #include "class_5.h" #include "class_7.h" #include <lib_9/class_4.h> #include <lib_16/class_0.h> #include <lib_18/class_6.h> #include <lib_6/class_9.h> #include <lib_9/class_8.h> class_5::class_5() {} class_5::~class_5() {}
fdae1a8a557678b148f3e2a89c6a6dcd33299f18
53a9dcde71b26bd3fb004adab40dd524c13a8679
/Lab10/Lab10/tests/Cos_tests.h
b4640df3a93c98e05d60b8d11a30cbff8e73fe03
[]
no_license
MxHonesty/oop-assignments
d11becbeede8b94959658b6bcb50eb101c322521
37e285cb0d97152ba534c19f268768944b2e48d9
refs/heads/main
2023-05-22T22:42:20.581968
2021-06-09T21:00:03
2021-06-09T21:00:03
344,814,540
0
0
null
null
null
null
UTF-8
C++
false
false
100
h
Cos_tests.h
#pragma once namespace Testing { /** Ruleaza toate testele de cos */ void run_all_cos_tests(); }
cfb504d3167e4e6907bb8ccfa7d0eb7fbd1fbae5
6dab957c19c6ad9471f86fa1a334b3929b839d6a
/Source/NansTimelineSystemUE4/Public/TimelineBlueprintHelpers.h
a0f74ed9d1437802382816782efa9532a4f415a4
[ "Apache-2.0" ]
permissive
djfm/UE4-TimelineSystem
27a48de788229297517cdff6cddf5acaf45f3cac
0fdd79f4510875f45e813f34555fa705ea7b9d46
refs/heads/master
2023-08-28T08:27:18.246285
2021-09-21T11:29:01
2021-09-21T11:29:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,407
h
TimelineBlueprintHelpers.h
// Copyright 2020-present Nans Pellicari (nans.pellicari@gmail.com). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "CoreMinimal.h" #include "Attribute/ConfiguredTimeline.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "TimelineBlueprintHelpers.generated.h" class UNEventBase; class UNTimelineManagerDecorator; /** * A simple Blueprint Library class to manage Timeline creation. */ UCLASS() class NANSTIMELINESYSTEMUE4_API UNTimelineBlueprintHelpers : public UBlueprintFunctionLibrary { GENERATED_BODY() public: /** * This class is a pass-through for the INTimelineGameInstance::GetTimeline() method. * It provides a standalone node to avoid getting the game instance in your BP graph. * * @param WorldContextObject - This is as a Outer object for UNTimelineManagerDecorator instantiation, it is implicitly * provided by kismet library thanks to UFUNCTION meta data "WorldContext" * @param Timeline - To allow having a combobox of configured timelines */ // @formatter:off UFUNCTION(BlueprintCallable, BlueprintPure, meta = (WorldContext = "WorldContextObject", DisplayName = "Get a NansTimeline by its configured name", Keywords = "Timeline get"), Category = "NansTimeline") static UNTimelineManagerDecorator* GetTimeline(UObject* WorldContextObject, FConfiguredTimeline Timeline); // @formatter:on // @formatter:off UFUNCTION(BlueprintCallable, BlueprintPure, meta = (DisplayName = "Compare NansTimeline name", Keywords = "Timeline compare"), Category = "NansTimeline") static bool Compare(const FConfiguredTimeline Timeline1, const FConfiguredTimeline Timeline2); // @formatter:on // @formatter:off UFUNCTION(BlueprintCallable, BlueprintPure, meta = (DisplayName = "Get NansTimeline name", Keywords = "Timeline get name"), Category = "NansTimeline") static FName GetName(const FConfiguredTimeline Timeline); // @formatter:on };
b1cf418150810d4ada50a833f93987180e935afc
4ede30953a3768d63f3a3c439824dc873d7d4dcd
/100.cpp
829c4ced78b2fa6cb128c9d735399502716def9b
[]
no_license
cmeng0321/leetcode
32323f28fb106ee71a17634056d9ab99fa574659
7f8d0acfa3b181b1113e91bde78f2c8d7371828f
refs/heads/master
2021-06-23T12:06:54.986893
2021-01-12T13:50:31
2021-01-12T13:50:31
186,436,755
0
0
null
null
null
null
GB18030
C++
false
false
1,888
cpp
100.cpp
/* 100. Same Tree Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Example 2: Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false Example 3: Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false solve 定义两个queue用来存储下一次要访问的节点,保证两个树所比较的位置相同 当两个节点一个存在,一个不存在时,说明不同 当两个节点均不存在时,要继续向后判断 当均存在,判断val */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if((!p&&!q)) return true; if((!p&&q)||(p&&!q)) return false; TreeNode* v1; TreeNode* v2; //可不定义,直接使用 p、q queue<TreeNode*> tree1; queue<TreeNode*> tree2; tree1.push(p); tree2.push(q); v1 = tree1.front(); v2 = tree2.front(); while(!tree1.empty()){ tree1.pop(); tree2.pop(); if((!v1&&v2)||(v1&&!v2)) return false; if((!v1&&!v2)) { v1 = tree1.front(); v2 = tree2.front(); continue; } if(v1->val != v2->val) return false; tree1.push(v1->left); tree1.push(v1->right); tree2.push(v2->left); tree2.push(v2->right); v1 = tree1.front(); v2 = tree2.front(); } return true; } };
4295c37e607c2c937f279432a621f9bc5617d6b7
c1096f2729fcc2e76dfcc9d4d277cebb669ef50f
/generator/Generator.h
5991e5a4a17a80d7c2bd310ee7e5da76e38c3d90
[]
no_license
mikeakohn/java_grinder
8d67f183aebfc412bff8537b23ff8be99f86dea6
273d6e97f46d3fa442b33ae19a2b2cde16dc5c4b
refs/heads/master
2023-08-15T13:17:50.551116
2023-06-20T21:44:37
2023-06-20T21:44:37
15,153,331
481
41
null
2020-01-28T02:30:24
2013-12-13T02:48:12
C++
UTF-8
C++
false
false
9,817
h
Generator.h
/** * Java Grinder * Author: Michael Kohn * Email: mike@mikekohn.net * Web: http://www.mikekohn.net/ * License: GPLv3 * * Copyright 2014-2022 by Michael Kohn * */ #ifndef JAVA_GRINDER_GENERATOR_GENERATOR_H #define JAVA_GRINDER_GENERATOR_GENERATOR_H #include <stdio.h> #include <stdint.h> #include <map> #include <string> #include "generator/API_Amiga.h" #include "generator/API_APPLEIIGS.h" #include "generator/API_Atari2600.h" #include "generator/API_C64.h" #include "generator/API_CPC.h" #include "generator/API_DSP.h" #include "generator/API_Draw3D.h" #include "generator/API_Grinder.h" #include "generator/API_Intellivision.h" #include "generator/API_Joystick.h" #include "generator/API_Keyboard.h" #include "generator/API_Math.h" #include "generator/API_Microcontroller.h" #include "generator/API_MSX.h" #include "generator/API_NES.h" #include "generator/API_Nintendo64.h" #include "generator/API_Parallella.h" #include "generator/API_Playstation2.h" #include "generator/API_Propeller.h" #include "generator/API_SegaGenesis.h" #include "generator/API_SNES.h" #include "generator/API_System.h" #include "generator/API_SXB.h" #include "generator/API_TI84.h" #include "generator/API_TI99.h" #include "generator/API_TRS80_Coco.h" class Generator : public API_Amiga, public API_AppleIIgs, public API_Atari2600, public API_C64, public API_CPC, public API_DSP, public API_Draw3D, public API_Grinder, public API_Intellivision, public API_Joystick, public API_Keyboard, public API_Math, public API_Microcontroller, public API_MSX, public API_NES, public API_Nintendo64, public API_Parallella, public API_Playstation2, public API_Propeller, public API_SegaGenesis, public API_SNES, public API_SXB, public API_System, public API_TI84, public API_TI99, public API_TRS80_Coco { public: Generator(); virtual ~Generator(); virtual int open(const char *filename); void close(); virtual int finish() { return 0; } virtual int get_cpu_byte_alignment() { return 2; } void label(std::string &name); virtual int start_init() = 0; virtual int insert_static_field_define(std::string &name, std::string &type, int index) = 0; virtual int init_heap(int field_count) = 0; //virtual int field_init_boolean(char *name, int index, int value) = 0; //virtual int field_init_byte(char *name, int index, int value) = 0; //virtual int field_init_short(char *name, int index, int value) = 0; virtual int field_init_int(std::string &name, int index, int value) = 0; virtual int field_init_ref(std::string &name, int index) = 0; virtual void method_start(int local_count, int max_stack, int param_count, std::string &name) = 0; virtual void method_end(int local_count) = 0; virtual int push_local_var_int(int index) = 0; virtual int push_local_var_ref(int index) = 0; virtual int push_local_var_float(int index); virtual int push_local_var_long(int index) { return -1; } virtual int push_ref_static(std::string &name, int index) = 0; virtual int push_fake() { return -1; } // move stack ptr without push virtual int set_integer_local(int index, int value) { return -1; } virtual int set_float_local(int index, float value); virtual int set_ref_local(int index, std::string &name) { return -1; } virtual int push_int(int32_t n) = 0; virtual int push_long(int64_t n); virtual int push_float(float f); virtual int push_double(double f); virtual int push_ref(std::string &name) = 0; virtual int pop_local_var_int(int index) = 0; virtual int pop_local_var_ref(int index) = 0; virtual int pop_local_var_float(int index) { return -1; } virtual int pop_local_var_long(int index) { return -1; } virtual int pop() = 0; virtual int dup() = 0; virtual int dup2() = 0; virtual int swap() = 0; virtual int add_integer() = 0; virtual int add_integer(int num) { return -1; } virtual int sub_integer() = 0; virtual int sub_integer(int num) { return -1; } virtual int mul_integer() = 0; virtual int div_integer() = 0; virtual int mod_integer() = 0; virtual int neg_integer() = 0; virtual int shift_left_integer() = 0; virtual int shift_left_integer(int count) { return -1; } virtual int shift_right_integer() = 0; virtual int shift_right_integer(int count) { return -1; } virtual int shift_right_uinteger() = 0; virtual int shift_right_uinteger(int count) { return -1; } virtual int and_integer() = 0; virtual int and_integer(int num) { return -1; } virtual int or_integer() = 0; virtual int or_integer(int num) { return -1; } virtual int xor_integer() = 0; virtual int xor_integer(int num) { return -1; } virtual int inc_integer(int index, int num) = 0; virtual int integer_to_byte() = 0; virtual int integer_to_short() = 0; virtual int integer_to_long() { return -1; } virtual int long_to_integer() { return -1; } virtual int add_float(); virtual int sub_float(); virtual int mul_float(); virtual int div_float(); virtual int neg_float(); virtual int float_to_integer(); virtual int integer_to_float(); virtual int add_long() { return -1; } virtual int sub_long() { return -1; } virtual int mul_long() { return -1; } virtual int div_long() { return -1; } virtual int mod_long() { return -1; } virtual int neg_long() { return -1; } virtual int shift_left_long() { return -1; } virtual int shift_right_long() { return -1; } virtual int shift_right_ulong() { return -1; } virtual int and_long() { return -1; } virtual int or_long() { return -1; } virtual int xor_long() { return -1; } virtual int compare_longs() { return -1; } virtual int jump_cond(std::string &label, int cond, int distance) = 0; virtual int jump_cond_zero(std::string &label, int cond, int distance) { return -1; } virtual int jump_cond_integer(std::string &label, int cond, int distance) = 0; virtual int jump_cond_integer(std::string &label, int cond, int const_val, int distance) { return -1; } virtual int compare_floats(int cond); virtual int ternary(int cond, int value_true, int value_false) = 0; virtual int ternary(int cond, int compare, int value_true, int value_false) = 0; virtual int return_local(int index, int local_count) = 0; virtual int return_integer(int local_count) = 0; virtual int return_void(int local_count) = 0; virtual int return_long(int local_count) { return -1; } virtual int jump(std::string &name, int distance) = 0; virtual int call(std::string &name) = 0; virtual int invoke_static_method(const char *name, int params, int is_void) = 0; virtual int put_static(std::string &name, int index) = 0; virtual int get_static(std::string &name, int index) = 0; virtual int brk() = 0; virtual int new_object(std::string &object_name, int field_count); virtual int new_array(uint8_t type) = 0; virtual int new_object_array(std::string &class_name); virtual int insert_array(std::string &name, int32_t *data, int len, uint8_t type) = 0; virtual int insert_string(std::string &name, uint8_t *bytes, int len) = 0; virtual int push_array_length() = 0; virtual int push_array_length(std::string &name, int field_id) = 0; virtual int array_read_byte() = 0; virtual int array_read_short() = 0; virtual int array_read_int() = 0; virtual int array_read_float(); virtual int array_read_long(); virtual int array_read_object(); virtual int array_read_byte(std::string &name, int field_id) = 0; virtual int array_read_short(std::string &name, int field_id) = 0; virtual int array_read_int(std::string &name, int field_id) = 0; virtual int array_read_float(std::string &name, int field_id); virtual int array_read_long(std::string &name, int field_id); virtual int array_read_object(std::string &name, int field_id); virtual int array_write_byte() = 0; virtual int array_write_short() = 0; virtual int array_write_int() = 0; virtual int array_write_float(); virtual int array_write_long(); virtual int array_write_object(); virtual int array_write_byte(std::string &name, int field_id) = 0; virtual int array_write_short(std::string &name, int field_id) = 0; virtual int array_write_int(std::string &name, int field_id) = 0; virtual int array_write_float(std::string &name, int field_id); virtual int array_write_long(std::string &name, int field_id); virtual int array_write_object(std::string &name, int field_id); // CPU virtual int cpu_asm_X(const char *code, int len); void add_newline(); void instruction_count_clear() { instruction_count = 0; } void instruction_count_inc() { instruction_count++; } int use_array_file(const char *filename, const char *array, int type); int ignore() { return 0; } protected: struct ArrayFiles { std::string name; int type; }; virtual int add_array_files(); virtual int get_int_size() { return 4; } int insert_db(std::string &name, int32_t *data, int len, uint8_t len_type); int insert_dw(std::string &name, int32_t *data, int len, uint8_t len_type); int insert_dc32(std::string &name, int32_t *data, int len, uint8_t len_type, const char *dc32 = "dc32"); int insert_float(std::string &name, int32_t *data, int len, uint8_t len_type, const char *dc32 = "dc32"); int get_constant(uint32_t constant); void insert_constants_pool(); int insert_utf8(std::string &name, uint8_t *bytes, int len); FILE *out; int label_count; int instruction_count; int preload_array_align; std::map<uint32_t, int> constants_pool; std::map<std::string, ArrayFiles> preload_arrays; }; enum { COND_EQUAL = 0, COND_NOT_EQUAL, COND_LESS, COND_LESS_EQUAL, COND_GREATER, COND_GREATER_EQUAL, }; // This is redundant enum { TYPE_BOOLEAN=4, TYPE_CHAR=5, TYPE_FLOAT=6, TYPE_DOUBLE=7, TYPE_BYTE=8, TYPE_SHORT=9, TYPE_INT=10, TYPE_LONG=11, }; #endif
2be48d8fc92445aa3a467ae964d86a8a96611c50
2edc8f86d8971d07f4cbf10072a44cf43170b17a
/uva/solved/104/10454.cc
339af66436b7b895520cdd4c0b0f5c91b2d89c68
[]
no_license
nya3jp/icpc
b9527da381d6f9cead905b540541f03505eb79c3
deb82dcdece5815e404f5ea33956d52a57e67158
refs/heads/master
2021-01-20T10:41:22.834961
2012-10-25T11:11:54
2012-10-25T11:19:37
4,337,683
2
2
null
null
null
null
UTF-8
C++
false
false
1,646
cc
10454.cc
/* * UVA 10454 - Trexpression * 2006-01-03 * by nya */ #include <cstdio> #include <cassert> #define MAX_OPERANDS 36 typedef long long int integer; integer BINTREES[MAX_OPERANDS+1]; void init() { BINTREES[0] = BINTREES[1] = 1; for(int n=2; n<=MAX_OPERANDS; n++) { BINTREES[n] = 0; for(int i=0; i<=n-1; i++) { int j = (n-1) - i; BINTREES[n] += BINTREES[i] * BINTREES[j]; } } /* for(int i=0; i<=MAX_OPERANDS; i++) { std::printf("%d: %llu\n", i, BINTREES[i]); } */ } integer eval_fact(char* (&p)); integer eval_term(char* (&p)); integer eval_expr(char* (&p)); integer eval_fact(char* (&p)) { integer n; if (*p == '(') { p++; n = eval_expr(p); assert(*p == ')'); p++; } else if ('0' <= *p && *p <= '9') { p++; n = 1; } else { assert(false); } return n; } integer eval_term(char* (&p)) { integer n = eval_fact(p); int oprs = 0; while(*p == '*') { p++; n *= eval_fact(p); oprs++; } return n * BINTREES[oprs]; } integer eval_expr(char* (&p)) { integer n = eval_term(p); int oprs = 0; while(*p == '+') { p++; n *= eval_term(p); oprs++; } return n * BINTREES[oprs]; } integer solve(char* p) { return eval_expr(p); } int main() { init(); char buf[150]; while(std::fgets(buf, sizeof(buf), stdin)) { std::printf("%llu\n", solve(buf)); } return 0; }
ab02e42248d1cbfc0e2faa1c5d69eead642597d7
6c94a9118e795401ab5bdf37f837f087ab14e713
/Item.h
af35e393731863163e23bea2cadfbccac40928c6
[]
no_license
JamesTanakrit/sfml-games1
07885878fe871aca12eff533dd2d863c32a12899
75b070b86376ca4f44de5824767201a952343273
refs/heads/main
2023-09-02T09:50:10.026653
2021-11-01T09:58:05
2021-11-01T09:58:05
423,415,036
0
0
null
null
null
null
UTF-8
C++
false
false
508
h
Item.h
#pragma once #include"AllHeader.h" class Item { private: RectangleShape shape; public: int tag; inline Item(Vector2f position, Vector2f size, int tag = 0, Texture* texture = nullptr) { shape.setPosition(position); shape.setSize(size); shape.setTexture(texture); this->tag = tag; } inline bool isPickedUp(FloatRect bound) { return shape.getGlobalBounds().intersects(bound); } inline void render(RenderWindow& window) { window.draw(shape); } };
7e7f1906422adb8f38bb6dbc4af242d44f7e5ae6
5a1d3819eb0179b8571868216fbf7c35fe163c9a
/03_04_iteration_bit_manipulation/04/04.cpp
029602b0d9e3ce98f89a456868611e533baa8d32
[ "MIT" ]
permissive
SurPichuk/intro-to-programming-labs
2aa60b9694c9cef4cb170fa64f07fd0487633db9
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
refs/heads/main
2023-02-27T19:08:00.379893
2021-02-07T17:14:39
2021-02-07T17:14:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
04.cpp
#include <iostream> int main() { int n; std::cin >> n; int prev_num, curr_num; bool consecutive_exist = false; std::cin >> curr_num; for (int i = 1; i < n; i++) { prev_num = curr_num; std::cin >> curr_num; if (prev_num == curr_num) { consecutive_exist = true; } } std::cout << (consecutive_exist ? "yes" : "no") << std::endl; }
74e98bffa1dd412ee50fe11d85794c1964b4916c
70fe72e90b104dcdcfbb89cf3caee42875960b25
/Others/TSCO2017/TSECJ104.cpp
eade80ed3556472f1f901c9512e20e3c94ddcb68
[]
no_license
MohitBaid/CodeChef
2421ddb573d537768282c4fee50379afa8dba677
47979ac21a1432a592cc561a905971ebd47a1025
refs/heads/master
2020-04-06T18:28:53.088274
2019-06-29T08:06:07
2019-06-29T08:06:07
157,699,700
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
TSECJ104.cpp
#include<bits/stdc++.h> using namespace std; int main() { int T; scanf("%d",&T); while(T--) { int n; scanf("%d",&n); int A[n],i,j,B[n]; for(i=0;i<n;i++) scanf("%d",&A[i]); for(i=n-1;i>=0;i--) { B[i]=0; for(j=i;j>=0;j--) { if(A[j]>A[i]) break; B[i]++; } } for(i=0;i<n;i++) printf("%d ",B[i]); printf("\n"); } }
e21f12d304ca4a1ec126d2bad6b37b363e6b07c3
2ab9eb69b98d27f8d6cbb9bc1dab6ee7be856d90
/CP Lectures/Inheritance/Inheritance_2.cpp
b63ebc72ccea0ed799c08b75088a9389097423c3
[]
no_license
Hammad-Ikhlaq/Computer-Programming
8b2fa66cbbf3f5d7c80dfeff68b41d07956f3374
d49f1089d16d78087f7dcc3654575614f12b2060
refs/heads/master
2020-12-02T07:21:32.368954
2019-12-30T15:33:38
2019-12-30T15:33:38
230,931,632
1
0
null
null
null
null
UTF-8
C++
false
false
1,556
cpp
Inheritance_2.cpp
#include<iostream> using namespace std; class A { int a; //Its access is private by default protected: int protectedData; public: A(); ~A(); void PrintInfo(); }; A::A() { cout << "A() Called.\n"; a = 10; protectedData = 100; } A::~A() { cout << "~A() Called.\n"; } void A::PrintInfo() { cout << "a = " << a << endl; cout << "ProtectedData = " << protectedData << endl; } //---------------------------------------------------------------------------------- class B : public A { int b; //Its access is private by default public: B(); ~B(); void PrintInfo(); }; B::B() { cout << "B() Called.\n"; protectedData = 200; //Overwriting the protected member which is accessible in this scope. b = 20; } B::~B() { cout << "~B() Called.\n"; } void B::PrintInfo() { A::PrintInfo(); cout << "b = " << b << endl; } //---------------------------------------------------------------------------------- class C : public B { int c; //Its access is private by default public: C(); ~C(); void PrintInfo(); }; C::C() { cout << "C() Called.\n"; protectedData = 300; //Overwriting the protected member which is accessible in this scope. c = 30; //b = 2000; //b is private data of B which is not directly accessible here } C::~C() { cout << "~C() Called.\n"; } void C::PrintInfo() { B::PrintInfo(); cout << "c = " << c << endl; } void main() { C objC; objC.PrintInfo(); //cout << objC.protectedData; //Protected data is not accessible here system("pause"); }
b671d2d599c55885b4f8ee83230ffa086b31b527
f3f23e02d40df2ea1cadeca0ab1c4a2a8674c627
/main.cpp
eaa50897f79c4ecd3ce92dfc9bafe902e44f5095
[]
no_license
snwfdhmp/population-genome-evolution
66ddfb3df776e61c7dd3e9e84eb3218ef6397ea2
2fad5aa79e4abad03985500ed4463b3c310152ac
refs/heads/master
2021-06-09T15:51:43.509505
2016-12-26T21:22:39
2016-12-26T21:22:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,106
cpp
main.cpp
#include <stdio.h> #include <stdlib.h> #include <jansson.h> #include <time.h> #include "GeneFile.h" #include "Gene.h" #include "Humain.h" #define NBRHUMAINS 50000 void generatePopulation(unsigned long long int taille, Humain* tab, TypeGene* genome, unsigned long long int nombreGenes) { int i,j,n; printf("GENERATION de %llu HUMAINS ALEATOIRES.\n", taille); tab = (Humain*) malloc(sizeof(Humain) * taille); // for(i=0; i < NBRHUMAINS; i++) { printf("Création humain n°%d\n", i+1); for(j=0; j<nombreGenes; j++) { //Pour chaque emplacement de gènes tab[i].genes[j].setType(genome[j].type); n = rand() % genome[j].taille(); tab[i].genes[j].setAlleleL(genome[j].getNumber(n)); n = rand() % genome[j].taille(); tab[i].genes[j].setAlleleR(genome[j].getNumber(n)); tab[i].genes[j].sortAlleles(); tab[i].printGene(j); } } } int main () { time_t t_start, t_end; //pour stocker le temps GeneFile fichierGene; //classe qui sert à traiter le fichier JSON des gènes TypeGene* genome; //contient l'intégralité des gènes possibles (uniformes) Humain* pop; //contenant la population initiale int i,j,n; //variables de parcours char path[] = "genes.json"; //path vers le fichier des gènes //On initialise le timer pour pouvoir obtenir la durée de traitement printf("Démarrage du timer\n"); time(&t_start); //On utilise srand() pour les futurs nombres aléatoires srand(time(NULL)); printf("On commence par lire la liste de gènes...\n"); //On traite le fichier de genes fichierGene.open(path); fichierGene.read(); fichierGene.parse(); fichierGene.giveGeneList(); //création des variables et tableaux utiles const unsigned long int nombreGenes = fichierGene.getNumberOfGenes(); genome = (TypeGene*) malloc(sizeof(TypeGene) * nombreGenes); //Remplissage du génome for(i=0; i < nombreGenes; i++) { genome[i] = fichierGene.getTypeGene(i); genome[i].printTypeGene(); } generatePopulation(NBRHUMAINS, pop, genome, nombreGenes); time(&t_end); double duree = difftime(t_end, t_start); printf("Durée : %f secondes\n", duree); return 0; }
63ed6c8f6d9caf538cfb1cf0ef9006cdd42f2cbf
937d695be0f4781d1fc48c48cdaf33baf3e9e7ae
/src/MapCell.cpp
78898274922a6ed1aaef46c4615d11333af702e7
[]
no_license
AdrianMillanR/Laberinto
6f48cde873acbc8a5675ff6deda257f13f4bf085
b2aaa4f5b44a4653a6d1bb8b4ff813a2bf1d7f5f
refs/heads/master
2022-12-13T06:47:05.435676
2020-09-16T21:07:06
2020-09-16T21:07:06
294,212,835
0
0
null
null
null
null
UTF-8
C++
false
false
101
cpp
MapCell.cpp
#include "MapCell.h" #include <iostream> using namespace std; MapCell::MapCell() { id=' '; }
3cd82fdb9929805fbaadb8cc80c0df0a5969aea5
701e220bb13e5efdc0de945a8d179d53f81d94bb
/42/KrpSim/hdezier/src/main.cpp
8db160d2aa312995b5ab77f553445506c81bf17f
[]
no_license
Elojah/Meuh2.0
486273ac9d5192c6f945f5ed9a56b3582f2aafb0
1706b6cd96deb56af8ab5b2164c05584435c7e35
refs/heads/master
2021-01-11T18:20:18.614432
2017-05-19T14:35:10
2017-05-19T14:35:10
28,937,663
0
0
null
null
null
null
UTF-8
C++
false
false
2,102
cpp
main.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: leeios <leeios@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/06/01 00:45:43 by leeios #+# #+# */ /* Updated: 2016/06/01 02:02:05 by leeios ### ########.fr */ /* */ /* ************************************************************************** */ #include "krpsim.h" #include "FileReader.h" #include "Lexer.h" #include "Parser.h" #include <iostream> #include <stdlib.h> /** * @brief Return main value * @details in: local err => out main err * * @param err local err * @return main err */ static int ret_err(const e_err err) { static const char * const err_msg[] = { "NONE", "Usage: ./krpsim [filename]", "Unrecognized error" }; if (err == e_err::NONE) return (EXIT_SUCCESS); std::cerr << err_msg[(int) err] << std::endl; return (EXIT_FAILURE); } /** * @brief main exec * @details read file => lex => parse => interpret => exec * * @param filename entry arg * @return local err */ static e_err exec(const char *filename) { FileReader fr; auto err = fr.open_file(filename); if (err != e_err::NONE) return (err); Lexer lex(fr.get_file_data()); Parser pars; err = lex.send_tokens(pars); if (err != e_err::NONE) return (err); return (e_err::NONE); } /** * @brief MAIN ENTRY * @details err: BAD_ARG_NUMBER * * @param ac n args * @param av args * * @return SUCCESS || FAILURE */ int main(int ac, char **av) { if (ac != 2) return (ret_err(e_err::BAD_ARG_NUMBER)); return (ret_err(exec(av[1]))); }
82942cfddb0e5f50dd4f9130e00d803e2be0019c
5fca9ab6310f854b655d318b50efa7fc83ad22f8
/feature_master/parameter/parameter_utils.cc
e331d809d9f2975324b39dc1fd11453798dec46f
[ "Apache-2.0" ]
permissive
algo-data-platform/PredictorService
4a73dbdac2bd1d72c18f53073fe80afbb4160bba
a7da427617885546c5b5e07aa7740b3dee690337
refs/heads/main
2023-03-11T17:08:35.351356
2021-02-24T08:46:08
2021-02-24T08:46:08
321,256,115
3
5
null
null
null
null
UTF-8
C++
false
false
646
cc
parameter_utils.cc
#include "feature_master/parameter/parameter_utils.h" #include <fstream> #include <sstream> #include "common/util.h" namespace { // constexpr char LOG_CATEGORY[] = "parameter_utils.cc"; } // namespace namespace feature_master { std::unique_ptr<feature_master::ParameterExtractorManager> createParameterExtractorManager( const std::string& config_file_name) { std::ifstream fin(config_file_name); std::stringstream buffer; buffer << fin.rdbuf(); auto feature_extractor_json_str = buffer.str(); return std::make_unique<feature_master::ParameterExtractorManager>(feature_extractor_json_str); } } // namespace feature_master
e9fc232e5297c346151ea256afbafd09e2335180
a15f8dfce3172227c7f47e8b072d6a18a3931eb3
/C++/p6/run.cxx
3981f7fe3c1e576b3c0e9ebe1640a5a5523cc4a9
[]
no_license
mwalkerhg/C
fa31a7c41db37ed319e4bc0c47ad2166de1adeb2
42bfe3e951558fb5bcdcecd82a5e590e2f702eca
refs/heads/master
2020-04-20T23:44:57.280903
2019-02-05T02:09:08
2019-02-05T02:09:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,675
cxx
run.cxx
//********************************************************************************* //AUTHOR :Mathew Walker //COURSE TITLE :Computer Programming II //COURSE NUMBER :CS216 //CLASS MEETS :MW/8:30-10:20 //PROF NAME :Moe Bidgoli //ASSIGNMENT NUMBER :#6 //DUE DATE :10-26-2015 //POSIBLE POINTS :30 //PURPOSE: // This program will read commands along with student ID and gpa // and add them to a linked list and process if they are valid // and print them, delete them, et.c, based on the command. //********************************************************************************* #include "SortedLinkedList.h" int main(){ ifstream inFile; ofstream outFile; inFile.open("in.data"); outFile.open("out.data"); if (inFile.fail() || outFile.fail()) { outFile << "Check your input and output file!" << endl; return 1; } //PRINT Header outFile << "<* Linked List of Students *>" << endl; outFile << " " << endl; //Initialize variables SortedType sort; sort.MakeEmpty(); char command; int item = 0; float gpa = 0.00; int invalid = 0; //Read and carry out commands inFile >> command; while(inFile) { if(command == 'I') { inFile >> item >> gpa; if(!sort.IsFull()) { if(sort.checkValid(item,gpa)) { sort.InsertItem(item, gpa); } else { outFile << item << " " << setprecision(2) << fixed << gpa << " ~~~ Invalid data" << endl; outFile << " " << endl; invalid ++; } } else { outFile << "List is full, you can not insert!" << endl; outFile << " " << endl; } } if(command == 'P') { if(sort.LengthIs() > 0) sort.Print(outFile,invalid); else { outFile << "List is empty, you can not print!" << endl; outFile << " " << endl; } } if(command == 'E') { sort.MakeEmpty(); outFile << "List is empty!" << endl;; outFile << "" << endl; } if(command == 'D') { inFile >> item; if(sort.LengthIs() > 0) { sort.DeleteItem(item); } else { outFile << "List is empty, you can not delete!" << endl; outFile << " " << endl; } } if(command == 'R') { inFile >> item; if(sort.LengthIs() > 0) { bool found; sort.RetrieveItem(item, gpa, found); if(found) outFile << "*Student " << item << " has GPA: " << gpa << endl; else { outFile << "*" << item << " Not Found!" << endl; outFile << " " << endl; } } else { outFile << "List is empty, you can not search!" << endl; outFile << " " << endl; } } inFile >> command; } outFile << "~~~(end)~~~" << endl; return 0; }
76ecc095e085735bfe46f8767fc3aafa2841c0cc
f1072da7dbff060ca7b538a81d3936571fec56ea
/src/cpe/pom_grp/tests-ut/test_om_grp_store_meta.cpp
345cd66664dd72a7281ca7ac46efd4de7c74c584
[]
no_license
Hkiller/workspace
e05374d30a6f309fa8cf1de83887ccb5d22736f9
660fc5900300786d7581a850a3fefc90f8d07a93
refs/heads/master
2021-03-30T22:44:17.469448
2017-04-12T06:08:02
2017-04-12T06:08:02
125,022,632
2
0
null
2018-03-13T09:07:03
2018-03-13T09:07:03
null
UTF-8
C++
false
false
9,643
cpp
test_om_grp_store_meta.cpp
#include "cpe/dr/dr_metalib_manage.h" #include "OmGrpStoreTest.hpp" TEST_F(OmGrpStoreTest, basic) { install( "TestObj:\n" " main-entry: entry1\n" " attributes:\n" " - entry1: { entry-type: normal, data-type: AttrGroup1 }\n" , "<metalib tagsetversion='1' name='net' version='1'>" " <struct name='AttrGroup1' version='1' align='1'>" " <entry name='a1' type='uint32' id='1'/>" " </struct>" "</metalib>" ) ; EXPECT_STREQ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<metalib tagsetversion=\"1\" name=\"TestObj\" version=\"1\">\n" " <struct name=\"AttrGroup1\" version=\"1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " </struct>\n" " <struct name=\"TestObj\" version=\"1\" align=\"1\">\n" " <entry name=\"entry1\" type=\"AttrGroup1\"/>\n" " </struct>\n" " <struct name=\"TestObjList\" version=\"1\" align=\"1\">\n" " <entry name=\"count\" type=\"uint32\"/>\n" " <entry name=\"data\" type=\"TestObj\" count=\"0\" refer=\"count\"/>\n" " </struct>\n" "</metalib>\n" , str_store_meta()); } TEST_F(OmGrpStoreTest, multi_normal) { install( "TestObj:\n" " main-entry: entry1\n" " attributes:\n" " - entry1: { entry-type: normal, data-type: AttrGroup1 }\n" " - entry2: { entry-type: normal, data-type: AttrGroup2 }\n" , "<metalib tagsetversion='1' name='net' version='1'>" " <struct name='AttrGroup1' version='1' align='1'>" " <entry name='a1' type='uint32' id='1'/>" " </struct>" " <struct name='AttrGroup2' version='1' align='1'>" " <entry name='b1' type='uint32' id='2'/>" " </struct>" "</metalib>" ); EXPECT_STREQ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<metalib tagsetversion=\"1\" name=\"TestObj\" version=\"1\">\n" " <struct name=\"AttrGroup1\" version=\"1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " </struct>\n" " <struct name=\"AttrGroup2\" version=\"1\" align=\"1\">\n" " <entry name=\"b1\" type=\"uint32\" id=\"2\"/>\n" " </struct>\n" " <struct name=\"TestObj\" version=\"1\" align=\"1\">\n" " <entry name=\"entry1\" type=\"AttrGroup1\"/>\n" " <entry name=\"entry2\" type=\"AttrGroup2\"/>\n" " </struct>\n" " <struct name=\"TestObjList\" version=\"1\" align=\"1\">\n" " <entry name=\"count\" type=\"uint32\"/>\n" " <entry name=\"data\" type=\"TestObj\" count=\"0\" refer=\"count\"/>\n" " </struct>\n" "</metalib>\n" , str_store_meta()); } TEST_F(OmGrpStoreTest, multi_ba) { install( "TestObj:\n" " main-entry: entry1\n" " attributes:\n" " - entry1: { entry-type: normal, data-type: AttrGroup1 }\n" " - entry2: { entry-type: ba, bit-capacity: 30, byte-per-page=2 }\n" , "<metalib tagsetversion='1' name='net' version='1'>" " <struct name='AttrGroup1' version='1' align='1'>" " <entry name='a1' type='uint32' id='1'/>" " </struct>" "</metalib>" ); EXPECT_STREQ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<metalib tagsetversion=\"1\" name=\"TestObj\" version=\"1\">\n" " <struct name=\"AttrGroup1\" version=\"1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " </struct>\n" " <struct name=\"TestObj\" version=\"1\" align=\"1\">\n" " <entry name=\"entry1\" type=\"AttrGroup1\"/>\n" " <entry name=\"entry2\" type=\"uint8\" count=\"4\"/>\n" " </struct>\n" " <struct name=\"TestObjList\" version=\"1\" align=\"1\">\n" " <entry name=\"count\" type=\"uint32\"/>\n" " <entry name=\"data\" type=\"TestObj\" count=\"0\" refer=\"count\"/>\n" " </struct>\n" "</metalib>\n" , str_store_meta()); } TEST_F(OmGrpStoreTest, multi_binary) { install( "TestObj:\n" " main-entry: entry1\n" " attributes:\n" " - entry1: { entry-type: normal, data-type: AttrGroup1 }\n" " - entry2: { entry-type: binary, capacity: 5 }\n" , "<metalib tagsetversion='1' name='net' version='1'>" " <struct name='AttrGroup1' version='1' align='1'>" " <entry name='a1' type='uint32' id='1'/>" " </struct>" "</metalib>" ); EXPECT_STREQ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<metalib tagsetversion=\"1\" name=\"TestObj\" version=\"1\">\n" " <struct name=\"AttrGroup1\" version=\"1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " </struct>\n" " <struct name=\"TestObj\" version=\"1\" align=\"1\">\n" " <entry name=\"entry1\" type=\"AttrGroup1\"/>\n" " <entry name=\"entry2\" type=\"uint8\" count=\"5\"/>\n" " </struct>\n" " <struct name=\"TestObjList\" version=\"1\" align=\"1\">\n" " <entry name=\"count\" type=\"uint32\"/>\n" " <entry name=\"data\" type=\"TestObj\" count=\"0\" refer=\"count\"/>\n" " </struct>\n" "</metalib>\n" , str_store_meta()); } TEST_F(OmGrpStoreTest, multi_list) { install( "TestObj:\n" " main-entry: entry1\n" " attributes:\n" " - entry1: { entry-type: normal, data-type: AttrGroup1 }\n" " - entry2: { entry-type: list, data-type: AttrGroup2, group-count: 3, capacity: 5 }\n" , "<metalib tagsetversion='1' name='net' version='1'>" " <struct name='AttrGroup1' version='1' align='1'>" " <entry name='a1' type='uint32' id='1'/>" " </struct>" " <struct name='AttrGroup2' version='1' align='1'>" " <entry name='b1' type='uint32' id='2'/>" " </struct>" "</metalib>" ); EXPECT_STREQ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<metalib tagsetversion=\"1\" name=\"TestObj\" version=\"1\">\n" " <struct name=\"AttrGroup1\" version=\"1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " </struct>\n" " <struct name=\"AttrGroup2\" version=\"1\" align=\"1\">\n" " <entry name=\"b1\" type=\"uint32\" id=\"2\"/>\n" " </struct>\n" " <struct name=\"TestObj\" version=\"1\" align=\"1\">\n" " <entry name=\"entry1\" type=\"AttrGroup1\"/>\n" " <entry name=\"entry2Count\" type=\"uint32\"/>\n" " <entry name=\"entry2\" type=\"AttrGroup2\" count=\"5\" refer=\"entry2Count\"/>\n" " </struct>\n" " <struct name=\"TestObjList\" version=\"1\" align=\"1\">\n" " <entry name=\"count\" type=\"uint32\"/>\n" " <entry name=\"data\" type=\"TestObj\" count=\"0\" refer=\"count\"/>\n" " </struct>\n" "</metalib>\n" , str_store_meta()); LPDRMETA data_meta = dr_lib_find_meta_by_name(store_meta(), "TestObj"); ASSERT_TRUE(data_meta); LPDRMETAENTRY data_entry = dr_meta_find_entry_by_name(data_meta, "entry2"); ASSERT_TRUE(data_entry); EXPECT_EQ((size_t)8, dr_entry_data_start_pos(data_entry, 0)); } TEST_F(OmGrpStoreTest, multi_list_standalone) { install( "TestObj:\n" " main-entry: entry1\n" " attributes:\n" " - entry1: { entry-type: normal, data-type: AttrGroup1 }\n" " - entry2: { entry-type: list, data-type: AttrGroup2, group-count: 3, capacity: 5, standalone: 1 }\n" , "<metalib tagsetversion='1' name='net' version='1'>" " <struct name='AttrGroup1' version='1' primarykey='a1' align='1'>" " <entry name='a1' type='uint32' id='1'/>" " </struct>" " <struct name='AttrGroup2' version='1' align='1'>" " <entry name='b1' type='uint32' id='2'/>" " </struct>" "</metalib>" ); EXPECT_STREQ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<metalib tagsetversion=\"1\" name=\"TestObj\" version=\"1\">\n" " <struct name=\"AttrGroup1\" version=\"1\" primarykey=\"a1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " </struct>\n" " <struct name=\"AttrGroup2\" version=\"1\" primarykey=\"a1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " <entry name=\"b1\" type=\"uint32\" id=\"2\"/>\n" " </struct>\n" " <struct name=\"TestObj\" version=\"1\" primarykey=\"a1\" align=\"1\">\n" " <entry name=\"a1\" type=\"uint32\" id=\"1\"/>\n" " <entry name=\"entry1\" type=\"AttrGroup1\"/>\n" " </struct>\n" " <struct name=\"TestObjList\" version=\"1\" align=\"1\">\n" " <entry name=\"count\" type=\"uint32\"/>\n" " <entry name=\"data\" type=\"TestObj\" count=\"0\" refer=\"count\"/>\n" " </struct>\n" "</metalib>\n" , str_store_meta()); }
b306364bc1fcad531ae7f5620e9bf46b704b0bd5
4509b9563e6591cff48bcd759ad5342a1ca2091c
/src/parser.cpp
3c114ccccdb860922b4e3bc75f81672ae82cdd0f
[]
no_license
doclin/LJson
02688b8b584f1e85663235a4e95cea858f4c9f36
112b910b736383d13d59bb528365ea36b6fec970
refs/heads/master
2021-07-09T21:09:20.737926
2017-10-07T13:56:33
2017-10-07T13:56:33
106,101,264
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
parser.cpp
#include <cstring> #include "parser.h" #include "utility.h" using namespace std; Parser::Parser() : document(NULL), doc_length(0), doc_position(0), line_number(1), line_position(0) {} Parser::~Parser() { for(size_t i=0; i<lexeme_stream.size(); i++) { if(lexeme_stream[i].lex_type == T_STRING) delete [] lexeme_stream[i].lex_string; } } void Parser::parse(const char* doc) { //init if(document != NULL) { json.clear(); for(size_t i=0; i<lexeme_stream.size(); i++) { if(lexeme_stream[i].lex_type == T_STRING) delete [] lexeme_stream[i].lex_string; } lexeme_stream.clear(); } document = doc; doc_length = strlen(document); doc_position = 0; line_number = 1; line_position = 0; if(document == NULL) return; lexical_analyse(); syntactic_analyse(); } const Json& Parser::get_json() { return json; }
878ff2015dff9adca97c0485b245b0e6fd8bbef7
38f10c1888975ba3e4a4c8bdd702cecd3f393774
/src/net/SslAcceptor.h
d1eabf28e860ff415f68e227700a36e74d450388
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
mfwass/Astron
f14c041da05adf37076b04d6373346afeacbb858
a0af7171295c1085f8006eb20bf908f2a0e02697
refs/heads/master
2020-12-28T20:19:25.967881
2015-06-15T18:54:09
2015-06-15T18:54:09
35,847,233
1
0
null
2016-03-12T20:51:47
2015-05-18T23:07:59
C++
UTF-8
C++
false
false
718
h
SslAcceptor.h
#pragma once #include "NetworkAcceptor.h" #include <functional> #include <boost/asio/ssl.hpp> namespace ssl = boost::asio::ssl; typedef std::function<void(ssl::stream<tcp::socket>*)> SslAcceptorCallback; class SslAcceptor : public NetworkAcceptor { public: SslAcceptor(boost::asio::io_service &io_service, ssl::context& ctx, SslAcceptorCallback &callback); virtual ~SslAcceptor() {} private: ssl::context& m_context; SslAcceptorCallback m_callback; virtual void start_accept(); void handle_accept(ssl::stream<tcp::socket> *socket, const boost::system::error_code &ec); void handle_handshake(ssl::stream<tcp::socket> *socket, const boost::system::error_code &ec); };
ccaa6c181526755a04e9de630dfdd42ea606a8d0
ba775bec7a8709a6b71d2b700b0e34af463e2231
/mainwindow.cpp
f2376796fb27d6f58a9a546351939360d4af715b
[]
no_license
musaddib1981/calcTable
721fcb35011c048328c84556d8acb0843b4d1545
a3d29b805bf03f59c5dfb3c8a7b39da4e4bf6a8b
refs/heads/master
2021-09-13T10:32:39.947712
2018-04-28T09:03:31
2018-04-28T09:03:31
109,934,187
0
0
null
null
null
null
UTF-8
C++
false
false
12,369
cpp
mainwindow.cpp
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { mainWidget = new QWidget(); mainLayout = new QGridLayout(); mainWidget->setLayout(mainLayout); this->setCentralWidget(mainWidget); //setFixedSize(1024,768); setMinimumSize(640, 480); label1 = new QLabel("Исходная таблица"); tableView1 = new QTableView(); tableModel1 = new CTableModel1(); label2 = new QLabel("Расчетная таблица"); tableView1->setModel(tableModel1); tableView1->setFixedWidth(603); tableView2 = new QTableView(); tableModel2 = new CTableModel2(); tableView2->setModel(tableModel2); tableView2->setFixedWidth(603); buttonAddUp = new QPushButton("Добавить выше"); buttonAddDown = new QPushButton("Добавить ниже"); buttonDelete = new QPushButton("Удалить"); buttonSave = new QPushButton("Сохранить"); buttonSaveAs = new QPushButton("Сохранить как..."); buttonLoad = new QPushButton("Загрузить"); buttonClear = new QPushButton("Очистить строку"); buttonCalc = new QPushButton("Рассчитать"); buttonAddUp->setFixedSize(150,30); buttonAddDown->setFixedSize(150,30); buttonDelete->setFixedSize(150,30); buttonSave->setFixedSize(150,30); buttonSaveAs->setFixedSize(150,30); buttonLoad->setFixedSize(150,30); buttonClear->setFixedSize(150,30); buttonCalc->setFixedSize(150,30); connect(buttonAddUp, SIGNAL(clicked(bool)), this, SLOT(slotButtonAddUp())); connect(buttonAddDown, SIGNAL(clicked(bool)), this, SLOT(slotButtonAddDown())); connect(buttonDelete, SIGNAL(clicked(bool)), this, SLOT(slotButtonDelete())); connect(buttonSave, SIGNAL(clicked(bool)), this, SLOT(slotButtonSave())); connect(buttonSaveAs, SIGNAL(clicked(bool)), this, SLOT(slotButtonSaveAs())); connect(buttonLoad, SIGNAL(clicked(bool)), this, SLOT(slotButtonLoad())); connect(buttonClear, SIGNAL(clicked(bool)), this, SLOT(slotButtonClear())); connect(buttonCalc, SIGNAL(clicked(bool)), this, SLOT(slotButtonCalc())); mainLayout->addWidget(label1,0,0); mainLayout->addWidget(tableView1,1,0,1,5); mainLayout->addWidget(label2,2,0); mainLayout->addWidget(tableView2,3,0,1,5); mainLayout->addWidget(buttonAddUp,4,0); mainLayout->addWidget(buttonAddDown,4,1); mainLayout->addWidget(buttonDelete,4,2); mainLayout->addWidget(buttonSave,4,3); mainLayout->addWidget(buttonSaveAs,5,0); mainLayout->addWidget(buttonLoad,5,1); mainLayout->addWidget(buttonClear,5,2); mainLayout->addWidget(buttonCalc,5,3); CDoubleSpinBoxDelegate *doubleSpinBox1 = new CDoubleSpinBoxDelegate(0, 1000, 2, 0.01); CDoubleSpinBoxDelegate *doubleSpinBox2 = new CDoubleSpinBoxDelegate(0, 10000, 4, 0.0001); CComboBoxDelegate *comboBox1 = new CComboBoxDelegate(); tableView1->setColumnWidth(0,120); tableView1->setColumnWidth(1,120); tableView1->setColumnWidth(2,120); tableView1->setColumnWidth(3,120); tableView1->setColumnWidth(4,120); tableView1->setItemDelegateForColumn(0, comboBox1); tableView1->setItemDelegateForColumn(1, doubleSpinBox1); tableView1->setItemDelegateForColumn(2, doubleSpinBox2); tableView1->setItemDelegateForColumn(3, doubleSpinBox2); tableView1->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); tableView1->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); tableView1->verticalHeader()->setDefaultSectionSize(20); tableView2->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); tableView2->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); tableView2->verticalHeader()->setDefaultSectionSize(20); //tableModel2->appendRow(); //tableModel2->setData(0,0,"sell"); //tableModel2->setData(1,0,0.01); } MainWindow::~MainWindow() { } void MainWindow::slotButtonAddUp(void) { if (tableView1->currentIndex().row() >= 0) tableModel1->insertStringUp(tableView1->currentIndex().row()); } void MainWindow::slotButtonAddDown(void) { if (tableView1->currentIndex().row() >= 0) tableModel1->insertStringDown(tableView1->currentIndex().row()); } void MainWindow::slotButtonDelete(void) { if (tableView1->currentIndex().row() >= 0) tableModel1->deleteString(tableView1->currentIndex().row()); } void MainWindow::slotButtonSave(void) { bool res; QMessageBox msgBox; QString filename; if (fname.isEmpty()) { filename = QFileDialog::getSaveFileName( this, tr("Сохранить таблицу"), QDir::currentPath(), tr("Файл таблицы (*.tfx)")); if ( filename.isEmpty() ) return; fname = filename; setWindowTitle("calcTable - " + fname); } res = tableModel1->save(fname ); if (res == false) { msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setText(""); msgBox.setIcon(QMessageBox::Critical); msgBox.setInformativeText("Ошибка записи"); msgBox.exec(); } } void MainWindow::slotButtonSaveAs(void) { bool res; QMessageBox msgBox; QString filename = QFileDialog::getSaveFileName( this, tr("Сохранить таблицу"), QDir::currentPath(), tr("Файл таблицы (*.tfx)")); if ( filename.isEmpty() ) return; fname = filename; setWindowTitle("calcTable - " + fname); res = tableModel1->save(filename ); if (res == false) { msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setText(""); msgBox.setIcon(QMessageBox::Critical); msgBox.setInformativeText("Ошибка записи"); msgBox.exec(); } } void MainWindow::slotButtonLoad(void) { bool res; QMessageBox msgBox; fname = QFileDialog::getOpenFileName( this, tr("Загрузить таблицу"), QDir::currentPath(), tr("Файл таблицы (*.tfx)") ); if ( fname.isEmpty() ) return; setWindowTitle("calcTable - " + fname); res = tableModel1->load(fname); if (res == false) { msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setText(""); msgBox.setIcon(QMessageBox::Critical); msgBox.setInformativeText("Ошибка загрузки"); msgBox.exec(); } else { tableModel2->clear(); } } bool searchDuplicate(float lev, const QVector<float> &vec) { QString level = QString::number(lev,'f',4); int i; for (i = 0; i < vec.size(); i++) if (QString::number(vec[i],'f',4) == level) return true; return false; } QVector<float> createPriceLevels(const CTableData &table) { int i; QString orderType; float price; float tp; QVector<float> vec; for (i = 0; i < table.rowCount(); i++) { orderType = table.getData(0,i).toString(); price = table.getData(2,i).toFloat(); tp = table.getData(3,i).toFloat(); if ((orderType == "buy" || orderType == "sell") && tp > 0.0001 && searchDuplicate(tp, vec) == false) vec.push_back(tp); else if ((orderType == "buy stop" || orderType == "sell stop" || orderType == "buy limit" || orderType == "sell limit") && searchDuplicate(price, vec) == false) vec.push_back(price); } return vec; } //Функция возвращает каких ордеров больше и на какой объем //Возвращаемое значение тип ордера, buy, sell или none, если объемы ордеров buy и sell равны //n - на сколько штук относительно рабочего объема идет превышение int MainWindow::getBuySell(const CTableData &tableData, float cur_volume, int &n) { int i; float buy_volume = 0; float sell_volume = 0; int count_buy = 0; int count_sell = 0; for (i = 0; i < tableData.rowCount(); i++) { if (tableData.getData(0,i) == "buy") buy_volume += tableData.getData(1,i).toFloat(); if (tableData.getData(0,i) == "sell") sell_volume += tableData.getData(1,i).toFloat(); } count_buy = buy_volume / cur_volume + 0.5; count_sell = sell_volume / cur_volume + 0.5; if (count_buy > count_sell) { n = count_buy - count_sell; return e_buy; } if (count_sell > count_buy) { n = count_sell - count_buy; return e_sell; } n = 0; return e_null; } void MainWindow::emulate(CTableData &tableData, float lev) { int i; unsigned int level = (lev + 0.00005) * 10000; for (i = 0; i < tableData.rowCount(); i++) { unsigned int price = (tableData.getData(2,i).toFloat() + 0.00005) *10000; unsigned int tp = (tableData.getData(3,i).toFloat() + 0.00005)*10000; if (tableData.getData(0,i) == "sell stop" && level <= price) tableData.setData(0,i,"sell"); else if (tableData.getData(0,i) == "sell limit" && level >=price) tableData.setData(0,i,"sell"); else if (tableData.getData(0,i) == "sell" && tp > 0 && level <= tp) tableData.clearRow(i); else if (tableData.getData(0,i) == "buy stop" && level >= price) tableData.setData(0,i,"buy"); else if (tableData.getData(0,i) == "buy limit" && level <=price) tableData.setData(0,i,"buy"); else if (tableData.getData(0,i) == "buy" && tp > 0 && level >= tp) tableData.clearRow(i); } } void MainWindow::slotButtonCalc(void) { float current_volume = -1; int i,j,k; //Находим минимальный объем - это будет рабочим объемом for (i = 0; i < tableModel1->rowCount(); i++) if (tableModel1->getData(0,i) != "" && current_volume < 0) current_volume = tableModel1->getData(1,i).toFloat(); else if (tableModel1->getData(0,i) != "" && current_volume > 0 && tableModel1->getData(1, i).toFloat() < current_volume) current_volume = tableModel1->getData(1,i).toFloat(); if (current_volume < 0) return; qDebug()<<"Рабочий объем: "<<current_volume; int op, n; COrders orders = COrders(tableModel1->getTableData(), current_volume); orders.print(); op = orders.getType(); n = orders.getNum(); CTableData tableData = tableModel1->getTableData(); CLevels levels; QVector<float> priceLevels = createPriceLevels(tableData); for (i = 0; i < priceLevels.size(); i++) { tableData = tableModel1->getTableData(); //эмулируем уровень какие ордера откроются или закроются на этом уровне emulate(tableData, priceLevels[i]); //смотрим превышение объема ордеров на данном уровне COrders orders2 = COrders(tableData, current_volume); //сопоставляем уровню превышение объема ордеров levels.addLevel(orders2.getType(), orders2.getNum(), priceLevels[i]); } tableModel2->clear(); QVector<CResOrders> vec = levels.getResult(op, n); for (i = 0, k = 0; i < vec.size(); i++) { for (j = 0; j < vec[i].getNum(); j++, k++) { tableModel2->appendRow(); tableModel2->setData(0, k, vec[i].getType()); tableModel2->setData(1, k, current_volume); if (vec[i].getType() == "buy" || vec[i].getType() == "sell") tableModel2->setData(3, k, vec[i].getPrice()); else tableModel2->setData(2, k, vec[i].getPrice()); } } } void MainWindow::slotButtonClear(void) { if (tableView1->currentIndex().row() >= 0) tableModel1->clearString(tableView1->currentIndex().row()); }
66568050b8d420776fb1ac40e45f1aa3585c9882
7ebb0cca6466c161a03da274a390e7456fda7363
/2d_engine/include/pool.h
df498aac2e0a073b097a427d4d2bb3169d32e1ca
[]
no_license
martinezcajm/2DEngine
993c523f21bdfe417c50f15c3331f53bc36fd100
1bddbdb3bf28a721d69e4f660c310acffca9533f
refs/heads/master
2022-12-19T12:41:35.215387
2020-09-23T11:44:06
2020-09-23T11:44:06
297,937,170
0
0
null
null
null
null
UTF-8
C++
false
false
6,831
h
pool.h
// pool.h // Jose Maria Martinez // Header of the functions of the pooling engine. #ifndef __POOL_H__ #define __POOL_H__ 1 #include <vector> #include "rect.h" #include "label.h" #include "sprite.h" #include "background.h" #include "wall.h" #include "brick.h" #include "ball.h" #include "player.h" /** @brief Class in charge of managing the pools * * Singleton of pools used to reuse the diverse graphical entities of the * application avoiding this way the destruction of objects during execution * as much as possible * */ class Pool{ public: /** @brief Gets the instance of our pool * * In charge of creating our singleton of pools in case it doesn't exist * or return it's instance if it exists. * * @return Pool& instance of the pool */ static Pool& instance(); /** @brief Initializes the pool * * Initializes the pool creating the first instances of the elements. * * @return void */ void init(); /** @brief Frees the pull * * Frees all the elements stored in the pools. * * @return void */ void free(); /** @brief Retrieves a Rect * * Returns a Rect from the pool, if the pool doesn't have more rects it * creates one using the rect factory. If the max of rects has been reached * it returns null ptr. * * @return Rect* pointer to rect if possible, nullptr if the maxim has been * reached */ Rect* getRect(); /** @brief Retrieves a Label * * Returns a Label from the pool, if the pool doesn't have more labels it * creates one using the label factory. If the max of labels has been reached * it returns null ptr. * * @return Label* pointer to label if possible, nullptr if the maxim has been * reached */ Label* getLabel(); /** @brief Retrieves a Sprite * * Returns a Sprite from the pool, if the pool doesn't have more sprites it * creates one using the sprite factory. If the max of sprites has been * reached it returns null ptr. * * @return Sprite* pointer to sprite if possible, nullptr if the maxim has * been reached */ Sprite* getSprite(); /** @brief Retrieves a Background * * Returns a Background from the pool, if the pool doesn't have more * backgrounds it creates one using the background factory. If the max of * backgrounds has been reached it returns null ptr. * * @return Background* pointer to background if possible, nullptr if the * maxim has been reached */ Background* getBackground(); /** @brief Retrieves a Wall * * Returns a Wall from the pool, if the pool doesn't have more * walls it creates one using the wall factory. If the max of * walls has been reached it returns null ptr. * * @return Wall* pointer to wall if possible, nullptr if the * maxim has been reached */ Wall* getWall(); /** @brief Retrieves a Brick * * Returns a Brick from the pool, if the pool doesn't have more * bricks it creates one using the brick factory. If the max of * bricks has been reached it returns null ptr. * * @return Brick* pointer to brick if possible, nullptr if the * maxim has been reached */ Brick* getBrick(); /** @brief Retrieves a Brick * * Returns a Brick from the pool, if the pool doesn't have more * bricks it creates one using the brick factory. If the max of * bricks has been reached it returns null ptr. * * @return Brick* pointer to brick if possible, nullptr if the * maxim has been reached */ Ball* getBall(); /** @brief Retrieves a Player * * Returns a Player from the pool, if the pool doesn't have more * players it creates one using the player factory. If the max of * players has been reached it returns null ptr. * * @return Player* pointer to player if possible, nullptr if the * maxim has been reached */ Player* getPlayer(); /** @brief Adds an existing rect to the pool * * Recieves an existing rect and resets it's value using the unuse function of * rect * * @return void */ void returnRect(Rect &rect); /** @brief Adds an existing label to the pool * * Recieves an existing label and resets it's value using the unuse function * of label * * @return void */ void returnLabel(Label &label); /** @brief Adds an existing sprite to the pool * * Recieves an existing sprite and resets it's value using the unuse function * of sprite * * @return void */ void returnSprite(Sprite &sprite); /** @brief Adds an existing background to the pool * * Recieves an existing background and resets it's value using the unuse * function of background * * @return void */ void returnBackground(Background &background); /** @brief Adds an existing wall to the pool * * Recieves an existing wall and resets it's value using the unuse * function of wall * * @return void */ void returnWall(Wall &wall); /** @brief Adds an existing brick to the pool * * Recieves an existing brick and resets it's value using the unuse * function of brick * * @return void */ void returnBrick(Brick &brick); /** @brief Adds an existing ball to the pool * * Recieves an existing ball and resets it's value using the unuse * function of ball * * @return void */ void returnBall(Ball &ball); /** @brief Adds an existing Player to the pool * * Recieves an existing player and resets it's value using the unuse * function of player * * @return void */ void returnPlayer(Player &player); std::vector<Rect*> rect_pool_; std::vector<Label*> label_pool_; std::vector<Sprite*> sprite_pool_; std::vector<Background*> bg_pool_; std::vector<Wall*> wall_pool_; std::vector<Brick*> brick_pool_; std::vector<Ball*> ball_pool_; std::vector<Player*> player_pool_; private: /** @brief Pool constructor * * In charge of creating the first instance that will use the singleton * * @return *Pool */ Pool(); /** @brief Pool copy constructor * * Pool copy constructor without anything to disable it. * * @return *Pool */ Pool(const Pool& o){}; /** @brief Pool destructor * * Destructor of class pool private so the pool can't be destroyed */ ~Pool(); //Number of entities that will create the pool at start of each type static const uint32_t start_rects_ = 20; static const uint32_t start_labels_ = 10; static const uint32_t start_sprites_ = 30; static const uint32_t start_backgrounds_ = 5; static const uint32_t start_walls_ = 5; static const uint32_t start_bricks_ = 20; static const uint32_t start_balls_ = 1; static const uint32_t start_players_ = 1; }; #endif
a516a3e2decfac96e7f968840368546fff5ce4dd
0f2e3765a060559116dea589ff71a384921837c0
/Project Source/Pathfinding/MathLib/src/Vec2.cpp
5063e978ac214bca5f9a54b052fa97703d1a98eb
[]
no_license
ShaneCoates/AIE-AI
f57f39cd6c86bc1e066642db80ea439ce01dd0e2
6562f2f827608f8d898db75b381e1e514bde8787
refs/heads/master
2021-01-10T19:36:45.408611
2015-09-03T22:42:37
2015-09-03T22:42:37
25,550,996
0
0
null
null
null
null
UTF-8
C++
false
false
1,993
cpp
Vec2.cpp
#include "Vec2.h" #include "Vec3.h" #include "Mat3x3.h" #include <math.h> float Vec2::Length() { return sqrt(x*x + y*y); } Vec2& Vec2::Normalise() { float len = Length(); x /= len; y /= len; return *this; } float Vec2::Dot(Vec2 &rhs) { return (x * rhs.x) + (y * rhs.y); } float Vec2::GetAngle(Vec2 A, Vec2 B) { return acosf(A.Dot(B) / (A.Length() * B.Length())); //A.Normalise(); //B.Normalise(); //Vec2 AP = Vec2(A.y, -A.x); //float rot = acos(A.Dot(B)); //if(AP.Dot(B) < 0) // rot = -rot; //return rot; } Vec2 Vec2::GetPerpClockwise(Vec2 A) { return Vec2(A.y, -A.x); } Vec2 Vec2::GetPerpCounterClockwise(Vec2 A) { return Vec2(-A.y, A.x); } //Vector2 overloads: Vec2 Vec2::operator+ (const Vec2 &rhs) const { return Vec2(x + rhs.x, y + rhs.y); } Vec2 Vec2::operator- (const Vec2 &rhs) const { return Vec2(x - rhs.x, y - rhs.y); } Vec2& Vec2::operator+= (const Vec2 &rhs) { x += rhs.x; y += rhs.y; return *this; } Vec2& Vec2::operator-= (const Vec2 &rhs) { x -= rhs.x; y -= rhs.y; return *this; } Vec2 Vec2::operator* (const Vec2 &rhs) const { return Vec2(x * rhs.x, y * rhs.y); } Vec2 Vec2::operator/ (const Vec2 &rhs) const { return Vec2(x / rhs.x, y / rhs.y); } Vec2& Vec2::operator*= (const Vec2 &rhs) { x *= rhs.x; y *= rhs.y; return *this; } Vec2& Vec2::operator/= (const Vec2 &rhs) { x /= rhs.x; y /= rhs.y; return *this; } //Scalar overloads: Vec2 Vec2::operator / (const float &rhs) const { return Vec2(x / rhs, y / rhs); } Vec2 Vec2::operator * (const float &rhs) const { return Vec2(x * rhs, y * rhs); } Vec2& Vec2::operator/= (const float &rhs) { x /= rhs; y /= rhs; return *this; } Vec2& Vec2::operator*= (const float &rhs) { x *= rhs; y *= rhs; return *this; } //Matrix overloads Vec2 Vec2::operator * (const Mat3x3& rhs) const { return Vec2(Vec3::DotProduct(Vec3((*this).x, (*this).y, 1.0f), Vec3(rhs.m1, rhs.m4, rhs.m7)), Vec3::DotProduct(Vec3((*this).x, (*this).y, 1.0f), Vec3(rhs.m2, rhs.m5, rhs.m8))); }
f57dafec2fed1fa3daad28cbd929a9821997630c
683a90831bb591526c6786e5f8c4a2b34852cf99
/Math/Computational geometry/point.cpp
1c2723513ff269c0454ccbc20a62e286e8bf1480
[]
no_license
dbetm/cp-history
32a3ee0b19236a759ce0a6b9ba1b72ceb56b194d
0ceeba631525c4776c21d547e5ab101f10c4fe70
refs/heads/main
2023-04-29T19:36:31.180763
2023-04-15T18:03:19
2023-04-15T18:03:19
164,786,056
8
0
null
null
null
null
UTF-8
C++
false
false
1,870
cpp
point.cpp
#include <bits/stdc++.h> using namespace std; struct point { // componentes del punto double x, y; // Constructores point(): x(0), y(0) {} point(double x, double y) : x(x), y(y) {} // Operaciones básicas point operator+(const point &p)const{return point(x + p.x, y + p.y);} point operator-(const point &p)const{return point(x - p.x, y - p.y);} point operator*(const double &k)const{return point(x * k, y * k);} point operator/(const double &k)const{return point(x / k, y / k);} bool operator==(const point &p)const{return x == p.x && y == p.y;} bool operator!=(const point &p)const{return !(*this == p);} // comparación con orden lexicográfico bool operator<(const point &p) const { if(x == p.x) return y < p.y; return x < p.x; } bool operator>(const point &p) const { if(x == p.x) return y > p.y; return x > p.x; } // Propiedades del punto double length()const{return sqrt(x*x + y*y);} point unit()const{return (*this) / length();} point perp()const{return point(-y, x);} point rotate(const double &ang) const { return point(x*cos(ang) - y*sin(ang), x*sin(ang) + y*cos(ang)); } }; // Utils istream& operator>>(istream& is, point &p) { return is >> p.x >> p.y; } ostream& operator<<(ostream &os, const point &p) { return os << "(" << p.x << ", " << p.y << ")"; } /*Ejemplo: + Se leen 2 puntos P y Q y un ángulo theta. + Se imprime como salida el punto que resulta de rotar el punto Q alrededor de P con un ángulo theta en sentido antihorario. */ int main() { point p, q; double theta; cout << "Type P: "; cin >> p; cout << "Type Q: "; cin >> q; cout << "Type theta: "; cin >> theta; point q_rotated = p + (q - p).rotate(theta); cout << "Q': " << q_rotated << endl; return 0; }
5ae46d961e9a93f5899a176ffaa91d9097a70e64
015b944dc0378e0fdd4548b1eb6ec2a5bfdfdeb3
/genuary_2021.ino
9ad362ee4228b963db44d9a55f372ed8423d2354
[]
no_license
flavioamieiro/genuary_2021
e8c7d9cf881457a194c67ba225c96262e16bfdf6
b2db8ab90c44542a271ef09c47b691da336955a9
refs/heads/main
2023-02-28T09:13:48.059083
2021-01-31T15:41:42
2021-01-31T15:41:42
326,520,805
1
0
null
null
null
null
UTF-8
C++
false
false
555
ino
genuary_2021.ino
#include <GxEPD2_BW.h> GxEPD2_BW<GxEPD2_750_T7, GxEPD2_750_T7::HEIGHT> display(GxEPD2_750_T7(/*CS=5*/ SS, /*DC=*/ 17, /*RST=*/ 16, /*BUSY=*/ 4)); int loop_count = 0; void setup() { initDisplay(); } void initDisplay() { display.init(0, true, 2, false); display.setRotation(0); } void fullRefresh() { display.clearScreen(); } void loop() { if (loop_count % 100 == 0) { fullRefresh(); } display.fillScreen(GxEPD_WHITE); // draw here. display.displayWindow(0, 0, display.width(), display.height()); delay(1000); loop_count++; }
f1b560c3434c4eceeeb315ff23a0885c56aa7d41
13d1c3806a29fdeaf63173819e22fdc6bd517ec3
/boost/config/user.hpp
f5d5200ccee9f9125cae09d9ac3882d6b5200f7c
[ "BSL-1.0" ]
permissive
vgteam/boost-subset
44fba6d25b6a012bd241b8e706a28e45958cd756
53ee8d82dbd2ae54825b49606d8a24d9d45bb142
refs/heads/master
2020-03-10T02:40:30.312168
2018-04-11T22:02:56
2018-04-11T22:02:56
129,142,377
0
0
null
null
null
null
UTF-8
C++
false
false
47
hpp
user.hpp
../../libs/config/include/boost/config/user.hpp
55ea29cb224fb1314d61e38c2b49265c428b033a
7fb149b31b9321fc14396dad040fabf7e6e6eb52
/build/tmp/expandedArchives/ntcore-cpp-2019.2.1-headers.zip_bb0cec940e93e7a2ed066107bd22e12e/networktables/NetworkTableValue.h
3aa0c013f5e86ca514d4cf1a0dc2d9cf39f4bdc6
[ "BSD-3-Clause" ]
permissive
FRCTeam5458DigitalMinds/Axon
4feb4e7cc1a50d93d77c204dbf6cca863850ba3f
af571142de3f9d6589252c89537210015a1a26a0
refs/heads/master
2020-04-18T20:14:50.004225
2019-10-30T03:05:29
2019-10-30T03:05:29
167,732,922
3
0
BSD-3-Clause
2019-03-11T01:25:14
2019-01-26T20:00:28
C++
UTF-8
C++
false
false
12,318
h
NetworkTableValue.h
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2015-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #ifndef NTCORE_NETWORKTABLES_NETWORKTABLEVALUE_H_ #define NTCORE_NETWORKTABLES_NETWORKTABLEVALUE_H_ #include <stdint.h> #include <cassert> #include <memory> #include <string> #include <type_traits> #include <utility> #include <vector> #include <wpi/ArrayRef.h> #include <wpi/StringRef.h> #include <wpi/Twine.h> #include "ntcore_c.h" namespace nt { using wpi::ArrayRef; using wpi::StringRef; using wpi::Twine; /** * A network table entry value. * @ingroup ntcore_cpp_api */ class Value final { struct private_init {}; public: Value(); Value(NT_Type type, uint64_t time, const private_init&); ~Value(); /** * Get the data type. * * @return The type. */ NT_Type type() const { return m_val.type; } /** * Get the data value stored. * * @return The type. */ const NT_Value& value() const { return m_val; } /** * Get the creation time of the value. * * @return The time, in the units returned by nt::Now(). */ uint64_t last_change() const { return m_val.last_change; } /** * Get the creation time of the value. * * @return The time, in the units returned by nt::Now(). */ uint64_t time() const { return m_val.last_change; } /** * @{ * @name Type Checkers */ /** * Determine if entry value contains a value or is unassigned. * * @return True if the entry value contains a value. */ bool IsValid() const { return m_val.type != NT_UNASSIGNED; } /** * Determine if entry value contains a boolean. * * @return True if the entry value is of boolean type. */ bool IsBoolean() const { return m_val.type == NT_BOOLEAN; } /** * Determine if entry value contains a double. * * @return True if the entry value is of double type. */ bool IsDouble() const { return m_val.type == NT_DOUBLE; } /** * Determine if entry value contains a string. * * @return True if the entry value is of string type. */ bool IsString() const { return m_val.type == NT_STRING; } /** * Determine if entry value contains a raw. * * @return True if the entry value is of raw type. */ bool IsRaw() const { return m_val.type == NT_RAW; } /** * Determine if entry value contains a rpc definition. * * @return True if the entry value is of rpc definition type. */ bool IsRpc() const { return m_val.type == NT_RPC; } /** * Determine if entry value contains a boolean array. * * @return True if the entry value is of boolean array type. */ bool IsBooleanArray() const { return m_val.type == NT_BOOLEAN_ARRAY; } /** * Determine if entry value contains a double array. * * @return True if the entry value is of double array type. */ bool IsDoubleArray() const { return m_val.type == NT_DOUBLE_ARRAY; } /** * Determine if entry value contains a string array. * * @return True if the entry value is of string array type. */ bool IsStringArray() const { return m_val.type == NT_STRING_ARRAY; } /** @} */ /** * @{ * @name Type-Safe Getters */ /** * Get the entry's boolean value. * * @return The boolean value. */ bool GetBoolean() const { assert(m_val.type == NT_BOOLEAN); return m_val.data.v_boolean != 0; } /** * Get the entry's double value. * * @return The double value. */ double GetDouble() const { assert(m_val.type == NT_DOUBLE); return m_val.data.v_double; } /** * Get the entry's string value. * * @return The string value. */ StringRef GetString() const { assert(m_val.type == NT_STRING); return m_string; } /** * Get the entry's raw value. * * @return The raw value. */ StringRef GetRaw() const { assert(m_val.type == NT_RAW); return m_string; } /** * Get the entry's rpc definition value. * * @return The rpc definition value. */ StringRef GetRpc() const { assert(m_val.type == NT_RPC); return m_string; } /** * Get the entry's boolean array value. * * @return The boolean array value. */ ArrayRef<int> GetBooleanArray() const { assert(m_val.type == NT_BOOLEAN_ARRAY); return ArrayRef<int>(m_val.data.arr_boolean.arr, m_val.data.arr_boolean.size); } /** * Get the entry's double array value. * * @return The double array value. */ ArrayRef<double> GetDoubleArray() const { assert(m_val.type == NT_DOUBLE_ARRAY); return ArrayRef<double>(m_val.data.arr_double.arr, m_val.data.arr_double.size); } /** * Get the entry's string array value. * * @return The string array value. */ ArrayRef<std::string> GetStringArray() const { assert(m_val.type == NT_STRING_ARRAY); return m_string_array; } /** @} */ /** * @{ * @name Factory functions */ /** * Creates a boolean entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeBoolean(bool value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_BOOLEAN, time, private_init()); val->m_val.data.v_boolean = value; return val; } /** * Creates a double entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeDouble(double value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_DOUBLE, time, private_init()); val->m_val.data.v_double = value; return val; } /** * Creates a string entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeString(const Twine& value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_STRING, time, private_init()); val->m_string = value.str(); val->m_val.data.v_string.str = const_cast<char*>(val->m_string.c_str()); val->m_val.data.v_string.len = val->m_string.size(); return val; } /** * Creates a string entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ #ifdef _MSC_VER template <typename T, typename = std::enable_if_t<std::is_same<T, std::string>>> #else template <typename T, typename std::enable_if<std::is_same<T, std::string>::value>::type> #endif static std::shared_ptr<Value> MakeString(T&& value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_STRING, time, private_init()); val->m_string = std::move(value); val->m_val.data.v_string.str = const_cast<char*>(val->m_string.c_str()); val->m_val.data.v_string.len = val->m_string.size(); return val; } /** * Creates a raw entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeRaw(StringRef value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_RAW, time, private_init()); val->m_string = value; val->m_val.data.v_raw.str = const_cast<char*>(val->m_string.c_str()); val->m_val.data.v_raw.len = val->m_string.size(); return val; } /** * Creates a raw entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ #ifdef _MSC_VER template <typename T, typename = std::enable_if_t<std::is_same<T, std::string>>> #else template <typename T, typename std::enable_if<std::is_same<T, std::string>::value>::type> #endif static std::shared_ptr<Value> MakeRaw(T&& value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_RAW, time, private_init()); val->m_string = std::move(value); val->m_val.data.v_raw.str = const_cast<char*>(val->m_string.c_str()); val->m_val.data.v_raw.len = val->m_string.size(); return val; } /** * Creates a rpc entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeRpc(StringRef value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_RPC, time, private_init()); val->m_string = value; val->m_val.data.v_raw.str = const_cast<char*>(val->m_string.c_str()); val->m_val.data.v_raw.len = val->m_string.size(); return val; } /** * Creates a rpc entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ template <typename T> static std::shared_ptr<Value> MakeRpc(T&& value, uint64_t time = 0) { auto val = std::make_shared<Value>(NT_RPC, time, private_init()); val->m_string = std::move(value); val->m_val.data.v_raw.str = const_cast<char*>(val->m_string.c_str()); val->m_val.data.v_raw.len = val->m_string.size(); return val; } /** * Creates a boolean array entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeBooleanArray(ArrayRef<bool> value, uint64_t time = 0); /** * Creates a boolean array entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeBooleanArray(ArrayRef<int> value, uint64_t time = 0); /** * Creates a double array entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeDoubleArray(ArrayRef<double> value, uint64_t time = 0); /** * Creates a string array entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value */ static std::shared_ptr<Value> MakeStringArray(ArrayRef<std::string> value, uint64_t time = 0); /** * Creates a string array entry value. * * @param value the value * @param time if nonzero, the creation time to use (instead of the current * time) * @return The entry value * * @note This function moves the values out of the vector. */ static std::shared_ptr<Value> MakeStringArray( std::vector<std::string>&& value, uint64_t time = 0); /** @} */ Value(const Value&) = delete; Value& operator=(const Value&) = delete; friend bool operator==(const Value& lhs, const Value& rhs); private: NT_Value m_val; std::string m_string; std::vector<std::string> m_string_array; }; bool operator==(const Value& lhs, const Value& rhs); inline bool operator!=(const Value& lhs, const Value& rhs) { return !(lhs == rhs); } /** * NetworkTable Value alias for similarity with Java. * @ingroup ntcore_cpp_api */ typedef Value NetworkTableValue; } // namespace nt #endif // NTCORE_NETWORKTABLES_NETWORKTABLEVALUE_H_
848991ee4fec1fe676c31b95330b4bd66d3681f6
3e6ac3346f04cd5dee6a3d4d7267cf35745bda1b
/hw9/car.h
df2a667a5134146544089ea154d49799fb817fd3
[]
no_license
ctorralba/C-Programming
2f948a02c7168e6a231157537098a9a59039348a
45857b4c785d82b115c94388948b56d33e3c49a6
refs/heads/master
2021-06-29T16:40:29.630394
2017-09-13T06:45:25
2017-09-13T06:45:25
103,363,804
0
0
null
null
null
null
UTF-8
C++
false
false
2,982
h
car.h
/*Programmer: Christopher Torralba Date:11/9/2015 Instructor: Leopold Section: J Purpose: This file contains the prototypes and global constants of the Car class. */ #include <iostream> #include "road.h" #ifndef CAR_H #define CAR_H using namespace std; const short STARTWIDTH = 4; //starting width for car const short STARTDAMAGE = 0; //starting damage for car const short BATTERYRANGE = 11; //range values for % rand gen const short BATTERYSTART = 90; //starting values for rand gen const char STARTSYMBOL = 'c'; //starting symbol for char const short HALFOBSWEIGHT = 2; //half the obstacle weight (kg) const short TENTHOBSWEIGHT = 10;//tenth of the obstacle weight (kg) const short OVER100 = 100; //used to check if values are over 100. const short OBSWEIGHTCHECK = 0; // used to check if obs is pos. const short CARPOS = 1; //where the car will be located on the road. class Car { private: int m_width, //# of sectors a car occupies m_pos; //position in sector float m_damage, //accumulated percentage of how damaged the car is. m_battery; //% of battery power remaining char m_symbol; //symbol used to represent the car public: /* Default constructor for Fraction Pre: None Post: width set to 4, damage set to 0, battery set to some random # between 90 & 100, symbol is set to c. Sets position in sector to 1. */ Car(); /* Accessor for width of the car. Pre: None Post: Value of width is returned */ int getWidth() const { return m_width; } /* Accessor for damage to the car. Pre: None. Post: Value of damage is returned. */ int getDamage() const { return m_damage; } /* Accessor for the car's remaining battery power. Pre: None. Post: Value of battery is returned. */ int getBattery() const { return m_battery; } /* Takes a value representing road obstacle and increases damage by 1/10 of it's weight. damage is to not exceed 100. Pre: None. Post: Damage is increased by a 1/10 of the obstacle's value. */ void incrBattery(int obstacleWeight); /* Takes a value representing road obstacle and increases damage by 1/10 of it's weight. damage is to not exceed 100. Pre: None. Post: Damage is increased by a 1/10 of the obstacle's value. */ void incrDamage(int obstacleWeight); /* Establishes a car on the road based on the width of the car. The car character, and the the starting left pos of the car. Pre: place car() Post: a passing has been placed across the scene. */ void enter_a_road(Road& r); /* Displays the state of the car Pre: None Post: Car's member variable values will be output to outs, modifying ostream outs. */ friend ostream& operator<<(ostream&outs, const Car& c); }; #endif
82ec530b12b64baba0816346edea80709ee9d09a
c0c2db74928fd3603ed52f5a45dde1945ec3bd4e
/BAB/BAB/BAB/Mole.cpp
8e10ccf18405627cbb92f737131a35f2fe97c0a6
[]
no_license
random-musings/Whack
94408e6e948a58f46096b5727cf072f9b0e3a750
a249f5fc29b3f0203fffdd3f74801ec0a8a1d3a5
refs/heads/master
2016-09-06T02:28:17.093266
2014-09-21T17:14:58
2014-09-21T17:14:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
Mole.cpp
#include "stdafx.h" Mole::Mole(void):GameObject() { mInPauseAtTop=false; } Mole::Mole(XMFLOAT3 newPos, XMFLOAT3 newVelocity) :GameObject(newPos,newVelocity) { mInPauseAtTop=false; } Mole::~Mole(void) { }
de768d48070242df4d59146f44965d0d6201a813
0e87f85863c18c5cecc876b5fcdeea68abb6108d
/cudaTracer/Model.h
866beb800efcc677417a312a21e66736df49f267
[]
no_license
MattiasLiljeson/CudaRayTracer
6562d09b636a0b448c213607d03471f54f03e2e9
b3e0fadf10fbcde991522956dc4ac6a7bc94ff65
refs/heads/master
2020-05-20T16:09:01.423636
2019-08-10T10:48:06
2019-08-10T10:48:06
185,660,344
1
0
null
null
null
null
UTF-8
C++
false
false
2,116
h
Model.h
#ifndef MODEL_H #define MODEL_H #include <string> #include <vector> //#include "Utils.h" #include "Vertex.cuh" namespace model { struct ObbFromFile { bool defined; enum { X, Y, Z }; float normals[3][3]; float lengths[3]; ObbFromFile() { defined = false; for (int i = 0; i < 3; i++) { lengths[i] = 0.0f; for (int j = 0; j < 3; j++) { normals[i][j] = 0.0f; } } } }; struct Material { std::string mtlName; std::string texturePath; std::string normalMapPath; std::string specularMapPath; }; class Model { public: // These are public for speed std::string name; // Blend maps are not implemented yet bool useBlendMap; std::string blendMapPath; ObbFromFile obb; // Used for culling std::vector<int> indices; std::vector<Vertex> vertices; std::vector<Material> materials; Model(); void clear(); void addVertex(Vertex p_vertex); void setVertices(std::vector<Vertex> p_vertices); void addIndex(int p_index); void setIndices(std::vector<int> p_indices); void setBlendMapPath(std::string p_blendMapPath); void addMaterial(Material p_material); void addMaterial(std::string p_texturePath, std::string p_normalMapPath, std::string p_specularMap); void setNormalMaps(std::vector<std::string> p_normalMapPaths); void setTextures(std::vector<std::string> p_texturePaths); void setSpecularMap(std::vector<std::string> p_specularMapPaths); void setUseBlendMap(bool p_useBlendMap); std::vector<Vertex> getVertices() const; std::vector<int> getIndices() const; std::string getBlendMapPath() const; std::vector<Material> getMaterials() const; std::vector<std::string> getNormalMapPaths() const; std::vector<std::string> getTexturePaths() const; std::vector<std::string> getSpecularMapPaths() const; int getNumMaterials() const; int getNumVertices() const; int getNumIndices() const; bool getUseBlendMap() const; }; } // namespace Model #endif // MODEL_H
2959d85617b97a343d48f4024abecb23e1e135b4
8288f97bef99ee8df06a56061e28ec5b8bc41091
/Game/SpBuffer.h
592d5363c3cb941f3f9dbb31ace813558248a8f5
[]
no_license
kyotento/KyotEngine
0cd99213b9e71b00ab69c163ad4974df8adc3634
f497fc5c34ec4129ad87bb7f5a4a3165dffc8a8f
refs/heads/master
2021-08-08T01:49:27.325396
2020-07-01T02:13:16
2020-07-01T02:13:16
196,294,097
0
0
null
null
null
null
UTF-8
C++
false
false
69
h
SpBuffer.h
#pragma once class SpBuffer { public: SpBuffer(); ~SpBuffer(); };
a0c0a8abbfa263ebb109407d4bee6d568d35abfb
e0bc31a6904b7b17839c86aff4a8da6d1c202af4
/RobotArm/RAMatrix.h
0e18b657112d15f5eb3d998e59bbf70b853005db
[]
no_license
transonvu/Robot-Arm
901e923e91abad1891c7d089c1715743eae54515
3ac721520d50556c00dea3a0a5166dddfd76ff07
refs/heads/master
2021-01-02T23:09:11.604489
2017-08-18T15:05:03
2017-08-18T15:05:03
99,477,188
0
0
null
null
null
null
UTF-8
C++
false
false
5,428
h
RAMatrix.h
#ifndef RAMATRIX_H #define RAMATRIX_H #include "RAArray.h" template<class T> class RAMatrix { private: RAArray<RAArray<T>> _elements; public: RAMatrix(); RAMatrix(int rows, int cols); RAMatrix(const RAArray<RAArray<T>> &elements); RAMatrix(const RAMatrix<T> &matrix); ~RAMatrix(); RAMatrix operator + (const RAMatrix<T> &matrix); RAMatrix operator - (const RAMatrix<T> &matrix); RAMatrix operator * (double factor); RAMatrix operator * (const RAMatrix<T> &matrix); RAMatrix operator / (double divisor); RAMatrix& operator += (const RAMatrix<T> &matrix); RAMatrix& operator -= (const RAMatrix<T> &matrix); RAMatrix& operator *= (double factor); RAMatrix& operator /= (double divisor); RAMatrix& operator = (const RAArray<RAArray<T>> &elements); RAMatrix& operator = (const RAMatrix<T> &matrix); RAMatrix transpose(); RAArray<T>& operator [] (int index); void resize(int rows, int cols); int rows() const; int cols() const; }; template<class T> RAMatrix<T>::RAMatrix() { _elements.resize(4); for (int i = 0; i < 4; ++i) { _elements[i].resize(4); } } template<class T> RAMatrix<T>::RAMatrix(int rows, int cols) { _elements.resize(rows); for (int i = 0; i < rows; ++i) { _elements[i].resize(cols); } } template<class T> RAMatrix<T>::RAMatrix(const RAArray<RAArray<T>> &elements) { _elements = elements; } template<class T> RAMatrix<T>::RAMatrix(const RAMatrix<T> &matrix) { _elements = matrix._elements; } template<class T> RAMatrix<T>::~RAMatrix() { } template<class T> RAMatrix<T> RAMatrix<T>::operator + (const RAMatrix<T> &matrix) { int nRows = rows(); int nCols = cols(); RAMatrix<T> t(nRows, nCols); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { t._elements[i][j] = _elements[i][j] + matrix._elements[i][j]; } } return t; } template<class T> RAMatrix<T> RAMatrix<T>::operator - (const RAMatrix<T> &matrix) { int nRows = rows(); int nCols = cols(); RAMatrix<T> t(nRows, nCols); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { t._elements[i][j] = _elements[i][j] - matrix._elements[i][j]; } } return t; } template<class T> RAMatrix<T> RAMatrix<T>::operator * (double factor) { int nRows = rows(); int nCols = cols(); RAMatrix<T> t(nRows, nCols); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { t._elements[i][j] = _elements[i][j] * factor; } } return t; } template<class T> RAMatrix<T> RAMatrix<T>::operator * (const RAMatrix<T> &matrix) { int nRows = rows(); int nCols1 = cols(); int nCols2 = matrix.cols(); RAMatrix<T> t(nRows, nCols2); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols2; ++j) { for (int k = 0; k < nCols1; ++k) { t._elements[i][j] += _elements[i][k] * matrix._elements[k][j]; } } } return t; } template<class T> RAMatrix<T> RAMatrix<T>::operator / (double divisor) { int nRows = rows(); int nCols = cols(); RAMatrix<T> t(nRows, nCols); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { t._elements[i][j] = _elements[i][j] / divisor; } } return t; } template<class T> RAMatrix<T>& RAMatrix<T>::operator += (const RAMatrix<T> &matrix) { int nRows = rows(); int nCols = cols(); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { _elements[i][j] += matrix._elements[i][j]; } } return (*this); } template<class T> RAMatrix<T>& RAMatrix<T>::operator -= (const RAMatrix<T> &matrix) { int nRows = rows(); int nCols = cols(); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { _elements[i][j] -= matrix._elements[i][j]; } } return (*this); } template<class T> RAMatrix<T>& RAMatrix<T>::operator *= (double factor) { int nRows = rows(); int nCols = cols(); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { _elements[i][j] *= factor; } } return (*this); } template<class T> RAMatrix<T>& RAMatrix<T>::operator /= (double divisor) { int nRows = rows(); int nCols = cols(); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { _elements[i][j] /= divisor; } } return (*this); } template<class T> RAMatrix<T>& RAMatrix<T>::operator = (const RAArray<RAArray<T>> &elements) { _elements = elements; return (*this); } template<class T> RAMatrix<T>& RAMatrix<T>::operator = (const RAMatrix<T> &matrix) { _elements = matrix._elements; return (*this); } template<class T> RAMatrix<T> RAMatrix<T>::transpose() { int nRows = rows(); int nCols = cols(); RAMatrix<T> t(nCols, nRows); for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { t._elements[j][i] = _elements[i][j]; } } return t; } template<class T> RAArray<T>& RAMatrix<T>::operator [] (int index) { return _elements[index]; } template<class T> void RAMatrix<T>::resize(int rows, int cols) { _elements.resize(rows); for (int i = 0; i < rows; ++i) { _elements[i].resize(cols); } } template<class T> int RAMatrix<T>::rows() const { return _elements.size(); } template<class T> int RAMatrix<T>::cols() const { if (rows() == 0) { return 0; } return _elements[0].size(); } #endif // RAMATRIX_H
63bb12504457d03dbf574b3c32fb7b597ccb9939
56a4cb943d085a672f8b0d08a8c047f772e6a45e
/code/server/GameServer/NoneResponser/OnLogout.h
85fc0422648a100c105438c58bd7e207af76d7e3
[]
no_license
robertveloso/suddenattack_legacy
2016fa21640d9a97227337ac8b2513af7b0ce00b
05ff49cced2ba651c25c18379fed156c58a577d7
refs/heads/master
2022-06-20T05:00:10.375695
2020-05-08T01:46:02
2020-05-08T01:46:02
262,199,345
3
1
null
null
null
null
UTF-8
C++
false
false
321
h
OnLogout.h
#pragma once #include "../INoneResponser.h" namespace GameServer { namespace NoneResponser { class OnLogout { public: typedef ::Dispatcher::IQuery IQUERY; public: OnLogout(); virtual ~OnLogout(); static void OnResponse( IQUERY * i_pQuery ); }; } /* NoneResponser */ } /* GameServer */
ebf7bff0091ccc1c132b9a00eb6d51b502303fd7
9e3400737b89eb30b17ab530ad17258c877d056d
/include/vulcan/voxel.h
a9cfa645f1e59b5eb46e7df087024af9cb4a345a
[]
no_license
mkaspr/Vulcan
972ee2051ae84d69718a6f20c01e4bd6050cebed
8764ac69af15936a48188c5fd9db0383be2b37db
refs/heads/master
2020-03-23T12:11:41.724127
2018-09-03T17:17:48
2018-09-03T17:17:48
141,542,839
1
1
null
null
null
null
UTF-8
C++
false
false
730
h
voxel.h
#pragma once #include <vulcan/device.h> #include <vulcan/matrix.h> namespace vulcan { class Voxel { public: VULCAN_HOST_DEVICE Voxel() { } VULCAN_HOST_DEVICE inline const Vector3f& GetColor() const { return color; } VULCAN_HOST_DEVICE inline void SetColor(const Vector3f& c) { color = c; } VULCAN_HOST_DEVICE static inline Voxel Empty() { Voxel result; result.distance = 1; result.color = Vector3f::Zeros(); result.distance_weight = 0; result.color_weight = 0; return result; } public: float distance; Vector3f color; short distance_weight; short color_weight; }; } // namespace vulcan
c9f85bce9896e4c03d4e135e11414604bd11ac5a
a72b8e5d6f257414e169dee9f4ba0661ce211d44
/game.h
5e5ed0438c83fd2900a936a3efcf8e014c382b74
[]
no_license
satchitns/Splatoon2D
5ad6bded1fce7485236574b4e25b5844b2151e3b
b63e05a30c6be11c750873b66dbbfc69128d5dc8
refs/heads/master
2021-04-09T14:13:12.349174
2018-03-17T01:15:47
2018-03-17T01:15:47
125,585,702
1
0
null
null
null
null
UTF-8
C++
false
false
827
h
game.h
class CGame { public: const char8_t *GetGameTitle(){return mGameTitle;} static CGame *CreateInstance(); static CGame *GetInstance() {return sInstance;}; ~CGame(); void DrawScene(); void UpdateFrame(DWORD milliseconds); void DestroyGame(); void init(); void shutdown(); static const uint32_t mScreenWidth = 1600; static const uint32_t mScreenHeight = 900; static const uint32_t mBitsPerPixel = 32; static const int32_t mViewingVolumeXMax = 569; static const int32_t mViewingVolumeXMin = -569; static const int32_t mViewingVolumeYMax = 320; static const int32_t mViewingVolumeYMin = -320; static const int32_t mViewingVolumeZMax = 100; static const int32_t mViewingVolumeZMin = -100; bool mGameOver; bool mIsInMainMenu; private: static const char8_t mGameTitle[20]; static CGame *sInstance; CGame(){}; };
7ab38ec15285b82f937d1432c4b0e9a7b3429e0a
602e0f4bae605f59d23688cab5ad10c21fc5a34f
/MyToolKit/Stock/CalcHexunResearchPaperQuery.cpp
e775279a50552906ff936259420d8ea232ddf465
[]
no_license
yanbcxf/cpp
d7f26056d51f85254ae1dd2c4e8e459cfefb2fb6
e059b02e7f1509918bbc346c555d42e8d06f4b8f
refs/heads/master
2023-08-04T04:40:43.475657
2023-08-01T14:03:44
2023-08-01T14:03:44
172,408,660
8
5
null
null
null
null
GB18030
C++
false
false
9,663
cpp
CalcHexunResearchPaperQuery.cpp
#include "StdAfx.h" #include "CalcHexunResearchPaperQuery.h" CCalcHexunResearchPaperQuery::CCalcHexunResearchPaperQuery(HWND hwnd, int logType) :CCalculateTask(hwnd, logType) { } CCalcHexunResearchPaperQuery::~CCalcHexunResearchPaperQuery(void) { } void CCalcHexunResearchPaperQuery::Execute1(void* firstArg) { CCalcHexunResearchPaperQuery * sink = (CCalcHexunResearchPaperQuery *)firstArg; sink->Execute(); } void CCalcHexunResearchPaperQuery::Execute() { /*汇总需要下载财务报表的股票*/ stringstream ss; m_vec_code.clear(); m_vec_abbreviation.clear(); m_vec_title.clear(); m_vec_source.clear(); m_vec_url.clear(); m_vec_abstract.clear(); m_vec_grade.clear(); m_vec_initial_year.clear(); m_vec_first_eps.clear(); m_vec_second_eps.clear(); m_vec_third_eps.clear(); m_vec_recent_close.clear(); try{ ////////////////////////////////////////////////////////////////////////// /*查询总的记录数*/ { ss.str(""); ss << "SELECT count(*) as cnt " << "FROM hexun_research_paper b " << "where 1=1 " ; if(m_vec_request_code.size()>0) { ss << " and code in ( "; for(int i=0; i< m_vec_request_code.size(); i++) { ss << m_vec_request_code[i]; if(i<m_vec_request_code.size()-1) ss << ","; } ss << ")"; } if(m_after_report_date.empty()==false) { ss << " and report_date >= \'" << m_after_report_date << "\' " ; } if(m_request_like.empty()==false) { ss << " and abstract like \'%" << m_request_like << "%\' "; } ss << " ORDER BY report_date desc"; string test = ss.str(); //test = Gbk2Utf8(test); int cnt; session sql(g_MysqlPool); sql << test, into(cnt); m_max_page = cnt /1000; if(cnt%1000 >0) m_max_page++; } if(m_page_no>m_max_page) m_page_no = m_max_page; if(m_page_no<1) m_page_no =1; ////////////////////////////////////////////////////////////////////////// ss.str(""); ss << "SELECT b.code, (select max(a.abbreviation) from stockinfo a where a.code = b.code ) as abbreviation ," << "b.report_date, b.title, b.source, b.grade, b.url, b.abstract, " << "b.initial_year, b.first_eps, b.second_eps, b.third_eps, " << " (select e.close from netease_trade_daily e where " << " e.code = b.code and e.TradeDate = (select max(d.TradeDate) " << " from netease_trade_daily d where b.code = d.code )) as recent_close " << "FROM hexun_research_paper b " << "where 1=1 " ; if(m_vec_request_code.size()>0) { ss << " and code in ( "; for(int i=0; i< m_vec_request_code.size(); i++) { ss << m_vec_request_code[i]; if(i<m_vec_request_code.size()-1) ss << ","; } ss << ")"; } if(m_after_report_date.empty()==false) { ss << " and report_date >= \'" << m_after_report_date << "\' " ; } if(m_request_like.empty()==false) { ss << " and abstract like \'%" << m_request_like << "%\' "; } ss << " ORDER BY report_date desc "; ss << " limit " << ((m_page_no - 1) * 1000) << ", 1000"; string test = ss.str(); //test = Gbk2Utf8(test); session sql(g_MysqlPool); row r; statement st = (sql.prepare << test,into(r)) ; st.execute(); vector<int> vecCalculateEps; int cnt = 0; while (st.fetch()) { int code = r.get<int>("code"); m_vec_code.insert(m_vec_code.end(), code); m_vec_abbreviation.insert(m_vec_abbreviation.end(), /*Utf8_GBK*/( r.get<string>("abbreviation"))); try { std::tm tm = r.get<std::tm>("report_date"); ss.str(""); ss << (tm.tm_year + 1900) << "-" << (tm.tm_mon + 1) << "-" << tm.tm_mday ; m_vec_report_date.insert(m_vec_report_date.end(), ss.str()); } catch(...) { m_vec_report_date.insert(m_vec_report_date.end(), ""); } m_vec_title.insert(m_vec_title.end(), /*Utf8_GBK*/( r.get<string>("title"))); m_vec_source.insert(m_vec_source.end(), /*Utf8_GBK*/( r.get<string>("source"))); m_vec_grade.insert(m_vec_grade.end(), /*Utf8_GBK*/( r.get<string>("grade"))); m_vec_url.insert(m_vec_url.end(), /*Utf8_GBK*/( r.get<string>("url"))); m_vec_abstract.insert(m_vec_abstract.end(), /*Utf8_GBK*/( r.get<string>("abstract"))); try { m_vec_initial_year.insert(m_vec_initial_year.end(), r.get<int>("initial_year")); } catch(...) { m_vec_initial_year.insert(m_vec_initial_year.end(), 0); vecCalculateEps.push_back(cnt); } try { m_vec_first_eps.insert(m_vec_first_eps.end(), r.get<double>("first_eps")); } catch(...) { m_vec_first_eps.insert(m_vec_first_eps.end(), 0); } try { m_vec_second_eps.insert(m_vec_second_eps.end(), r.get<double>("second_eps")); } catch(...) { m_vec_second_eps.insert(m_vec_second_eps.end(), 0); } try { m_vec_third_eps.insert(m_vec_third_eps.end(), r.get<double>("third_eps")); } catch(...) { m_vec_third_eps.insert(m_vec_third_eps.end(), 0); } try { m_vec_recent_close.insert(m_vec_recent_close.end(), r.get<double>("recent_close")); } catch(...) { m_vec_recent_close.insert(m_vec_recent_close.end(), 0); } cnt++; } /*从研报中抽取 EPS (每股收益)*/ for(int i=0; i<vecCalculateEps.size(); i++) { int k = vecCalculateEps[i]; string val; vector<string> firstMatch; int nLastPosition; string str1 = FindLastString(m_vec_abstract[k],"每股收益分别", nLastPosition); if(str1.empty()) str1 = FindLastString(m_vec_abstract[k],"每股收益为", nLastPosition); if(str1.empty()) str1 = FindLastString(m_vec_abstract[k],"EPS分别", nLastPosition); if(str1.empty()) str1 = FindLastString(m_vec_abstract[k],"EPS", nLastPosition); if(str1.empty()) str1 = FindLastString(m_vec_abstract[k],"eps", nLastPosition); if(str1.empty()==false) { val = str1.substr(0,64); val = ReplaceString(val, "元/股", "/"); val = ReplaceString(val, "、", "/"); val = ReplaceString(val, "和", "/"); val = ReplaceString(val, "及", "/"); val = ReplaceString(val, "与", "/"); val = ReplaceString(val, ",", "/"); val = ReplaceString(val, "元", "/"); string left = ""; firstMatch.clear(); if(Pcre2Grep(_T("[\\d\\.\\-]+[元]?/+[\\d\\.\\-]+[元]?/+[\\d\\.\\-]+[元]?"), val.c_str(), firstMatch )>0) { val = firstMatch[0]; left = m_vec_abstract[k].substr(0, nLastPosition); } else if(Pcre2Grep(_T("[\\d\\.\\-]+[元]?/+[\\d\\.\\-]+[元]?"), val.c_str(), firstMatch )>0) { val = firstMatch[0]; left = m_vec_abstract[k].substr(0, nLastPosition); } else val = ""; if(left.empty()==false) { string left1 = ReplaceString(left, "。", "!@#$"); left1 = ReplaceString(left1, "预计", "!@#$"); left1 = FindLastString(left1,"!@#$", nLastPosition); if(left1.empty()==false) left = left1; left = ReplaceString(left, "~", "_"); left = ReplaceString(left, "、", "_"); left = ReplaceString(left, ",", "_"); left = ReplaceString(left, "/", "_"); left = ReplaceString(left, "-", "_"); left = ReplaceString(left, "~", "_"); left = ReplaceString(left, "年", "_"); firstMatch.clear(); if(Pcre2Grep(_T("[\\d]{2,}[_]{1}"), left.c_str(), firstMatch )>0) { val = (firstMatch[0].length()>=4 ? firstMatch[0] : ("20" + firstMatch[0])) + ":" + val; } } } else { val = ""; } if(val.empty()==false) { val = ReplaceString(val, "_", ""); val = ReplaceString(val, "///", "/"); val = ReplaceString(val, "//", "/"); firstMatch.clear(); if(Pcre2Split(_T("[\\:]+"), val.c_str(), firstMatch )>0) { m_vec_initial_year[k] = atoi(firstMatch[0].c_str()); val = firstMatch[1]; } firstMatch.clear(); if(Pcre2Split(_T("[/]+"), val.c_str(), firstMatch )>0) { if(firstMatch.size()>=1) m_vec_first_eps[k] = String2Double(firstMatch[0]); if(firstMatch.size()>=2) m_vec_second_eps[k] = String2Double(firstMatch[1]); if(firstMatch.size()>=3) m_vec_third_eps[k] = String2Double(firstMatch[2]); } /*保存到数据库中*/ if(m_vec_initial_year[k]>0) { session sql(g_MysqlPool); ss.str(""); ss << "update hexun_research_paper set initial_year= " << Int2String(m_vec_initial_year[k]); ss << ", first_eps=" << Double2String(m_vec_first_eps[k]); ss << ", second_eps=" << Double2String(m_vec_second_eps[k]); ss << ", third_eps=" << Double2String(m_vec_third_eps[k]); ss << " where report_date=\'" << m_vec_report_date[k] << "\' " << " and title=\'" << m_vec_title[k] << "\' " << " and Code=" << Int2String(m_vec_code[k]) << " "; string test = ss.str(); //test = Gbk2Utf8(test); sql << test; } } } /*计算今年研报预测的 pe 值*/ COleDateTime t = COleDateTime::GetCurrentTime(); m_vec_today_pe.clear(); int nowYear = t.GetYear(); for(int i=0; i< m_vec_code.size(); i++) { if(m_vec_initial_year[i]==nowYear && m_vec_first_eps[i]>0) { m_vec_today_pe.insert(m_vec_today_pe.end(), m_vec_recent_close[i]/m_vec_first_eps[i]); } else if(m_vec_initial_year[i]==nowYear-1 && m_vec_second_eps[i]>0) { m_vec_today_pe.insert(m_vec_today_pe.end(), m_vec_recent_close[i]/m_vec_second_eps[i]); } else { m_vec_today_pe.insert(m_vec_today_pe.end(), 3000); } } ss.str(""); ss << "和讯研报查询完成"; sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType); } catch(std::exception const & e) { ss.str(""); ss << e.what() << ' \r\n'; sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType); } }
f57626689e95e472c0e11a226058c68331e58291
62f123ea5277a3c309987acec9c653827c14b83b
/Genie2Rat/genie2rat.cc
8c8d53af6e80652bae3e1704bd0fc0186b54a671
[]
no_license
kalpanasingh/rat-tools
a0a2236f0193927d422e373ea9abff5761665a9c
788ba2af58375fd72d21a3e29b63f7246471fd2c
refs/heads/master
2021-01-11T13:28:48.139541
2017-02-09T16:59:29
2017-02-09T16:59:29
81,473,659
1
0
null
null
null
null
UTF-8
C++
false
false
5,202
cc
genie2rat.cc
// takes the output of gevgen_atmo and creates a RAT root file // // genie2rat -i [input genie filename] -o [output root filename] (-n [number of events to process]) #include <string> #include <TSystem.h> #include <TFile.h> #include <TTree.h> #include <TIterator.h> #include <TVector3.h> #include "EVGCore/EventRecord.h" #include "GHEP/GHepParticle.h" #include "Ntuple/NtpMCFormat.h" #include "Ntuple/NtpMCTreeHeader.h" #include "Ntuple/NtpMCEventRecord.h" #include "Messenger/Messenger.h" #include "PDG/PDGCodes.h" #include "Utils/CmdLnArgParser.h" #include <RAT/DS/Entry.hh> #include <RAT/DS/MC.hh> #include <RAT/DS/MCParticle.hh> using std::string; using namespace genie; void GetCommandLineArgs (int argc, char ** argv); int gOptNEvt; string gOptInpFilename; string gOptOutFilename; int main(int argc, char ** argv) { GetCommandLineArgs (argc, argv); //-- open the ROOT file and get the TTree & its header TTree * tree = 0; NtpMCTreeHeader * thdr = 0; TFile file(gOptInpFilename.c_str(),"READ"); tree = dynamic_cast <TTree *> ( file.Get("gtree") ); thdr = dynamic_cast <NtpMCTreeHeader *> ( file.Get("header") ); if(!tree) return 1; NtpMCEventRecord * mcrec = 0; tree->SetBranchAddress("gmcrec", &mcrec); int nev = (gOptNEvt > 0) ? TMath::Min(gOptNEvt, (int)tree->GetEntries()) : (int) tree->GetEntries(); // set up output file TFile *outfile = new TFile(gOptOutFilename.c_str(),"RECREATE"); TTree *outtree = new TTree("T","RAT Tree"); RAT::DS::Entry branchDS; outtree->Branch("ds",branchDS.ClassName(),&branchDS,32000,99); // // Loop over all events // double time = 0; for(int i = 0; i < nev; i++) { // get next tree entry tree->GetEntry(i); // get the GENIE event EventRecord & event = *(mcrec->event); double x = 1000.0*event.Vertex()->X(); // distances from GENIE are in meters double y = 1000.0*event.Vertex()->Y(); // distances from GENIE are in meters double z = 1000.0*event.Vertex()->Z(); // distances from GENIE are in meters RAT::DS::Entry ds; RAT::DS::MC mc; mc.SetMCTime(time); // GENIE does not give global time, so we just add arbitrary times for RAT mc.SetMCID(i); // // Loop over all particles in this event // GHepParticle * p = 0; TIter event_iter(&event); while((p=dynamic_cast<GHepParticle *>(event_iter.Next()))) { // check if it is the initial state neutrino if (p->Status() == kIStInitialState && (p->Pdg() == kPdgNuE || p->Pdg() == kPdgAntiNuE || p->Pdg() == kPdgNuMu || p->Pdg() == kPdgAntiNuMu || p->Pdg() == kPdgNuTau || p->Pdg() == kPdgAntiNuTau)){ RAT::DS::MCParticle parent; parent.SetPDGCode(p->Pdg()); parent.SetTime(0); // GENIE does not give particles time separate from event parent.SetPosition(TVector3(x,y,z)); // GENIE outputs particle distance from event in fm, basically 0 parent.SetMomentum(TVector3(1000.0*p->Px(),1000.0*p->Py(),1000.0*p->Pz())); // GENIE outputs momentum and energy in GeV parent.SetKineticEnergy(1000.0*p->KinE()); mc.AddMCParent(parent); } if (p->Status() == kIStStableFinalState){ // skip if it is a GENIE special particle (final state unsimulated hadronic energy etc) if (p->Pdg() > 2000000000){ continue; } RAT::DS::MCParticle particle; particle.SetPDGCode(p->Pdg()); particle.SetTime(0); // GENIE does not give particles time separate from event particle.SetPosition(TVector3(x,y,z)); // GENIE outputs particle distance from event in fm, basically 0 particle.SetMomentum(TVector3(1000.0*p->Px(),1000.0*p->Py(),1000.0*p->Pz())); // GENIE outputs momentum and energy in GeV particle.SetKineticEnergy(1000.0*p->KinE()); mc.AddMCParticle(particle); } }// end loop over particles // clear current mc event record ds.SetMC(mc); mcrec->Clear(); branchDS = ds; outtree->Fill(); time += 1e9; // GENIE does not calculate time of events so we arbitrarily add a second }//end loop over events // close input GHEP event file file.Close(); outfile->Write(); outfile->Close(); LOG("genie2rat", pNOTICE) << "Done!"; return 0; } void GetCommandLineArgs(int argc, char ** argv) { LOG("genie2rat", pINFO) << "Parsing commad line arguments"; CmdLnArgParser parser(argc,argv); // get GENIE event sample if( parser.OptionExists('i') ) { LOG("genie2rat", pINFO) << "Reading event sample filename"; gOptInpFilename = parser.ArgAsString('i'); } else { LOG("genie2rat", pFATAL) << "Unspecified input filename - Exiting"; exit(1); } if ( parser.OptionExists('o') ) { gOptOutFilename = parser.ArgAsString('o'); } else{ gOptOutFilename = "output.ntuple.root"; } // number of events to analyse if( parser.OptionExists('n') ) { LOG("genie2rat", pINFO) << "Reading number of events to analyze"; gOptNEvt = parser.ArgAsInt('n'); } else { LOG("genie2rat", pINFO) << "Unspecified number of events to analyze - Use all"; gOptNEvt = -1; } }
5a54b29468be5c5d1f92baf738311e21c70866be
52fa059909244a18d6a214a0ea35732395551e03
/core/include/hammer/core/cmdline_builder.h
269dbe9631010aea07384f32580126d6f8360f27
[]
no_license
tee3/hammer
5c956c53f2a8c2f708aa063f1450c98ffbc42227
ce24aeea840b9789f7482736e335b3a2f3cc2710
refs/heads/master
2021-01-19T17:13:00.279968
2019-01-13T19:19:19
2019-01-26T13:43:08
82,438,939
0
0
null
2017-02-19T06:01:22
2017-02-19T06:01:22
null
UTF-8
C++
false
false
954
h
cmdline_builder.h
#pragma once #include <string> #include <vector> #include <memory> #include <map> #include <boost/shared_ptr.hpp> namespace hammer { class build_environment; class argument_writer; class feature; class build_node; class cmdline_builder { public: typedef std::map<const std::string, boost::shared_ptr<argument_writer> > writers_t; cmdline_builder(const std::string& cmd); template<typename T> cmdline_builder& operator +=(boost::shared_ptr<T>& v) { add(v); return *this; } void write(std::ostream& output, const build_node& node, const build_environment& environment) const; const writers_t& writers() const { return writers_; } void writers(const writers_t& w) { writers_ = w; } std::vector<const feature*> valuable_features() const; private: std::string cmd_; writers_t writers_; void add(const boost::shared_ptr<argument_writer>& v); }; }
d13eab34790a3fb7ccda80db4532c097105512ab
6567133acef4548343303613b54d2e4c09d9ba50
/samples/Hello/third-party/fuzzylite/fuzzylite/src/Complexity.cpp
8a91c60ae1910fe412963e168099b32bd7a0cad4
[ "GPL-3.0-only", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
okocsis/ios-cmake
3939f8bd764c96bdf0c9d27537fbb6f314b215ea
ca61d83725bc5b1a755928f4592badbd9a8b37f4
refs/heads/master
2020-05-31T16:28:31.115578
2019-06-10T14:11:50
2019-06-10T14:11:50
190,382,466
0
0
BSD-3-Clause
2019-06-05T11:29:58
2019-06-05T11:29:58
null
UTF-8
C++
false
false
9,035
cpp
Complexity.cpp
/* fuzzylite (R), a fuzzy logic control library in C++. Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved. Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com> This file is part of fuzzylite. fuzzylite is free software: you can redistribute it and/or modify it under the terms of the FuzzyLite License included with the software. You should have received a copy of the FuzzyLite License along with fuzzylite. If not, see <http://www.fuzzylite.com/license/>. fuzzylite is a registered trademark of FuzzyLite Limited. */ #include "fl/Complexity.h" #include "fl/Engine.h" #include "fl/variable/InputVariable.h" #include "fl/variable/OutputVariable.h" #include "fl/rule/RuleBlock.h" #include "fl/rule/Rule.h" namespace fl { Complexity::Complexity(scalar all) : _comparison(all), _arithmetic(all), _function(all) { } Complexity::Complexity(scalar comparison, scalar arithmetic, scalar function) : _comparison(comparison), _arithmetic(arithmetic), _function(function) { } Complexity::~Complexity() { } Complexity& Complexity::operator+=(const Complexity& other) { return this->plus(other); } Complexity& Complexity::operator-=(const Complexity& other) { return this->minus(other); } Complexity& Complexity::operator*=(const Complexity& other) { return this->multiply(other); } Complexity& Complexity::operator/=(const Complexity& other) { return this->divide(other); } Complexity Complexity::operator+(const Complexity& rhs) const { return Complexity(*this).plus(rhs); } Complexity Complexity::operator-(const Complexity& rhs) const { return Complexity(*this).minus(rhs); } Complexity Complexity::operator*(const Complexity& rhs) const { return Complexity(*this).multiply(rhs); } Complexity Complexity::operator/(const Complexity& rhs) const { return Complexity(*this).divide(rhs); } bool Complexity::operator==(const Complexity& rhs) const { return equals(rhs); } bool Complexity::operator!=(const Complexity& rhs) const { return not equals(rhs); } bool Complexity::operator<(const Complexity& rhs) const { return lessThan(rhs); } bool Complexity::operator<=(const Complexity& rhs) const { return lessThanOrEqualsTo(rhs); } bool Complexity::operator>(const Complexity& rhs) const { return greaterThan(rhs); } bool Complexity::operator>=(const Complexity& rhs) const { return greaterThanOrEqualsTo(rhs); } Complexity& Complexity::plus(const Complexity& other) { this->_arithmetic += other._arithmetic; this->_comparison += other._comparison; this->_function += other._function; return *this; } Complexity& Complexity::plus(scalar x) { return this->plus(Complexity().arithmetic(x).comparison(x).function(x)); } Complexity& Complexity::minus(const Complexity& other) { this->_comparison -= other._comparison; this->_arithmetic -= other._arithmetic; this->_function -= other._function; return *this; } Complexity& Complexity::minus(scalar x) { return this->minus(Complexity().arithmetic(x).comparison(x).function(x)); } Complexity& Complexity::multiply(const Complexity& other) { this->_comparison *= other._comparison; this->_arithmetic *= other._arithmetic; this->_function *= other._function; return *this; } Complexity& Complexity::multiply(scalar x) { return this->multiply(Complexity().arithmetic(x).comparison(x).function(x)); } Complexity& Complexity::divide(const Complexity& other) { this->_comparison /= other._comparison; this->_arithmetic /= other._arithmetic; this->_function /= other._function; return *this; } Complexity& Complexity::divide(scalar x) { return this->divide(Complexity().arithmetic(x).comparison(x).function(x)); } bool Complexity::equals(const Complexity& x, scalar macheps) const { return Op::isEq(_comparison, x._comparison, macheps) and Op::isEq(_arithmetic, x._arithmetic, macheps) and Op::isEq(_function, x._function, macheps); } bool Complexity::lessThan(const Complexity& x, scalar macheps) const { return Op::isLt(_comparison, x._comparison, macheps) and Op::isLt(_arithmetic, x._arithmetic, macheps) and Op::isLt(_function, x._function, macheps); } bool Complexity::lessThanOrEqualsTo(const Complexity& x, scalar macheps) const { return Op::isLE(_comparison, x._comparison, macheps) and Op::isLE(_arithmetic, x._arithmetic, macheps) and Op::isLE(_function, x._function, macheps); } bool Complexity::greaterThan(const Complexity& x, scalar macheps) const { return Op::isGt(_comparison, x._comparison, macheps) and Op::isGt(_arithmetic, x._arithmetic, macheps) and Op::isGt(_function, x._function, macheps); } bool Complexity::greaterThanOrEqualsTo(const Complexity& x, scalar macheps) const { return Op::isGE(_comparison, x._comparison, macheps) and Op::isGE(_arithmetic, x._arithmetic, macheps) and Op::isGE(_function, x._function, macheps); } Complexity& Complexity::comparison(scalar comparison) { this->_comparison += comparison; return *this; } void Complexity::setComparison(scalar comparison) { this->_comparison = comparison; } scalar Complexity::getComparison() const { return _comparison; } Complexity& Complexity::arithmetic(scalar arithmetic) { this->_arithmetic += arithmetic; return *this; } void Complexity::setArithmetic(scalar arithmetic) { this->_arithmetic = arithmetic; } scalar Complexity::getArithmetic() const { return _arithmetic; } Complexity& Complexity::function(scalar trigonometric) { this->_function += trigonometric; return *this; } void Complexity::setFunction(scalar trigonometric) { this->_function = trigonometric; } scalar Complexity::getFunction() const { return _function; } std::vector<Complexity::Measure> Complexity::measures() const { std::vector<Measure> result; result.push_back(Measure("arithmetic", _arithmetic)); result.push_back(Measure("comparison", _comparison)); result.push_back(Measure("function", _function)); return result; } scalar Complexity::sum() const { return _arithmetic + _comparison + _function; } scalar Complexity::norm() const { return std::sqrt(Complexity(*this).multiply(*this).sum()); } std::string Complexity::toString() const { std::vector<std::string> result; result.push_back("a=" + Op::str(_arithmetic)); result.push_back("c=" + Op::str(_comparison)); result.push_back("f=" + Op::str(_function)); return "C[" + Op::join(result, ", ") + "]"; } Complexity Complexity::compute(const Engine* engine) const { return engine->complexity(); } Complexity Complexity::compute(const InputVariable* inputVariable) const { return inputVariable->complexity(); } Complexity Complexity::compute(const OutputVariable* outputVariable) const { return outputVariable->complexity(); } Complexity Complexity::compute(const RuleBlock* ruleBlock) const { return ruleBlock->complexity(); } Complexity Complexity::compute(const std::vector<InputVariable*>& inputVariables) const { Complexity result; for (std::size_t i = 0; i < inputVariables.size(); ++i) { result += inputVariables.at(i)->complexity(); } return result; } Complexity Complexity::compute(const std::vector<OutputVariable*>& outputVariables, bool complexityOfDefuzzification) const { Complexity result; for (std::size_t i = 0; i < outputVariables.size(); ++i) { if (complexityOfDefuzzification) result += outputVariables.at(i)->complexityOfDefuzzification(); else result += outputVariables.at(i)->complexity(); } return result; } Complexity Complexity::compute(const std::vector<Variable*>& variables) const { Complexity result; for (std::size_t i = 0; i < variables.size(); ++i) { result += variables.at(i)->complexity(); } return result; } Complexity Complexity::compute(const std::vector<RuleBlock*>& ruleBlocks) const { Complexity result; for (std::size_t i = 0; i < ruleBlocks.size(); ++i) { result += ruleBlocks.at(i)->complexity(); } return result; } }
a55358dc35762bc86f32304b56294306b57822a5
a2438cca3a3a743ab08089c24aed1b6b1e00f84c
/leetcode/83.cpp
0002c82fabc07fda4b9a61cd24dd2917374101a6
[ "Apache-2.0" ]
permissive
Moonshile/AlgorithmCandy
a3a8e3bbc2adbbe474d3934f40249e3ee692cd7e
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
refs/heads/master
2020-04-12T12:50:41.370625
2016-11-26T02:54:29
2016-11-26T02:54:29
25,446,167
2
3
null
null
null
null
UTF-8
C++
false
false
584
cpp
83.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* i = head, *j = head ? head->next : nullptr, *tmp; while (j) { while (j && j->val == i->val) { tmp = j; j = j->next; delete tmp; } i->next = j; i = j; j = j ? j->next : nullptr; } return head; } };
4b1dc912b685fd056122d6f9fa2510e574416356
52437ba11fca0e060373c2997cd86b0491427453
/BOJ/cpp/2206(fail).cpp
34748fc4c0727083c68ab4c58e37d8555b7f8d3f
[]
no_license
rheehot/Algorithm-57
6e0eedf264bc1e96352654294c78914c22ac0d7f
dd70f5083da0460ecb533dcbf97bc4acd18ce5de
refs/heads/master
2023-07-20T13:34:42.199950
2021-09-03T06:16:53
2021-09-03T06:16:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,624
cpp
2206(fail).cpp
/* 문제 N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 당신은 (1, 1)에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로로 이동하려 한다. 최단경로는 맵에서 가장 적은 개수의 칸을 지나는 경로를 말하는데, 이때 시작하는 칸과 끝나는 칸도 포함해서 센다. 만약에 이동하는 도중에 한 개의 벽을 부수고 이동하는 것이 좀 더 경로가 짧아진다면, 벽을 한 개 까지 부수고 이동하여도 된다. 한 칸에서 이동할 수 있는 칸은 상하좌우로 인접한 칸이다. 맵이 주어졌을 때, 최단 경로를 구해 내는 프로그램을 작성하시오. 입력 첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 1,000)이 주어진다. 다음 N개의 줄에 M개의 숫자로 맵이 주어진다. (1, 1)과 (N, M)은 항상 0이라고 가정하자. 출력 첫째 줄에 최단 거리를 출력한다. 불가능할 때는 -1을 출력한다. */ #include <iostream> #include <queue> #include <vector> #include <algorithm> #include <string> #define MAX 1001 using namespace std; int n,m; string line; int graph[MAX][MAX]; bool visited[MAX][MAX][2]; int dy[4]={0,1,0,-1}; int dx[4]={1,0,-1,0}; void Input(){ cin>>n>>m; for(int i=0; i<n; i++){ cin>>line; for(int j=0; j<m; j++){ graph[i][j]=line[j]-'0'; } } } int BFS(){ queue<pair<pair<int, int>, pair<int, int>>> q; q.push(make_pair(make_pair(0, 0), make_pair(0, 1))); visited[0][0][0]=true; while(!q.empty()){ int y=q.front().first.first; int x=q.front().first.second; int block=q.front().second.first; int cnt=q.front().second.second; q.pop(); if(y==n-1&&x==m-1) return cnt; for(int i=0; i<4; i++){ int ny=dy[i]+y; int nx=dx[i]+x; if(ny>=0&&nx>=0&&ny<n&&nx<m){ if(graph[ny][nx]==1&&block==0){ visited[ny][nx][block+1]=true; q.push(make_pair(make_pair(ny,nx), make_pair(block+1, cnt+1))); } else if(graph[ny][nx]==0&&!visited[ny][nx][block]){ visited[ny][nx][block]=true; q.push(make_pair(make_pair(ny, nx), make_pair(block, cnt+1))); } } } } return -1; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); Input(); cout<<BFS()<<endl; return 0; }
9790e6a2e91f03805e800db9f0d2d4457f73b99d
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/TopQuarkAnalysis/TopObjectResolutions/interface/MET.h
6cc2130222e4ca022c8540fb409b5fe46fdad7d2
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
1,497
h
MET.h
#ifndef TopObjetcResolutionsMET_h #define TopObjetcResolutionsMET_h #include <cmath> namespace res { class HelperMET { public: HelperMET(){}; ~HelperMET(){}; inline double met(double met); inline double a(double pt); inline double b(double pt); inline double c(double pt); inline double d(double pt); inline double theta(double pt); inline double phi(double pt); inline double et(double pt); inline double eta(double pt); }; } // namespace res inline double res::HelperMET::met(double met) { return 1.14 * exp(-2.16e-3 * met) + 0.258; } inline double res::HelperMET::a(double pt) { double res = 0.241096 + 0.790046 * exp(-(0.0248773 * pt)); return res; } inline double res::HelperMET::b(double pt) { double res = -141945 + 141974 * exp(-(-1.20077e-06 * pt)); return res; } inline double res::HelperMET::c(double pt) { double res = 21.5615 + 1.13958 * exp(-(-0.00921408 * pt)); return res; } inline double res::HelperMET::d(double pt) { double res = 0.376192 + 15.2485 * exp(-(0.116907 * pt)); return res; } inline double res::HelperMET::theta(double pt) { double res = 1000000.; return res; } inline double res::HelperMET::phi(double pt) { double res = 0.201336 + 1.53501 * exp(-(0.0216707 * pt)); return res; } inline double res::HelperMET::et(double pt) { double res = 11.7801 + 0.145218 * pt; return res; } inline double res::HelperMET::eta(double pt) { double res = 1000000.; return res; } #endif
069b5e93d06f560cc885600410a90c2da2bb7572
ebac271d0e182b899bf0c50591df54feda29b10b
/src/signalhandler.cpp
8b1ac4d6ad7761c629eddcb0b9a0b903b7cf6c11
[ "MIT" ]
permissive
w545029118/telematics-api
1c4c11b2ade02ccb3e20e8ccd14ed095726779eb
f967bc845cf8384d87ec1dc419cf5e3eb0bc0609
refs/heads/main
2023-03-11T05:27:53.919568
2021-02-27T22:23:51
2021-02-27T22:23:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
89,973
cpp
signalhandler.cpp
/*! \license * * MIT License * * 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. * * \copyright 2021 Dan Fernández * * \file Class definition for \p SignalHandler. * * \author fdaniel, trice2 */ #include "signalhandler.hpp" #include "picosha2.h" using namespace std::placeholders; /*! * List of all signals sent in the payload of the TCM_LM PDU */ lm_signal_t TCM_lm_t[] = { // 1 {TCM_LM::AppCalcCheck, "AppCalcCheck", 0, 0, 16}, {TCM_LM::LMDviceAliveCntRMT, "LMDviceAliveCntRMT", 0, 0, 4}, {TCM_LM::ManeuverEnableInput, "ManeuverEnableInput", 0, 0, 2}, {TCM_LM::ManeuverGearSelect, "ManeuverGearSelect", 0, 0, 2}, {TCM_LM::NudgeSelect, "NudgeSelect", 0, 0, 2}, {TCM_LM::RCDOvrrdReqRMT, "RCDOvrrdReqRMT", 0, 0, 2}, {TCM_LM::AppSliderPosY, "AppSliderPosY", 0, 0, 12}, {TCM_LM::AppSliderPosX, "AppSliderPosX", 0, 0, 11}, {TCM_LM::RCDSpeedChngReqRMT, "RCDSpeedChngReqRMT", 0, 0, 6}, {TCM_LM::RCDSteWhlChngReqRMT, "RCDSteWhlChngReqRMT", 0, 0, 10}, // 11 {TCM_LM::ConnectionApproval, "ConnectionApproval", 0, 0, 2}, {TCM_LM::ManeuverButtonPress, "ManeuverButtonPress", 0, 0, 3}, {TCM_LM::DeviceControlMode, "DeviceControlMode", 0, 0, 4}, {TCM_LM::ManeuverTypeSelect, "ManeuverTypeSelect", 0, 0, 2}, {TCM_LM::ManeuverDirectionSelect, "ManeuverDirectionSelect", 0, 0, 2}, {TCM_LM::ExploreModeSelect, "ExploreModeSelect", 0, 0, 1}, {TCM_LM::RemoteDeviceBatteryLevel, "RemoteDeviceBatteryLevel", 0, 0, 7}, {TCM_LM::PairedWKeyId, "PairedWKeyId", 0, 0, 8}, {TCM_LM::ManeuverSideSelect, "ManeuverSideSelect", 0, 0, 2}, {TCM_LM::LMDviceRngeDistRMT, "LMDviceRngeDistRMT", 0, 0, 10}, // 21 {TCM_LM::TTTTTTTTTT, "TTTTTTTTTT", 0, 0, 4}, {TCM_LM::LMRemoteChallengeVDC, "LMRemoteChallengeVDC", 0, 0, 64}, {TCM_LM::MobileChallengeReply, "MobileChallengeReply", 0, 0, 64}, {TCM_LM::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_LM_Session PDU */ lm_signal_t TCM_lm_session_t[] = { // 1 {TCM_LM_Session::LMEncrptSessionCntVDC_1, "LMEncrptSessionCntVDC_1", 0, 0, 64}, {TCM_LM_Session::LMEncrptSessionCntVDC_2, "LMEncrptSessionCntVDC_2", 0, 0, 64}, {TCM_LM_Session::LMEncryptSessionIDVDC_1, "LMEncryptSessionIDVDC_1", 0, 0, 64}, {TCM_LM_Session::LMEncryptSessionIDVDC_2, "LMEncryptSessionIDVDC_2", 0, 0, 64}, {TCM_LM_Session::LMTruncMACVDC, "LMTruncMACVDC", 0, 0, 64}, {TCM_LM_Session::LMTruncSessionCntVDC, "LMTruncSessionCntVDC", 0, 0, 8}, {TCM_LM_Session::LMSessionControlVDC, "LMSessionControlVDC", 0, 0, 3}, {TCM_LM_Session::LMSessionControlVDCExt, "LMSessionControlVDCExt", 0, 0, 5}, {TCM_LM_Session::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_RemoteControl PDU */ lm_signal_t TCM_remotecontrol_t[] = { {TCM_RemoteControl::TCMRemoteControl, "TCMRemoteControl", 0, 0, 64}, {TCM_RemoteControl::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_TransportKey PDU */ lm_signal_t TCM_transportkey_t[] = { {TCM_TransportKey::LMSessionKeyIDVDC, "LMSessionKeyIDVDC", 0, 0, 16}, {TCM_TransportKey::LMHashEnTrnsportKeyVDC, "LMHashEnTrnsportKeyVDC", 0, 0, 16}, {TCM_TransportKey::LMEncTransportKeyVDC_1, "LMEncTransportKeyVDC_1", 0, 0, 64}, {TCM_TransportKey::LMEncTransportKeyVDC_2, "LMEncTransportKeyVDC_2", 0, 0, 64}, {TCM_TransportKey::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_LM_App PDU */ lm_signal_t TCM_lm_app_t[] = { {TCM_LM_App::LMAppTimeStampRMT, "LMAppTimeStampRMT", 0, 0, 64}, {TCM_LM_App::AppAccelerationX, "AppAccelerationX", 0, 0, 64}, {TCM_LM_App::AppAccelerationY, "AppAccelerationY", 0, 0, 64}, {TCM_LM_App::AppAccelerationZ, "AppAccelerationZ", 0, 0, 64}, {TCM_LM_App::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_LM_KeyID PDU */ lm_signal_t TCM_lm_keyid_t[] = { {TCM_LM_KeyID::NOT_USED_ONE_BIT, "NOT_USED_ONE_BIT", 0, 0, 1}, {TCM_LM_KeyID::LMRotKeyChkACKVDC, "LMRotKeyChkACKVDC", 0, 0, 3}, {TCM_LM_KeyID::LMSessionKeyIDVDCExt, "LMSessionKeyIDVDCExt", 0, 0, 4}, {TCM_LM_KeyID::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_LM_KeyAlpha PDU */ lm_signal_t TCM_lm_keyalpha_t[] = { {TCM_LM_KeyAlpha::LMHashEnRotKeyAlphaVDC, "LMHashEnRotKeyAlphaVDC", 0, 0, 16}, {TCM_LM_KeyAlpha::LMEncRotKeyAlphaVDC_1, "LMEncRotKeyAlphaVDC_1", 0, 0, 64}, {TCM_LM_KeyAlpha::LMEncRotKeyAlphaVDC_2, "LMEncRotKeyAlphaVDC_2", 0, 0, 64}, {TCM_LM_KeyAlpha::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_LM_KeyBeta PDU */ lm_signal_t TCM_lm_keybeta_t[] = { {TCM_LM_KeyBeta::LMHashEncRotKeyBetaVDC, "LMHashEncRotKeyBetaVDC", 0, 0, 16}, {TCM_LM_KeyBeta::LMEncRotKeyBetaVDC_1, "LMEncRotKeyBetaVDC_1", 0, 0, 64}, {TCM_LM_KeyBeta::LMEncRotKeyBetaVDC_2, "LMEncRotKeyBetaVDC_2", 0, 0, 64}, {TCM_LM_KeyBeta::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the TCM_LM_KeyGamma PDU */ lm_signal_t TCM_lm_keygamma_t[] = { {TCM_LM_KeyGamma::LMHashEncRotKeyGamaVDC, "LMHashEncRotKeyGamaVDC", 0, 0, 16}, {TCM_LM_KeyGamma::LMEncRotKeyGammaVDC_1, "LMEncRotKeyGammaVDC_1", 0, 0, 64}, {TCM_LM_KeyGamma::LMEncRotKeyGammaVDC_2, "LMEncRotKeyGammaVDC_2", 0, 0, 64}, {TCM_LM_KeyGamma::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the ASPM_LM PDU */ lm_signal_t ASPM_lm_t[] = { // 1 {ASPM_LM::LMAppConsChkASPM, "LMAppConsChkASPM", 0, 0, 16}, {ASPM_LM::ActiveAutonomousFeature, "ActiveAutonomousFeature", 0, 0, 4}, {ASPM_LM::CancelAvailability, "CancelAvailability", 0, 0, 2}, {ASPM_LM::ConfirmAvailability, "ConfirmAvailability", 0, 0, 2}, {ASPM_LM::LongitudinalAdjustAvailability, "LongitudinalAdjustAvailability", 0, 0, 2}, {ASPM_LM::ManeuverDirectionAvailability, "ManeuverDirectionAvailability", 0, 0, 2}, {ASPM_LM::ManeuverSideAvailability, "ManeuverSideAvailability", 0, 0, 2}, {ASPM_LM::ActiveManeuverOrientation, "ActiveManeuverOrientation", 0, 0, 2}, {ASPM_LM::ActiveParkingMode, "ActiveParkingMode", 0, 0, 2}, {ASPM_LM::DirectionChangeAvailability, "DirectionChangeAvailability", 0, 0, 2}, // 11 {ASPM_LM::ParkTypeChangeAvailability, "ParkTypeChangeAvailability", 0, 0, 2}, {ASPM_LM::ExploreModeAvailability, "ExploreModeAvailability", 0, 0, 2}, {ASPM_LM::ActiveManeuverSide, "ActiveManeuverSide", 0, 0, 2}, {ASPM_LM::ManeuverStatus, "ManeuverStatus", 0, 0, 4}, {ASPM_LM::RemoteDriveOverrideState, "RemoteDriveOverrideState", 0, 0, 2}, {ASPM_LM::ActiveParkingType, "ActiveParkingType", 0, 0, 3}, {ASPM_LM::ResumeAvailability, "ResumeAvailability", 0, 0, 2}, {ASPM_LM::ReturnToStartAvailability, "ReturnToStartAvailability", 0, 0, 2}, {ASPM_LM::NNNNNNNNNN, "NNNNNNNNNN", 0, 0, 2}, {ASPM_LM::KeyFobRange, "KeyFobRange", 0, 0, 3}, // 21 {ASPM_LM::LMDviceAliveCntAckRMT, "LMDviceAliveCntAckRMT", 0, 0, 4}, {ASPM_LM::NoFeatureAvailableMsg, "NoFeatureAvailableMsg", 0, 0, 4}, {ASPM_LM::LMFrwdCollSnsType1RMT, "LMFrwdCollSnsType1RMT", 0, 0, 1}, {ASPM_LM::LMFrwdCollSnsType2RMT, "LMFrwdCollSnsType2RMT", 0, 0, 1}, {ASPM_LM::LMFrwdCollSnsType3RMT, "LMFrwdCollSnsType3RMT", 0, 0, 1}, {ASPM_LM::LMFrwdCollSnsType4RMT, "LMFrwdCollSnsType4RMT", 0, 0, 1}, {ASPM_LM::LMFrwdCollSnsZone1RMT, "LMFrwdCollSnsZone1RMT", 0, 0, 4}, {ASPM_LM::LMFrwdCollSnsZone2RMT, "LMFrwdCollSnsZone2RMT", 0, 0, 4}, {ASPM_LM::LMFrwdCollSnsZone3RMT, "LMFrwdCollSnsZone3RMT", 0, 0, 4}, {ASPM_LM::LMFrwdCollSnsZone4RMT, "LMFrwdCollSnsZone4RMT", 0, 0, 4}, // 31 {ASPM_LM::InfoMsg, "InfoMsg", 0, 0, 6}, {ASPM_LM::InstructMsg, "InstructMsg", 0, 0, 5}, {ASPM_LM::LateralControlInfo, "LateralControlInfo", 0, 0, 3}, {ASPM_LM::LongitudinalAdjustLength, "LongitudinalAdjustLength", 0, 0, 10}, {ASPM_LM::LongitudinalControlInfo, "LongitudinalControlInfo", 0, 0, 3}, {ASPM_LM::ManeuverAlignmentAvailability, "ManeuverAlignmentAvailability", 0, 0, 3}, {ASPM_LM::RemoteDriveAvailability, "RemoteDriveAvailability", 0, 0, 2}, {ASPM_LM::PauseMsg2, "PauseMsg2", 0, 0, 4}, {ASPM_LM::PauseMsg1, "PauseMsg1", 0, 0, 4}, {ASPM_LM::LMRearCollSnsType1RMT, "LMRearCollSnsType1RMT", 0, 0, 1}, // 41 {ASPM_LM::LMRearCollSnsType2RMT, "LMRearCollSnsType2RMT", 0, 0, 1}, {ASPM_LM::LMRearCollSnsType3RMT, "LMRearCollSnsType3RMT", 0, 0, 1}, {ASPM_LM::LMRearCollSnsType4RMT, "LMRearCollSnsType4RMT", 0, 0, 1}, {ASPM_LM::LMRearCollSnsZone1RMT, "LMRearCollSnsZone1RMT", 0, 0, 4}, {ASPM_LM::LMRearCollSnsZone2RMT, "LMRearCollSnsZone2RMT", 0, 0, 4}, {ASPM_LM::LMRearCollSnsZone3RMT, "LMRearCollSnsZone3RMT", 0, 0, 4}, {ASPM_LM::LMRearCollSnsZone4RMT, "LMRearCollSnsZone4RMT", 0, 0, 4}, {ASPM_LM::LMRemoteFeatrReadyRMT, "LMRemoteFeatrReadyRMT", 0, 0, 2}, {ASPM_LM::CancelMsg, "CancelMsg", 0, 0, 4}, {ASPM_LM::LMVehMaxRmteVLimRMT, "LMVehMaxRmteVLimRMT", 0, 0, 6}, // 51 {ASPM_LM::ManueverPopupDisplay, "ManueverPopupDisplay", 0, 0, 1}, {ASPM_LM::ManeuverProgressBar, "ManeuverProgressBar", 0, 0, 7}, {ASPM_LM::MobileChallengeSend, "MobileChallengeSend", 0, 0, 64}, {ASPM_LM::LMRemoteResponseASPM, "LMRemoteResponseASPM", 0, 0, 64}, {ASPM_LM::MAXSignal, "MAXSignal", 0, 0, 0}, }; /*! * List of all signals sent in the payload of the ASPM_LM_ObjSegment PDU */ lm_signal_t ASPM_lm_objsegment_t[] = { // 1 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType1RMT, "ASPMFrontSegType1RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist1RMT, "ASPMFrontSegDist1RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType2RMT, "ASPMFrontSegType2RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist2RMT, "ASPMFrontSegDist2RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType3RMT, "ASPMFrontSegType3RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist3RMT, "ASPMFrontSegDist3RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType4RMT, "ASPMFrontSegType4RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist4RMT, "ASPMFrontSegDist4RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType5RMT, "ASPMFrontSegType5RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist5RMT, "ASPMFrontSegDist5RMT", 0, 0, 5}, // 11 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType6RMT, "ASPMFrontSegType6RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist6RMT, "ASPMFrontSegDist6RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType7RMT, "ASPMFrontSegType7RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist7RMT, "ASPMFrontSegDist7RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType8RMT, "ASPMFrontSegType8RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist8RMT, "ASPMFrontSegDist8RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType9RMT, "ASPMFrontSegType9RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist9RMT, "ASPMFrontSegDist9RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType10RMT, "ASPMFrontSegType10RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist10RMT, "ASPMFrontSegDist10RMT", 0, 0, 5}, // 21 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType11RMT, "ASPMFrontSegType11RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist11RMT, "ASPMFrontSegDist11RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType12RMT, "ASPMFrontSegType12RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist12RMT, "ASPMFrontSegDist12RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType13RMT, "ASPMFrontSegType13RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist13RMT, "ASPMFrontSegDist13RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType14RMT, "ASPMFrontSegType14RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist14RMT, "ASPMFrontSegDist14RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType15RMT, "ASPMFrontSegType15RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist15RMT, "ASPMFrontSegDist15RMT", 0, 0, 5}, // 31 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMFrontSegType16RMT, "ASPMFrontSegType16RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMFrontSegDist16RMT, "ASPMFrontSegDist16RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType1RMT, "ASPMRearSegType1RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist1RMT, "ASPMRearSegDist1RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType2RMT, "ASPMRearSegType2RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist2RMT, "ASPMRearSegDist2RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType3RMT, "ASPMRearSegType3RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist3RMT, "ASPMRearSegDist3RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType4RMT, "ASPMRearSegType4RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist4RMT, "ASPMRearSegDist4RMT", 0, 0, 5}, // 41 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType5RMT, "ASPMRearSegType5RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist5RMT, "ASPMRearSegDist5RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType6RMT, "ASPMRearSegType6RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist6RMT, "ASPMRearSegDist6RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType7RMT, "ASPMRearSegType7RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist7RMT, "ASPMRearSegDist7RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType8RMT, "ASPMRearSegType8RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist8RMT, "ASPMRearSegDist8RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType9RMT, "ASPMRearSegType9RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist9RMT, "ASPMRearSegDist9RMT", 0, 0, 5}, // 51 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType10RMT, "ASPMRearSegType10RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist10RMT, "ASPMRearSegDist10RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType11RMT, "ASPMRearSegType11RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist11RMT, "ASPMRearSegDist11RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType12RMT, "ASPMRearSegType12RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist12RMT, "ASPMRearSegDist12RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType13RMT, "ASPMRearSegType13RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist13RMT, "ASPMRearSegDist13RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType14RMT, "ASPMRearSegType14RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist14RMT, "ASPMRearSegDist14RMT", 0, 0, 5}, // 61 {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType15RMT, "ASPMRearSegType15RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist15RMT, "ASPMRearSegDist15RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::ASPMXXXXX, "ASPMXXXXX", 0, 0, 1}, {ASPM_LM_ObjSegment::ASPMRearSegType16RMT, "ASPMRearSegType16RMT", 0, 0, 2}, {ASPM_LM_ObjSegment::ASPMRearSegDist16RMT, "ASPMRearSegDist16RMT", 0, 0, 5}, {ASPM_LM_ObjSegment::MAXSignal, "MAXSignal", 0, 0, 0} }; /*! * List of all signals sent in the payload of the ASPM_RemoteTarget PDU */ lm_signal_t ASPM_remotetarget_t[] = { {ASPM_RemoteTarget::TCMRemoteTarget, "TCMRemoteTarget", 0, 0, 64}, {ASPM_RemoteTarget::MAXSignal, "MAXSignal", 0, 0, 0} }; /*! * List of all signals sent in the payload of the ASPM_LM_Session PDU */ lm_signal_t ASPM_lm_session_t[] = { {ASPM_LM_Session::LMEncrptSessionCntASPM_1, "LMEncrptSessionCntASPM_1", 0, 0, 64}, {ASPM_LM_Session::LMEncrptSessionCntASPM_2, "LMEncrptSessionCntASPM_2", 0, 0, 64}, {ASPM_LM_Session::LMEncryptSessionIDASPM_1, "LMEncryptSessionIDASPM_1", 0, 0, 64}, {ASPM_LM_Session::LMEncryptSessionIDASPM_2, "LMEncryptSessionIDASPM_2", 0, 0, 64}, {ASPM_LM_Session::LMTruncMACASPM, "LMTruncMACASPM", 0, 0, 64}, {ASPM_LM_Session::LMTruncSessionCntASPM, "LMTruncSessionCntASPM", 0, 0, 8}, {ASPM_LM_Session::LMSessionControlASPM, "LMSessionControlASPM", 0, 0, 3}, {ASPM_LM_Session::LMSessionControlASPMExt, "LMSessionControlASPMExt", 0, 0, 5}, {ASPM_LM_Session::MAXSignal, "MAXSignal", 0, 0, 0} }; /*! * List of all signals sent in the payload of the ASPM_LM_Trunc PDU */ lm_signal_t ASPM_lm_trunc_t[] = { {ASPM_LM_Trunc::LMTruncEnPsPrasRotASPM_1, "LMTruncEnPsPrasRotASPM_1", 0, 0, 64}, {ASPM_LM_Trunc::LMTruncEnPsPrasRotASPM_2, "LMTruncEnPsPrasRotASPM_2", 0, 0, 64}, {ASPM_LM_Trunc::MAXSignal, "MAXSignal", 0, 0, 0} }; // Constructor initializes all member variables. SignalHandler::SignalHandler( ) : mtx( ), hasVehicleMoved( false ), ConnectionApproval( TCM::ConnectionApproval::NoDevice ), DeviceControlMode( TCM::DeviceControlMode::NoMode ), ManeuverButtonPress( TCM::ManeuverButtonPress::None ), ManeuverTypeSelect( TCM::ManeuverTypeSelect::None ), ManeuverDirectionSelect( TCM::ManeuverDirectionSelect::None ), ManeuverGearSelect( TCM::ManeuverGearSelect::Park ), ManeuverSideSelect( TCM::ManeuverSideSelect::None ), ManeuverEnableInput( TCM::ManeuverEnableInput::NoScrnInput ), ExploreModeSelect( TCM::ExploreModeSelect::NotPressed ), NudgeSelect( TCM::NudgeSelect::NudgeNotAvailable), AppSliderPosX( 0000 ), AppSliderPosY( 0000 ), RemoteDeviceBatteryLevel( 77 ), AppCalcCheck( 0000 ), MobileChallengeReply( 0000 ), AppAccelerationX( 0000 ), AppAccelerationY( 0000 ), AppAccelerationZ( 0000 ), InfoMsg( ASP::InfoMsg::None ), ActiveAutonomousFeature( ASP::ActiveAutonomousFeature::NoFeatureActive ), ActiveParkingType( ASP::ActiveParkingType::None ), ActiveParkingMode( ASP::ActiveParkingMode::None ), ManeuverStatus( ASP::ManeuverStatus::NotActive ), NoFeatureAvailableMsg( ASP::NoFeatureAvailableMsg::None ), CancelMsg( ASP::CancelMsg::None ), PauseMsg1( ASP::PauseMsg1::None ), PauseMsg2( ASP::PauseMsg2::None ), InstructMsg( ASP::InstructMsg::None ), ExploreModeAvailability( ASP::ExploreModeAvailability::None ), DirectionChangeAvailability( ASP::DirectionChangeAvailability::None ), RemoteDriveAvailability( ASP::RemoteDriveAvailability::None ), ManeuverSideAvailability( ASP::ManeuverSideAvailability::None ), ActiveManeuverSide( ASP::ActiveManeuverSide::None ), ActiveManeuverOrientation( ASP::ActiveManeuverOrientation::None ), ParkTypeChangeAvailability( ASP::ParkTypeChangeAvailability::None ), ManeuverDirectionAvailability( ASP::ManeuverDirectionAvailability::None ), ManeuverAlignmentAvailability( ASP::ManeuverAlignmentAvailability::None ), ConfirmAvailability( ASP::ConfirmAvailability::None ), ResumeAvailability( ASP::ResumeAvailability::None ), ReturnToStartAvailability( ASP::ReturnToStartAvailability::None ), LongitudinalAdjustAvailability( ASP::LongitudinalAdjustAvailability::None ), LongitudinalAdjustLength( 0000 ), ManeuverProgressBar( 000 ), ASPMFrontSegDistxxRMT( 16, 19 ), ASPMRearSegDistxxRMT( 16, 19 ), MobileChallengeSend( 0000 ), ASPMFrontSegTypexxRMT( 16, 0 ), ASPMRearSegTypexxRMT( 16, 0 ), AcknowledgeRemotePIN( DCM::AcknowledgeRemotePIN::None ), ErrorMsg( DCM::ErrorMsg::None ), rangingRequestRate_( DCM::FobRangeRequestRate::None ), InControlRemotePIN_( DCM::PIN_NOT_SET ), pinStoredInVDC_( DCM::PIN_NOT_SET ), maneuverButtonPressTime_( (struct timeval){0} ), pinEntryLockoutTime_( (struct timeval){0} ), pinIncorrectCount_( 0 ), pinLockoutLimit_( 0 ), socketHandler_( ), running_( true ), engine_off_( false ), doors_locked_( false ) { // Prepopulate structs threatDistanceData.ASPMFrontSegDist1RMT = 19; threatDistanceData.ASPMFrontSegDist2RMT = 19; threatDistanceData.ASPMFrontSegDist3RMT = 19; threatDistanceData.ASPMFrontSegDist4RMT = 19; threatDistanceData.ASPMFrontSegDist5RMT = 19; threatDistanceData.ASPMFrontSegDist6RMT = 19; threatDistanceData.ASPMFrontSegDist7RMT = 19; threatDistanceData.ASPMFrontSegDist8RMT = 19; threatDistanceData.ASPMFrontSegDist9RMT = 19; threatDistanceData.ASPMFrontSegDist10RMT = 19; threatDistanceData.ASPMFrontSegDist11RMT = 19; threatDistanceData.ASPMFrontSegDist12RMT = 19; threatDistanceData.ASPMFrontSegDist13RMT = 19; threatDistanceData.ASPMFrontSegDist14RMT = 19; threatDistanceData.ASPMFrontSegDist15RMT = 19; threatDistanceData.ASPMFrontSegDist16RMT = 19; threatDistanceData.ASPMRearSegDist1RMT = 19; threatDistanceData.ASPMRearSegDist2RMT = 19; threatDistanceData.ASPMRearSegDist3RMT = 19; threatDistanceData.ASPMRearSegDist4RMT = 19; threatDistanceData.ASPMRearSegDist5RMT = 19; threatDistanceData.ASPMRearSegDist6RMT = 19; threatDistanceData.ASPMRearSegDist7RMT = 19; threatDistanceData.ASPMRearSegDist8RMT = 19; threatDistanceData.ASPMRearSegDist9RMT = 19; threatDistanceData.ASPMRearSegDist10RMT = 19; threatDistanceData.ASPMRearSegDist11RMT = 19; threatDistanceData.ASPMRearSegDist12RMT = 19; threatDistanceData.ASPMRearSegDist13RMT = 19; threatDistanceData.ASPMRearSegDist14RMT = 19; threatDistanceData.ASPMRearSegDist15RMT = 19; threatDistanceData.ASPMRearSegDist16RMT = 19; threatTypeData.ASPMFrontSegType1RMT = 0; threatTypeData.ASPMFrontSegType2RMT = 0; threatTypeData.ASPMFrontSegType3RMT = 0; threatTypeData.ASPMFrontSegType4RMT = 0; threatTypeData.ASPMFrontSegType5RMT = 0; threatTypeData.ASPMFrontSegType6RMT = 0; threatTypeData.ASPMFrontSegType7RMT = 0; threatTypeData.ASPMFrontSegType8RMT = 0; threatTypeData.ASPMFrontSegType9RMT = 0; threatTypeData.ASPMFrontSegType10RMT = 0; threatTypeData.ASPMFrontSegType11RMT = 0; threatTypeData.ASPMFrontSegType12RMT = 0; threatTypeData.ASPMFrontSegType13RMT = 0; threatTypeData.ASPMFrontSegType14RMT = 0; threatTypeData.ASPMFrontSegType15RMT = 0; threatTypeData.ASPMFrontSegType16RMT = 0; threatTypeData.ASPMRearSegType1RMT = 0; threatTypeData.ASPMRearSegType2RMT = 0; threatTypeData.ASPMRearSegType3RMT = 0; threatTypeData.ASPMRearSegType4RMT = 0; threatTypeData.ASPMRearSegType5RMT = 0; threatTypeData.ASPMRearSegType6RMT = 0; threatTypeData.ASPMRearSegType7RMT = 0; threatTypeData.ASPMRearSegType8RMT = 0; threatTypeData.ASPMRearSegType9RMT = 0; threatTypeData.ASPMRearSegType10RMT = 0; threatTypeData.ASPMRearSegType11RMT = 0; threatTypeData.ASPMRearSegType12RMT = 0; threatTypeData.ASPMRearSegType13RMT = 0; threatTypeData.ASPMRearSegType14RMT = 0; threatTypeData.ASPMRearSegType15RMT = 0; threatTypeData.ASPMRearSegType16RMT = 0; srand( time( NULL ) ); int i; // from TCM->ASP for (i = 0; (TCM_LM::ID) TCM_lm_t[i].index < TCM_LM::MAXSignal ; ++i) vt_TCM_lm.push_back(std::make_shared<LMSignalInfo>(TCM_lm_t[i])); for (i = 0; (TCM_LM_Session::ID) TCM_lm_session_t[i].index < TCM_LM_Session::MAXSignal ; ++i) vt_TCM_lm_session.push_back(std::make_shared<LMSignalInfo>(TCM_lm_session_t[i])); for (i = 0; (TCM_RemoteControl::ID) TCM_remotecontrol_t[i].index < TCM_RemoteControl::MAXSignal ; ++i) vt_TCM_remotecontrol.push_back(std::make_shared <LMSignalInfo>(TCM_remotecontrol_t[i])); for (i = 0; (TCM_TransportKey::ID) TCM_transportkey_t[i].index < TCM_TransportKey::MAXSignal ; ++i) vt_TCM_transportkey.push_back(std::make_shared <LMSignalInfo>(TCM_transportkey_t[i])); for (i = 0; (TCM_LM_App::ID) TCM_lm_app_t[i].index < TCM_LM_App::MAXSignal ; ++i) vt_TCM_lm_app.push_back(std::make_shared <LMSignalInfo>(TCM_lm_app_t[i])); for (i = 0; (TCM_LM_KeyID::ID) TCM_lm_keyid_t[i].index < TCM_LM_KeyID::MAXSignal ; ++i) vt_TCM_lm_keyid.push_back(std::make_shared< LMSignalInfo>(TCM_lm_keyid_t[i])); for (i = 0; (TCM_LM_KeyAlpha::ID) TCM_lm_keyalpha_t[i].index < TCM_LM_KeyAlpha::MAXSignal ; ++i) vt_TCM_lm_keyalpha.push_back(std::make_shared< LMSignalInfo>(TCM_lm_keyalpha_t[i])); for (i = 0; (TCM_LM_KeyBeta::ID) TCM_lm_keybeta_t[i].index < TCM_LM_KeyBeta::MAXSignal ; ++i) vt_TCM_lm_keybeta.push_back(std::make_shared <LMSignalInfo>(TCM_lm_keybeta_t[i])); for (i = 0; (TCM_LM_KeyGamma::ID) TCM_lm_keygamma_t[i].index < TCM_LM_KeyGamma::MAXSignal ; ++i) vt_TCM_lm_keygamma.push_back(std::make_shared< LMSignalInfo>(TCM_lm_keygamma_t[i])); // from ASP->TCM for (i = 0; (ASPM_LM::ID) ASPM_lm_t[i].index < ASPM_LM::MAXSignal ; ++i) vt_ASPM_lm.push_back(std::make_shared<LMSignalInfo>(ASPM_lm_t[i])); for (i = 0; (ASPM_LM_ObjSegment::ID) ASPM_lm_objsegment_t[i].index < ASPM_LM_ObjSegment::MAXSignal ; ++i) vt_ASPM_lm_objsegment.push_back(std::make_shared <LMSignalInfo>(ASPM_lm_objsegment_t[i])); for (i = 0; (ASPM_RemoteTarget::ID) ASPM_remotetarget_t[i].index < ASPM_RemoteTarget::MAXSignal ; ++i) vt_ASPM_remotetarget.push_back(std::make_shared <LMSignalInfo>(ASPM_remotetarget_t[i])); for (i = 0; (ASPM_LM_Session::ID) ASPM_lm_session_t[i].index < ASPM_LM_Session::MAXSignal ; ++i) vt_ASPM_lm_session.push_back(std::make_shared <LMSignalInfo>(ASPM_lm_session_t[i])); for (int i = 0; (ASPM_LM_Trunc::ID) ASPM_lm_trunc_t[i].index < ASPM_LM_Trunc::MAXSignal ; ++i) vt_ASPM_lm_trunc.push_back(std::make_shared <LMSignalInfo>(ASPM_lm_trunc_t[i])); } void SignalHandler::stop( ) { running_ = false; socketHandler_.disconnectClient( false ); socketHandler_.disconnectServer( ); signalLoopHandler_.join( ); rangingLoopHandler_.join( ); buttonPressLoopHandler_.join( ); } SignalHandler::~SignalHandler( ) {} std::mutex& SignalHandler::getMutex( ) { return mtx; } void SignalHandler::initiateEventLoops( ) { // Generate a new UDP socket socketHandler_.connectServer( (int32_t)SOCK_DGRAM, (uint64_t)UDP_ADDR, (uint16_t)UDP_PORT, true ); // Kick off threads signalLoopHandler_ = std::thread( &SignalHandler::updateSignalEventLoop_, this ); // 30ms loop rangingLoopHandler_ = std::thread( &SignalHandler::rangingRequestEventLoop_, this ); // dmh-related buttonPressLoopHandler_ = std::thread( &SignalHandler::buttonPressEventLoop_, this ); // maneuver button press rmt - 240ms countdown // ** FOR LG ** change below to whatever proprietary process needed // Set the PIN from value stored in VDC memory after socketHandler connects. getPinFromVDC_( ); } MANOUEVRE SignalHandler::parseManeuverString( const std::string& maneuver ) { if( maneuver == "OutLftFwd" || maneuver == "OLF" || maneuver == "POLF" ) { return MANOUEVRE::POLF; } else if( maneuver == "OutLftRvs" || maneuver == "OLR" || maneuver == "POLR" ) { return MANOUEVRE::POLR; } else if( maneuver == "OutRgtFwd" || maneuver == "ORF" || maneuver == "PORF" ) { return MANOUEVRE::PORF; } else if( maneuver == "OutRgtRvs" || maneuver == "ORR" || maneuver == "PORR" ) { return MANOUEVRE::PORR; } else if( maneuver == "OutLftPrl" || maneuver == "OLP" || maneuver == "POLP" ) { return MANOUEVRE::POLP; } else if( maneuver == "OutRgtPrl" || maneuver == "ORP" || maneuver == "PORP" ) { return MANOUEVRE::PORP; } else if( maneuver == "InLftFwd" || maneuver == "ILF" || maneuver == "PILF" ) { return MANOUEVRE::PILF; } else if( maneuver == "InLftRvs" || maneuver == "ILR" || maneuver == "PILR" ) { return MANOUEVRE::PILR; } else if( maneuver == "InRgtFwd" || maneuver == "IRF" || maneuver == "PIRF" ) { return MANOUEVRE::PIRF; } else if( maneuver == "InRgtRvs" || maneuver == "IRR" || maneuver == "PIRR" ) { return MANOUEVRE::PIRR; } else if( maneuver == "NdgFwd" || maneuver == "NF" ) { return MANOUEVRE::NF; } else if( maneuver == "NdgRvs" || maneuver == "NR" ) { return MANOUEVRE::NR; } else if( maneuver == "StrFwd" || maneuver == "SF" ) { return MANOUEVRE::SF; } else if( maneuver == "StrRvs" || maneuver == "SR" ) { return MANOUEVRE::SR; } else if( maneuver == "RtnToOgn" || maneuver == "RTO" || maneuver == "RTS" ) { return MANOUEVRE::RTS; } else { return MANOUEVRE::NADA; } } void SignalHandler::setInputManeuverSignals( const MANOUEVRE& maneuver ) { // set shared signals switch( maneuver ) { case MANOUEVRE::POLF: case MANOUEVRE::PORF: case MANOUEVRE::POLR: case MANOUEVRE::PORR: case MANOUEVRE::POLP: case MANOUEVRE::PORP: case MANOUEVRE::PILF: case MANOUEVRE::PIRF: case MANOUEVRE::PILR: case MANOUEVRE::PIRR: { ExploreModeSelect = TCM::ExploreModeSelect::NotPressed; NudgeSelect = TCM::NudgeSelect::NudgeNotPressed; break; } case MANOUEVRE::NF: case MANOUEVRE::NR: { ExploreModeSelect = TCM::ExploreModeSelect::NotPressed; NudgeSelect = TCM::NudgeSelect::NudgePressed; ManeuverTypeSelect = TCM::ManeuverTypeSelect::None; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::None; ManeuverSideSelect = TCM::ManeuverSideSelect::Center; break; } case MANOUEVRE::SF: case MANOUEVRE::SR: { ExploreModeSelect = TCM::ExploreModeSelect::Pressed; NudgeSelect = TCM::NudgeSelect::NudgeNotPressed; ManeuverTypeSelect = TCM::ManeuverTypeSelect::None; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::None; ManeuverSideSelect = TCM::ManeuverSideSelect::Center; break; } case MANOUEVRE::RTS: case MANOUEVRE::NADA: default: { std::cout << "Error setting input maneuver signals." << std::endl; return; } } // set more specific signals switch( maneuver ) { case MANOUEVRE::POLF: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::NoseFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; ManeuverSideSelect = TCM::ManeuverSideSelect::Left; return; } case MANOUEVRE::PORF: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::NoseFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; ManeuverSideSelect = TCM::ManeuverSideSelect::Right; return; } case MANOUEVRE::POLR: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::RearFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Reverse; ManeuverSideSelect = TCM::ManeuverSideSelect::Left; return; } case MANOUEVRE::PORR: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::RearFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Reverse; ManeuverSideSelect = TCM::ManeuverSideSelect::Right; return; } case MANOUEVRE::POLP: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Parallel; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::None; ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; ManeuverSideSelect = TCM::ManeuverSideSelect::Left; return; } case MANOUEVRE::PORP: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Parallel; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::None; ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; ManeuverSideSelect = TCM::ManeuverSideSelect::Right; return; } case MANOUEVRE::PILF: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::NoseFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; ManeuverSideSelect = TCM::ManeuverSideSelect::Left; return; } case MANOUEVRE::PIRF: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::NoseFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; ManeuverSideSelect = TCM::ManeuverSideSelect::Right; return; } case MANOUEVRE::PILR: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::RearFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Reverse; ManeuverSideSelect = TCM::ManeuverSideSelect::Left; return; } case MANOUEVRE::PIRR: { ManeuverTypeSelect = TCM::ManeuverTypeSelect::Perpendicular; ManeuverDirectionSelect = TCM::ManeuverDirectionSelect::RearFirst; ManeuverGearSelect = TCM::ManeuverGearSelect::Reverse; ManeuverSideSelect = TCM::ManeuverSideSelect::Right; return; } case MANOUEVRE::NF: case MANOUEVRE::SF: { ManeuverGearSelect = TCM::ManeuverGearSelect::Forward; return; } case MANOUEVRE::NR: case MANOUEVRE::SR: { ManeuverGearSelect = TCM::ManeuverGearSelect::Reverse; return; } case MANOUEVRE::RTS: case MANOUEVRE::NADA: default: { std::cout << "Error setting input maneuver signals." << std::endl; return; } } } void SignalHandler::setDeviceControlMode( const TCM::DeviceControlMode& mode ) { // **For LG** any time a member variable is updated, the corresponding ASP // should likewise be updated. DeviceControlMode = mode; } void SignalHandler::setManeuverButtonPress( const TCM::ManeuverButtonPress& mode ) { // **For LG** any time a member variable is updated, the corresponding ASP // should likewise be updated. ManeuverButtonPress = mode; // Threading: after 240ms, this value should reset to 'None' gettimeofday( &maneuverButtonPressTime_, NULL ); } void SignalHandler::setManeuverEnableInput( const uint16_t& xCoord, const uint16_t& yCoord, const int64_t& gesturePercent, const bool& validGesture ) { // **For LG** any time a member variable is updated, the corresponding ASP // should likewise be updated. AppSliderPosX = xCoord; AppSliderPosY = yCoord; AppAccelerationZ = gesturePercent; if( validGesture == true ) { ManeuverEnableInput = TCM::ManeuverEnableInput::ValidScrnInput; } else { ManeuverEnableInput = TCM::ManeuverEnableInput::NoScrnInput; } } void SignalHandler::setInControlRemotePin( const std::string& pin ) { // **For LG** any time a member variable is updated, the corresponding DCM // process should likewise be executed and appropriate signals updated. if( pinStoredInVDC_ == DCM::PIN_NOT_SET ) { AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::NotSetInDCM; std::cout << "No PIN stored in memory; authorisation failed." << std::endl; return; } else if( pin == DCM::PIN_NOT_SET && AcknowledgeRemotePIN == DCM::AcknowledgeRemotePIN::CorrectPIN ) { AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::ExpiredPIN; std::cout << "PIN reset upon disconnection of mobile device." << std::endl; return; } InControlRemotePIN_ = pin; // **For LG** the below code should be replaced with whatever methods are // used to authenticate PIN IAW [REQ NAME HERE]. if( !isTimevalZero( pinEntryLockoutTime_ ) ) { DCM::AcknowledgeRemotePIN currentPIN = AcknowledgeRemotePIN; if( currentPIN == DCM::AcknowledgeRemotePIN::IncorrectPIN3xLockIndefinite ) { // game over, my man!! std::cout << "PIN entries locked out indefinitely." << std::endl; } else if( !checkTimeout( pinEntryLockoutTime_, pinLockoutLimit_ ) ) { timeval currentTime; gettimeofday( &currentTime, NULL ); unsigned int dTime( pinLockoutLimit_ ); dTime -= diffTimeval( currentTime, pinEntryLockoutTime_ ); dTime /= 1000000; std::cout << "PIN entries locked out for " << dTime << " sec. " << std::endl; return; } else { pinEntryLockoutTime_ = (struct timeval){0}; } } // if no lockouts remain, then check the PIN against pinStoredInVDC_ if( InControlRemotePIN_ != pinStoredInVDC_ ) { switch( AcknowledgeRemotePIN ) { case( DCM::AcknowledgeRemotePIN::IncorrectPIN3xLockIndefinite ): case( DCM::AcknowledgeRemotePIN::IncorrectPIN3xLock3600s ): { gettimeofday( &pinEntryLockoutTime_, NULL ); pinLockoutLimit_ = 4294967295; // max uint value AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::IncorrectPIN3xLockIndefinite; break; } case( DCM::AcknowledgeRemotePIN::IncorrectPIN3xLock300s ): { gettimeofday( &pinEntryLockoutTime_, NULL ); pinLockoutLimit_ = 3600000000; // 3600sec AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::IncorrectPIN3xLock3600s; break; } case( DCM::AcknowledgeRemotePIN::IncorrectPIN3xLock60s ): { gettimeofday( &pinEntryLockoutTime_, NULL ); pinLockoutLimit_ = 300000000; // 300sec AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::IncorrectPIN3xLock300s; break; } case( DCM::AcknowledgeRemotePIN::IncorrectPIN ): { if( ++pinIncorrectCount_ >= 3 ) { gettimeofday( &pinEntryLockoutTime_, NULL ); pinLockoutLimit_ = 60000000; // 60sec AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::IncorrectPIN3xLock60s; pinIncorrectCount_ = 2; break; } } case( DCM::AcknowledgeRemotePIN::CorrectPIN ): case( DCM::AcknowledgeRemotePIN::InvalidSig ): default: { AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::IncorrectPIN; ++pinIncorrectCount_; } } } else { AcknowledgeRemotePIN = DCM::AcknowledgeRemotePIN::CorrectPIN; pinIncorrectCount_ = 0; } // Leave below for LG debugging #if 0 /**LGE Code** SRD___TELEM_RCD9722___v1: Once the Telematics_VM: - Received a confirmation that the disclaimer is agreed (DisclaimerRejected_RD=0), and - The customer input the correct InControl Remote PIN (AcknowledgeRemotePIN_DCM=1), - Received a ranging request from the mobile phone (RequestWKeyDist_RD), The Telematics_VM shall: - instruct the RFA to start ranging: - RequestWKeyDist=0x01 - provide RFA with the information "which key to range against": PairedWKeyId ''NOTE: the mobile phone will request the Telematics to proceed to ranging until the driver is close enough, then the Telematics VM will start the engine." */ LOGD("CAN TX to RFA (RequestWKeyDist=0x01, PairedWKeyID=%d)=====================================>", m_RCDLog->getPairedWKeyId()); m_RCDUtils->setCanValue(VS_CAN_REQUESTWKEYDIST_IDX, 0x01); //if(m_RCDSignal->getSigValue(WkeyVehDist) == -1) m_RCDUtils->setCanValue(VS_CAN_PAIREDWKEYID_IDX , m_RCDLog->getPairedWKeyId()); LOGD("PIN Authenticated. Passing RCMainMenu to ASP."); #endif return; } void SignalHandler::setConnectionApproval( const TCM::ConnectionApproval& mode ) { // **For LG** Advanced logic for checking device compatibility should be // added here. For FDJ demo, API assumes that WiFi connection indicates a // compatible device, which does not hold true for production app. ConnectionApproval = mode; // std::cout << "ConnectionApproval: " << (int)ConnectionApproval << std::endl; } void SignalHandler::setFobRangeRequestRate( const DCM::FobRangeRequestRate& rate ) { // Set private member variable rangingRequestRate_ = rate; } void SignalHandler::setCabinCommands( bool engine_off, bool doors_locked ) { engine_off_ = engine_off; doors_locked_ = doors_locked; } bool SignalHandler::getEngineOff( ) const { return engine_off_; } bool SignalHandler::getDoorsLocked( ) const { return doors_locked_; } std::string SignalHandler::getManeuverFromASP( ) { if( ActiveParkingType == ASP::ActiveParkingType::PushPull ) { // Check parallel, perpendicular rear or front switch( ActiveManeuverOrientation ) { // int value of 0 --> ** UNKNOWN ** case ASP::ActiveManeuverOrientation::None: break; // int value of 1 --> PushPull Parallel does not make sense case ASP::ActiveManeuverOrientation::Parallel: break; // int value of 2 --> PerpendicularRear case ASP::ActiveManeuverOrientation::PerpendicularRear: { return "StrRvs"; } // int value of 3 --> PerpendicularFront case ASP::ActiveManeuverOrientation::PerpendicularFront: { return "StrFwd"; } // scaffolding to parse improperly initialized sig if needed case ASP::ActiveManeuverOrientation::InvalidSig: break; default: break; } } else if( ActiveParkingType == ASP::ActiveParkingType::Remote ) { switch( ActiveParkingMode ) { case ASP::ActiveParkingMode::ParkIn: { switch ( ActiveManeuverOrientation ) { case ASP::ActiveManeuverOrientation::PerpendicularFront: { switch ( ActiveManeuverSide ) { case ASP::ActiveManeuverSide::Left: { return "InLftFwd"; } case ASP::ActiveManeuverSide::Right: { return "InRgtFwd"; } default: break; } break; } case ASP::ActiveManeuverOrientation::PerpendicularRear: { switch ( ActiveManeuverSide ) { case ASP::ActiveManeuverSide::Left: { return "InLftRvs"; } case ASP::ActiveManeuverSide::Right: { return "InRgtRvs"; } default: break; } break; } default: break; } break; } case ASP::ActiveParkingMode::ParkOut: { switch ( ActiveManeuverOrientation ) { case ASP::ActiveManeuverOrientation::Parallel: { switch ( ActiveManeuverSide ) { case ASP::ActiveManeuverSide::Left: { return "OutLftPrl"; } case ASP::ActiveManeuverSide::Right: { return "OutRgtPrl"; } default: break; } break; } case ASP::ActiveManeuverOrientation::PerpendicularFront: { switch ( ActiveManeuverSide ) { case ASP::ActiveManeuverSide::Left: { return "OutLftFwd"; } case ASP::ActiveManeuverSide::Right: { return "OutRgtFwd"; } default: break; } break; } case ASP::ActiveManeuverOrientation::PerpendicularRear: { switch ( ActiveManeuverSide ) { case ASP::ActiveManeuverSide::Left: { return "OutLftRvs"; } case ASP::ActiveManeuverSide::Right: { return "OutRgtRvs"; } default: break; } break; } default: break; } break; } default: break; } } else if (ActiveParkingType == ASP::ActiveParkingType::LongitudinalAssist) { switch ( ActiveManeuverOrientation ) { case ASP::ActiveManeuverOrientation::PerpendicularFront: { return "NdgFwd"; } case ASP::ActiveManeuverOrientation::PerpendicularRear: { return "NdgRvs"; } default: break; } } // TODO: how to determine if current maneuver is "RtnToOgn"? return ""; } uint8_t SignalHandler::getASPMFrontSegDistxxRMT( int& sensorID ) { switch( sensorID ) { case 0: return threatDistanceData.ASPMFrontSegDist1RMT; case 1: return threatDistanceData.ASPMFrontSegDist2RMT; case 2: return threatDistanceData.ASPMFrontSegDist3RMT; case 3: return threatDistanceData.ASPMFrontSegDist4RMT; case 4: return threatDistanceData.ASPMFrontSegDist5RMT; case 5: return threatDistanceData.ASPMFrontSegDist6RMT; case 6: return threatDistanceData.ASPMFrontSegDist7RMT; case 7: return threatDistanceData.ASPMFrontSegDist8RMT; case 8: return threatDistanceData.ASPMFrontSegDist9RMT; case 9: return threatDistanceData.ASPMFrontSegDist10RMT; case 10: return threatDistanceData.ASPMFrontSegDist11RMT; case 11: return threatDistanceData.ASPMFrontSegDist12RMT; case 12: return threatDistanceData.ASPMFrontSegDist13RMT; case 13: return threatDistanceData.ASPMFrontSegDist14RMT; case 14: return threatDistanceData.ASPMFrontSegDist15RMT; case 15: return threatDistanceData.ASPMFrontSegDist16RMT; // return 19 if bad value default: return 19; } } uint8_t SignalHandler::getASPMRearSegDistxxRMT( int& sensorID ) { switch( sensorID ) { case 0: return threatDistanceData.ASPMRearSegDist1RMT; case 1: return threatDistanceData.ASPMRearSegDist2RMT; case 2: return threatDistanceData.ASPMRearSegDist3RMT; case 3: return threatDistanceData.ASPMRearSegDist4RMT; case 4: return threatDistanceData.ASPMRearSegDist5RMT; case 5: return threatDistanceData.ASPMRearSegDist6RMT; case 6: return threatDistanceData.ASPMRearSegDist7RMT; case 7: return threatDistanceData.ASPMRearSegDist8RMT; case 8: return threatDistanceData.ASPMRearSegDist9RMT; case 9: return threatDistanceData.ASPMRearSegDist10RMT; case 10: return threatDistanceData.ASPMRearSegDist11RMT; case 11: return threatDistanceData.ASPMRearSegDist12RMT; case 12: return threatDistanceData.ASPMRearSegDist13RMT; case 13: return threatDistanceData.ASPMRearSegDist14RMT; case 14: return threatDistanceData.ASPMRearSegDist15RMT; case 15: return threatDistanceData.ASPMRearSegDist16RMT; // return 19 if bad value default: return 19; } } uint8_t SignalHandler::getASPMFrontSegTypexxRMT( int& sensorID ) { switch( sensorID ) { case 0: return threatTypeData.ASPMFrontSegType1RMT; case 1: return threatTypeData.ASPMFrontSegType2RMT; case 2: return threatTypeData.ASPMFrontSegType3RMT; case 3: return threatTypeData.ASPMFrontSegType4RMT; case 4: return threatTypeData.ASPMFrontSegType5RMT; case 5: return threatTypeData.ASPMFrontSegType6RMT; case 6: return threatTypeData.ASPMFrontSegType7RMT; case 7: return threatTypeData.ASPMFrontSegType8RMT; case 8: return threatTypeData.ASPMFrontSegType9RMT; case 9: return threatTypeData.ASPMFrontSegType10RMT; case 10: return threatTypeData.ASPMFrontSegType11RMT; case 11: return threatTypeData.ASPMFrontSegType12RMT; case 12: return threatTypeData.ASPMFrontSegType13RMT; case 13: return threatTypeData.ASPMFrontSegType14RMT; case 14: return threatTypeData.ASPMFrontSegType15RMT; case 15: return threatTypeData.ASPMFrontSegType16RMT; // return 19 if bad value default: return 19; } } uint8_t SignalHandler::getASPMRearSegTypexxRMT( int& sensorID ) { switch( sensorID ) { case 0: return threatTypeData.ASPMRearSegType1RMT; case 1: return threatTypeData.ASPMRearSegType2RMT; case 2: return threatTypeData.ASPMRearSegType3RMT; case 3: return threatTypeData.ASPMRearSegType4RMT; case 4: return threatTypeData.ASPMRearSegType5RMT; case 5: return threatTypeData.ASPMRearSegType6RMT; case 6: return threatTypeData.ASPMRearSegType7RMT; case 7: return threatTypeData.ASPMRearSegType8RMT; case 8: return threatTypeData.ASPMRearSegType9RMT; case 9: return threatTypeData.ASPMRearSegType10RMT; case 10: return threatTypeData.ASPMRearSegType11RMT; case 11: return threatTypeData.ASPMRearSegType12RMT; case 12: return threatTypeData.ASPMRearSegType13RMT; case 13: return threatTypeData.ASPMRearSegType14RMT; case 14: return threatTypeData.ASPMRearSegType15RMT; case 15: return threatTypeData.ASPMRearSegType16RMT; // return 19 if bad value default: return 19; } } bool SignalHandler::checkTimeout( timeval& tv, const unsigned int& maxVal ) { timeval curTime; gettimeofday( &curTime, NULL ); if( diffTimeval( curTime, tv ) > maxVal ) { return true; } return false; } unsigned int SignalHandler::diffTimeval( timeval& t1, timeval& t2 ) { return ( ( t1.tv_sec - t2.tv_sec ) * 1000000 ) + ( t1.tv_usec - t2.tv_usec ); } bool SignalHandler::isTimevalZero( timeval& tv ) { return ( tv.tv_sec == 0 ) && ( tv.tv_usec == 0 ); } void SignalHandler::getPinFromVDC_( ) { // **For LG** the process for polling and assigning the PIN value stored in // vehicle memory should be defined here and replace DCM::POC_PIN pinStoredInVDC_ = picosha2::hash256_hex_string( std::string( DCM::POC_PIN ) ); return; } void SignalHandler::rangingRequestEventLoop_( ) { while( running_.load( ) ) { while( ConnectionApproval == TCM::ConnectionApproval::AllowedDevice && (uint32_t)rangingRequestRate_ != 0 && running_.load( ) ) { // update rangingRequestRate_ to DeadmanRate if maneuver is underway if( ManeuverStatus == ASP::ManeuverStatus::Confirming || ManeuverStatus == ASP::ManeuverStatus::Maneuvering ) { setFobRangeRequestRate( DCM::FobRangeRequestRate::DeadmanRate ); hasVehicleMoved = true; } else { setFobRangeRequestRate( DCM::FobRangeRequestRate::DefaultRate ); } // // Leave below for ranging debugging. // float showRate( (unsigned int)rangingRequestRate_ ); // showRate /= 1000000; // // time_t curTime( time( NULL ) ); // // std::cout << "Loop ran at: " << ctime( &curTime ); // std::cout << "Loop periodicity: "; // std::cout << std::fixed << std::setprecision( 2 ) << showRate; // std::cout << " seconds." << std::endl; /* * ** FOR LG ** Insert request to check Key Fob Range here */ usleep( (uint32_t)rangingRequestRate_ ); } // To prevent memory leakage, if the FobRangeRequestRate is currently // None (0), put the loop to sleep at the highest frequency. usleep( (uint32_t)DCM::FobRangeRequestRate::DeadmanRate ); } return; } void SignalHandler::buttonPressEventLoop_( ) { while( running_.load( ) ) { usleep( ASP_REFRESH_RATE ); if( ManeuverButtonPress == TCM::ManeuverButtonPress::None ) { // do nothing, we only need to check when not "None" continue; } if( isTimevalZero( maneuverButtonPressTime_ ) ) { // if not initialized, reset the button press time gettimeofday( &maneuverButtonPressTime_, NULL ); continue; } if( checkTimeout( maneuverButtonPressTime_, BUTTON_TIMEOUT_RATE ) ) { // if timeout, reset button to none and clear time holder. ManeuverButtonPress = TCM::ManeuverButtonPress::None; maneuverButtonPressTime_ = (struct timeval){0}; } } return; } // ** FOR LG ** function renamed to fit threading // void SignalHandler::udpSocketSendLoop_( ) { } void SignalHandler::updateSignalEventLoop_( ) { uint8_t bufferToASP[ UDP_BUF_MAX ]; uint8_t bufferToTCM[ UDP_BUF_MAX ]; // spin in perpetuity while( running_.load( ) ) { // While an appropriate mobile device is connected, send/receive UDP while( ConnectionApproval != TCM::ConnectionApproval::NoDevice && running_.load( ) ) { bzero( bufferToASP, UDP_BUF_MAX ); bzero( bufferToTCM, UDP_BUF_MAX ); { // while updating signals, stop actions on concurrent threads. std::lock_guard<std::mutex> lock( getMutex( ) ); // convert from integer to bit uint16_t outBufSize = encodeTCMSignalData(bufferToASP); int sentLen = (int)socketHandler_.sendUDP( bufferToASP, outBufSize ); // // leave per commonly-used state debugging statements. // std::cout << "---" << std::endl << "Message sent.\t"; // std::cout << "ConnectionApproval: " << (int)ConnectionApproval; // std::cout << "\tDeviceControlMode: " << (int)DeviceControlMode; // std::cout << std::endl; // Print sent message // printf( "** %i-Bytes of UDP data sent **\n", sentLen ); // for( int k = 0; k < sentLen; ) { // printf( "%02X ", bufferToASP[k] ); // if(++k%20==0) printf("\n"); // } // printf( "\n\n" ); ssize_t bytes_received = socketHandler_.receiveUDP( bufferToTCM, sizeof(bufferToTCM) ); if (bytes_received == ASPM_TOTAL_PACKET_SIZE) { decodeASPMSignalData(bufferToTCM); } else if (bytes_received == 0) { std::cout << "Socket disconnected" << std::endl; } else { std::cout << "ERROR: received malformed UDP packet of length " << bytes_received << std::endl; } // leave per commonly-used state debugging statements. // std::cout << "---" << std::endl << "ManeuverStatus: " << (int)ManeuverStatus; // std::cout << "\tManeuverProgressBar: " << (int)ManeuverProgressBar; // std::cout << "MobileChallengeSend:\t" << (int)MobileChallengeSend << std::endl; // std::cout << std::endl; } // reset the DMH input so that it can timeout on the ASP side. // ManeuverEnableInput = TCM::ManeuverEnableInput::NoScrnInput; usleep( ASP_REFRESH_RATE ); } // To prevent memory leakage, go to sleep usleep( ASP_REFRESH_RATE ); } return; } uint64_t SignalHandler::getTCMSignal( uint8_t header_id, const uint16_t& sigid ) { // // leave for LG debugging. //uint32_t value = 0; //printf("Sig:%d", sigid); //RCD_LOGP("Sig:%d", sigid); if (header_id == HRD_ID_OF_TCM_LM) //ID:57 { switch(sigid) { //1=============================== case TCM_LM::AppCalcCheck: return (uint64_t)AppCalcCheck; //length:16bits case TCM_LM::LMDviceAliveCntRMT: return 0x0; //length:4bits case TCM_LM::ManeuverEnableInput: return (uint64_t)ManeuverEnableInput; //length:2bits case TCM_LM::ManeuverGearSelect: return (uint64_t)ManeuverGearSelect; //length:2bits case TCM_LM::NudgeSelect: return (uint64_t)NudgeSelect; //length:2bits case TCM_LM::RCDOvrrdReqRMT: return 0x0; //length:2bits case TCM_LM::AppSliderPosY: return (uint64_t)AppSliderPosY; //length:12bits case TCM_LM::AppSliderPosX: return (uint64_t)AppSliderPosX; //length:11bits case TCM_LM::RCDSpeedChngReqRMT: return 0x00; //length:6bits case TCM_LM::RCDSteWhlChngReqRMT: return 0x000; //length:10bits //11=============================== case TCM_LM::ConnectionApproval: return (uint64_t)ConnectionApproval; //length:2bits case TCM_LM::ManeuverButtonPress: return (uint64_t)ManeuverButtonPress; case TCM_LM::DeviceControlMode: return (uint64_t)DeviceControlMode; case TCM_LM::ManeuverTypeSelect: return (uint64_t)ManeuverTypeSelect; case TCM_LM::ManeuverDirectionSelect: return (uint64_t)ManeuverDirectionSelect; case TCM_LM::ExploreModeSelect: return (uint64_t)ExploreModeSelect; case TCM_LM::RemoteDeviceBatteryLevel: return (uint64_t)RemoteDeviceBatteryLevel; //length:7bits case TCM_LM::PairedWKeyId: return 0x00; //length:8bits case TCM_LM::ManeuverSideSelect: return (uint64_t)ManeuverSideSelect; case TCM_LM::LMDviceRngeDistRMT: return 0x00; //length:10bits //21 ============================ case TCM_LM::TTTTTTTTTT: return 0x0; //length:4bits, garbage value case TCM_LM::LMRemoteChallengeVDC: return 0x0000000000000000; //length:64bits case TCM_LM::MobileChallengeReply: return (uint64_t)MobileChallengeReply; //length:64bits default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_LM_Session) //ID:68 { switch(sigid) { case TCM_LM_Session::LMEncrptSessionCntVDC_1: return 0x0000000000000000; case TCM_LM_Session::LMEncrptSessionCntVDC_2: return 0x0000000000000000; case TCM_LM_Session::LMEncryptSessionIDVDC_1: return 0x0000000000000000; case TCM_LM_Session::LMEncryptSessionIDVDC_2: return 0x0000000000000000; case TCM_LM_Session::LMTruncMACVDC: return 0x0000000000000000; case TCM_LM_Session::LMTruncSessionCntVDC: return 0x00; case TCM_LM_Session::LMSessionControlVDC: return 0x00; case TCM_LM_Session::LMSessionControlVDCExt: return 0x00; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_RemoteControl) //ID:67 { switch(sigid) { case TCM_RemoteControl::TCMRemoteControl: return 0x0000000000000000; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_TransportKey) //ID:69 { switch(sigid) { case TCM_TransportKey::LMSessionKeyIDVDC: return 0x0000; case TCM_TransportKey::LMHashEnTrnsportKeyVDC: return 0x0000; case TCM_TransportKey::LMEncTransportKeyVDC_1: return 0x0000000000000000; case TCM_TransportKey::LMEncTransportKeyVDC_2: return 0x0000000000000000; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_LM_App) //ID:73 { switch(sigid) { case TCM_LM_App::LMAppTimeStampRMT: return 0x0000000000000000; case TCM_LM_App::AppAccelerationX: return 0x0000000000000000; case TCM_LM_App::AppAccelerationY: return 0x0000000000000000; case TCM_LM_App::AppAccelerationZ: return (uint64_t)AppAccelerationZ; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_LM_KeyID) //ID:75 { switch(sigid) { case TCM_LM_KeyID::NOT_USED_ONE_BIT: /*1*/ return 0x0; case TCM_LM_KeyID::LMRotKeyChkACKVDC: /*3*/ return 0x0; case TCM_LM_KeyID::LMSessionKeyIDVDCExt: /*4*/ return 0x0; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_LM_KeyAlpha) //ID:70 { switch(sigid) { case TCM_LM_KeyAlpha::LMHashEnRotKeyAlphaVDC: /*16*/ return 0x0000; case TCM_LM_KeyAlpha::LMEncRotKeyAlphaVDC_1: /*64*/ return 0x0000000000000000; case TCM_LM_KeyAlpha::LMEncRotKeyAlphaVDC_2: /*64*/ return 0x0000000000000000; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_LM_KeyBeta) //ID:71 { switch(sigid) { case TCM_LM_KeyBeta::LMHashEncRotKeyBetaVDC: /*16*/ return 0x0000; case TCM_LM_KeyBeta::LMEncRotKeyBetaVDC_1: /*64*/ return 0x0000000000000000; case TCM_LM_KeyBeta::LMEncRotKeyBetaVDC_2: /*64*/ return 0x0000000000000000; default: printf("receive unknown signal:%d", sigid); return 0; } } else if (header_id == HRD_ID_OF_TCM_LM_KeyGamma) //ID:72 { switch(sigid) { case TCM_LM_KeyGamma::LMHashEncRotKeyGamaVDC: /*16*/ return 0x0000; case TCM_LM_KeyGamma::LMEncRotKeyGammaVDC_1: /*64*/ return 0x0000000000000000; case TCM_LM_KeyGamma::LMEncRotKeyGammaVDC_2: /*64*/ return 0x0000000000000000; default: printf("receive unknown signal:%d", sigid); return 0; } } else { printf("receive unknown signal:%d, header_id: %d", sigid, header_id); } return 0; } void SignalHandler::setASPSignal(uint8_t header_id, const int16_t& sigid, uint64_t value ) { // // leave for LG debugging. // printf("Header: %d, Sig: %d, Val: %lx\n", header_id, sigid, value); if (header_id == HRD_ID_OF_ASPM_LM) { switch(sigid) { //1=============================== case ASPM_LM::LMAppConsChkASPM: return; case ASPM_LM::ActiveAutonomousFeature: ActiveAutonomousFeature = (ASP::ActiveAutonomousFeature)value; return; case ASPM_LM::CancelAvailability: return; case ASPM_LM::ConfirmAvailability: ConfirmAvailability = (ASP::ConfirmAvailability)value; return; case ASPM_LM::LongitudinalAdjustAvailability: LongitudinalAdjustAvailability = (ASP::LongitudinalAdjustAvailability)value; return; case ASPM_LM::ManeuverDirectionAvailability: ManeuverDirectionAvailability = (ASP::ManeuverDirectionAvailability)value; return; case ASPM_LM::ManeuverSideAvailability: ManeuverSideAvailability = (ASP::ManeuverSideAvailability)value; return; case ASPM_LM::ActiveManeuverOrientation: ActiveManeuverOrientation = (ASP::ActiveManeuverOrientation)value; return; case ASPM_LM::ActiveParkingMode: ActiveParkingMode = (ASP::ActiveParkingMode)value; return; case ASPM_LM::DirectionChangeAvailability: DirectionChangeAvailability = (ASP::DirectionChangeAvailability)value; return; //11=============================== case ASPM_LM::ParkTypeChangeAvailability: ParkTypeChangeAvailability = (ASP::ParkTypeChangeAvailability)value; return; case ASPM_LM::ExploreModeAvailability: ExploreModeAvailability = (ASP::ExploreModeAvailability)value; return; case ASPM_LM::ActiveManeuverSide: ActiveManeuverSide = (ASP::ActiveManeuverSide)value; return; case ASPM_LM::ManeuverStatus: ManeuverStatus = (ASP::ManeuverStatus)value; return; case ASPM_LM::RemoteDriveOverrideState: return; case ASPM_LM::ActiveParkingType: ActiveParkingType = (ASP::ActiveParkingType)value; return; case ASPM_LM::ResumeAvailability: ResumeAvailability = (ASP::ResumeAvailability)value; case ASPM_LM::ReturnToStartAvailability: ReturnToStartAvailability = (ASP::ReturnToStartAvailability)value; return; case ASPM_LM::NNNNNNNNNN: return; case ASPM_LM::KeyFobRange: return; case ASPM_LM::LMDviceAliveCntAckRMT: return; //21=============================== case ASPM_LM::NoFeatureAvailableMsg: NoFeatureAvailableMsg = (ASP::NoFeatureAvailableMsg)value; return; case ASPM_LM::LMFrwdCollSnsType1RMT: return; case ASPM_LM::LMFrwdCollSnsType2RMT: return; case ASPM_LM::LMFrwdCollSnsType3RMT: return; case ASPM_LM::LMFrwdCollSnsType4RMT: return; case ASPM_LM::LMFrwdCollSnsZone1RMT: return; case ASPM_LM::LMFrwdCollSnsZone2RMT: return; case ASPM_LM::LMFrwdCollSnsZone3RMT: return; case ASPM_LM::LMFrwdCollSnsZone4RMT: return; case ASPM_LM::InfoMsg: InfoMsg = (ASP::InfoMsg)value; return; //31=============================== case ASPM_LM::InstructMsg: InstructMsg = (ASP::InstructMsg)value; return; case ASPM_LM::LateralControlInfo: return; case ASPM_LM::LongitudinalAdjustLength: LongitudinalAdjustLength = (ASP::LongitudinalAdjustLength)value; return; case ASPM_LM::LongitudinalControlInfo: return; case ASPM_LM::ManeuverAlignmentAvailability: ManeuverAlignmentAvailability = (ASP::ManeuverAlignmentAvailability)value; return; case ASPM_LM::RemoteDriveAvailability: RemoteDriveAvailability = (ASP::RemoteDriveAvailability)value; return; case ASPM_LM::PauseMsg2: PauseMsg2 = (ASP::PauseMsg2)value; return; case ASPM_LM::PauseMsg1: PauseMsg1 = (ASP::PauseMsg1)value; return; case ASPM_LM::LMRearCollSnsType1RMT: return; //41=============================== case ASPM_LM::LMRearCollSnsType2RMT: return; case ASPM_LM::LMRearCollSnsType3RMT: return; case ASPM_LM::LMRearCollSnsType4RMT: return; case ASPM_LM::LMRearCollSnsZone1RMT: return; case ASPM_LM::LMRearCollSnsZone2RMT: return; case ASPM_LM::LMRearCollSnsZone3RMT: return; case ASPM_LM::LMRearCollSnsZone4RMT: return; case ASPM_LM::LMRemoteFeatrReadyRMT: return; case ASPM_LM::CancelMsg: CancelMsg = (ASP::CancelMsg)value; return; case ASPM_LM::LMVehMaxRmteVLimRMT: return; case ASPM_LM::ManueverPopupDisplay: return; //51=============================== case ASPM_LM::ManeuverProgressBar: ManeuverProgressBar = (ASP::ManeuverProgressBar)value; return; case ASPM_LM::MobileChallengeSend: MobileChallengeSend = (ASP::MobileChallengeSend)value; return; case ASPM_LM::LMRemoteResponseASPM: return; default: printf("receive unknown signal:%d", sigid); return; } } else if (header_id == HRD_ID_OF_ASPM_RemoteTarget) { switch(sigid) { case ASPM_RemoteTarget::TCMRemoteTarget: return; default: printf("receive unknown signal:%d", sigid); return; } } else if (header_id == HRD_ID_OF_ASPM_LM_Session) { switch(sigid) { case ASPM_LM_Session::LMEncrptSessionCntASPM_1: return; case ASPM_LM_Session::LMEncrptSessionCntASPM_2: return; case ASPM_LM_Session::LMEncryptSessionIDASPM_1: return; case ASPM_LM_Session::LMEncryptSessionIDASPM_2: return; case ASPM_LM_Session::LMTruncMACASPM: return; case ASPM_LM_Session::LMTruncSessionCntASPM: return; case ASPM_LM_Session::LMSessionControlASPM: return; case ASPM_LM_Session::LMSessionControlASPMExt: return; default: printf("receive unknown signal:%d", sigid); return; } } else if (header_id == HRD_ID_OF_ASPM_LM_ObjSegment) { switch(sigid) { case ASPM_LM_ObjSegment::ASPMXXXXX: return; //not used case ASPM_LM_ObjSegment::ASPMFrontSegType1RMT: threatTypeData.ASPMFrontSegType1RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist1RMT: threatDistanceData.ASPMFrontSegDist1RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType2RMT: threatTypeData.ASPMFrontSegType2RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist2RMT: threatDistanceData.ASPMFrontSegDist2RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType3RMT: threatTypeData.ASPMFrontSegType3RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist3RMT: threatDistanceData.ASPMFrontSegDist3RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType4RMT: threatTypeData.ASPMFrontSegType4RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist4RMT: threatDistanceData.ASPMFrontSegDist4RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType5RMT: threatTypeData.ASPMFrontSegType5RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist5RMT: threatDistanceData.ASPMFrontSegDist5RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType6RMT: threatTypeData.ASPMFrontSegType6RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist6RMT: threatDistanceData.ASPMFrontSegDist6RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType7RMT: threatTypeData.ASPMFrontSegType7RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist7RMT: threatDistanceData.ASPMFrontSegDist7RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType8RMT: threatTypeData.ASPMFrontSegType8RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist8RMT: threatDistanceData.ASPMFrontSegDist8RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType9RMT: threatTypeData.ASPMFrontSegType9RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist9RMT: threatDistanceData.ASPMFrontSegDist9RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType10RMT: threatTypeData.ASPMFrontSegType10RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist10RMT: threatDistanceData.ASPMFrontSegDist10RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType11RMT: threatTypeData.ASPMFrontSegType11RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist11RMT: threatDistanceData.ASPMFrontSegDist11RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType12RMT: threatTypeData.ASPMFrontSegType12RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist12RMT: threatDistanceData.ASPMFrontSegDist12RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType13RMT: threatTypeData.ASPMFrontSegType13RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist13RMT: threatDistanceData.ASPMFrontSegDist13RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType14RMT: threatTypeData.ASPMFrontSegType14RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist14RMT: threatDistanceData.ASPMFrontSegDist14RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType15RMT: threatTypeData.ASPMFrontSegType15RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist15RMT: threatDistanceData.ASPMFrontSegDist15RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegType16RMT: threatTypeData.ASPMFrontSegType16RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMFrontSegDist16RMT: threatDistanceData.ASPMFrontSegDist16RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType1RMT: threatTypeData.ASPMRearSegType1RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist1RMT: threatDistanceData.ASPMRearSegDist1RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType2RMT: threatTypeData.ASPMRearSegType2RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist2RMT: threatDistanceData.ASPMRearSegDist2RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType3RMT: threatTypeData.ASPMRearSegType3RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist3RMT: threatDistanceData.ASPMRearSegDist3RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType4RMT: threatTypeData.ASPMRearSegType4RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist4RMT: threatDistanceData.ASPMRearSegDist4RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType5RMT: threatTypeData.ASPMRearSegType5RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist5RMT: threatDistanceData.ASPMRearSegDist5RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType6RMT: threatTypeData.ASPMRearSegType6RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist6RMT: threatDistanceData.ASPMRearSegDist6RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType7RMT: threatTypeData.ASPMRearSegType7RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist7RMT: threatDistanceData.ASPMRearSegDist7RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType8RMT: threatTypeData.ASPMRearSegType8RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist8RMT: threatDistanceData.ASPMRearSegDist8RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType9RMT: threatTypeData.ASPMRearSegType9RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist9RMT: threatDistanceData.ASPMRearSegDist9RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType10RMT: threatTypeData.ASPMRearSegType10RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist10RMT: threatDistanceData.ASPMRearSegDist10RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType11RMT: threatTypeData.ASPMRearSegType11RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist11RMT: threatDistanceData.ASPMRearSegDist11RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType12RMT: threatTypeData.ASPMRearSegType12RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist12RMT: threatDistanceData.ASPMRearSegDist12RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType13RMT: threatTypeData.ASPMRearSegType13RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist13RMT: threatDistanceData.ASPMRearSegDist13RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType14RMT: threatTypeData.ASPMRearSegType14RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist14RMT: threatDistanceData.ASPMRearSegDist14RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType15RMT: threatTypeData.ASPMRearSegType15RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist15RMT: threatDistanceData.ASPMRearSegDist15RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegType16RMT: threatTypeData.ASPMRearSegType16RMT = (uint8_t)value; return; case ASPM_LM_ObjSegment::ASPMRearSegDist16RMT: threatDistanceData.ASPMRearSegDist16RMT = (uint8_t)value; return; default: printf("receive unknown signal:%d", sigid); return; } } else if (header_id == HRD_ID_OF_ASPM_LM_Trunc) { switch(sigid) { case ASPM_LM_Trunc::LMTruncEnPsPrasRotASPM_1: return; case ASPM_LM_Trunc::LMTruncEnPsPrasRotASPM_2: return; default: printf("receive unknown signal:%d", sigid); return; } } else { printf("Not valid header_id(%d)", header_id); } } uint16_t SignalHandler::encodeTCMSignalData(uint8_t* buffer) { int8_t ii, jj, kk = 0; uint16_t size_total = 0; uint8_t* curr_packet = buffer; uint8_t length = 0; uint8_t length_new = 0; uint8_t currValue = 0; int8_t loop = 0; int8_t startBit = 0; int8_t remainBits = 0; int pdu_header[NUMBER_OF_TCM_PDU] = {HRD_ID_OF_TCM_LM, HRD_ID_OF_TCM_LM_Session, HRD_ID_OF_TCM_RemoteControl, HRD_ID_OF_TCM_TransportKey, HRD_ID_OF_TCM_LM_App, HRD_ID_OF_TCM_LM_KeyID, HRD_ID_OF_TCM_LM_KeyAlpha, HRD_ID_OF_TCM_LM_KeyBeta, HRD_ID_OF_TCM_LM_KeyGamma }; memset(buffer, 0x00, UDP_BUF_MAX); for (kk = 0; kk<NUMBER_OF_TCM_PDU ; ++kk) { uint16_t index = 0; //printf("=> curr_packet addr : %p ", curr_packet); std::shared_ptr<SomePacket> packet = std::make_shared<SomePacket>(reinterpret_cast<char*>(curr_packet), UdpPacketType::SendTCMPacket); packet->putHeaderID(pdu_header[kk]); char* data = (char *)packet->getPayloadStartAddress(); std::vector<std::shared_ptr<LMSignalInfo>>& vt_signal = get_TCM_vector(pdu_header[kk]); for (ii=0; ii < vt_signal.size(); ii++) { length = vt_signal.at(ii)->getBitLength(); loop = (length-1)/8 ; for (jj = loop; jj >= 0; jj--) { unsigned long int x = 0xff; // 0xFF was int value in original code, this is not allowed to shift as int's max bit. So 0xFF should be defined as 8bytes(64bits) //currValue = ((m_RCDSignal->getSigValue(signalPack[ii])) & (0xFF << (8 * jj))) >> (8 * jj); //ORIGIN currValue = ( (getTCMSignal(packet->getHeaderID(), vt_signal.at(ii)->getIndex()) ) & (x << (8 * jj))) >> (8 * jj); //SANGGIL if (length > 8) { length_new = length - (8 * jj); length -= length_new; } else { length_new = length; currValue = (currValue & ((1 << length_new)-1)); } remainBits = 8 - startBit; if (length_new <= remainBits) { data[index] |= currValue << (remainBits - length_new); startBit = (startBit + length_new) % 8; if (startBit == 0) index++; } else { startBit = length_new - remainBits; data[index] |= currValue >> startBit; data[++index] |= currValue << (8 - startBit); } //LOGI("data[%d]: %02X", index } } uint16_t move_len = sizeof(pdu_header_t) + packet->getPayloadLength(); size_total += move_len; curr_packet += move_len; } //LOGE("==========================================(size_total: %d)", size_total); return size_total; } void SignalHandler::decodeASPMSignalData(uint8_t* buffer) { int8_t ii = 0, jj = 0; uint8_t length = 0; uint8_t bits_read = 0, bits_to_read = 0; uint8_t lmask = 0, rmask = 0, value_byte = 0; uint8_t bits_remaining = 0; uint64_t value = 0; uint8_t* curr_packet = buffer; uint16_t index = 0; for (ii = 0; ii < NUMBER_OF_ASPM_PDU; ++ii) { std::shared_ptr<SomePacket> packet = std::make_shared<SomePacket>(reinterpret_cast<char*>(curr_packet), UdpPacketType::ReadASPMPacket); char* data = (char *)packet->getPayloadStartAddress(); index = 0; std::vector<std::shared_ptr<LMSignalInfo>>& vt_signal = get_ASP_vector(packet->getHeaderID()); for (jj=0; jj < vt_signal.size(); ++jj) { length = vt_signal.at(jj)->getBitLength(); bits_read = value = 0; while(bits_read < length) { if (bits_remaining) { lmask = (uint8_t)0xFF >> (8 - bits_remaining); bits_to_read = std::min((uint8_t)(length - bits_read), bits_remaining); rmask = (uint8_t)0xFF << (bits_remaining - bits_to_read); bits_remaining -= bits_to_read; value_byte = (data[index] & lmask & rmask) >> bits_remaining; } else { bits_to_read = std::min((uint8_t)(length - bits_read), (uint8_t)8); rmask = (uint8_t)0xFF << (8 - bits_to_read); bits_remaining = 8 - bits_to_read; value_byte = (data[index] & rmask) >> bits_remaining; } bits_read += bits_to_read; value |= (uint64_t)value_byte << (length - bits_read); if (!bits_remaining) { ++index; } } setASPSignal(packet->getHeaderID(), vt_signal[jj]->getIndex(), value); } curr_packet += sizeof(pdu_header_t) + packet->getPayloadLength(); } } std::vector<std::shared_ptr<LMSignalInfo>>& SignalHandler::get_TCM_vector (int header_id) { switch( header_id ) { case HRD_ID_OF_TCM_LM: return this->vt_TCM_lm; case HRD_ID_OF_TCM_RemoteControl: return this->vt_TCM_remotecontrol; case HRD_ID_OF_TCM_LM_Session: return this->vt_TCM_lm_session; case HRD_ID_OF_TCM_TransportKey: return this->vt_TCM_transportkey; case HRD_ID_OF_TCM_LM_App: return this->vt_TCM_lm_app; case HRD_ID_OF_TCM_LM_KeyID: return this->vt_TCM_lm_keyid; case HRD_ID_OF_TCM_LM_KeyAlpha: return this->vt_TCM_lm_keyalpha; case HRD_ID_OF_TCM_LM_KeyBeta: return this->vt_TCM_lm_keybeta; case HRD_ID_OF_TCM_LM_KeyGamma: return this->vt_TCM_lm_keygamma; } return this->vt_TCM_lm; } std::vector<std::shared_ptr<LMSignalInfo>>& SignalHandler::get_ASP_vector (int header_id) { switch( header_id ) { case HRD_ID_OF_ASPM_LM: return this->vt_ASPM_lm; case HRD_ID_OF_ASPM_RemoteTarget: return this->vt_ASPM_remotetarget; case HRD_ID_OF_ASPM_LM_Session: return this->vt_ASPM_lm_session; case HRD_ID_OF_ASPM_LM_ObjSegment: return this->vt_ASPM_lm_objsegment; case HRD_ID_OF_ASPM_LM_Trunc: return this->vt_ASPM_lm_trunc; } return this->vt_ASPM_lm; }
b8e56517d08bb608d396cd3fbe38926cf285218f
2b519199b4b3c2060049950c5a8d96297f19d3cd
/cpp/13.罗马数字转整数.cpp
c5b2b1c20e7698ff7cebaa214278a706d5d34217
[]
no_license
JasonWu008/Leetcode
d0d821504c66f191fa11c5e51955592c8d72863c
1d042a400085aea548d79495a92020f663413784
refs/heads/master
2020-07-11T06:04:13.787792
2020-02-18T14:26:23
2020-02-18T14:26:23
166,430,796
1
0
null
null
null
null
UTF-8
C++
false
false
439
cpp
13.罗马数字转整数.cpp
class Solution { public: int romanToInt(string s) { map<char,int> a={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}}; int ans=0; for(int i=0;i<s.length();++i) { if(i==s.length()-1||a[s[i+1]]<=a[s[i]]) { ans+=a[s[i]]; } else { ans-=a[s[i]]; } } return ans; } };
33bd944b27ca426f9ca7e8a8afb567889c93a3a6
6a30f09dadfed64cfa90a9cdcaa5e8e4a05190f1
/BackendGuI/BackendGuI/GeneratedFiles/ui_loginwarn.h
a2290267296cbd0ca753a42c2929e207dc321903
[]
no_license
LarkHunter/lark
3fd80d047f45643aafd7b371e4ecc19026d2bb7a
105cec4b46e04919ea50724beb0e87db9abcec1e
refs/heads/master
2020-04-22T02:53:16.289076
2019-06-12T09:48:31
2019-06-12T09:48:31
170,066,604
1
0
null
null
null
null
UTF-8
C++
false
false
1,522
h
ui_loginwarn.h
/******************************************************************************** ** Form generated from reading UI file 'loginwarn.ui' ** ** Created by: Qt User Interface Compiler version 5.7.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_LOGINWARN_H #define UI_LOGINWARN_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_loginWarn { public: QLabel *label; void setupUi(QWidget *loginWarn) { if (loginWarn->objectName().isEmpty()) loginWarn->setObjectName(QStringLiteral("loginWarn")); loginWarn->resize(670, 422); label = new QLabel(loginWarn); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(80, 40, 501, 341)); retranslateUi(loginWarn); QMetaObject::connectSlotsByName(loginWarn); } // setupUi void retranslateUi(QWidget *loginWarn) { loginWarn->setWindowTitle(QApplication::translate("loginWarn", "loginWarn", Q_NULLPTR)); label->setText(QApplication::translate("loginWarn", "TextLabel", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class loginWarn: public Ui_loginWarn {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_LOGINWARN_H
506337295b1a92a48262b92a27f6a919ce46f94b
16dc54384a53f8bcd6dfdecfbabd385d51acb7de
/2017_summer_acmcode/self pratice/POJ 3320/main.cpp
7ff0d5ab563eecef6e1006cfec5accd04272a233
[]
no_license
kkkkBlueSky/HUAS_ACM
629771b4b583a0725ee0955ddbf35cdfaddec652
3b9aad20476ec09bb5f12f951340829e68152094
refs/heads/master
2021-12-17T21:47:13.245217
2017-09-22T12:54:51
2017-09-22T12:54:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
main.cpp
#include <iostream> #include <cstdio> #include <set> #include <map> using namespace std; const int maxn=1000005; int p, data[maxn]; set<int> book; map<int, int> cnt; int main() { while(~scanf("%d", &p)){ book.clear(); cnt.clear(); for(int i=0;i<p;i++){ scanf("%d", &data[i]); book.insert(data[i]); } int all=book.size(); int l=0, r=0, ans=p, num=0; for(;;){ while(r<p && num<all){ if(cnt[data[r]]==0){ num++; } cnt[data[r]]++; r++; } if(num<all)break; ans=min(ans, r-l); if(--cnt[data[l++]]==0)num--; } printf("%d\n", ans); } return 0; }
df77a8789131f82d5b3d7d704b62e56975841b0c
19194c2f2c07ab3537f994acfbf6b34ea9b55ae7
/android-33/android/view/accessibility/AccessibilityWindowInfo.hpp
376eac0fac3bf4e1efdaeaab12e41d4bbc69775b
[ "GPL-3.0-only" ]
permissive
YJBeetle/QtAndroidAPI
e372609e9db0f96602da31b8417c9f5972315cae
ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c
refs/heads/Qt6
2023-08-05T03:14:11.842336
2023-07-24T08:35:31
2023-07-24T08:35:31
249,539,770
19
4
Apache-2.0
2022-03-14T12:15:32
2020-03-23T20:42:54
C++
UTF-8
C++
false
false
6,640
hpp
AccessibilityWindowInfo.hpp
#pragma once #include "../../graphics/Rect.def.hpp" #include "../../graphics/Region.def.hpp" #include "../../os/Parcel.def.hpp" #include "./AccessibilityNodeInfo.def.hpp" #include "../../../JString.hpp" #include "../../../JObject.hpp" #include "../../../JString.hpp" #include "./AccessibilityWindowInfo.def.hpp" namespace android::view::accessibility { // Fields inline JObject AccessibilityWindowInfo::CREATOR() { return getStaticObjectField( "android.view.accessibility.AccessibilityWindowInfo", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } inline jint AccessibilityWindowInfo::TYPE_ACCESSIBILITY_OVERLAY() { return getStaticField<jint>( "android.view.accessibility.AccessibilityWindowInfo", "TYPE_ACCESSIBILITY_OVERLAY" ); } inline jint AccessibilityWindowInfo::TYPE_APPLICATION() { return getStaticField<jint>( "android.view.accessibility.AccessibilityWindowInfo", "TYPE_APPLICATION" ); } inline jint AccessibilityWindowInfo::TYPE_INPUT_METHOD() { return getStaticField<jint>( "android.view.accessibility.AccessibilityWindowInfo", "TYPE_INPUT_METHOD" ); } inline jint AccessibilityWindowInfo::TYPE_MAGNIFICATION_OVERLAY() { return getStaticField<jint>( "android.view.accessibility.AccessibilityWindowInfo", "TYPE_MAGNIFICATION_OVERLAY" ); } inline jint AccessibilityWindowInfo::TYPE_SPLIT_SCREEN_DIVIDER() { return getStaticField<jint>( "android.view.accessibility.AccessibilityWindowInfo", "TYPE_SPLIT_SCREEN_DIVIDER" ); } inline jint AccessibilityWindowInfo::TYPE_SYSTEM() { return getStaticField<jint>( "android.view.accessibility.AccessibilityWindowInfo", "TYPE_SYSTEM" ); } // Constructors inline AccessibilityWindowInfo::AccessibilityWindowInfo() : JObject( "android.view.accessibility.AccessibilityWindowInfo", "()V" ) {} inline AccessibilityWindowInfo::AccessibilityWindowInfo(android::view::accessibility::AccessibilityWindowInfo &arg0) : JObject( "android.view.accessibility.AccessibilityWindowInfo", "(Landroid/view/accessibility/AccessibilityWindowInfo;)V", arg0.object() ) {} // Methods inline android::view::accessibility::AccessibilityWindowInfo AccessibilityWindowInfo::obtain() { return callStaticObjectMethod( "android.view.accessibility.AccessibilityWindowInfo", "obtain", "()Landroid/view/accessibility/AccessibilityWindowInfo;" ); } inline android::view::accessibility::AccessibilityWindowInfo AccessibilityWindowInfo::obtain(android::view::accessibility::AccessibilityWindowInfo arg0) { return callStaticObjectMethod( "android.view.accessibility.AccessibilityWindowInfo", "obtain", "(Landroid/view/accessibility/AccessibilityWindowInfo;)Landroid/view/accessibility/AccessibilityWindowInfo;", arg0.object() ); } inline jint AccessibilityWindowInfo::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } inline jboolean AccessibilityWindowInfo::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } inline android::view::accessibility::AccessibilityNodeInfo AccessibilityWindowInfo::getAnchor() const { return callObjectMethod( "getAnchor", "()Landroid/view/accessibility/AccessibilityNodeInfo;" ); } inline void AccessibilityWindowInfo::getBoundsInScreen(android::graphics::Rect arg0) const { callMethod<void>( "getBoundsInScreen", "(Landroid/graphics/Rect;)V", arg0.object() ); } inline android::view::accessibility::AccessibilityWindowInfo AccessibilityWindowInfo::getChild(jint arg0) const { return callObjectMethod( "getChild", "(I)Landroid/view/accessibility/AccessibilityWindowInfo;", arg0 ); } inline jint AccessibilityWindowInfo::getChildCount() const { return callMethod<jint>( "getChildCount", "()I" ); } inline jint AccessibilityWindowInfo::getDisplayId() const { return callMethod<jint>( "getDisplayId", "()I" ); } inline jint AccessibilityWindowInfo::getId() const { return callMethod<jint>( "getId", "()I" ); } inline jint AccessibilityWindowInfo::getLayer() const { return callMethod<jint>( "getLayer", "()I" ); } inline android::view::accessibility::AccessibilityWindowInfo AccessibilityWindowInfo::getParent() const { return callObjectMethod( "getParent", "()Landroid/view/accessibility/AccessibilityWindowInfo;" ); } inline void AccessibilityWindowInfo::getRegionInScreen(android::graphics::Region arg0) const { callMethod<void>( "getRegionInScreen", "(Landroid/graphics/Region;)V", arg0.object() ); } inline android::view::accessibility::AccessibilityNodeInfo AccessibilityWindowInfo::getRoot() const { return callObjectMethod( "getRoot", "()Landroid/view/accessibility/AccessibilityNodeInfo;" ); } inline android::view::accessibility::AccessibilityNodeInfo AccessibilityWindowInfo::getRoot(jint arg0) const { return callObjectMethod( "getRoot", "(I)Landroid/view/accessibility/AccessibilityNodeInfo;", arg0 ); } inline JString AccessibilityWindowInfo::getTitle() const { return callObjectMethod( "getTitle", "()Ljava/lang/CharSequence;" ); } inline jint AccessibilityWindowInfo::getType() const { return callMethod<jint>( "getType", "()I" ); } inline jint AccessibilityWindowInfo::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } inline jboolean AccessibilityWindowInfo::isAccessibilityFocused() const { return callMethod<jboolean>( "isAccessibilityFocused", "()Z" ); } inline jboolean AccessibilityWindowInfo::isActive() const { return callMethod<jboolean>( "isActive", "()Z" ); } inline jboolean AccessibilityWindowInfo::isFocused() const { return callMethod<jboolean>( "isFocused", "()Z" ); } inline jboolean AccessibilityWindowInfo::isInPictureInPictureMode() const { return callMethod<jboolean>( "isInPictureInPictureMode", "()Z" ); } inline void AccessibilityWindowInfo::recycle() const { callMethod<void>( "recycle", "()V" ); } inline JString AccessibilityWindowInfo::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } inline void AccessibilityWindowInfo::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::view::accessibility // Base class headers #ifdef QT_ANDROID_API_AUTOUSE using namespace android::view::accessibility; #endif
85967889ccdd90cdd43510dba44c9fcc6750d85f
082253ba1d986f8e57589a6979211f096aa419c7
/mycommonexpenses.cpp
f085285879ae1f00c9f5e3d5bdcc1935e4fa1cd9
[]
no_license
sokratisathancsd/qtQuick-myWalletApplication-csdauth
131cdc3d4b1c777bfe67a7ca9c82bc5b352a7878
cedfab4bf751ccbb97b1f8f81ba024ec61517d34
refs/heads/main
2023-05-01T02:40:42.640093
2021-05-14T09:28:08
2021-05-14T09:28:08
367,313,860
0
0
null
null
null
null
UTF-8
C++
false
false
742
cpp
mycommonexpenses.cpp
#include "mycommonexpenses.h" myCommonExpenses::myCommonExpenses(const QString &title,const QString &cost, const QString &category) : m_title(title), m_cost(cost), m_category(category){ } QString myCommonExpenses::title() const{ return m_title; } void myCommonExpenses::setTitle(const QString &title){ if(title != m_title){ m_title=title; } } QString myCommonExpenses::cost() const{ return m_cost; } void myCommonExpenses::setCost(const QString &cost){ if(cost != m_cost){ m_cost=cost; } } QString myCommonExpenses::category()const{ return m_category; } void myCommonExpenses::setCategory(const QString &category){ if(category != m_category){ m_category=category; } }
8b001b6a24d34bfee753e3403d098ea32b179e52
8791397de8f3ffaa8cad0c321bedf52d034be11c
/cpp06/ex02/main.cpp
a7baebc85414e67897079566aecace6a67488236
[]
no_license
Pizzagami/cpp
56999b5328ec6289156a428997bf348abd99c574
e6626f2035bdea451cf696a4d2ddeb61e0b2011a
refs/heads/master
2023-04-02T13:34:22.316763
2021-03-30T13:09:04
2021-03-30T13:09:04
334,195,656
0
1
null
null
null
null
UTF-8
C++
false
false
622
cpp
main.cpp
#include <iostream> #include "A.hpp" #include "B.hpp" #include "C.hpp" void identify_from_pointer(Base *p) { if (dynamic_cast<A*>(p)) std::cout << "A" << std::endl; else if (dynamic_cast<B*>(p)) std::cout << "B" << std::endl; else if (dynamic_cast<C*>(p)) std::cout << "C" << std::endl; } void identify_from_reference(Base &p) { identify_from_pointer(&p); } int main(void) { A a; B b; C c; identify_from_pointer(&a); identify_from_pointer(&b); identify_from_pointer(&c); std::cout << std::endl; identify_from_reference(c); identify_from_reference(b); identify_from_reference(a); return 0; }
ba8bc524e286548d201eb81823ac1241bf4693bf
8ff4b9db2db900514e0a0509227b68d9bc7cf5e3
/include/util.h
71ac0190fe163f4ddc62f3742244482a562cef65
[ "BSD-2-Clause" ]
permissive
ankwinters/StereoTracking
b7f80bba5b0e3f4f5e7bd5e2dfc94b74bd66547b
f7e2c52c0c4481303560a1d03603a9d4971e8103
refs/heads/master
2021-11-12T22:16:01.905275
2016-12-27T13:08:40
2016-12-27T13:08:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
212
h
util.h
// // Created by lab on 16-12-27. // #ifndef POEST_UTIL_H #define POEST_UTIL_H namespace tracker { enum LogOption { debug = 0, check = 1, release = 2 }; } #endif //POEST_UTIL_H
c58b63824364f1ebec5c8aa4a06d231b7f89c1c8
593d187dd1339b8ff2c585d35cc9684acb0cc4a5
/Shape.h
86e9f795c63f48731b8ab8b0db617a078097baba
[]
no_license
yifannir/QTdrawTable
8772ed1e0aeb5714ef00f2a3b0951615778d5307
d982b8451d51f78c9556646fb176bd6ed33ed81e
refs/heads/master
2020-03-30T07:41:15.284683
2018-11-15T13:41:05
2018-11-15T13:41:05
150,958,778
0
0
null
null
null
null
UTF-8
C++
false
false
491
h
Shape.h
#pragma once #include <QPoint> #include <QPainter> #include <qevent.h> class Shape :public QObject { Q_OBJECT public: Shape(); ~Shape(); virtual void dodata_p(); virtual void dodata_m(); virtual void dodata_r(); virtual void doda_m_move(); virtual void doda_p_move(); virtual void draw(QPainter & painter); virtual bool isShot(); virtual bool drawisOver(); virtual int getType(); virtual void save(); virtual void load(std::string data); };
df6c1bb250c7f8b2a67c9a9e48e8a2da5dbff9b7
dc888595f079eade0807235c1880642600974d95
/seven day_1/gridLayout/main.cpp
75f9e82df2825a14e7f605e0f2ef070675072f7d
[]
no_license
WenchaoZhang/qt_learing
53377594e4102a68ddcadfab121d502ffab72a53
33e4dbdbd3a2c35e124c923b850e6e244aab320b
refs/heads/master
2021-01-23T19:29:10.871224
2017-09-30T04:40:22
2017-09-30T04:40:22
102,826,803
2
0
null
null
null
null
UTF-8
C++
false
false
2,409
cpp
main.cpp
#include "widget.h" #include <QApplication> #include <QLabel> #include <QWidget> #include <QGridLayout> #include <QLineEdit> #include <QPalette> #include <QPixmap> #include <QDebug> #include <QCheckBox> #include <QPushButton> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget mywidget; mywidget.resize(400,200); mywidget.setStyleSheet("border-color:rgb(1,0,0)"); mywidget.setWindowTitle("登陆界面"); QPalette pt(mywidget.palette()); pt.setColor(QPalette::Background,QColor(70,70,70)); //设置图片 QPixmap *img = new QPixmap("C:/Users/admin/Desktop/qt project/catch.PNG"); QLabel lb1; *img = img->scaled(mywidget.size()/2,Qt::KeepAspectRatio); lb1.setPixmap(*img); //初始化布局 QGridLayout *gl = new QGridLayout; gl->setSpacing(10); gl->addWidget(&lb1,0,0,3,3); //做行编辑器 QLineEdit *le1 = new QLineEdit; QLineEdit *le2 = new QLineEdit; le1->setPlaceholderText(QStringLiteral("QQ号/邮箱/手机号登陆")); le1->setStyleSheet("border-radius:2px;border:1px solid rgb(48,153,216)"); le1->setMinimumHeight(23); le2->setPlaceholderText(QStringLiteral("QQ密码")); le2->setStyleSheet("border-radius:2px;border:1px solid rgb(48,153,216)"); le2->setMinimumHeight(23); gl->addWidget(le1,0,3,1,3); gl->addWidget(le2,1,3,1,3); //做复选框 QCheckBox ck1("记住密码"); QCheckBox ck2("自动登录"); ck1.setStyleSheet("color:rgb(255,255,255)"); ck2.setStyleSheet("color:rgb(255,255,255)"); gl->addWidget(&ck1,2,3,1,1); gl->addWidget(&ck2,2,5,1,1); //做按键 QPushButton *bnt1 = new QPushButton("登陆"); bnt1->setStyleSheet("color: rgb(255,255,255);background-color: rgb(48,153,216);border-radius:3px"); bnt1->setMinimumHeight(30); bnt1->setFlat(true); gl->addWidget(bnt1,3,3,1,3); QPushButton *bnt2 = new QPushButton("注册账号"); bnt2->setFlat(true); bnt2->setStyleSheet("color: rgb(48,153,216)"); gl->addWidget(bnt2,0,6,1,2); QPushButton *bnt3 = new QPushButton("忘记密码"); bnt3->setStyleSheet("color:rgb(48,153,216)"); bnt3->setFlat(true); gl->addWidget(bnt3,1,6,1,2); qDebug() << lb1.size() << endl; qDebug() << mywidget.size() << endl; mywidget.setLayout(gl); mywidget.setPalette(pt); mywidget.show(); return a.exec(); }
8d5eef0bdd919414ba88639d6d2c1676b20c8ecc
84897b6a25f876b21246c2c7e1404c9c411be987
/src/src/format/hfs/RCHfsArchiveInfo.cpp
fbf366e2e81aa2174679b1ed0586ce5cd6fb5667
[]
no_license
drivestudy/HaoZip
07718a53e38bc5893477575ddf3fccfb3b18c5fd
9e0564b4a11870224543357004653b798fd625e0
refs/heads/master
2021-07-24T06:33:24.651453
2017-11-05T01:19:18
2017-11-05T01:19:18
null
0
0
null
null
null
null
GB18030
C++
false
false
2,049
cpp
RCHfsArchiveInfo.cpp
/******************************************************************************** * 版权所有(C)2008,2009,2010,好压软件工作室,保留所有权利。 * ******************************************************************************** * 作者 : HaoZip * * 版本 : 1.7 * * 联系方式: haozip@gmail.com * * 官方网站: www.haozip.com * ********************************************************************************/ //include files #include "format/hfs/RCHfsArchiveInfo.h" #include "format/hfs/RCHfsHandler.h" ///////////////////////////////////////////////////////////////// //RCHfsArchiveInfo class implementation BEGIN_NAMESPACE_RCZIP IInArchive* CreateRCHfsHandlerIn() { RCHfsHandler* hfs = new RCHfsHandler; if (hfs) { return (IInArchive*)hfs; } return 0; } IOutArchive* CreateRCHfsHandlerOut() { return 0; } RCHfsArchiveInfo::RCHfsArchiveInfo() { } RCHfsArchiveInfo::~RCHfsArchiveInfo() { } RCArchiveID RCHfsArchiveInfo::GetArchiveID() const { return RC_ARCHIVE_HFS ; } RCString RCHfsArchiveInfo::GetName() const { return RC_ARCHIVE_TYPE_HFS ; } RCString RCHfsArchiveInfo::GetExt() const { return _T("hfs") ; } RCString RCHfsArchiveInfo::GetAddExt() const { return _T("") ; } void RCHfsArchiveInfo::GetSignature(std::vector<byte_t>& signature) const { signature.clear() ; signature.push_back('H') ; signature.push_back('+') ; signature.push_back(0) ; signature.push_back(4) ; } bool RCHfsArchiveInfo::IsKeepName() const { return false ; } PFNCreateInArchive RCHfsArchiveInfo::GetCreateInArchiveFunc(void) const { return CreateRCHfsHandlerIn ; } PFNCreateOutArchive RCHfsArchiveInfo::GetCreateOutArchiveFunc(void) const { return CreateRCHfsHandlerOut ; } END_NAMESPACE_RCZIP
58b7e1bb80e574d871e03139ce64d272e257095a
99101626591f8576323a1fa7dcb0ff225e83658e
/include/DataFile.h
bce2158c452792a1e41ba3838674d9d464836f18
[]
no_license
seelabutk/pbnj
a2f6425754fc554533edf98b5850b93c7130d01e
64a3a7e5c1b9c8a08b1f81cfe1cdec94a60f61d7
refs/heads/master
2021-01-19T06:12:53.877491
2019-04-16T17:57:37
2019-04-16T17:57:37
100,629,012
5
3
null
2019-04-15T14:29:59
2017-08-17T17:33:05
C++
UTF-8
C++
false
false
1,072
h
DataFile.h
#ifndef PBNJ_DATAFILE_H #define PBNJ_DATAFILE_H #include <string> #include <pbnj.h> namespace pbnj { enum FILETYPE {UNKNOWN, BINARY, NETCDF}; class DataFile { public: DataFile(int x, int y, int z); ~DataFile(); void loadFromFile(std::string filename, std::string variable="", bool memmap=false); void calculateStatistics(); void printStatistics(); // experimental void bin(unsigned int num_bins); std::string filename; FILETYPE filetype; unsigned long int xDim; unsigned long int yDim; unsigned long int zDim; unsigned long int numValues; float minVal; // these should float maxVal; // float avgVal; // eventually be float stdDev; // float *data; // template types bool statsCalculated; private: FILETYPE getFiletype(); bool wasMemoryMapped; }; } #endif
3f62202c005e66f8d9716ddab6294f699bf8de71
95e16bafd205898b07fb385b1fd62ee5f3b4c89f
/DC_Enemy_Assault_2021.altis/cau/extendedchat/emojipack/twemoji/popular/data/wave.cpp
651e6bb7aae7d67585449cffc0f092f4382eea6b
[ "CC-BY-4.0" ]
permissive
rkfnql322/DC_Enemy_assault_2021
d7a5e596a61cb6e1ea51b8d52617b5b224fbd64e
61831d9fb8472476898b088bf38db38359be600f
refs/heads/main
2023-08-02T15:20:30.001631
2021-08-31T11:24:36
2021-08-31T11:24:36
405,390,780
0
0
null
2021-09-11T13:47:29
2021-09-11T13:47:28
null
UTF-8
C++
false
false
173
cpp
wave.cpp
class wave { displayName="Waving Hand Sign"; icon="cau\extendedchat\emojipack\twemoji\popular\data\wave.paa"; keywords[]={"wave"}; shortcuts[]={}; condition="true"; };
a50aa2aaceb1af1fdfb362518eb2e169b1533238
385cfbb27ee3bcc219ec2ac60fa22c2aa92ed8a0
/Gui3d/LayoutCenter.h
b4827db15f742efbb85981f5e7f926ca1a733c17
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
palestar/medusa
edbddf368979be774e99f74124b9c3bc7bebb2a8
7f8dc717425b5cac2315e304982993354f7cb27e
refs/heads/develop
2023-05-09T19:12:42.957288
2023-05-05T12:43:35
2023-05-05T12:43:35
59,434,337
35
18
MIT
2018-01-21T01:34:01
2016-05-22T21:05:17
C++
UTF-8
C++
false
false
539
h
LayoutCenter.h
/* LayoutCenter.h (c)2005 Palestar Inc, Richard Lyle */ #ifndef LAYOUTCENTER_H #define LAYOUTCENTER_H #include "Gui3d/WindowLayout.h" #include "Gui3d/GUI3DDll.h" //---------------------------------------------------------------------------- class DLL LayoutCenter : public WindowLayout { public: DECLARE_WIDGET_CLASS(); // Construction LayoutCenter(); }; //---------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------- //EOF
c3215dd3e49bced3ba6e2474601e5ae05e43a02f
3b7fbde71e0ddb558d8bdc6522895b9c11df051c
/src/view/player_widget.h
86c2e41fdb462b55de114c8b07309240087b36fa
[]
no_license
imagora/Gump
21f3b44a7640f2be3edf5ab2b06a0e264274699a
359ed37dd2c0d40f8a33fc6a06b79e44203ed30d
refs/heads/master
2022-03-29T10:33:27.147590
2019-03-24T07:05:20
2019-03-24T07:05:20
93,634,918
2
1
null
null
null
null
UTF-8
C++
false
false
1,065
h
player_widget.h
// Copyright (c) 2014-2019 winking324 // #pragma once // NOLINT(build/header_guard) #include <QLabel> #include <QString> #include <QWidget> #include <QtAV/QtAV> #include <string> namespace gump { class PlayerWidget : public QWidget { Q_OBJECT public: explicit PlayerWidget(QWidget *parent = nullptr); virtual ~PlayerWidget(); void PlayStream(const std::string &stream); void BufferStream(const std::string &stream); void StopStream(); void StartStream(); void PauseStream(); void ShowDetails(); void WindowMove(); private slots: void OnMediaStatusChanged(QtAV::MediaStatus status); void OnPlayerError(const QtAV::AVError& e); void RefreshMediaInfoTimer(); private: QString PlayerStatus(uint32_t status = 0); private: bool is_show_details_; int current_screen_number_; int current_screen_ratio_; QtAV::VideoOutput *video_output_; QtAV::AVPlayer *player_; QtAV::AVPlayer *buffered_player_; QLabel *player_status_; std::string stream_; std::string buffered_stream_; }; } // namespace gump
225cfc6dcf47762489af9e0ffbb5b7e7d9f77ee6
f41b9f9995d69dd4a4c1e9b443339da65a259a3c
/carcounter.cpp
0404a510ad4257c221d4970d353976e607c57cd6
[]
no_license
neslihaneciogluu/countingCar
3cd68eae60860cc54fd774dd39d408c70788b68f
782f913ec3848d6897b8c472992330f35278d011
refs/heads/master
2023-01-22T14:29:05.761024
2019-01-10T17:20:14
2019-01-10T17:20:14
165,100,971
0
0
null
null
null
null
UTF-8
C++
false
false
7,191
cpp
carcounter.cpp
#include "carcounter.h" carCounter::carCounter() { } cv::VideoWriter video("outcp.avi",CV_FOURCC('M','J','P','G'),10, cv::Size(640,360)); void carCounter::methodProcess(){ yoloClass *yoloInstance=yoloInstance->getInstance(); QDir mainDirVideoFolder(m_pathOfVideoFolder); QStringList allFilesInsideFolder = mainDirVideoFolder.entryList(QDir::NoDotAndDotDot | QDir::Files); for(int videos=0;videos<allFilesInsideFolder.length();videos++) { QString videoPath=mainDirVideoFolder.absolutePath()+ "/" + allFilesInsideFolder.at(videos); try { cv::VideoCapture vc(videoPath.toUtf8().constData()); while(true) { vc.read(m_frameReading); m_frameNumber++; if(m_frameReading.cols != 0 && m_frameReading.rows != 0){ //Vehicle Detection yoloClass::yoloReturnValues vehicleDetectionInfo=yoloInstance->yoloConvert(m_frameReading); std::vector<cv::Rect2d> vehicleBBox=vehicleDetectionInfo.bboxes; std::vector<std::string> vehicleNames=vehicleDetectionInfo.names; //if the reading the first frame,initialize the map if(m_frameNumber==1){ for(int i=0;i<vehicleBBox.size();i++){ if(vehicleNames.at(i)=="car" ||vehicleNames.at(i)=="truck" ){ m_pair.first=vehicleBBox.at(i); m_pair.second=1; m_map.insert(m_vehicleIndex,m_pair); m_vehicleIndex++; } } } //Otherwise,update the map values. else{ //flag variable is used to find out if the car has just entered or not bool flag=false; for(int i=0;i<vehicleBBox.size();i++) { if(vehicleNames.at(i)=="car" ||vehicleNames.at(i)=="truck" ){ cv::rectangle(m_frameReading,vehicleBBox.at(i),cv::Scalar(255,255,0),2); //The code draws the line to the range as follows.If the car //passess to this range,the code counts the car. cv::line(m_frameReading,cv::Point(0,m_frameReading.rows/2),cv::Point(m_frameReading.cols,m_frameReading.rows/2),cv::Scalar(255,0,0),5); //For tracking the car,the following code runs for (m_ik = m_map.begin(); m_ik != m_map.end(); ++m_ik){ cv::Rect2d bboxes; bboxes.x=m_ik.value().first.x; bboxes.y=m_ik.value().first.y; bboxes.width=m_ik.value().first.width; bboxes.height=m_ik.value().first.height; int mapI=m_ik.key(); //All detected coordinates are compared with the ones in the map. //if the intersection of coordinates biiger than the following area //then track the detected coordinates as new id.The old value of in the map,erase if((bboxes & vehicleBBox.at(i)).area() > bboxes.area()*m_intersectionValue){ m_map.erase(m_ik); m_pair.first=vehicleBBox.at(i); m_pair.second++; m_map.insert(mapI,m_pair); flag=true; } } //if the coordinate does not match any bbox,then flag is false.This vehicle enters newly if(flag ==false){ m_pair.first=vehicleBBox.at(i); m_pair.second=1; m_map.insert(m_vehicleIndex,m_pair); m_vehicleIndex++; } } } } for (m_ik = m_map.begin(); m_ik != m_map.end(); ++m_ik){ cv::Rect2d bboxes; bboxes.x=m_ik.value().first.x; bboxes.y=m_ik.value().first.y; bboxes.width=m_ik.value().first.width; bboxes.height=m_ik.value().first.height; if((bboxes.y>m_frameReading.rows/2)){ for(int ii=0;ii<m_IDOfVehicle.size();ii++){ m_control++; if(std::find(m_IDOfVehicle.begin(), m_IDOfVehicle.end(), m_ik.key()) != m_IDOfVehicle.end()) { if(m_ik.value().second>100){ //map.remove(ik.key()); m_erasingVector.push_back(m_ik.key()); continue; } } else {//if the ID is not in the map,counts and add this ID to vector. m_numberOfCar++; m_IDOfVehicle.push_back(m_ik.key()); } } if(m_IDOfVehicle.size()==0){ m_numberOfCar++; m_IDOfVehicle.push_back(m_ik.key()); } } } cv::putText(m_frameReading,QString::number(m_numberOfCar).toStdString(), cv::Point(m_frameReading.rows/2,m_frameReading.cols/2), CV_FONT_HERSHEY_COMPLEX,2, cv::Scalar(0, 0, 255),2); QString annotatedImage="images/"; QDir().mkdir(annotatedImage); QString pathOfImage =annotatedImage+ QString::number(m_imageName)+".jpg"; m_imageName++; std::string imagePath = pathOfImage.toUtf8().constData(); imwrite(imagePath,m_frameReading); for(int i=0;i<m_erasingVector.size();i++){ m_IDOfVehicle.erase(std::remove(m_IDOfVehicle.begin(), m_IDOfVehicle.end(), m_erasingVector.at(i)), m_IDOfVehicle.end()); m_map.remove(m_erasingVector.at(i)); } m_erasingVector.clear(); } video.write(m_frameReading); } } catch( cv::Exception& e ) { const char* err_msg = e.what(); std::cout << "Exception caught: " << err_msg << std::endl; } } }
51b9871f02334963387a56d3b4de1629cd5fa15c
c8aaa3d846dcda4842896b27a3f67ed47c173b57
/src/algorithms/Profiler/Profiler.cc
479734efa827084521e5f8a2ade7c1246f01add8
[]
no_license
Refeel/OmnetppTrafficHandlingSimulation
91b7548c2f4e2177dd215fcf1518a05f456fff14
7fbaea1a54096f2db7d3c5d5b675cb97d7811545
refs/heads/master
2020-12-24T16:23:38.965239
2013-06-02T16:56:36
2013-06-02T16:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,262
cc
Profiler.cc
/* * Profiler.cc * * Created on: 19-04-2013 * Author: Rafa? */ #include "Profiler.h" namespace omnetpptraffichandlingsimulation { Profiler::Profiler() { // TODO Auto-generated constructor stub } Profiler::~Profiler() { // TODO Auto-generated destructor stub } void Profiler::initialize() { hist.setName("delayStats"); hist.setRangeAutoUpper(0,40000,2.0); inputHist.setName("inputStats"); inputHist.setRangeAutoUpper(0,1000,2.0); outputHist.setName("outputStats"); outputHist.setRangeAutoUpper(0,1000,2.0); deletedCount = 0; packetsSum = 0; } void Profiler::forwardPacket(SimplePacket *sp) { double delay = simTime().dbl() - timeStampQueue.front(); timeStampQueue.pop(); hist.collect(delay); outputHist.collect(simTime().dbl()); send(sp, "out", 0); // for single output } void Profiler::addTimeStamp() { timeStampQueue.push(simTime().dbl()); } void Profiler::handleMessage(cMessage *msg) { send(msg, "out", 0); } void Profiler::finish() { hist.recordAs("delays_count"); inputHist.recordAs("input_count"); outputHist.recordAs("output_count"); recordScalar("deletedMessagesRate", (double)deletedCount/packetsSum); } } /* namespace omnetpptrafficgenerators */