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
830aa65fff3e0591ff451d3aac1350d7f0e51663
9dea335fd82ea91fcca8facbba65009ca9c59355
/Dev/Cpp/common/EffekseerPluginModel.cpp
7e8aa8597031d9915e5373c3c6c4e76a4b59c8b5
[ "MIT" ]
permissive
effekseer/EffekseerForUnity
529d43dd198f825ec3fe1d95c7f8610b7b91741b
9004b1002daec41e5cf45716e26bad8e83e97ab2
refs/heads/master
2023-08-18T18:29:50.987077
2023-08-03T03:54:01
2023-08-03T03:54:01
66,772,750
50
28
MIT
2023-08-03T03:52:55
2016-08-28T14:31:50
C#
UTF-8
C++
false
false
2,115
cpp
EffekseerPluginModel.cpp
#include "EffekseerPluginModel.h" #include <algorithm> namespace EffekseerPlugin { ModelLoader::ModelLoader(ModelLoaderLoad load, ModelLoaderUnload unload, GetUnityIDFromPath getUnityId) : load(load), unload(unload), getUnityId_(getUnityId) { memoryFile = Effekseer::MakeRefPtr<MemoryFile>(1 * 1024 * 1024); } Effekseer::ModelRef ModelLoader::Load(const EFK_CHAR* path) { auto id = getUnityId_(path); Effekseer::ModelRef generated; if (id2Obj_.TryLoad(id, generated)) { return generated; } // Load with unity int requiredDataSize = 0; auto modelPtr = load((const char16_t*)path, memoryFile->LoadedBuffer.data(), (int)memoryFile->LoadedBuffer.size(), requiredDataSize); if (requiredDataSize == 0) { // Failed to load return nullptr; } if (modelPtr == nullptr) { // Lack of memory memoryFile->Resize(requiredDataSize); // Load with unity modelPtr = load((const char16_t*)path, memoryFile->LoadedBuffer.data(), (int)memoryFile->LoadedBuffer.size(), requiredDataSize); if (modelPtr == nullptr) { // Failed to load return nullptr; } } memoryFile->LoadedSize = (size_t)requiredDataSize; auto modelDataPtr = internalLoader->Load(path); id2Obj_.Register(id, modelDataPtr, modelPtr); return modelDataPtr; } void ModelLoader::Unload(Effekseer::ModelRef source) { if (source == nullptr) { return; } int32_t id{}; void* nativePtr{}; if (id2Obj_.Unload(source, id, nativePtr)) { unload(id, nativePtr); // delay unload auto instance = RenderThreadEvent::GetInstance(); if (instance != nullptr) { source->AddRef(); instance->AddEvent( [source]() { // a resource must be unload in a rendering thread source->Release(); }); } } } void ProceduralModelGenerator::Ungenerate(Effekseer::ModelRef model) { if (model == nullptr) { return; } // delay unload auto instance = RenderThreadEvent::GetInstance(); if (instance != nullptr) { model->AddRef(); instance->AddEvent( [model]() { // a resource must be unload in a rendering thread model->Release(); }); } } } // namespace EffekseerPlugin
55f8846ef0450681b62807a9eebe820216059cee
ba444c530390b369d92d2a446b2667ed10674ac4
/problems/12502.cpp
7b212084df0ab96f2b770917b772428db4d5753f
[]
no_license
mkroflin/UVa
62c00eede8b803487fa96c6f34dc089b7ea80df5
aa9815f710db094fb67ceafb485b139de58e9745
refs/heads/master
2022-03-21T05:04:32.445579
2018-11-15T19:44:19
2018-11-15T19:44:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
12502.cpp
#include <iostream> using namespace std; int main() { int t, a, b, m; cin >> t; while (t--) { cin >> a >> b >> m; int r; if (2 * a <= b) r = 0; else if (a < 2 * b) r = (2 * m * a - m * b) / (a + b); else r = m; cout << r << '\n'; } }
996f334afabf102c74ad5af11afa99be300c3cef
49fea82ce3cb1b9eef5de574c640333c28aba12d
/1091OOPIMW04/TS0402/Fraction.cpp
deaff61fbf636df42bcecc9c954ea39ad1884a46
[]
no_license
FelixH-XCIX/Object-Oriented-Programming
fb369f0dde1bad0516f004249466a78929ca8858
4df804521cedb7ea840eeeeedb169e988be8e4cc
refs/heads/main
2023-02-07T11:31:27.030364
2021-01-02T16:13:21
2021-01-02T16:13:21
319,557,384
1
0
null
null
null
null
UTF-8
C++
false
false
2,289
cpp
Fraction.cpp
#include "Fraction.h" #include <vector> int Gcd(int a, int b) { while (b) b ^= a ^= b ^= a %= b; return a; } void Fraction::setNumerator(int nu) { numerator = nu; } void Fraction::setDenominator(int de) { denominator = de; } //numerator = a, denominator = b void Fraction::getDouble() { int tempn = numerator, tempd = denominator; int n = 7; if (tempd == 0) { cout << "Infinite" << endl; return; } if (tempn == 0) { cout << 0 << endl; return; } if (n <= 0) { cout << tempn / tempd << endl; return; } if (((tempn > 0) && (tempd < 0)) || ((tempn < 0) && (tempd > 0))) { cout << "-"; tempn = tempn > 0 ? tempn : -tempn; tempd = tempd > 0 ? tempd : -tempd; } //out << tempn << " " << tempd << endl; int res = tempn / tempd; //cout << res << "this is res" << endl; vector<int> dec; dec.push_back(res); bool noRem = false; for (int i = 0; i <= n; i++) { //cout << tempn << " " << tempd << endl; dec.push_back(res); tempn = tempn - (tempd * res); if (tempn == 0) { noRem = true; break; } tempn = tempn * 10; res = tempn / tempd; } //cout << "dec size = " << dec.size() << noRem << endl; for (int i = 1; i < dec.size(); i++) { //cout << "i = " << i << endl; if (!noRem && i == dec.size() - 2) if (dec[i + 1] >= 5 && dec[i + 1] != NULL) { cout << dec[i] + 1; break; } else { cout << dec[i]; break; } else cout << dec[i]; if (i == 1 && !noRem) cout << "."; } //cout << endl; //cout << tempn << " " << tempd << endl; cout << endl; } void Fraction::outputReducedFraction() { int gcd = Gcd(numerator, denominator); //cout << "gcd is " << gcd << endl; cout << numerator / gcd; if (denominator / gcd != 0 && denominator / gcd != 1) { cout << "/" << denominator / gcd; } cout << endl; }
16f32d1e4025bd4ca06e407c69da6cddd4b32954
aeef4d7bab4ca441fbecc2823815e9f94cb4563b
/src/sim/include/simio.h
042ca53526649a0551c4f204160c99358837d8e5
[ "BSD-2-Clause" ]
permissive
FreeFalcon/freefalcon-central
8fc80b6d82eab44ce314a39860e6ee8e6f5ee71a
c28d807183ab447ef6a801068aa3769527d55deb
refs/heads/develop
2021-01-23T20:49:45.844619
2014-10-30T18:32:35
2014-10-30T18:32:35
7,615,342
133
90
null
2014-10-30T18:32:35
2013-01-15T00:02:23
C++
ISO-8859-10
C++
false
false
10,586
h
simio.h
/******************************************************************************/ /* */ /* Unit Name : simio.h */ /* */ /* Abstract : Header file with class definition for SIMLIB_IO_CLASS and */ /* defines used in its implementation. */ /* */ /* Dependencies : Auto-Generated */ /* */ /* Operating System : MS-DOS 6.2, Windows 3.1 */ /* */ /* Compiler : MSVC V1.5 */ /* */ /* Naming Conventions : */ /* */ /* Public Functions : Mixed case with no underscores */ /* Private Functions : Mixed case with no underscores */ /* Public Functions : Mixed case with no underscores */ /* Global Variables : Mixed case with no underscores */ /* Classless Functions : Mixed case with no underscores */ /* Classes : All upper case seperated by an underscore */ /* Defined Constants : All upper case seperated by an underscore */ /* Macros : All upper case seperated by an underscore */ /* Structs/Types : All upper case seperated by an underscore */ /* Private Variables : All lower case seperated by an underscore */ /* Public Variables : All lower case seperated by an underscore */ /* Local Variables : All lower case seperated by an underscore */ /* */ /* Development History : */ /* Date Programer Description */ /*----------------------------------------------------------------------------*/ /* 23-Jan-95 LR Initial Write */ /* */ /******************************************************************************/ #ifndef _SIMIO_H #define _SIMIO_H // Retro 31Dec2003 - major rewrite #include "sinput.h" /* all axis I could think of right now.. this defines the order in the 'analog' array in which the values are stored */ typedef enum { AXIS_START = 0, AXIS_PITCH = AXIS_START, // bipolar AXIS_ROLL, // bipolar AXIS_YAW, // bipolar AXIS_THROTTLE, // leftmost, or EXCLUSIVE, throttle unipolar AXIS_THROTTLE2, // bipolar AXIS_TRIM_PITCH, // bipolar AXIS_TRIM_YAW, // bipolar AXIS_TRIM_ROLL, // bipolar AXIS_BRAKE_LEFT, // left, or EXCLUSIVE, brake unipolar // AXIS_BRAKE_RIGHT, // unipolar AXIS_FOV, // Field of View unipolar AXIS_ANT_ELEV, // Radar Antenna Elevation bipolar AXIS_CURSOR_X, // Cursor/Enable-X bipolar AXIS_CURSOR_Y, // Cursor/Enable-X bipolar AXIS_RANGE_KNOB, // bipolar AXIS_COMM_VOLUME_1, // Comms Channel 1 Volume unipolar AXIS_COMM_VOLUME_2, // Comms Channel 2 Volume unipolar AXIS_MSL_VOLUME, // unipolar AXIS_THREAT_VOLUME, // unipolar AXIS_HUD_BRIGHTNESS, // HUD Symbology Intensity unipolar AXIS_RET_DEPR, // Manual Reticle Depression unipolar AXIS_ZOOM, // View Zoom unipolar AXIS_INTERCOM_VOLUME, // InterCom Volume, thatīs kinda a 'master volume' for all comm channels // unipolar AXIS_MAX // Add any additional axis BEFORE that one } GameAxis_t; #define SIMLIB_MAX_ANALOG AXIS_MAX // max number of axis #define SIMLIB_MAX_DIGITAL 32 // max number of dinput buttons per device (the rest would have to be emulated as keypresses) #define SIMLIB_MAX_POV 4 // max number of POVs per device struct DeviceAxis { int Device; int Axis; int Deadzone; int Saturation; DeviceAxis() { Device = Axis = Saturation = -1; Deadzone = 100; } }; enum { DX_XAXIS = 0, DX_YAXIS, DX_ZAXIS, DX_RXAXIS, DX_RYAXIS, DX_RZAXIS, DX_SLIDER0, DX_SLIDER1, DX_MOUSEWHEEL = 0 // Retro 17Jan2004 }; void ResetDeviceAxis(DeviceAxis* t); struct AxisMapping { int FlightControlDevice; // these 2 are sanity values, to find out if the user attach/detached additional // DXDevices since the last mapping GUID FlightControllerGUID; int totalDeviceCount; DeviceAxis Pitch; DeviceAxis Bank; DeviceAxis Yaw; DeviceAxis Throttle; DeviceAxis Throttle2; DeviceAxis BrakeLeft; DeviceAxis BrakeRight; DeviceAxis FOV; DeviceAxis PitchTrim; DeviceAxis YawTrim; DeviceAxis BankTrim; DeviceAxis AntElev; DeviceAxis RngKnob; DeviceAxis CursorX; DeviceAxis CursorY; DeviceAxis Comm1Vol; DeviceAxis Comm2Vol; DeviceAxis MSLVol; DeviceAxis ThreatVol; DeviceAxis InterComVol; DeviceAxis HudBrt; DeviceAxis RetDepr; DeviceAxis Zoom; AxisMapping() { FlightControlDevice = -1; memset(&FlightControllerGUID, 0, sizeof(GUID)); totalDeviceCount = 0; } }; /* representation in the UI (ControlTab) */ struct AxisIDStuff { char* DXAxisName; int DXAxisID; int DXDeviceID; bool isMapped; AxisIDStuff() { DXAxisName = 0; DXAxisID = -1; DXDeviceID = -1; isMapped = false; } }; /*****************************************************************************/ // Retro 23Jan2004 // Custom axis shaping.. /*****************************************************************************/ struct AxisCalibration { bool active[AXIS_MAX]; DIPROPCPOINTS CalibPoints[AXIS_MAX]; AxisCalibration() { for (int i = 0; i < AXIS_MAX; i++) { active[i] = false; CalibPoints[i].dwCPointsNum = 0; for (int j = 0; j < MAXCPOINTSNUM; j++) { CalibPoints[i].cp[j].lP = 0; CalibPoints[i].cp[j].dwLog = 0; } } } }; extern AxisCalibration AxisShapes; // Retro 23Jan2004 end /* representation in the game (actually, this is used on polling) */ typedef struct { int* device; int* axis; int* deadzone; int* saturation; bool isUniPolar; } GameAxisSetup_t; // these structs define the in-game-axis properties typedef struct { SIM_LONG center; // used to recenter pitch/bank axis and as ABDetent for throttles SIM_LONG cutoff; // idle cutoff val for throttles SIM_LONG ioVal; // 'raw' read value ?? bool isUsed; // well... waddaya think ? SIM_FLOAT engrValue; // dunno what the abbreviation means but this is the processed input (with input linearity applied etc..) bool isReversed; // well.. SIM_LONG smoothingFactor; // Retro 19Feb2004 - has to be power of 2, 0 if deactivated } SIMLIB_ANALOG_TYPE; /***************************************************************************/ // OK this class just holds the processed data retrived from the joysticks, // and some flags on what to do with em (min, max, center) // // the actual polling, processing, mapping is done by other (global.. urgs) // functions that write into this class // // sijoy.cpp siloop.cpp and controltab.cpp are the prime suspects for this // // the mapping of in-game axis to real device axis is also done elsewhere /***************************************************************************/ class SIMLIB_IO_CLASS { public: SIMLIB_ANALOG_TYPE analog[SIMLIB_MAX_ANALOG]; // array of all axis SIM_SHORT digital[SIMLIB_MAX_DIGITAL*SIM_NUMDEVICES]; // array of all buttons of all devices DWORD povHatAngle[SIMLIB_MAX_POV]; // array of all POVs public: /* constructor, basically sets all to '0' or 'false' */ SIMLIB_IO_CLASS(); /* called on entering the 3d, use to init axisvalues etc */ SIM_INT Init(char *fname); /* data retrieval stuff */ SIM_FLOAT ReadAnalog(GameAxis_t id); // Retro 28Dec2003 - this return the (processed, normalised ?) engrValue, of MPS vintage. used for primary flight stuff (pitch/yaw/bank/throttle) SIM_INT GetAxisValue(GameAxis_t id); // Retro 28Dec2003 - this returns the ioVal, -10000 to 10000 (bipolar), 0-15000 (unipolar) SIM_INT ReadDigital(SIM_INT id); /* axis status stuff */ bool AnalogIsUsed(GameAxis_t id) { return (analog[id].isUsed); }; void SetAnalogIsUsed(GameAxis_t id, bool flag) { analog[id].isUsed = flag; }; bool AnalogIsReversed(GameAxis_t id) { return (analog[id].isReversed); } void SetAnalogIsReversed(GameAxis_t id, bool flag) { analog[id].isReversed = flag; }; long GetAxisCutoffValue(GameAxis_t id) { return analog[id].cutoff; } bool IsAxisCutOff(GameAxis_t id) { return (analog[id].ioVal > (analog[id].cutoff + idleCutoffPad)); // MD -- 20040210 } long GetAxisSmoothing(GameAxis_t id) { return (analog[id].smoothingFactor); } void SetAxisSmoothing(GameAxis_t id, long factor) { analog[id].smoothingFactor = factor; // factor has to be power of 2 } // reads/writes offset-values for bipolar axis int ReadFile(void); int SaveFile(void); // reads/writes mapping of real axis to ingame axis int ReadAxisMappingFile(); int WriteAxisMappingFile(); // loads the custom axis shaping data int LoadAxisCalibrationFile(); // Retro 23Jan2004 void Reset(); void ResetAllInputs(); bool MouseWheelExists() { return mouseWheelPresent; } void SetMouseWheelExists(bool yesno) { mouseWheelPresent = yesno; } private: void SaveGUIDAndCount(); bool mouseWheelPresent; int idleCutoffPad; // MD -- 20040210: add variable pad to make sure we return cutoff only when we mean it, not on jitter/repeatability boundaries for flaky joystick pots }; extern SIMLIB_IO_CLASS IO; #endif // #define _SIMIO_H
e702fcba6f6a2af2ba3d04e8d459f16a866f6252
c32d00bb23c66afb1126c9637746350c7417ec2e
/Tuple.h
439eee250fa9cfe2c4aa13c09cd358c9d69db0ad
[]
no_license
dahenderson98/RelationalDatabase
e20932807bb1008d238b0a3d99c4ef783fd6626e
de99c03d3837a196fc4dd4d42dff368c5345c2c5
refs/heads/main
2023-07-19T10:56:13.848550
2021-09-14T02:11:53
2021-09-14T02:11:53
387,247,352
1
0
null
null
null
null
UTF-8
C++
false
false
959
h
Tuple.h
/* Dallin Henderson Tuple.h Project 4: Rule Evaluation */ #ifndef TUPLE_H #define TUPLE_H #include <iostream> #include <vector> using namespace std; class Tuple { public: void addVals(Parameter* param1, vector<Parameter*> parameterList) { values.push_back(param1->toString()); for (unsigned int i = 0; i < parameterList.size(); i++) { values.push_back(parameterList.at(i)->toString()); } } void addVal(string newStr) { values.push_back(newStr); } int getSize() const { return values.size(); } vector<string> getVals() const { return values; } bool operator< (const Tuple & other) const { return values < other.values; } void erase(int index) { values.erase(values.begin() + index); } int getSize() { return values.size(); } string toString() const { string output; for (unsigned int i = 0; i < values.size(); i++) { output += values.at(i) + '\t'; } return output; } private: vector<string> values; }; #endif
417eab5329358d791f54777f94f8bfb19234786c
1d208d6ccbaa6b048b50532b9f58e787b71fba2f
/Skin.cpp
f440e1373e1fcb925834690d38a8ae719a85527f
[]
no_license
ZiqiGan/CSE-169
1d8ef8e15c5639b7041d110c398163812748217c
38c497c775d3ce3763de668e4cb60105c45f614a
refs/heads/master
2021-10-28T14:46:00.103984
2018-03-03T22:02:11
2018-03-03T22:02:11
118,568,536
0
0
null
null
null
null
UTF-8
C++
false
false
7,930
cpp
Skin.cpp
#include "Skin.h" const float PI = 3.14159265359; Skin::Skin() { t = new Tokenizer(); } Skin::~Skin() { } void Skin::load(const char * filename) { t->Open(filename); //load .skin file while (1) { char temp[256]; t->GetToken(temp); if (strcmp(temp, "positions") == 0) { int numVertices = t->GetInt(); t->FindToken("{"); for (int i = 0; i < numVertices; i++) { float x = t->GetFloat(); float y = t->GetFloat(); float z = t->GetFloat(); vec3 pos = vec3(x, y, z); this->vtPos.push_back(pos); this->vertices.push_back(new Vertex(pos)); } } else if (strcmp(temp, "normals") == 0) { int numFaces = t->GetInt(); t->FindToken("{"); for (unsigned int i = 0; i < numFaces; i++) { float x = t->GetFloat(); float y = t->GetFloat(); float z = t->GetFloat(); vec3 norm = vec3(x, y, z); this->vtNorm.push_back(norm); //set the normal to corresponding vertex this->vertices[i]->normal = norm; } } else if (strcmp(temp, "skinweights") == 0) { int numWeight = t->GetInt(); t->FindToken("{"); for (unsigned int i = 0; i < numWeight; i++) { int numAttach = t->GetInt(); this->vertices[i]->numAttachments = numAttach; this->vertices[i]->weights.reserve(numAttach); for (unsigned int j = 0; j < numAttach;j++) { int jointNum = t->GetInt(); float weight = t->GetFloat(); vertices[i]->weights.push_back(pair<int, float>(jointNum, weight)); } } } else if (strcmp(temp, "triangles") == 0) { int numFaces = t->GetInt(); t->FindToken("{"); for (unsigned int i = 0; i < numFaces; i++) { Face* face = new Face(); //push corresponding vertices into the face for (unsigned int j = 0; j < 3; j++) { int index = t->GetInt(); this->indices.push_back(index); face->vertices.push_back(this->vertices[index]); } this->faces.push_back(face); } } else if (strcmp(temp, "texcoords") == 0) { int numTexs = t->GetInt(); t->FindToken("{"); for (int i = 0; i < numTexs; i++) { float x = t->GetFloat(); float y = t->GetFloat(); this->texCoords.push_back(glm::vec2(x,y)); } } else if (strcmp(temp, "bindings") == 0) { int numBindings = t->GetInt(); t->FindToken("{"); for (unsigned int i = 0; i < numBindings; i++) { t->FindToken("matrix {"); float ax = t->GetFloat(); float ay = t->GetFloat(); float az = t->GetFloat(); float bx = t->GetFloat(); float by = t->GetFloat(); float bz = t->GetFloat(); float cx = t->GetFloat(); float cy = t->GetFloat(); float cz = t->GetFloat(); float dx = t->GetFloat(); float dy = t->GetFloat(); float dz = t->GetFloat(); glm::mat4 bindingMatrix = mat4(ax, bx, cx, dx, ay, by, cy, dy, az, bz, cz, dz, 0.0f, 0.0f, 0.0f,1.0f); this->Bindings.push_back(bindingMatrix); bindingMatrix = glm::transpose(bindingMatrix); this->inverseBindings.push_back(glm::inverse(bindingMatrix)); } break; } else { t->SkipLine(); } } t->Close(); } void Skin::update(Skeleton * skel) { //update all vertices for (int i = 0; i < this->vertices.size(); i++) { glm::mat4 deform = glm::mat4(0.0f); vec3 updatedPos = vec3(0.0f); vec3 updatedNorm = vec3(0.0f); for (int j = 0; j < vertices[i]->numAttachments; j++) { int index = vertices[i]->weights[j].first; float weight = vertices[i]->weights[j].second; mat4 weightMatrix = skel->joints[index]->getWorldMatrix()*this->inverseBindings[index]; updatedPos = updatedPos + vec3(weight*weightMatrix*vec4(vertices[i]->position, 1.0f)); updatedNorm = updatedNorm + glm::normalize(vec3(weight*weightMatrix*vec4(vertices[i]->normal, 1.0f))); } //vertices[i]->position = updatedPos; vtPos[i] = updatedPos; //vertices[i]->normal = updatedNorm; vtNorm[i] = updatedNorm; } } void Skin::setupMesh() { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &NBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); // Vertex Positions to layout location 0 glBindBuffer(GL_ARRAY_BUFFER, this->VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*this->vtPos.size(), &this->vtPos[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vec3), (GLvoid*)0); glBindBuffer(GL_ARRAY_BUFFER, this->NBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*this->vtNorm.size(), &this->vtNorm[0], GL_STATIC_DRAW); // Vertex Normals to layout location 1 glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vec3), (GLvoid*)0); //Texture coordinates to layout location 2 if (this->hasTexture == 1) { glBindBuffer(GL_ARRAY_BUFFER, this->TBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vec2)*this->vtPos.size(), &this->texCoords[0], GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(vec2), (GLvoid*)0); LoadGlTextures(); cout << "texture loaded" << endl; } //indices array glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*indices.size(), &this->indices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Skin::Draw(Shader & shader, glm::mat4 view, glm::mat4 proj) { glm::mat4 modelView = view * this->model; glUseProgram(shader.Program); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(this->model)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "modelview"), 1, GL_FALSE, glm::value_ptr(modelView)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(proj)); ////set up material properties glUniform4f(glGetUniformLocation(shader.Program, "mtl.ambient"), 0.6f, 0.6f, 0.6f, 1.0f); glUniform4f(glGetUniformLocation(shader.Program, "mtl.diffuse"), 0.8f, 0.8f, 0.8f, 1.0f); glUniform4f(glGetUniformLocation(shader.Program, "mtl.specular"), 1.0f, 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(shader.Program, "mtl.shininess"), 100.0f); //set up texture if (this->hasTexture) { glUniform1i(glGetUniformLocation(shader.Program, "hasTexture"), 1); glUniform1i(glGetUniformLocation(shader.Program, "tex"), 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } //set up lights GLfloat positions[8]; GLfloat colors[8]; glm::vec4 light1Pos = vec4(-6.0f, 3.0f, 0.0f, 0.0f); glm::vec4 light2Pos = vec4(6.0f, 3.0f, 0.0f, 0.0f); glm::vec4 light1Col = vec4(1.0f, 0.0f, 0.1f, 1.0f); glm::vec4 light2Col = vec4(0.1f, 0.0f, 1.0f, 1.0f); for (int i = 0; i < 4; i++) { positions[i] = light1Pos[i]; colors[i] = light1Col[i]; } for (int i = 4; i < 8; i++) { positions[i] = light2Pos[i - 4]; colors[i] = light2Col[i - 4]; } glUniform1i(glGetUniformLocation(shader.Program, "numLight"), 2); glUniform4fv(glGetUniformLocation(shader.Program, "lightPos"), 2, positions); glUniform4fv(glGetUniformLocation(shader.Program, "lightColor"), 2, colors); glBindVertexArray(this->VAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0);; } // Load Bitmaps And Convert To Textures void Skin::LoadGlTextures() { if (!image1.load("head.bmp")) exit(1); // Create Texture glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // note that BMP images store their data in BRG order, not RGB glTexImage2D(GL_TEXTURE_2D, 0, 3, image1.sizeX, image1.sizeY, 0, GL_BGR, GL_UNSIGNED_BYTE, image1.data); };
2299d85fea783756e554af1684f8e79e08fbae25
82621767a8fffb6f5c1e0323879d4f2f7555e3b0
/balloc/balloc.cpp
9bd15f569c34ec2ceccdc8fd8052f8402ed5ee19
[ "Zlib" ]
permissive
abelianwang/malloc-survey
40b46b1507ec8c5666157b53326d4a23e31ac88e
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
refs/heads/master
2023-03-18T09:16:13.401077
2016-07-06T15:11:27
2016-07-06T15:11:27
534,266,709
1
0
Zlib
2022-09-08T15:06:26
2022-09-08T15:06:26
null
UTF-8
C++
false
false
2,191
cpp
balloc.cpp
// http://stackoverflow.com/questions/1995871/how-to-write-a-thread-safe-and-efficient-lock-free-memory-allocator-in-c // http://stackoverflow.com/users/3186/christopher #include <windows.h> #include <stdio.h> #ifndef byte #define byte unsigned char #endif typedef struct { union{ SLIST_ENTRY entry; void* list; }; byte mem[]; } mem_block; typedef struct { SLIST_HEADER root; } mem_block_list; #define BUCKET_COUNT 4 #define BLOCKS_TO_ALLOCATE 16 namespace { mem_block_list Buckets[BUCKET_COUNT]; bool init_buckets() { for( int i = 0; i < BUCKET_COUNT; ++i ) { InitializeSListHead( &Buckets[i].root ); for( int j = 0; j < BLOCKS_TO_ALLOCATE; ++j ) { mem_block* p = (mem_block*) malloc( sizeof( mem_block ) + (0x1 << i) * 0x8 ); //printf("creating block of %d bytes\n", (0x1 << i) * 0x8 ); InterlockedPushEntrySList( &Buckets[i].root, &p->entry ); } } return true; } const bool init = init_buckets(); } void* balloc( size_t size ) { for( int i = 0; i < BUCKET_COUNT; ++i ) { if( size <= (0x1 << i) * 0x8 ) { mem_block* p = (mem_block*) InterlockedPopEntrySList( &Buckets[i].root ); p->list = &Buckets[i]; return ((byte *)p + sizeof( p->entry )); } } return 0; // block too large } void bfree( void* p ) { mem_block* block = (mem_block*) (((byte*)p) - sizeof( block->entry )); InterlockedPushEntrySList( &((mem_block_list*)block)->root, &block->entry ); } // also, // http://stackoverflow.com/questions/11749386/implement-own-memory-pool typedef struct pool { char * next; char * end; } POOL; POOL * pool_create( size_t size ) { POOL * p = (POOL*)malloc( size + sizeof(POOL) ); p->next = (char*)&p[1]; p->end = p->next + size; return p; } void pool_destroy( POOL *p ) { free(p); } size_t pool_available( POOL *p ) { return p->end - p->next; } void * pool_alloc( POOL *p, size_t size ) { if( pool_available(p) < size ) return NULL; void *mem = (void*)p->next; p->next += size; return mem; }
cb820193872d3c1e6d81502de38289c4fdf6ca18
cb2f6028e2edeee86a42a4c5cd20ccdf6e2508c7
/example_tunnel_object/src/ofApp.cpp
ea5a96bca7b622e5c1f99d3f78cfe794133a5c76
[]
no_license
antimodular/ofxExtrude
7eb19888744b4bdec9b01823c210ee18a0f196b5
0fefcfbf7fe7e79f8c65500d0c05c53959532753
refs/heads/master
2020-05-20T05:53:57.128577
2019-05-07T14:30:05
2019-05-07T14:30:05
185,417,876
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { tunnel_object.setup(); ofBackground(64); } //-------------------------------------------------------------- void ofApp::update(){ tunnel_object.update(); } //-------------------------------------------------------------- void ofApp::draw(){ ofEnableDepthTest(); if(usecamera){ camera.begin(); } tunnel_object.draw(); if(usecamera){ camera.end(); } ofDisableDepthTest(); tunnel_object.panel.draw(); ofDrawBitmapString("key c to change camera", 300, 10); ofDrawBitmapString("key x to clear tunnel shape", 300, 30); ofDrawBitmapString("only change tunnel depth z", 300, 50); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } void ofApp::keyReleased(int key){ if(key == 'c'){ usecamera = !usecamera; } if(key == 'x'){ tunnel_object.points.clear(); } } void ofApp::mouseDragged(int x, int y, int button){ //if we are using the camera, the mouse moving should rotate it around the whole sculpture if(usecamera == false){ ofVec3f mousePoint(x,y,0); tunnel_object.addPoint(mousePoint); } }
3ad64a23dad59392c4255890bda32d790553d3f3
647279d2a3f43217a1ae830f07301357b3a24b68
/src/cpp/LassoRegression.cpp
554fd086b378bc03cafd117c2fc58456910ebc3f
[ "Apache-2.0" ]
permissive
aflorio81/Amazon-MIT-RoutingChallenge
7e16244a7cf920f713da97c3613172b849e2904b
cbacc7b62a41b81c3e4b9ffde0f8dea0f81d3f5a
refs/heads/main
2023-08-18T10:53:24.337175
2021-10-06T15:14:30
2021-10-06T15:14:30
397,329,177
0
0
null
null
null
null
UTF-8
C++
false
false
12,265
cpp
LassoRegression.cpp
#include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <memory> #include <numeric> #include <random> #include <string> #include <mlpack/core.hpp> #include <mlpack/methods/lars/lars.hpp> #include "LassoRegression.h" #include "Model.h" #include "Stopwatch.h" using namespace std; void LassoRegression::checkData() const { for (const auto& dp : cv_data) { if (!isfinite(dp.y)) cout<<"warning: y value is '"<<dp.y<<"'"<<endl; for (const auto& kv : dp.x) if (!isfinite(kv.second)) { cout<<"warning: feature \""<<kv.first<<"\" is '"<<kv.second <<"'"<<endl; } } for (const auto& dp : tr_data) { if (!isfinite(dp.y)) cout<<"warning: y value is '"<<dp.y<<"'"<<endl; for (const auto& kv : dp.x) if (!isfinite(kv.second)) { cout<<"warning: feature \""<<kv.first<<"\" is '"<<kv.second <<"'"<<endl; } } } void LassoRegression::computeNormMinMax() { const auto featset=featureSet(); unordered_map<string, vector<double>> featvals; for (const auto& dp : cv_data) for (const auto& feat : featset) if (dp.x.count(feat)==1) featvals[feat].push_back(dp.x.at(feat)); else featvals[feat].push_back(0); for (const auto& dp : tr_data) for (const auto& feat : featset) if (dp.x.count(feat)==1) featvals[feat].push_back(dp.x.at(feat)); else featvals[feat].push_back(0); for (const auto& kv : featvals) { norm_min[kv.first]=*min_element(kv.second.begin(), kv.second.end()); norm_max[kv.first]=*max_element(kv.second.begin(), kv.second.end()); if (norm_max[kv.first]-norm_min[kv.first]<=0) { cout<<"warning: feature \""<<kv.first<<"\":"<<endl; cout<<" invalid 0-1 normalization parameters: min: " <<norm_min[kv.first]<<" , max: "<<norm_max[kv.first]<<endl; cout<<" resetting to min=0 and max=1"<<endl; norm_min[kv.first]=0; norm_max[kv.first]=1; } } } void LassoRegression::exportCSV(const string& csvfile) const { cout<<"exporting regression model to "<<csvfile<<" ..."<<endl; ofstream csv(csvfile); csv<<setprecision(15); const auto featset=featureSet(); for (const auto& feat : featset) csv<<feat<<","; csv<<"y"<<endl; for (const auto& dp : cv_data) { for (const auto& feat : featset) csv<<(dp.x.count(feat)==1 ? to_string(dp.x.at(feat)) : "0")<<","; csv<<dp.y<<endl; } for (const auto& dp : tr_data) { for (const auto& feat : featset) csv<<(dp.x.count(feat)==1 ? to_string(dp.x.at(feat)) : "0")<<","; csv<<dp.y<<endl; } } unordered_set<string> LassoRegression::featureSet() const { unordered_set<string> featset; for (const auto& dp : cv_data) for (const auto& kv : dp.x) featset.insert(kv.first); for (const auto& dp : tr_data) for (const auto& kv : dp.x) featset.insert(kv.first); return featset; } double LassoRegression::predict(const unordered_map<string, double>& x) const { if (beta.empty()) return numeric_limits<double>::max(); double pred=beta_0; for (const auto& kv : x) if (beta.count(kv.first)==1) pred+=beta.at(kv.first)*normalize(kv); return pred; } void LassoRegression::printBeta() const { cout<<"beta_zero (intercept): "<<beta_0<<endl; for (const auto& kv : beta) cout<<"beta[\""<<kv.first<<"\"]: "<<kv.second<<endl; } // this is extremely unnice but we need to protect against mlpack deadlocking void LassoRegression::save() { // assuming that if mastermodel is set then this is an evaluation model if (mastermodel!=nullptr) { LassoRegression modelcopy; // deep copy, everything but the data modelcopy.feat_to_idx=feat_to_idx; modelcopy.idx_to_feat=idx_to_feat; modelcopy.norm_min=norm_min; modelcopy.norm_max=norm_max; modelcopy.beta_0=beta_0; modelcopy.beta=beta; mastermodel->setEvaluationModel(move(modelcopy)); // persistent save: if mlpack deadlocks, at least we have something mastermodel->save(); } else cout<<"warning: master model not set"<<endl; } void LassoRegression::solve(const double l1_ini) { // parameters const double l1_sm=1.07; // step multiplier cout<<"lasso: setting up data ..."<<endl; checkData(); computeNormMinMax(); updateIndices(); cout<<"lasso: "<<tr_data.size()<<" training data points ; "<<cv_data.size() <<" CV data points ; "<<feat_to_idx.size()<<" features"<<endl; Stopwatch sw; cout<<"tuning l1 coefficient by cross validation"<<endl; double min_err=numeric_limits<double>::max(); double l1_best=l1_ini; int noupdate=0; size_t n_its=0; for (double l1=l1_ini; n_its<200; ++n_its) { const auto errors=solveL1withCV(l1); if (errors.first<min_err*1.01) { printBeta(); if (mastermodel!=nullptr) save(); // mlpack sometimes deadlocks ... if (errors.first<min_err) cout<<"*"; else cout<<" "; min_err=min(errors.first, min_err); l1_best=l1; cout<<"*"; noupdate=0; } else { cout<<" "; noupdate++; } cout<<"l1="<<l1<<": in-sample error: "<<errors.second<<" CV error: " <<errors.first<<" ("<<sw.elapsedSeconds()<<" s)"<<endl; if (errors.first>1.015*min_err && noupdate>=5) break; l1*=l1_sm; } cout<<"setting l1 regularization coefficient to "<<l1_best<<endl; solveAllData(l1_best); printBeta(); cout<<"l1 coefficient tuning: elapsed time: "<<sw.elapsedSeconds()<<" s" <<endl; } void LassoRegression::solveAllData(double l1) { cout<<"solving for l1="<<l1<<" (all data)"<<endl; arma::mat X(tr_data.size()+cv_data.size(), feat_to_idx.size(), arma::fill::zeros); arma::rowvec Y(tr_data.size()+cv_data.size(), arma::fill::zeros); for (size_t i=0; i<tr_data.size(); ++i) { const auto& dp=tr_data[i]; for (const auto& kv : dp.x) X(i, feat_to_idx.at(kv.first))=normalize(kv); Y(i)=dp.y; } for (size_t i=0; i<cv_data.size(); ++i) { const auto& dp=cv_data[i]; for (const auto& kv : dp.x) X(i+tr_data.size(), feat_to_idx.at(kv.first))=normalize(kv); Y(i+tr_data.size())=dp.y; } cout<<"covariates matrix populated: "<<X.n_rows<<" rows, "<<X.n_cols <<" columns, "<<arma::accu(X!=0)<<" nonzeros"<<endl; using namespace mlpack::regression; shared_ptr<LARS> lars=make_shared<LARS>(X, Y, false, false, l1); auto B=lars->Beta(); cout<<"beta vector: "<<B.n_rows<<" rows, "<<B.n_cols<<" columns, " <<arma::accu(B!=0)<<" nonzeros"<<endl; if (B.n_rows!=feat_to_idx.size()) cout<<"warning: dimensions not matching"<<endl; beta.clear(); // in case we are modifying the current model for (size_t i=0; i<B.n_rows; ++i) { if (B(i)!=0) { cout<<"beta_"<<i<<" (\""<<idx_to_feat.at(i)<<"\"): "<<B(i)<<endl; beta.insert({idx_to_feat.at(i), B(i)}); } if (!isfinite(B(i))) { cout<<"warning: invalid beta"<<endl; cout<<" calling recursively with l1="<<l1*1.05<<endl; solveAllData(l1*1.05); return; } } // save intercept term arma::mat X0(1, feat_to_idx.size(), arma::fill::zeros); arma::rowvec B0; lars->Predict(X0, B0, true); beta_0=B0(0); cout<<"beta_zero (intercept): "<<beta_0<<endl; arma::rowvec predY; lars->Predict(X, predY, true); double loss=0; for (size_t i=0; i<predY.n_cols; ++i) { if (i<tr_data.size()) { if (abs(predY(i)-predict(tr_data.at(i).x))>1e-6 || abs(Y(i)-tr_data.at(i).y)>1e-6) cout<<"warning: values mismatching"<<endl; } else { if (abs(predY(i)-predict(cv_data.at(i-tr_data.size()).x))>1e-6 || abs(Y(i)-cv_data.at(i-tr_data.size()).y)>1e-6) cout<<"warning: values mismatching"<<endl; } double diff=predY(i)-Y(i); loss+=diff*diff; } loss/=predY.n_cols; cout<<"l1="<<l1<<": training error: "<<loss<<endl; } pair<double, double> LassoRegression::solveL1withCV(const double l1) { double totcvloss=0, tottrloss=0; // matrix for training arma::mat X_tr(tr_data.size(), feat_to_idx.size(), arma::fill::zeros); // matrix for CV arma::mat X_cv(cv_data.size(), feat_to_idx.size(), arma::fill::zeros); // Y vectors for training and CV arma::rowvec Y_tr(tr_data.size(), arma::fill::zeros); arma::rowvec Y_cv(cv_data.size(), arma::fill::zeros); for (size_t i=0; i<tr_data.size(); ++i) { const auto& dp=tr_data[i]; for (const auto& kv : dp.x) X_tr(i, feat_to_idx.at(kv.first))=normalize(kv); Y_tr(i)=dp.y; } for (size_t i=0; i<cv_data.size(); ++i) { const auto& dp=cv_data[i]; for (const auto& kv : dp.x) X_cv(i, feat_to_idx.at(kv.first))=normalize(kv); Y_cv(i)=dp.y; } using namespace mlpack::regression; LARS lars(X_tr, Y_tr, false, false, l1); auto B=lars.Beta(); cout<<"beta vector: "<<B.n_rows<<" rows, "<<B.n_cols<<" columns, " <<arma::accu(B!=0)<<" nonzeros"<<endl; if (B.n_rows!=feat_to_idx.size()) cout<<"warning: dimensions not matching"<<endl; beta.clear(); // in case we are modifying the current model if (B.has_nan()) { cout<<"invalid (NaN) element in beta vector"<<endl; return {numeric_limits<double>::max(), numeric_limits<double>::max()}; } for (size_t i=0; i<B.n_rows; ++i) { if (B(i)!=0) { cout<<"beta_"<<i<<" (\""<<idx_to_feat.at(i)<<"\"): "<<B(i)<<endl; beta.insert({idx_to_feat.at(i), B(i)}); } if (!isfinite(B(i))) { cout<<"warning: invalid beta"<<endl; return {numeric_limits<double>::max(), numeric_limits<double>::max()}; } } // save intercept term arma::mat X0(1, feat_to_idx.size(), arma::fill::zeros); arma::rowvec B0; lars.Predict(X0, B0, true); beta_0=B0(0); cout<<"beta_zero (intercept): "<<beta_0<<endl; { // in-sample error arma::rowvec predY; lars.Predict(X_tr, predY, true); if (predY.n_cols!=tr_data.size()) cout<<"warning: dimensions not matching"<<endl; double loss=0; for (size_t j=0; j<predY.n_cols; ++j) { double diff=predY(j)-Y_tr(j); loss+=diff*diff; } tottrloss+=loss/predY.n_cols; } { // cross validation error arma::rowvec predY; lars.Predict(X_cv, predY, true); if (predY.n_cols!=cv_data.size()) cout<<"warning: dimensions not matching"<<endl; double loss=0; for (size_t j=0; j<predY.n_cols; ++j) { double diff=predY(j)-Y_cv(j); loss+=diff*diff; } totcvloss+=loss/predY.n_cols; } return {totcvloss, tottrloss}; } void LassoRegression::updateIndices() { if (feat_to_idx.size()!=idx_to_feat.size()) cout<<"warning: sizes of indices differ"<<endl; for (const auto& dp : tr_data) for (const auto& kv : dp.x) if (feat_to_idx.count(kv.first)==0) { feat_to_idx.insert({kv.first, idx_to_feat.size()}); idx_to_feat.push_back(kv.first); } for (const auto& dp : cv_data) for (const auto& kv : dp.x) if (feat_to_idx.count(kv.first)==0) { feat_to_idx.insert({kv.first, idx_to_feat.size()}); idx_to_feat.push_back(kv.first); } }
7de24b4319eb447149e3000186e74c3a52fa7004
2fe0389b7640d83b7e0256829117327d88182ec3
/CortexLib/Tools/RegistersGenerator/Msp432P401Y/FieldValues/itmfieldvalues.hpp
8db04eabfa06bc6b04ce54b4ce6d23d1ca6b9411
[ "MIT" ]
permissive
ntsiopliakis/CourseWork
31cb142df39ce6a8ffdb56eff9ae1240257bc844
14b4ca4b06cdd7b41b69be26da860eb61ed86911
refs/heads/main
2023-05-04T06:49:54.638017
2021-05-23T13:03:33
2021-05-23T13:03:33
370,057,028
0
0
null
null
null
null
UTF-8
C++
false
false
6,551
hpp
itmfieldvalues.hpp
/******************************************************************************* * Filename : itmfieldvalues.hpp * * Details : Enumerations related with ITM peripheral. This header file is * auto-generated for MSP432P401Y device. * * *******************************************************************************/ #if !defined(ITMENUMS_HPP) #define ITMENUMS_HPP #include "fieldvalue.hpp" //for FieldValues template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TER_STIMENA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TPR_PRIVMASK_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 1U> ; using Value2 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 2U> ; using Value3 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 3U> ; using Value4 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 4U> ; using Value5 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 5U> ; using Value6 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 6U> ; using Value7 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 7U> ; using Value8 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 8U> ; using Value9 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 9U> ; using Value10 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 10U> ; using Value11 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 11U> ; using Value12 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 12U> ; using Value13 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 13U> ; using Value14 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 14U> ; using Value15 = FieldValue<ITM_ITM_TPR_PRIVMASK_Values, BaseType, 15U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_ITMENA_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TCR_ITMENA_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TCR_ITMENA_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_TSENA_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TCR_TSENA_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TCR_TSENA_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_SYNCENA_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TCR_SYNCENA_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TCR_SYNCENA_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_DWTENA_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TCR_DWTENA_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TCR_DWTENA_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_SWOENA_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TCR_SWOENA_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TCR_SWOENA_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_TSPRESCALE_Values: public RegisterField<Reg, offset, size, AccessMode> { using en_0b00 = FieldValue<ITM_ITM_TCR_TSPRESCALE_Values, BaseType, 0U> ; using en_0b01 = FieldValue<ITM_ITM_TCR_TSPRESCALE_Values, BaseType, 1U> ; using en_0b10 = FieldValue<ITM_ITM_TCR_TSPRESCALE_Values, BaseType, 2U> ; using en_0b11 = FieldValue<ITM_ITM_TCR_TSPRESCALE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_ATBID_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_TCR_BUSY_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_TCR_BUSY_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_TCR_BUSY_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_IWR_ATVALIDM_Values: public RegisterField<Reg, offset, size, AccessMode> { using en_0b0 = FieldValue<ITM_ITM_IWR_ATVALIDM_Values, BaseType, 0U> ; using en_0b1 = FieldValue<ITM_ITM_IWR_ATVALIDM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_IMCR_INTEGRATION_Values: public RegisterField<Reg, offset, size, AccessMode> { using en_0b0 = FieldValue<ITM_ITM_IMCR_INTEGRATION_Values, BaseType, 0U> ; using en_0b1 = FieldValue<ITM_ITM_IMCR_INTEGRATION_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_LAR_LOCK_ACCESS_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_LSR_PRESENT_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_LSR_PRESENT_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_LSR_PRESENT_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_LSR_ACCESS_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_LSR_ACCESS_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_LSR_ACCESS_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct ITM_ITM_LSR_BYTEACC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<ITM_ITM_LSR_BYTEACC_Values, BaseType, 0U> ; using Value1 = FieldValue<ITM_ITM_LSR_BYTEACC_Values, BaseType, 1U> ; } ; #endif //#if !defined(ITMENUMS_HPP)
f47c6c75502b3bbe169ec5c424f1d1664b99534e
48a4561db7d797c2f768314e55d0c2f3dc164cf0
/checkpoint/q1/getalltimes.cpp
edf57a62888902de70b5b61cf215b21965b7b504
[]
no_license
kjain1810/SPP-Assignment-1
28f368aaf074796b6cdef73bef195d854f232e5e
f40540eccf069b7e7894bd540cc9f4031230c865
refs/heads/master
2023-03-27T04:18:14.984643
2021-03-28T20:41:57
2021-03-28T20:41:57
347,781,202
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
getalltimes.cpp
#include <iostream> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <string> #define BILLION 1000000000L; int main(int argc, char **argv) { std::string x = "./run <Q1/"; std::string y = ".txt >myout/"; std::string z = ".out"; std::string cases[] = {"0", "5", "10", "15", "20", "30", "40", "50", "55", "60", "70", "75", "80", "85", "90"}; std::string diffx = "diff ./Q1out/"; std::string diffy = ".txt ./myout/"; std::string diffz = ".out | wc -l"; double total = 0; for (int a = 0; a < 15; a++) { struct timespec start, stop; double accum; if (clock_gettime(CLOCK_REALTIME, &start) == -1) { perror("clock gettime"); return 1; } std::string command = x + cases[a] + y + cases[a] + z; system(command.c_str()); if (clock_gettime(CLOCK_REALTIME, &stop) == -1) { perror("clock gettime"); return 1; } accum = (stop.tv_sec - start.tv_sec) + (double)(stop.tv_nsec - start.tv_nsec) / (double)BILLION; std::cout << command << "\n" << accum << "\n"; command = diffx + cases[a] + diffy + cases[a] + diffz; system(command.c_str()); total += accum; } std::cout<<"Total: " << total<<"\n"; return 0; }
0d974dade9835109aca4d12ed80c0ed3c0f9bf11
45e8a78cf44825d7b64f23b3a527f6ccde9abea3
/Lista de TecProg 1(INTRO C++)/Questao 2/main.cpp
8b5c34b701bc38369e784fb1bfb99f377e0aa9c9
[]
no_license
nicolasrls/codigos
f9b7c33f52b732f8e576081a2db43a330e460c47
d63d9f689c7790e28aeb877964eef8a4b4dc7659
refs/heads/master
2021-06-24T19:30:28.002374
2021-04-24T16:25:27
2021-04-24T16:25:27
218,394,029
3
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
main.cpp
#include <iostream> #include <locale.h> using namespace std; int main() { setlocale(LC_ALL, "Portuguese"); cout << "Tamanho do inteiro = " << sizeof(int) << endl; cout << "Tamanho do inteiro = " << sizeof(short) << endl; cout << "Tamanho do inteiro = " << sizeof(long) << endl; cout << "Tamanho do inteiro = " << sizeof(char) << endl; cout << "Tamanho do inteiro = " << sizeof(float) << endl; cout << "Tamanho do inteiro = " << sizeof(double) << endl; cout << "Tamanho do inteiro = " << sizeof(bool) << endl; return 0; }
d8bb97ade0777b2a8840d477ecb27b38dd3af55e
f8bf1bfe3e43918f767813a2115080bc58983d03
/Cracking_Coding_Interview/1_3.cpp
48b659c7a02fbd62c7541c66268174044764ba5f
[]
no_license
iliemihai/ALGORITHMS
39926dbce91b28823b8a037d451478c6192bfd31
1ee8a2bed623821ca67cd3479d9951ddae1e2bf6
refs/heads/master
2020-09-12T01:46:58.423496
2019-11-17T14:26:51
2019-11-17T14:26:51
222,260,066
0
0
null
null
null
null
UTF-8
C++
false
false
1,046
cpp
1_3.cpp
#include<iostream> using namespace std; //idea edit string from end. first we count the number of spaces // triple it and compute how many extra chars we will have in final //string. in the second pass in reverse order replace space with %20, if no space copy original char void replace_chars(char* str, int length) { int count=0, final_index; for(int i=0; i<length; i++){ if(str[i]==' '){ count++; } } final_index = length+count*2; if(length < sizeof(str)/sizeof(char)) str[length] = '\0';//end array for(int i=length-1; i>=0; i--){ if(str[i]==' '){ str[final_index-1]='0'; str[final_index-2]='2'; str[final_index-3]='%'; final_index-=3; }else{ str[final_index-1] = str[i]; final_index--; } } } int main() { char str[]="Mr John SMith "; std::cout << "Actual string " << str << std::endl; replace_chars(str, 13); std::cout << "Modified " << str << std::endl; }
00f1e2392eb35fd6f9785bbd6a6ffccd69dd371a
be28bc01135a691b324650988eee7c99310bc5a5
/llarp/service/handler.hpp
9fabb6b9543763c9f5bf7776f2f360fbad01bbaf
[ "CC0-1.0", "Zlib" ]
permissive
neuroscr/loki-network
ab559c038bccf6ee14c05c38507b907a59cdc73c
6af3512dfa7d2ef5da1e5c6ec235a84f4813a3cf
refs/heads/master
2020-03-20T21:14:14.151285
2020-01-08T12:57:37
2020-01-08T12:57:37
137,730,176
2
1
null
2018-06-18T08:58:34
2018-06-18T08:58:34
null
UTF-8
C++
false
false
2,101
hpp
handler.hpp
#ifndef LLARP_SERVICE_HANDLER_HPP #define LLARP_SERVICE_HANDLER_HPP #include <crypto/types.hpp> #include <path/path.hpp> #include <service/intro_set.hpp> #include <util/aligned.hpp> #include <memory> #include <set> namespace llarp { namespace service { using ConvoTag = AlignedBuffer< 16 >; struct ProtocolMessage; struct RecvDataEvent { path::Path_ptr fromPath; PathID_t pathid; std::shared_ptr< ProtocolMessage > msg; }; struct ProtocolMessage; struct IDataHandler { virtual bool HandleDataMessage(path::Path_ptr path, const PathID_t from, std::shared_ptr< ProtocolMessage > msg) = 0; virtual bool GetCachedSessionKeyFor(const ConvoTag& remote, SharedSecret& secret) const = 0; virtual void PutCachedSessionKeyFor(const ConvoTag& remote, const SharedSecret& secret) = 0; virtual void MarkConvoTagActive(const ConvoTag& tag) = 0; virtual void RemoveConvoTag(const ConvoTag& remote) = 0; virtual bool HasConvoTag(const ConvoTag& remote) const = 0; virtual void PutSenderFor(const ConvoTag& remote, const ServiceInfo& si, bool inbound) = 0; virtual bool GetSenderFor(const ConvoTag& remote, ServiceInfo& si) const = 0; virtual void PutIntroFor(const ConvoTag& remote, const Introduction& intro) = 0; virtual bool GetIntroFor(const ConvoTag& remote, Introduction& intro) const = 0; virtual void PutReplyIntroFor(const ConvoTag& remote, const Introduction& intro) = 0; virtual bool GetReplyIntroFor(const ConvoTag& remote, Introduction& intro) const = 0; virtual bool GetConvoTagsForService(const Address& si, std::set< ConvoTag >& tag) const = 0; virtual bool HasInboundConvo(const Address& addr) const = 0; virtual void QueueRecvData(RecvDataEvent ev) = 0; }; } // namespace service } // namespace llarp #endif
7c6ec89e570f93b461223b88b6675ee6d9f33ef3
fe779be32c5e2ebf1baf9fb2f48ec98e818a3c52
/Capitulo 5/Date.cpp
26bd3570ae602c21b3792d2c8f99acd7c8c38bc2
[]
no_license
andrefmrocha/MIEIC_17_18_PROG
ff57eef863837f1080b0a0884a829c9439edc54c
95e0f02adcdb0eb4576668058ae5171a2cca41a9
refs/heads/master
2021-03-27T13:06:55.852646
2018-04-18T08:59:23
2018-04-18T08:59:23
123,624,664
0
1
null
null
null
null
UTF-8
C++
false
false
4,491
cpp
Date.cpp
// // Created by andrefmrocha on 18-04-2018. // #include "Date.h" Date::Date(unsigned int year, unsigned int month, unsigned int day) { this->day = day; this->month = month; this->year = year; } Date::Date(string yearMonthDay) { year = stoi(yearMonthDay.substr(0,4).c_str()); month = stoi(yearMonthDay.substr(5,2).c_str()); day = stoi(yearMonthDay.substr(8,2).c_str()); } string Date::getDate() { string date = to_string(year) + '/' + to_string(month) + '/' + to_string(day); return date; } unsigned int Date::getDay() const { return day; } unsigned int Date::getMonth() const { return month; } unsigned int Date::getYear() const { return year; } void Date::setDate(unsigned int year, unsigned int month, unsigned int day) { this->month = month; this->day = day; this->year = year; } void Date::setDay(unsigned int day) { this->day = day; } void Date::setMonth(unsigned int month) { this->month = month; } void Date::setYear(unsigned int year) { this->year = year; } void Date::show() { cout << getDate() << endl; } bool Date::isLeap() { if((year % 4 == 0 && year % 100 != 0)|| year % 100 == 0) return true; else return false; } bool Date::isValid() { if(month == 0 || month > 12 || year < 0 || day > 31 || day == 0) return false; else if(month == 2) { if(isLeap()) { if(day <= 29) { return true; } else { return false; } } else { if(day <= 28) { return true; } else { return false; } } } else { switch (month) { case 1: if(day <= 31) return true; else return false; case 3: if(day <= 31) return true; else return false; case 4: if(day <= 30) return true; else return false; case 5: if(day <= 31) return true; else return false; case 6: if(day <= 30) return true; else return false; case 7: if(day <= 31) return true; else return false; case 8: if(day <= 31) return true; else return false; case 9: if(day <= 30) return true; else return false; case 10: if(day <= 31) return true; else return false; case 11: if(day <= 30) return true; else return false; case 12: if(day <= 31) return true; else return false; } } } bool Date::isEqualTo(const Date &d1) const { if(year == d1.getYear() && month == d1.getMonth() && day == d1.getDay()) return true; else return false; } bool Date::isNotEqualTo(const Date &d1) const { if(year == d1.getYear() && month == d1.getMonth() && day == d1.getDay()) return false; else return true; } bool Date::isAfter(const Date &d1) const { if(year > d1.getYear()) return true; else if(year == d1.getYear()) { if(month > d1.getMonth()) return true; else if(month == d1.getMonth()) { if(day > d1.getDay()) { return false; } return false; } else return false; } else return false; } bool Date::isBefore(const Date &d1) const { if(isAfter(d1)) return false; else if(isNotEqualTo(d1)) return true; } Date::Date() { time_t now = time(0); tm *now_time = localtime(&now); year = now_time->tm_year + 1900; month = now_time->tm_mon + 1; day = now_time->tm_mday; }
c16b85789ebac0afe1ce7fe459bbbf93d9f4fa64
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/xdktools/Producer/CommandStripMgr/CommandPPGMgr.cpp
fcbb0f8591e20cd8dafad03b20c39f30a5354cdc
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,396
cpp
CommandPPGMgr.cpp
// CommandPPGMgr.cpp: implementation of the CCommandPPGMgr class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CommandStripMgr.h" #include "FileIO.h" #include "CommandPPGMgr.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // CCommandPPGMgr Construction/Destruction ////////////////////////////////////////////////////////////////////// CCommandPPGMgr::CCommandPPGMgr() : CStaticPropPageManager() { m_pCommandPPG = NULL; m_GUIDManager = GUID_CommandPPGMgr; } CCommandPPGMgr::~CCommandPPGMgr() { if( m_pCommandPPG ) { delete m_pCommandPPG; } } ///////////////////////////////////////////////////////////////////////////// // CCommandPPGMgr IDMUSProdPropPageManager implementation ///////////////////////////////////////////////////////////////////////////// // CCommandPPGMgr IDMUSProdPropPageManager::GetPropertySheetTitle HRESULT CCommandPPGMgr::GetPropertySheetTitle( BSTR* pbstrTitle, BOOL* pfAddPropertiesText ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if(( pbstrTitle == NULL ) || ( pfAddPropertiesText == NULL )) { return E_POINTER; } *pfAddPropertiesText = TRUE; CString strTitle; strTitle.LoadString( IDS_PROPPAGE_COMMAND ); *pbstrTitle = strTitle.AllocSysString(); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // CCommandPPGMgr IDMUSProdPropPageManager::GetPropertySheetPages HRESULT CCommandPPGMgr::GetPropertySheetPages( IDMUSProdPropSheet *pIPropSheet, LONG *hPropSheetPage[], short *pnNbrPages ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if(( hPropSheetPage == NULL ) || ( pnNbrPages == NULL )) { return E_POINTER; } if( pIPropSheet == NULL ) { return E_INVALIDARG; } m_pIPropSheet = pIPropSheet; m_pIPropSheet->AddRef(); HPROPSHEETPAGE hPage; // If the property page has already been created, get a handle for it. if( m_pCommandPPG ) { hPage = ::CreatePropertySheetPage( (LPCPROPSHEETPAGE)&m_pCommandPPG->m_psp ); if( hPage ) { hPropSheetPage[0] = (long *) hPage; *pnNbrPages = 1; return S_OK; } *pnNbrPages = 0; delete m_pCommandPPG; m_pCommandPPG = NULL; return E_OUTOFMEMORY; } // Otherwise, create a new property page m_pCommandPPG = new CCommandPPG(); if( m_pCommandPPG ) { m_pCommandPPG->m_pPageManager = this; hPage = ::CreatePropertySheetPage( (LPCPROPSHEETPAGE)&m_pCommandPPG->m_psp ); if( hPage ) { hPropSheetPage[0] = (long *) hPage; *pnNbrPages = 1; return S_OK; } delete m_pCommandPPG; m_pCommandPPG = NULL; } // We couldn't create the page *pnNbrPages = 0; return E_OUTOFMEMORY; } ///////////////////////////////////////////////////////////////////////////// // CCommandPPGMgr IDMUSProdPropPageManager::OnRemoveFromPropertySheet HRESULT CCommandPPGMgr::OnRemoveFromPropertySheet() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr; hr = CBasePropPageManager::OnRemoveFromPropertySheet(); if( FAILED( hr )) { return hr; } if( m_pIPropSheet ) { m_pIPropSheet->Release(); m_pIPropSheet = NULL; } if( m_pCommandPPG ) { hr = m_pCommandPPG->SetData( NULL ); } return hr; } ///////////////////////////////////////////////////////////////////////////// // CCommandPPGMgr IDMUSProdPropPageManager::RefreshData HRESULT CCommandPPGMgr::RefreshData( void ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = S_OK; PPGCommand* pCommand = NULL; if( m_pIPropPageObject != NULL ) { hr = m_pIPropPageObject->GetData( (void **) &pCommand ); if( FAILED( hr )) { return hr; } } if( m_pCommandPPG ) { hr = m_pCommandPPG->SetData( pCommand ); } return hr; } ///////////////////////////////////////////////////////////////////////////// // CCommandPPGMgr IDMUSProdPropPageManager::RemoveObject HRESULT CCommandPPGMgr::RemoveObject( IDMUSProdPropPageObject* pIPropPageObject ) { HRESULT hr; hr = CStaticPropPageManager::RemoveObject( pIPropPageObject ); if( SUCCEEDED( hr )) { if( m_pCommandPPG ) { hr = m_pCommandPPG->SetData( NULL ); } } return hr; }
ef20e74126f14b4bcf1c1bcc0f5f6827d3307b02
c7365b9c98cdced58ba6b1fdd10c5e093af09e20
/luciolinae_ctl/src/AnimLuxeonTest.cpp
189b61fd7466b563af41914cc678826eabcced43
[]
no_license
damian0815/Luciolinae
bf600362216517d5843e13046182d2f41f3b7b1d
aa398f1b434ebed24ff7e1d3c595dfd9226a0638
refs/heads/master
2021-05-27T12:29:15.833026
2013-07-07T09:31:28
2013-07-07T09:31:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
865
cpp
AnimLuxeonTest.cpp
/* * AnimLuxeonTest.cpp * luciolinae_ctl * * Created by damian on 17/05/10. * Copyright 2010 frey damian@frey.co.nz. All rights reserved. * */ #include "AnimLuxeonTest.h" extern void delayUs( unsigned long us ); static const int BLACK_TIME = 3.0f; static const int ON_TIME = 0.02f; AnimLuxeonTest::AnimLuxeonTest( Lights* _lights ) :Animation( _lights ) { board = 0x10; current_light = 0; timer = BLACK_TIME; } void AnimLuxeonTest::update( float elapsed ) { timer -= elapsed; if ( timer >= 0 ) { } else if ( timer < 0 ) { printf("turning on %i\n", current_light); lights->set( current_light, 1.0f ); lights->flush(); delayUs( 50 ); printf("turning off %i\n", current_light); lights->set( current_light, 0.0f ); lights->flush(); current_light++; if ( current_light > 1 ) current_light =0; timer = BLACK_TIME; } }
7aa9a29aa6085fabf6a516960acd36a41fac4e4c
adb838c748a4609f185cce25ecfb141c7fc8395c
/UnpDaytimeTcpSrv1/daytimetcpsrv1.cc
710fb8e05ed3d43e419c5669695ddd6fb13b8a52
[]
no_license
sunyongjie1984/UNPSUNYJ
af8691272ead737a07c7f7eea866693326bb6644
365bbb05587fded561b495e66d017ad9c451d148
refs/heads/master
2021-01-10T03:10:11.043965
2016-02-15T08:24:29
2016-02-15T08:24:29
50,342,886
0
0
null
null
null
null
UTF-8
C++
false
false
2,328
cc
daytimetcpsrv1.cc
#include <time.h> #include "../lib/unpsunyj.h" // Daytime server that prints client IP address and port int main(int argc, char **argv) { int listenfd; int connfd; socklen_t len; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; // 它将存放客户的协议地址 char buff[MAXLINE]; time_t ticks; // listenfd = Socket(AF_INET, SOCK_STREAM, 0); if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) err_sys("socket error"); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(13); /* daytime server */ //Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); if (bind(listenfd, (sockaddr*)&servaddr, sizeof(servaddr)) < 0) { err_sys("bind error"); } // Listen(listenfd, LISTENQ); if (listen(listenfd, LISTENQ) < 0) { err_sys("listen error"); } for ( ; ; ) { len = sizeof(cliaddr); // connfd = Accept(listenfd, (SA *) &cliaddr, &len); again: if ((connfd = accept(listenfd, (sockaddr*)&cliaddr, &len)) < 0) { #ifdef EPROTO if (errno == EPROTO || errno == ECONNABORTED) #else if (errno == ECONNABORTED) #endif goto again; else err_sys("accept error"); } const char *ptr; if ((ptr = inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff))) == NULL) err_sys("inet_ntop error"); /* sets errno */ printf("connection from %s, port %d\n", // Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)), ptr, ntohs(cliaddr.sin_port)); ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); // Write(connfd, buff, strlen(buff)); int length = strlen(buff); if (write(connfd, buff, length) != length) { err_sys("write error"); } // Close(connfd); if (close(connfd) == -1) { err_sys("close error"); } } }
b9e873754d6ffb1417f44c7df26c0ffc53e6e8f0
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/Inside-Windows-Debugging/chapter_03/BasicException/main.cpp
1d4f961cca89d110dfc8079ec60aed37d1ae9a7e
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UTF-8
C++
false
false
101
cpp
main.cpp
#include "stdafx.h" int __cdecl wmain() { throw "This program raised an error"; return 0; }
240710ae2c5923a51cb4ebbf34f5cb1b5e50d87a
948df734bc05a4b816160067597f749913859340
/src/G2PAppBase.cc
99586427cafbafba0a8be3b568eb1565bc8d941a
[]
no_license
zhupengjia/g2prec
92c8f69eb27c6f99adadd72e5faacd3e9aba3b94
8c7d41705e1a2017ff25b1f595b25a6da042a949
refs/heads/master
2021-01-23T16:29:57.546245
2014-12-19T20:30:24
2014-12-19T20:30:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,750
cc
G2PAppBase.cc
// -*- C++ -*- /* class G2PAppBase * Abstract base class for g2p reconstruction tools. * It provides fundamental functions like parsing configuration files. */ // History: // Mar 2013, C. Gu, First public version. // Sep 2013, C. Gu, Add configure functions. // Feb 2014, C. Gu, Modified for G2PRec. // #include <cstdlib> #include <cstdio> #include <cmath> #include "TROOT.h" #include "TError.h" #include "TObject.h" #include "G2PConf.hh" #include "G2PAppBase.hh" using namespace std; static const double kLT[4] = {-1.001135e+00, -3.313373e-01, -4.290819e-02, +4.470852e-03}; static const double kLY[4] = {-8.060915e-03, +1.071977e-03, +9.019102e-04, -3.239615e-04}; static const double kLP[4] = {-2.861912e-03, -2.469069e-03, +8.427172e-03, +2.274635e-03}; static const double kRT[4] = {-1.004600e+00, -3.349200e-01, -4.078700e-02, +0.000000e+00}; static const double kRY[4] = {-5.157400e-03, +2.642400e-04, +2.234600e-03, +0.000000e+00}; static const double kRP[4] = {-7.435500e-04, -2.130200e-03, +1.195000e-03, +0.000000e+00}; G2PAppBase::G2PAppBase() : fDebug(0) { // Constructor } G2PAppBase::~G2PAppBase() { // Destructor } void G2PAppBase::TCS2HCS(double x_tr, double y_tr, double z_tr, double angle, double &x_lab, double &y_lab, double &z_lab) { // Position transform function from TCS to HCS static const char* const here = "TCS2HCS()"; double cosang = cos(angle); double sinang = sin(angle); x_lab = y_tr * cosang + z_tr*sinang; y_lab = -x_tr; z_lab = z_tr * cosang - y_tr*sinang; if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e\n", x_tr, y_tr, z_tr, x_lab, y_lab, z_lab); } void G2PAppBase::TCS2HCS(double t_tr, double p_tr, double angle, double &t_lab, double &p_lab) { // Angle transform function from TCS to HCS static const char* const here = "TCS2HCS()"; double x = tan(t_tr); double y = tan(p_tr); double z = 1.0; TCS2HCS(x, y, z, angle, x, y, z); t_lab = acos(z / sqrt(x * x + y * y + z * z)); p_lab = atan2(y, x); if (fDebug > 2) Info(here, "%10.3e %10.3e -> %10.3e %10.3e\n", t_tr, p_tr, t_lab, p_lab); } void G2PAppBase::HCS2TCS(double x_lab, double y_lab, double z_lab, double angle, double &x_tr, double &y_tr, double &z_tr) { // Position transform function from HCS to TCS static const char* const here = "HCS2TCS()"; double cosang = cos(angle); double sinang = sin(angle); x_tr = -y_lab; y_tr = x_lab * cosang - z_lab*sinang; z_tr = x_lab * sinang + z_lab*cosang; if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e\n", x_lab, y_lab, z_lab, x_tr, y_tr, z_tr); } void G2PAppBase::HCS2TCS(double t_lab, double p_lab, double angle, double &t_tr, double &p_tr) { // Angle transform function from HCS to TCS static const char* const here = "HCS2TCS()"; double x = sin(t_lab) * cos(p_lab); double y = sin(t_lab) * sin(p_lab); double z = cos(t_lab); HCS2TCS(x, y, z, angle, x, y, z); t_tr = atan2(x, z); p_tr = atan2(y, z); if (fDebug > 2) Info(here, "%10.3e %10.3e -> %10.3e %10.3e", t_lab, p_lab, t_tr, p_tr); } void G2PAppBase::Project(double x, double y, double z, double zout, double t, double p, double &xout, double &yout) { // Project along z direction static const char* const here = "Project()"; double xsave = x; double ysave = y; xout = xsave + (zout - z) * tan(t); yout = ysave + (zout - z) * tan(p); if (fDebug > 1) Info(here, "%10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e", xsave, ysave, z, xout, yout, zout); } void G2PAppBase::TRCS2FCS(const double* V5_tr, double angle, double* V5_fp) { static const char* const here = "TRCS2FCS()"; double x_tr = V5_tr[0]; double t_tr = tan(V5_tr[1]); double y_tr = V5_tr[2]; double p_tr = tan(V5_tr[3]); double x = x_tr; double x1 = x; double x2 = x1*x; double x3 = x2*x; const double* tMat; const double* yMat; const double* pMat; if (angle > 0) { tMat = kLT; yMat = kLY; pMat = kLP; } else { tMat = kRT; yMat = kRY; pMat = kRP; } double t_mat = tMat[0] + tMat[1] * x1 + tMat[2] * x2 + tMat[3] * x3; double y_mat = yMat[0] + yMat[1] * x1 + yMat[2] * x2 + yMat[3] * x3; double p_mat = pMat[0] + pMat[1] * x1 + pMat[2] * x2 + pMat[3] * x3; double tan_rho_0 = tMat[0]; double cos_rho_0 = 1.0 / sqrt(1.0 + tan_rho_0 * tan_rho_0); double t_det = (t_tr - tan_rho_0) / (1 + t_tr * tan_rho_0); double p_det = p_tr * (1.0 - t_det * tan_rho_0) * cos_rho_0; double tan_rho = t_mat; double cos_rho = 1.0 / sqrt(1.0 + tan_rho * tan_rho); double y = y_tr - y_mat; double t = (t_det + tan_rho) / (1.0 - t_det * tan_rho); double p = (p_det - p_mat) / ((1.0 - t_det * tan_rho) * cos_rho); V5_fp[0] = x; V5_fp[1] = atan(t); V5_fp[2] = y; V5_fp[3] = atan(p); if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e %10.3e", V5_tr[0], V5_tr[1], V5_tr[2], V5_tr[3], V5_fp[0], V5_fp[1], V5_fp[2], V5_fp[3]); } void G2PAppBase::FCS2TRCS(const double* V5_fp, double angle, double* V5_tr) { static const char* const here = "FCS2TRCS()"; double x = V5_fp[0]; double t = tan(V5_fp[1]); double y = V5_fp[2]; double p = tan(V5_fp[3]); double x1 = x; double x2 = x1*x; double x3 = x2*x; const double* tMat; const double* yMat; const double* pMat; if (angle > 0) { tMat = kLT; yMat = kLY; pMat = kLP; } else { tMat = kRT; yMat = kRY; pMat = kRP; } double t_mat = tMat[0] + tMat[1] * x1 + tMat[2] * x2 + tMat[3] * x3; double y_mat = yMat[0] + yMat[1] * x1 + yMat[2] * x2 + yMat[3] * x3; double p_mat = pMat[0] + pMat[1] * x1 + pMat[2] * x2 + pMat[3] * x3; double tan_rho = t_mat; double cos_rho = 1.0 / sqrt(1.0 + tan_rho * tan_rho); double x_tr = x; double y_tr = y + y_mat; double t_det = (t - tan_rho) / (1.0 + t * tan_rho); double p_det = p * (1.0 - t_det * tan_rho) * cos_rho + p_mat; double tan_rho_0 = tMat[0]; double cos_rho_0 = 1.0 / sqrt(1.0 + tan_rho_0 * tan_rho_0); double t_tr = (t_det + tan_rho_0) / (1.0 - t_det * tan_rho_0); double p_tr = p_det / (cos_rho_0 * (1.0 - t_det * tan_rho_0)); V5_tr[0] = x_tr; V5_tr[1] = atan(t_tr); V5_tr[2] = y_tr; V5_tr[3] = atan(p_tr); if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e %10.3e", V5_fp[0], V5_fp[1], V5_fp[2], V5_fp[3], V5_tr[0], V5_tr[1], V5_tr[2], V5_tr[3]); } void G2PAppBase::TRCS2DCS(const double* V5_tr, double angle, double* V5_det) { static const char* const here = "TRCS2DCS()"; const double* tMat; if (angle > 0) { tMat = kLT; } else { tMat = kRT; } double tan_rho_0 = tMat[0]; double cos_rho_0 = 1.0 / sqrt(1.0 + tan_rho_0 * tan_rho_0); double x_tr = V5_tr[0]; double t_tr = tan(V5_tr[1]); double y_tr = V5_tr[2]; double p_tr = tan(V5_tr[3]); double x_det = x_tr / (cos_rho_0 * (1 + t_tr * tan_rho_0)); double y_det = y_tr - tan_rho_0 * cos_rho_0 * p_tr*x_det; double t_det = (t_tr - tan_rho_0) / (1 + t_tr * tan_rho_0); double p_det = p_tr * (1.0 - t_det * tan_rho_0) * cos_rho_0; V5_det[0] = x_det; V5_det[1] = atan(t_det); V5_det[2] = y_det; V5_det[3] = atan(p_det); if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e %10.3e", V5_tr[0], V5_tr[1], V5_tr[2], V5_tr[3], V5_det[0], V5_det[1], V5_det[2], V5_det[3]); } void G2PAppBase::DCS2TRCS(const double* V5_det, double angle, double* V5_tr) { static const char* const here = "DCS2TRCS()"; const double* tMat; if (angle > 0) { tMat = kLT; } else { tMat = kRT; } double tan_rho_0 = tMat[0]; double cos_rho_0 = 1.0 / sqrt(1.0 + tan_rho_0 * tan_rho_0); double x_det = V5_det[0]; double t_det = tan(V5_det[1]); double y_det = V5_det[2]; double p_det = tan(V5_det[3]); double t_tr = (t_det + tan_rho_0) / (1.0 - t_det * tan_rho_0); double p_tr = p_det / (cos_rho_0 * (1.0 - t_det * tan_rho_0)); double x_tr = x_det * cos_rho_0 * (1 + t_tr * tan_rho_0); double y_tr = y_det + tan_rho_0 * cos_rho_0 * p_tr*x_det; V5_tr[0] = x_tr; V5_tr[1] = atan(t_tr); V5_tr[2] = y_tr; V5_tr[3] = atan(p_tr); if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e %10.3e", V5_det[0], V5_det[1], V5_det[2], V5_det[3], V5_tr[0], V5_tr[1], V5_tr[2], V5_tr[3]); } void G2PAppBase::FCS2DCS(const double* V5_fp, double angle, double* V5_det) { static const char* const here = "FCS2DCS()"; double V5_tr[5]; int save = fDebug; fDebug = 0; FCS2TRCS(V5_fp, angle, V5_tr); TRCS2DCS(V5_tr, angle, V5_det); fDebug = save; if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e %10.3e", V5_fp[0], V5_fp[1], V5_fp[2], V5_fp[3], V5_det[0], V5_det[1], V5_det[2], V5_det[3]); } void G2PAppBase::DCS2FCS(const double* V5_det, double angle, double* V5_fp) { static const char* const here = "DCS2FCS()"; double V5_tr[5]; int save = fDebug; fDebug = 0; DCS2TRCS(V5_det, angle, V5_tr); TRCS2FCS(V5_tr, angle, V5_fp); fDebug = save; if (fDebug > 2) Info(here, "%10.3e %10.3e %10.3e %10.3e -> %10.3e %10.3e %10.3e %10.3e", V5_det[0], V5_det[1], V5_det[2], V5_det[3], V5_fp[0], V5_fp[1], V5_fp[2], V5_fp[3]); } int G2PAppBase::Configure() { //static const char* const here = "Configure()"; gConfig->lookupValue("debug", fDebug); return 0; } ClassImp(G2PAppBase)
a80d3050d817be5aef57b19845d5661485f5553c
282aaadc0f9b8458a053ebda72f8887ca2cb2e6f
/C++ Games/Tetris/childblocktemplate.cpp
6c359e6d14a1f43d60af34efc2a8c124614f942c
[]
no_license
milletf1/BIT
0be30452eaa531a9780c5950138b8b7c990fa931
0c216b96719062096e6a8fe781fbbeb259823b8a
refs/heads/master
2020-12-31T00:54:47.039435
2017-06-03T06:05:33
2017-06-03T06:05:33
80,593,207
0
0
null
null
null
null
UTF-8
C++
false
false
1,509
cpp
childblocktemplate.cpp
#include "StdAfx.h" #include "child.h" child::child(Point^ startDrawPoint, Point^startOffset, Color startColor, Graphics^ startCanvas) : BlockTemplate (startDrawPoint, startOffset, startColor, startCanvas) { } void child::Rotate() { //Declare a temporary Point for passing the starting grid point to each cell Point^ newPoint; //Set new block direction myBlockDirection = BlockDirection::new; //Set cell 1 newPoint = gcnew Point(blockArray[0]->getGridPoint()->X - 1, blockArray[0]->getGridPoint()->Y + 1); blockArray[0]->setGridPoint(newPoint); //Set cell 3 newPoint = gcnew Point(blockArray[2]->getGridPoint()->X + 1, blockArray[2]->getGridPoint()->Y - 1); blockArray[2]->setGridPoint(newPoint); //Set cell 4 newPoint = gcnew Point(blockArray[3]->getGridPoint()->X + 2, blockArray[2]->getGridPoint()->Y - 2); blockArray[3]->setGridPoint(newPoint); } void child::InitializeBlockArray(Point^ startDrawPoint) { //Declare a temporary Point for passing the starting grid point to each cell Point^ newPoint; //set cell 0 newPoint = gcnew Point(startDrawPoint->X, startDrawPoint->Y); blockArray[0]->setGridPoint(newPoint); //set cell 1 newPoint = gcnew Point(startDrawPoint->X, startDrawPoint->Y); blockArray[1]->setGridPoint(newPoint); //set cell 2 newPoint = gcnew Point(startDrawPoint->X, startDrawPoint->Y); blockArray[2]->setGridPoint(newPoint); //set cell 3 newPoint = gcnew Point(startDrawPoint->X, startDrawPoint->Y); blockArray[3]->setGridPoint(newPoint); }
bef19de6b3fe8c34d056f14c97fcf675d1f74739
7886e7cc3b564019535a7f805f8de4933719c31f
/examples/test/protobuf/login.pb.h
06eb8fbc4d4943a656aa0fb055e790f91e03f314
[]
no_license
JohnnyXiaoYang/mongo
d56f4e69f243a26acfc0fba640016c53a984a3d0
b0c52dd3af0616ff1101e68b8322148ac8d0462d
refs/heads/master
2022-09-21T00:54:55.301854
2020-06-05T11:13:49
2020-06-05T11:13:49
null
0
0
null
null
null
null
UTF-8
C++
false
true
20,708
h
login.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: login.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_login_2eproto #define GOOGLE_PROTOBUF_INCLUDED_login_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3011000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3011004 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_login_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_login_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[2] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_login_2eproto; namespace mongo { class LoginCS; class LoginCSDefaultTypeInternal; extern LoginCSDefaultTypeInternal _LoginCS_default_instance_; class LoginSC; class LoginSCDefaultTypeInternal; extern LoginSCDefaultTypeInternal _LoginSC_default_instance_; } // namespace mongo PROTOBUF_NAMESPACE_OPEN template<> ::mongo::LoginCS* Arena::CreateMaybeMessage<::mongo::LoginCS>(Arena*); template<> ::mongo::LoginSC* Arena::CreateMaybeMessage<::mongo::LoginSC>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace mongo { enum LoginResult : int { SUCCESS = 0, USERNAME_NOT_EXIST = 1, PASSWORD_NOT_CORRECT = 2, LoginResult_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), LoginResult_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; bool LoginResult_IsValid(int value); constexpr LoginResult LoginResult_MIN = SUCCESS; constexpr LoginResult LoginResult_MAX = PASSWORD_NOT_CORRECT; constexpr int LoginResult_ARRAYSIZE = LoginResult_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* LoginResult_descriptor(); template<typename T> inline const std::string& LoginResult_Name(T enum_t_value) { static_assert(::std::is_same<T, LoginResult>::value || ::std::is_integral<T>::value, "Incorrect type passed to function LoginResult_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( LoginResult_descriptor(), enum_t_value); } inline bool LoginResult_Parse( const std::string& name, LoginResult* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<LoginResult>( LoginResult_descriptor(), name, value); } // =================================================================== class LoginCS : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mongo.LoginCS) */ { public: LoginCS(); virtual ~LoginCS(); LoginCS(const LoginCS& from); LoginCS(LoginCS&& from) noexcept : LoginCS() { *this = ::std::move(from); } inline LoginCS& operator=(const LoginCS& from) { CopyFrom(from); return *this; } inline LoginCS& operator=(LoginCS&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const LoginCS& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const LoginCS* internal_default_instance() { return reinterpret_cast<const LoginCS*>( &_LoginCS_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(LoginCS& a, LoginCS& b) { a.Swap(&b); } inline void Swap(LoginCS* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline LoginCS* New() const final { return CreateMaybeMessage<LoginCS>(nullptr); } LoginCS* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<LoginCS>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const LoginCS& from); void MergeFrom(const LoginCS& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(LoginCS* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mongo.LoginCS"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_login_2eproto); return ::descriptor_table_login_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kUsernameFieldNumber = 1, kPasswordFieldNumber = 2, kTimestampFieldNumber = 3, }; // string username = 1; void clear_username(); const std::string& username() const; void set_username(const std::string& value); void set_username(std::string&& value); void set_username(const char* value); void set_username(const char* value, size_t size); std::string* mutable_username(); std::string* release_username(); void set_allocated_username(std::string* username); private: const std::string& _internal_username() const; void _internal_set_username(const std::string& value); std::string* _internal_mutable_username(); public: // string password = 2; void clear_password(); const std::string& password() const; void set_password(const std::string& value); void set_password(std::string&& value); void set_password(const char* value); void set_password(const char* value, size_t size); std::string* mutable_password(); std::string* release_password(); void set_allocated_password(std::string* password); private: const std::string& _internal_password() const; void _internal_set_password(const std::string& value); std::string* _internal_mutable_password(); public: // int64 timestamp = 3; void clear_timestamp(); ::PROTOBUF_NAMESPACE_ID::int64 timestamp() const; void set_timestamp(::PROTOBUF_NAMESPACE_ID::int64 value); private: ::PROTOBUF_NAMESPACE_ID::int64 _internal_timestamp() const; void _internal_set_timestamp(::PROTOBUF_NAMESPACE_ID::int64 value); public: // @@protoc_insertion_point(class_scope:mongo.LoginCS) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr username_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr password_; ::PROTOBUF_NAMESPACE_ID::int64 timestamp_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_login_2eproto; }; // ------------------------------------------------------------------- class LoginSC : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mongo.LoginSC) */ { public: LoginSC(); virtual ~LoginSC(); LoginSC(const LoginSC& from); LoginSC(LoginSC&& from) noexcept : LoginSC() { *this = ::std::move(from); } inline LoginSC& operator=(const LoginSC& from) { CopyFrom(from); return *this; } inline LoginSC& operator=(LoginSC&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const LoginSC& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const LoginSC* internal_default_instance() { return reinterpret_cast<const LoginSC*>( &_LoginSC_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(LoginSC& a, LoginSC& b) { a.Swap(&b); } inline void Swap(LoginSC* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline LoginSC* New() const final { return CreateMaybeMessage<LoginSC>(nullptr); } LoginSC* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<LoginSC>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const LoginSC& from); void MergeFrom(const LoginSC& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(LoginSC* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mongo.LoginSC"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_login_2eproto); return ::descriptor_table_login_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kResultFieldNumber = 1, }; // .mongo.LoginResult result = 1; void clear_result(); ::mongo::LoginResult result() const; void set_result(::mongo::LoginResult value); private: ::mongo::LoginResult _internal_result() const; void _internal_set_result(::mongo::LoginResult value); public: // @@protoc_insertion_point(class_scope:mongo.LoginSC) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; int result_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_login_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // LoginCS // string username = 1; inline void LoginCS::clear_username() { username_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline const std::string& LoginCS::username() const { // @@protoc_insertion_point(field_get:mongo.LoginCS.username) return _internal_username(); } inline void LoginCS::set_username(const std::string& value) { _internal_set_username(value); // @@protoc_insertion_point(field_set:mongo.LoginCS.username) } inline std::string* LoginCS::mutable_username() { // @@protoc_insertion_point(field_mutable:mongo.LoginCS.username) return _internal_mutable_username(); } inline const std::string& LoginCS::_internal_username() const { return username_.GetNoArena(); } inline void LoginCS::_internal_set_username(const std::string& value) { username_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); } inline void LoginCS::set_username(std::string&& value) { username_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:mongo.LoginCS.username) } inline void LoginCS::set_username(const char* value) { GOOGLE_DCHECK(value != nullptr); username_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:mongo.LoginCS.username) } inline void LoginCS::set_username(const char* value, size_t size) { username_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:mongo.LoginCS.username) } inline std::string* LoginCS::_internal_mutable_username() { return username_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* LoginCS::release_username() { // @@protoc_insertion_point(field_release:mongo.LoginCS.username) return username_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void LoginCS::set_allocated_username(std::string* username) { if (username != nullptr) { } else { } username_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), username); // @@protoc_insertion_point(field_set_allocated:mongo.LoginCS.username) } // string password = 2; inline void LoginCS::clear_password() { password_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline const std::string& LoginCS::password() const { // @@protoc_insertion_point(field_get:mongo.LoginCS.password) return _internal_password(); } inline void LoginCS::set_password(const std::string& value) { _internal_set_password(value); // @@protoc_insertion_point(field_set:mongo.LoginCS.password) } inline std::string* LoginCS::mutable_password() { // @@protoc_insertion_point(field_mutable:mongo.LoginCS.password) return _internal_mutable_password(); } inline const std::string& LoginCS::_internal_password() const { return password_.GetNoArena(); } inline void LoginCS::_internal_set_password(const std::string& value) { password_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); } inline void LoginCS::set_password(std::string&& value) { password_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:mongo.LoginCS.password) } inline void LoginCS::set_password(const char* value) { GOOGLE_DCHECK(value != nullptr); password_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:mongo.LoginCS.password) } inline void LoginCS::set_password(const char* value, size_t size) { password_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:mongo.LoginCS.password) } inline std::string* LoginCS::_internal_mutable_password() { return password_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* LoginCS::release_password() { // @@protoc_insertion_point(field_release:mongo.LoginCS.password) return password_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void LoginCS::set_allocated_password(std::string* password) { if (password != nullptr) { } else { } password_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), password); // @@protoc_insertion_point(field_set_allocated:mongo.LoginCS.password) } // int64 timestamp = 3; inline void LoginCS::clear_timestamp() { timestamp_ = PROTOBUF_LONGLONG(0); } inline ::PROTOBUF_NAMESPACE_ID::int64 LoginCS::_internal_timestamp() const { return timestamp_; } inline ::PROTOBUF_NAMESPACE_ID::int64 LoginCS::timestamp() const { // @@protoc_insertion_point(field_get:mongo.LoginCS.timestamp) return _internal_timestamp(); } inline void LoginCS::_internal_set_timestamp(::PROTOBUF_NAMESPACE_ID::int64 value) { timestamp_ = value; } inline void LoginCS::set_timestamp(::PROTOBUF_NAMESPACE_ID::int64 value) { _internal_set_timestamp(value); // @@protoc_insertion_point(field_set:mongo.LoginCS.timestamp) } // ------------------------------------------------------------------- // LoginSC // .mongo.LoginResult result = 1; inline void LoginSC::clear_result() { result_ = 0; } inline ::mongo::LoginResult LoginSC::_internal_result() const { return static_cast< ::mongo::LoginResult >(result_); } inline ::mongo::LoginResult LoginSC::result() const { // @@protoc_insertion_point(field_get:mongo.LoginSC.result) return _internal_result(); } inline void LoginSC::_internal_set_result(::mongo::LoginResult value) { result_ = value; } inline void LoginSC::set_result(::mongo::LoginResult value) { _internal_set_result(value); // @@protoc_insertion_point(field_set:mongo.LoginSC.result) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace mongo PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::mongo::LoginResult> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::mongo::LoginResult>() { return ::mongo::LoginResult_descriptor(); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_login_2eproto
a7b3026602dabb14b8bd5c2cc35ddbc6edb0dc79
b0acb392f8353bd4b1a003e42f776fbbe8c7b633
/src/ImageProcessor.cpp
1a4efa5bf2757c92cd36b803a7f2d069ddcb7c8b
[ "Apache-2.0" ]
permissive
agruzdev/ShibaView
c494de77ad5b37a35231fac29f12f2ee7e32ee73
c663a23f97e4aa64ea3e970c2e6a54cac119b419
refs/heads/master
2023-07-06T22:39:08.192563
2023-07-02T12:13:14
2023-07-02T12:13:14
216,082,570
13
3
null
null
null
null
UTF-8
C++
false
false
7,778
cpp
ImageProcessor.cpp
/** * @file * * Copyright 2018-2023 Alexey Gruzdev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ImageProcessor.h" #include "Utilities.h" #include <stdexcept> namespace { QImage makeQImageView(FIBITMAP* bmp) { assert(bmp != nullptr); QImage imageView; switch (FreeImage_GetBPP(bmp)) { case 1: imageView = QImage(FreeImage_GetBits(bmp), FreeImage_GetWidth(bmp), FreeImage_GetHeight(bmp), FreeImage_GetPitch(bmp), QImage::Format_Mono); break; case 8: imageView = QImage(FreeImage_GetBits(bmp), FreeImage_GetWidth(bmp), FreeImage_GetHeight(bmp), FreeImage_GetPitch(bmp), QImage::Format_Grayscale8); break; case 24: imageView = QImage(FreeImage_GetBits(bmp), FreeImage_GetWidth(bmp), FreeImage_GetHeight(bmp), FreeImage_GetPitch(bmp), QImage::Format_RGB888); break; case 32: imageView = QImage(FreeImage_GetBits(bmp), FreeImage_GetWidth(bmp), FreeImage_GetHeight(bmp), FreeImage_GetPitch(bmp), QImage::Format_RGBA8888); break; default: throw std::logic_error("Internal image must be 1, 8, 24 or 32 bit"); } return imageView; } } ImageProcessor::ImageProcessor() : mProcessBuffer(nullptr, &::FreeImage_Unload) { } ImageProcessor::~ImageProcessor() = default; FIBITMAP* ImageProcessor::process(const ImageFrame& frame) { FIBITMAP* target = frame.bmp; // 1. Tonemap auto imgType = FreeImage_GetImageType(target); if (imgType == FIT_RGBF || imgType == FIT_RGBAF || imgType == FIT_FLOAT || imgType == FIT_DOUBLE) { UniqueBitmap tonemapped(FreeImageExt_ToneMapping(target, mToneMapping), &::FreeImage_Unload); if (tonemapped) { mProcessBuffer = std::move(tonemapped); target = mProcessBuffer.get(); } } // 2. Rotate if (mRotation != Rotation::eDegree0) { UniqueBitmap rotated(FreeImage_Rotate(target, static_cast<double>(toDegree(mRotation))), &::FreeImage_Unload); if (rotated) { mProcessBuffer = std::move(rotated); target = mProcessBuffer.get(); } } // 3. Flip if (mFlips[FlipType::eHorizontal]) { if (target == frame.bmp) { mProcessBuffer.reset(FreeImage_Clone(frame.bmp)); target = mProcessBuffer.get(); } FreeImage_FlipHorizontal(target); } if (mFlips[FlipType::eVertical]) { if (target == frame.bmp) { mProcessBuffer.reset(FreeImage_Clone(frame.bmp)); target = mProcessBuffer.get(); } FreeImage_FlipVertical(target); } // 4. Gamma if (mGammaValue != 1.0) { imgType = FreeImage_GetImageType(target); if (imgType == FIT_BITMAP) { if (target == frame.bmp) { mProcessBuffer.reset(FreeImage_Clone(frame.bmp)); target = mProcessBuffer.get(); } FreeImage_AdjustGamma(target, 1.0 / mGammaValue); } } // 5. Swizzle if (mSwizzleType != ChannelSwizzle::eRGB) { UniqueBitmap swizzled(nullptr, &::FreeImage_Unload); switch(mSwizzleType) { case ChannelSwizzle::eBGR: if (target == frame.bmp) { mProcessBuffer.reset(FreeImage_Clone(frame.bmp)); target = mProcessBuffer.get(); } SwapRedBlue32(target); break; case ChannelSwizzle::eRed: swizzled.reset(FreeImage_GetChannel(target, FICC_RED)); break; case ChannelSwizzle::eBlue: swizzled.reset(FreeImage_GetChannel(target, FICC_BLUE)); break; case ChannelSwizzle::eGreen: swizzled.reset(FreeImage_GetChannel(target, FICC_GREEN)); break; case ChannelSwizzle::eAlpha: swizzled.reset(FreeImage_GetChannel(target, FICC_ALPHA)); break; default: break; } if (swizzled) { mProcessBuffer = std::move(swizzled); target = mProcessBuffer.get(); } } mIsBuffered = (target == mProcessBuffer.get()); return target; } const QPixmap& ImageProcessor::getResultPixmap() { if (!mIsValid) { const auto pImg = mSrcImage.lock(); if (pImg) { const ImageFrame& frame = pImg->getFrame(); if (frame.bmp != nullptr) { mDstPixmap = QPixmap::fromImage(makeQImageView(process(frame))); mIsValid = true; } } } return mDstPixmap; } const UniqueBitmap& ImageProcessor::getResultBitmap() { if (mIsValid && mIsBuffered) { return mProcessBuffer; } else { const auto pImg = mSrcImage.lock(); if (pImg) { const ImageFrame& frame = pImg->getFrame(); if (frame.bmp) { const auto bmp = process(frame); if (!mIsBuffered) { mProcessBuffer.reset(FreeImage_Clone(bmp)); mIsBuffered = true; } mIsValid = true; } } } return mProcessBuffer; } void ImageProcessor::attachSource(QWeakPointer<Image> image) { detachSource(); mSrcImage = std::move(image); if (mSrcImage) { const auto pImg = mSrcImage.lock(); if(pImg) { pImg->addListener(this); } } } void ImageProcessor::detachSource() { if (mSrcImage) { const auto pImg = mSrcImage.lock(); if(pImg) { pImg->removeListener(this); } } mProcessBuffer.reset(); mIsValid = false; } void ImageProcessor::onInvalidated(Image* emitter) { assert(emitter == mSrcImage.lock().get()); (void)emitter; mIsValid = false; } uint32_t ImageProcessor::width() const { return !mDstPixmap.isNull() ? mDstPixmap.width() : 0; } uint32_t ImageProcessor::height() const { return !mDstPixmap.isNull() ? mDstPixmap.height() : 0; } bool ImageProcessor::getPixel(uint32_t y, uint32_t x, Pixel* p) const { const auto pImg = mSrcImage.lock(); bool success = false; if (pImg && p && y < height() && x < width()) { if (mFlips[FlipType::eHorizontal]) { x = width() - 1 - x; } if (mFlips[FlipType::eVertical]) { y = height() - 1 - y; } uint32_t srcY = y; uint32_t srcX = x; switch(mRotation) { case Rotation::eDegree90: srcY = x; srcX = pImg->width() - 1 - y; break; case Rotation::eDegree180: srcY = pImg->height() - 1 - y; srcX = pImg->width() - 1 - x; break; case Rotation::eDegree270: srcY = pImg->height() - 1 - x; srcX = y; break; default: break; } if (srcX < pImg->width() && srcY < pImg->height()) { success = pImg->getPixel(pImg->height() - 1 - srcY, srcX, p); if (success) { p->y = srcY; p->x = srcX; } } } return success; }
97a8c535f4ecbeb30d579c4838ef72f18f3dee12
6a6b52e5fbdcaee944fb39e983b7831ee0a1c699
/headers/Teewee.h
d8d8e12544442f3f8ab7e1224ecc7ec7d873d53f
[]
no_license
artonglocke/TetrisExcerciseMachina
39476e8a6ca817e3ae4d284f7a792482dd2d48fe
41fbd5f9906f816f5f81d5323c7bf9b6263456e7
refs/heads/master
2022-12-08T15:23:15.797936
2020-09-07T17:31:15
2020-09-07T17:31:15
281,204,572
0
0
null
null
null
null
UTF-8
C++
false
false
99
h
Teewee.h
#pragma once #include "IShape.h" class Teewee : public IShape { public: Teewee(); ~Teewee(); };
78e3fc754149b6b0ec37e40ceb7109025f4adb7e
64178ab5958c36c4582e69b6689359f169dc6f0d
/vscode/wg/sdk/FBoneNode.hpp
bb788d7de20d3084dd5a8e2c09e82113b19f098a
[]
no_license
c-ber/cber
47bc1362f180c9e8f0638e40bf716d8ec582e074
3cb5c85abd8a6be09e0283d136c87761925072de
refs/heads/master
2023-06-07T20:07:44.813723
2023-02-28T07:43:29
2023-02-28T07:43:29
40,457,301
5
5
null
2023-05-30T19:14:51
2015-08-10T01:37:22
C++
UTF-8
C++
false
false
1,382
hpp
FBoneNode.hpp
#pragma once #include "EBoneTranslationRetargetingMode.hpp" #ifdef _MSC_VER #pragma pack(push, 1) #endif namespace PUBGSDK { struct alignas(1) FBoneNode // Size: 0x10 { public: FName Name; /* Ofs: 0x0 Size: 0x8 NameProperty Engine.BoneNode.Name */ int32_t ParentIndex; /* Ofs: 0x8 Size: 0x4 IntProperty Engine.BoneNode.ParentIndex */ TEnumAsByte<enum EBoneTranslationRetargetingMode> TranslationRetargetingMode; /* Ofs: 0xC Size: 0x1 ByteProperty Engine.BoneNode.TranslationRetargetingMode */ uint8_t UnknownDataD[0x3]; }; #ifdef VALIDATE_SDK namespace Validation{ auto constexpr sizeofFBoneNode = sizeof(FBoneNode); // 16 static_assert(sizeof(FBoneNode) == 0x10, "Size of FBoneNode is not correct."); auto constexpr FBoneNode_Name_Offset = offsetof(FBoneNode, Name); static_assert(FBoneNode_Name_Offset == 0x0, "FBoneNode::Name offset is not 0"); auto constexpr FBoneNode_ParentIndex_Offset = offsetof(FBoneNode, ParentIndex); static_assert(FBoneNode_ParentIndex_Offset == 0x8, "FBoneNode::ParentIndex offset is not 8"); auto constexpr FBoneNode_TranslationRetargetingMode_Offset = offsetof(FBoneNode, TranslationRetargetingMode); static_assert(FBoneNode_TranslationRetargetingMode_Offset == 0xc, "FBoneNode::TranslationRetargetingMode offset is not c"); } #endif } #ifdef _MSC_VER #pragma pack(pop) #endif
8c23c537b1479b5115d0cf73874dcdbe0924510f
90a256bc1b33d5466388635d5a796bd28918b116
/1206A.cpp
06b09a9beffc095fcf261b94f64c416f4ba16068
[]
no_license
moonwarnishan/CodeForces2
75f9774f9537f77e2922bbfe0da9516c7f12f448
a1048ad5ea7cf5aed4f078f4af6b4a9dbab343fa
refs/heads/main
2023-08-29T01:54:53.097658
2021-11-10T15:41:00
2021-11-10T15:41:00
408,134,976
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
1206A.cpp
#include<bits/stdc++.h> using namespace std; int main() { long long int n;cin>>n; long long int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } long long int m; cin>>m; long long int b[m]; for(int j=0;j<m;j++) { cin>>b[j]; } sort(a,a+n); sort(b,b+m); cout<<a[n-1]<<" "<<b[m-1]<<endl; }
d59d9ca1b335a2cb78efe20c54b6096dd246072d
35e79b51f691b7737db254ba1d907b2fd2d731ef
/yukicoder/424.cpp
58bda3ca27c28d839fa15feac635f700e73d8a13
[]
no_license
rodea0952/competitive-programming
00260062d00f56a011f146cbdb9ef8356e6b69e4
9d7089307c8f61ea1274a9f51d6ea00d67b80482
refs/heads/master
2022-07-01T02:25:46.897613
2022-06-04T08:44:42
2022-06-04T08:44:42
202,485,546
0
0
null
null
null
null
UTF-8
C++
false
false
2,428
cpp
424.cpp
#pragma GCC optimize("O3") #include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #include <cfloat> #include <climits> #include <ctime> #include <cassert> #include <numeric> #include <fstream> #include <functional> #include <bitset> using namespace std; using ll = long long; using P = pair<int, int>; using T = tuple<int, int, int>; template <class T> inline T chmax(T &a, const T b) {return a = (a < b) ? b : a;} template <class T> inline T chmin(T &a, const T b) {return a = (a > b) ? b : a;} constexpr int MOD = 1e9 + 7; constexpr int inf = 1e9; constexpr long long INF = 1e18; constexpr double pi = acos(-1); constexpr double EPS = 1e-10; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; int main(){ cin.tie(0); ios::sync_with_stdio(false); int h, w; cin>>h>>w; int sy, sx, gy, gx; cin>>sy>>sx>>gy>>gx; sy--, sx--, gy--, gx--; vector<string> b(h); for(int i=0; i<h; i++) cin>>b[i]; queue<P> que; que.emplace(sy, sx); vector<vector<bool>> visited(h, vector<bool>(w, false)); visited[sy][sx] = true; bool valid = false; while(que.size()){ int cy, cx; tie(cy, cx) = que.front(); que.pop(); int cnum = b[cy][cx] - '0'; if(cy == gy && cx == gx){ valid = true; break; } for(int i=0; i<4; i++){ int ny = cy + dy[i]; int nx = cx + dx[i]; if(0 <= ny && ny < h && 0 <= nx && nx < w && !visited[ny][nx]){ int nnum = b[ny][nx] - '0'; if(abs(cnum - nnum) <= 1){ visited[ny][nx] = true; que.emplace(ny, nx); } } int nny = ny + dy[i]; int nnx = nx + dx[i]; if(0 <= nny && nny < h && 0 <= nnx && nnx < w && !visited[nny][nnx]){ int nnum = b[ny][nx] - '0'; int nnnum = b[nny][nnx] - '0'; if(cnum == nnnum && nnum < nnnum){ visited[nny][nnx] = true; que.emplace(nny, nnx); } } } } if(valid) cout << "YES" << endl; else cout << "NO" << endl; }
02b4da3cc333805f9046fb461993a27ddc5b32ee
e5d54d3ff26818b28197f7f3d79c44df98482f68
/src/SMAboutDialog.cpp
d16f62ee064f962a8c9db83e57a03cc18d4c00c4
[]
no_license
el-X/steganomonkey
78700bdc10a558181f5779b11eb017e82493e624
5526a02d49973225500a22978869e469016ff1ec
refs/heads/master
2016-09-06T02:48:15.640469
2014-06-24T08:37:37
2014-06-24T08:37:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,797
cpp
SMAboutDialog.cpp
/* * File: SMAboutDialog.cpp * Author: Alexander Keller, Robert Heimsoth, Thomas Matern * * HS BREMEN, SS2014, TI6.2 */ #include "SMAboutDialog.h" SMAboutDialog::SMAboutDialog(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size) : wxDialog(parent, id, title, pos, size) { this->SetTitle(TEXT_TITLE); this->create(); this->doLayout(); } /** * Erstellt alle Widgets des About-Dialogs. */ void SMAboutDialog::create() { mainPanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); appImage = new wxStaticBitmap(mainPanel, wxID_ANY, wxBITMAP_PNG(monkey_about), wxDefaultPosition, wxDefaultSize, 0); appImage->SetFocus(); separator = new wxStaticLine(mainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); developerHeadingLabel = new wxStaticText(mainPanel, wxID_ANY, TEXT_DEVELOPER_HEADING, wxDefaultPosition, wxDefaultSize, 0); developerHeadingLabel->SetFont(FONT_BOLD); developerLabel1 = new wxStaticText(mainPanel, wxID_ANY, TEXT_DEVELOPER1, wxDefaultPosition, wxDefaultSize, 0); developerLabel2 = new wxStaticText(mainPanel, wxID_ANY, TEXT_DEVELOPER2, wxDefaultPosition, wxDefaultSize, 0); copyleftImage = new wxStaticBitmap(mainPanel, wxID_ANY, wxBITMAP_PNG(copyleft15x15), wxDefaultPosition, wxDefaultSize, 0); copyleftImage->SetToolTip(TOOLTIP_COPYLEFT); copyleftLabel = new wxStaticText(mainPanel, wxID_ANY, TEXT_COPYLEFT, wxDefaultPosition, wxDefaultSize, 0); clipartLabel = new wxStaticText(mainPanel, wxID_ANY, TEXT_CLIPART_BY, wxDefaultPosition, wxDefaultSize, 0); clipartLink = new wxHyperlinkCtrl(mainPanel, wxID_ANY, TEXT_CLIPART, LINK_CLIPART); clipartLink->SetToolTip(LINK_CLIPART); iconLabel = new wxStaticText(mainPanel, wxID_ANY, TEXT_ICON_BY, wxDefaultPosition, wxDefaultSize, 0); iconLink = new wxHyperlinkCtrl(mainPanel, wxID_ANY, TEXT_ICON, LINK_ICON); iconLink->SetToolTip(LINK_ICON); } /** * Sorgt für das Layout des About-Dialogs. */ void SMAboutDialog::doLayout() { wxBoxSizer* mainPanelSizer; wxBoxSizer* mainSizer; wxBoxSizer* copyleftSizer; wxBoxSizer* clipartSizer; wxBoxSizer* iconSizer; // Oberer Bereich mainSizer = new wxBoxSizer(wxVERTICAL); mainSizer->Add(appImage, 0, wxALL | wxEXPAND, 5); mainSizer->Add(separator, 0, wxEXPAND | wxALL, 5); mainSizer->Add(developerHeadingLabel, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); mainSizer->Add(developerLabel1, 0, wxALIGN_CENTER_HORIZONTAL, 5); mainSizer->Add(developerLabel2, 0, wxALIGN_CENTER_HORIZONTAL, 5); // Copyleft copyleftSizer = new wxBoxSizer(wxHORIZONTAL); copyleftSizer->Add(copyleftImage, 0, wxALIGN_CENTER_VERTICAL, 5); copyleftSizer->Add(copyleftLabel, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxTOP | wxBOTTOM, 5); mainSizer->Add(copyleftSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxTOP | wxLEFT | wxRIGHT, 5); // Clipart clipartSizer = new wxBoxSizer(wxHORIZONTAL); clipartSizer->Add(clipartLabel, 0, wxALIGN_CENTER_VERTICAL, 5); clipartSizer->Add(clipartLink, 0, wxALIGN_CENTER_VERTICAL, 5); mainSizer->Add(clipartSizer, 0, wxALIGN_CENTER_HORIZONTAL, 5); // Icon iconSizer = new wxBoxSizer(wxHORIZONTAL); iconSizer->Add(iconLabel, 0, wxALIGN_CENTER_VERTICAL, 5); iconSizer->Add(iconLink, 0, wxALIGN_CENTER_VERTICAL, 5); mainSizer->Add(iconSizer, 0, wxALIGN_CENTER_HORIZONTAL, 5); mainPanel->SetSizer(mainSizer); mainPanel->Layout(); mainSizer->Fit(mainPanel); mainPanelSizer = new wxBoxSizer(wxVERTICAL); mainPanelSizer->Add(mainPanel, 1, wxEXPAND | wxALL, 5); this->SetSizer(mainPanelSizer); this->Layout(); mainPanelSizer->Fit(this); this->Centre(wxBOTH); }
0c1f4d80928667fb9ce7c54a271ef948d0c871c0
d3d3cf3afd7a7cc9d7cf5f18551ad59dbbaaedf6
/imageprocessingtoolboxwidget.cpp
57c560d2af5cfe84adc61eb45e581493045ba2ce
[]
no_license
taiiksi/ImageProcessingOpenCV
ea8662a43b934e4559b797c34a68ca46589f1559
0a11df3ba5ace4c1b44e7430b89f62023334fd98
refs/heads/master
2021-01-15T12:55:00.643593
2016-04-04T20:15:31
2016-04-04T20:15:31
55,525,597
1
0
null
2016-04-05T16:51:52
2016-04-05T16:51:52
null
UTF-8
C++
false
false
1,253
cpp
imageprocessingtoolboxwidget.cpp
#include "imageprocessingtoolboxwidget.h" ImageProcessingToolBoxWidget::ImageProcessingToolBoxWidget(QWidget *parent) : QWidget(parent), layout(new QGridLayout), toolBox(new QToolBox), firstToolSet(new QWidget), secondToolSet(new QWidget), thirdToolSet(new QWidget), fourthToolSet(new QWidget) { setupImageProcessingToolBox(); } ImageProcessingToolBoxWidget::~ImageProcessingToolBoxWidget() { delete fourthToolSet; delete thirdToolSet; delete secondToolSet; delete firstToolSet; delete toolBox; delete layout; } void ImageProcessingToolBoxWidget::setupImageProcessingToolBox() { layout->addWidget(toolBox,0,0); layout->setColumnStretch(0,1); layout->setRowStretch(0,1); setLayout(layout); toolBox->addItem(firstToolSet,QIcon(QString("C:\\Users\\Umamaheswaran\\Desktop\\button.png")),"Page1"); toolBox->addItem(secondToolSet,QIcon(QString("C:\\Users\\Umamaheswaran\\Desktop\\button.png")),"Page2"); toolBox->addItem(thirdToolSet,QIcon(QString("C:\\Users\\Umamaheswaran\\Desktop\\button.png")),"Page3"); toolBox->addItem(fourthToolSet,QIcon(QString("C:\\Users\\Umamaheswaran\\Desktop\\button.png")),"Page4"); toolBox->layout()->setSpacing(0); }
8e98eb7cd576d5ed2e6cb62c4653b8f621dc4ba1
59f762e5bd4e49489d6e1e3e14ae377497e98c56
/3DEngine/ComponentTransform.h
72584100fe1db3c14603e9f4b457b71994015d11
[ "MIT" ]
permissive
PolCarCat/3D--Engine
e7ef1d225868a8d8dd4da6dc6b0b5548d0e4841d
009eb20f5dd5b48d6b9725e119104d5222732e34
refs/heads/master
2020-03-28T16:08:26.536759
2018-12-23T21:20:33
2018-12-23T21:20:33
148,663,548
0
0
MIT
2018-10-09T08:05:48
2018-09-13T16:04:39
C++
UTF-8
C++
false
false
609
h
ComponentTransform.h
#ifndef __COMPONENT_TRANSFORM_H__ #define __COMPONENT_TRANSFORM_H__ #include "Component.h" #include "MathGeoLib/MathGeoLib.h" class ComponentTransform : public Component { public: ComponentTransform(); ~ComponentTransform(); bool Start(); bool Update(); void UpdateUI(); bool CleanUp(); bool Save(JSON_Object* json, JsonDoc* doc); bool Load(JSON_Object* json, JsonDoc* doc); void CalcMatrix(); void CalcVectors(); float3 position = { 0, 0, 0 }; float3 scale = { 0, 0, 0 }; Quat rotation = { 0, 0, 0, 0 }; float4x4 localMartix; float4x4 globalMartix; }; #endif //__COMPONENT_TRANSFORM_H__
2c7219a6f0530b059838e71ab8de8103173850c5
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/organization/src/v20210331/model/OrgProductFinancial.cpp
3b9e8efe6372fcd6009e821803570ac877312ed5
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
5,200
cpp
OrgProductFinancial.cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/organization/v20210331/model/OrgProductFinancial.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Organization::V20210331::Model; using namespace std; OrgProductFinancial::OrgProductFinancial() : m_productNameHasBeenSet(false), m_productCodeHasBeenSet(false), m_totalCostHasBeenSet(false), m_ratioHasBeenSet(false) { } CoreInternalOutcome OrgProductFinancial::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("ProductName") && !value["ProductName"].IsNull()) { if (!value["ProductName"].IsString()) { return CoreInternalOutcome(Core::Error("response `OrgProductFinancial.ProductName` IsString=false incorrectly").SetRequestId(requestId)); } m_productName = string(value["ProductName"].GetString()); m_productNameHasBeenSet = true; } if (value.HasMember("ProductCode") && !value["ProductCode"].IsNull()) { if (!value["ProductCode"].IsString()) { return CoreInternalOutcome(Core::Error("response `OrgProductFinancial.ProductCode` IsString=false incorrectly").SetRequestId(requestId)); } m_productCode = string(value["ProductCode"].GetString()); m_productCodeHasBeenSet = true; } if (value.HasMember("TotalCost") && !value["TotalCost"].IsNull()) { if (!value["TotalCost"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `OrgProductFinancial.TotalCost` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_totalCost = value["TotalCost"].GetDouble(); m_totalCostHasBeenSet = true; } if (value.HasMember("Ratio") && !value["Ratio"].IsNull()) { if (!value["Ratio"].IsString()) { return CoreInternalOutcome(Core::Error("response `OrgProductFinancial.Ratio` IsString=false incorrectly").SetRequestId(requestId)); } m_ratio = string(value["Ratio"].GetString()); m_ratioHasBeenSet = true; } return CoreInternalOutcome(true); } void OrgProductFinancial::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_productNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProductName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_productName.c_str(), allocator).Move(), allocator); } if (m_productCodeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProductCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_productCode.c_str(), allocator).Move(), allocator); } if (m_totalCostHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TotalCost"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_totalCost, allocator); } if (m_ratioHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Ratio"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_ratio.c_str(), allocator).Move(), allocator); } } string OrgProductFinancial::GetProductName() const { return m_productName; } void OrgProductFinancial::SetProductName(const string& _productName) { m_productName = _productName; m_productNameHasBeenSet = true; } bool OrgProductFinancial::ProductNameHasBeenSet() const { return m_productNameHasBeenSet; } string OrgProductFinancial::GetProductCode() const { return m_productCode; } void OrgProductFinancial::SetProductCode(const string& _productCode) { m_productCode = _productCode; m_productCodeHasBeenSet = true; } bool OrgProductFinancial::ProductCodeHasBeenSet() const { return m_productCodeHasBeenSet; } double OrgProductFinancial::GetTotalCost() const { return m_totalCost; } void OrgProductFinancial::SetTotalCost(const double& _totalCost) { m_totalCost = _totalCost; m_totalCostHasBeenSet = true; } bool OrgProductFinancial::TotalCostHasBeenSet() const { return m_totalCostHasBeenSet; } string OrgProductFinancial::GetRatio() const { return m_ratio; } void OrgProductFinancial::SetRatio(const string& _ratio) { m_ratio = _ratio; m_ratioHasBeenSet = true; } bool OrgProductFinancial::RatioHasBeenSet() const { return m_ratioHasBeenSet; }
d457308e9dec8142b2689030a3d366b08f1f3389
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5706278382862336_1/C++/mlazowik/a.cpp
776d001d3f5947f50727c3a222a69055e4db0ed4
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,252
cpp
a.cpp
// Michał Łazowik #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <utility> using namespace std; typedef long long LL; #define REP(x, n) for (int x = 0; x < n; ++x) #define FOR(x, b, e) for (int x = b; x <= (e); ++x) #define FORD(x, b, e) for (int x = b; x >= (e); --x) #define FOREACH(it, cont) for (__typeof(cont.begin()) it = cont.begin(); it != cont.end(); ++it) #define F first #define S second #define MP make_pair #define PB push_back LL nwd(LL a, LL b) { LL c; while (b != 0) { c = a % b; a = b; b = c; } return a; } int log2(LL a) { int ret = 0; while (a > 1) { if (a % 2 == 1) { return -1; } a /= 2; ret++; } return ret; } int solve(LL a, LL b) { LL div = nwd(a, b); a /= div; b /= div; int ret = 0; int anc = log2(b); if (a > b || anc == -1 || anc > 40) { return -1; } while (a < b) { b /= 2; ret++; } return ret; } int main() { int t; LL a, b; scanf("%d", &t); FOR(q, 1, t) { scanf("%lld/%lld", &a, &b); printf("Case #%d: ", q); int tmp = solve(a, b); if (tmp == -1) { printf("impossible"); } else { printf("%d", tmp); } printf("\n"); } return 0; }
fadd0af18e1ac19450db5fd814e3265119f1c3e5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_5092.cpp
4fe6e84a0972fe042cbea13cd112f03501e601a1
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
httpd_old_hunk_5092.cpp
* * (This is usually the case when the client forces an SSL * renegotiation which is handled implicitly by OpenSSL.) */ outctx->rc = APR_EAGAIN; } else if (ssl_err == SSL_ERROR_SYSCALL) { ap_log_cerror(APLOG_MARK, APLOG_INFO, outctx->rc, c, APLOGNO(01993) "SSL output filter write failed."); } else /* if (ssl_err == SSL_ERROR_SSL) */ { /*
ad5fe1778898ddfd19e42bcdc998235c4229b802
52e430d46f0edbf72553b4ff513e8fcbdcb1c385
/Algorithmic_toolbox/Week_5/1.5.1.cpp
a1b6d82556584797a312bd37763f7b0f16967e56
[]
no_license
ivk22/Data_Structures_and_Algorithm
5ffd040a26764428bf26cefd88219032d0dbdb93
8e6cceba2a9806b31dee54c89986f15b430c1639
refs/heads/master
2021-07-11T21:23:00.875599
2020-08-19T06:30:51
2020-08-19T06:30:51
191,723,271
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
cpp
1.5.1.cpp
// 1.5.1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> using namespace std; int main() { size_t n = 0; cin >> n; size_t* arr = new size_t[n+1]; arr[0]=0; size_t* coins = new size_t[3]; coins[0] = 1; coins[1] = 3; coins[2] = 4; for (size_t i = 1; i <= n; ++i) { size_t mn = 0; for (size_t j = 0; j < 3; ++j) { if (i >= coins[j]) { if (arr[i - coins[j]] + 1 < mn || !mn) { mn = arr[i - coins[j]] + 1; } } } arr[i] = mn; } cout << arr[n]; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
a797087151c1a3582c9a69adc29737ec1c993640
d04b7ee933b9b0dd151aa6f5cd6967fe0adcbe92
/CodeChef_problems/The Tom and Jerry Game!/solution2.cpp
2f2271474fe8f4bcfd13750100ff59301ac12d18
[ "MIT" ]
permissive
deepak1214/CompetitiveCode
69e0e54c056ca7d360dac9f1099eaf018d202bd0
1e1449064dbe2c52269a6ac393da74f6571ebebc
refs/heads/main
2023-01-04T11:36:03.723271
2020-10-31T20:44:34
2020-10-31T20:44:34
308,840,332
4
0
MIT
2020-10-31T08:46:15
2020-10-31T08:46:14
null
UTF-8
C++
false
false
1,410
cpp
solution2.cpp
/* We have to make sure that Jerry wins. It is mentioned that Jerry can only win if If TS is odd and JS is even, Jerry wins the game. Until Jerry wins we have to make sure that the game goes on. The condition for the game to proceed is If both TS and JS are even, their values get divided by 2 and the game proceeds with the next turn. We are only given the TS value as input for each testcase. To solve this problem, consider the bit representation of the TS number. Say TS = 11 (Eleven) then its bit representation would be TS = 1011 (in binary) Find k such that pow(2,k) is the highest power that divides TS then JS must have atleast a factor of pow(2,k+1). Find pow(2,k) such that k is the highest power of 2 which divides TS. Divide TS by pow(2,k+1) and take the floor. Let that be z. z is the number of possible values of JS. */ #include <bits/stdc++.h> using namespace std; #define sync \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); #define ll long long int void solve() { ll n; cin >> n; ll temp = n; ll k = 0; while (temp % 2 == 0) { temp = temp >> 1; k++; } ll ans = (1ll << (k + 1)); ans = n / ans; cout << ans << '\n'; } int main() { sync; int testCases; cin >> testCases; while (testCases--) { solve(); } return 0; }
e617916b7884841f9f478277baa035cdbceafbf9
2ebd7fc32d3937865fb36cc301aed9a23302f99c
/sequential/seq_tree.h
e1ef35ff21bad9f88217773807b3b43461f2fef2
[]
no_license
irbowen/b_trees
fbe0780d34d1760b3310b170d86f2449babdd03a
14a2b5c2f448b442e4e4ef4afc3243177c374a14
refs/heads/master
2021-01-10T09:48:52.383186
2016-01-03T18:46:58
2016-01-03T18:46:58
45,809,564
2
0
null
2015-12-04T22:52:12
2015-11-09T02:13:37
TeX
UTF-8
C++
false
false
298
h
seq_tree.h
#ifndef SEQ_TREE_H #define SEQ_TREE_H #include <vector> #include <algorithm> #include <iostream> #include "inner_node.h" #include "leaf_node.h" class Sequential_Tree { public: Inner_Node* root; Sequential_Tree(); void insert(int, int); void print_all(); int get_value(int); }; #endif
389243f0240955fa77e382df657321f6e36ac061
73b2b2ec3706168331d07a2d4cdcff8a646dc4f7
/MyCryptoLib/src/sha256.cpp
09ae9b9ba1451633dde9c1ad4b93962758eac550
[ "Unlicense" ]
permissive
KoSeAn97/MyCryptoLib
ee849e90cc0c1d9f151cb0c5fe4b0d83ce6d1fae
6bbad3c5075013dcd841eb28188dfeff2be16e25
refs/heads/master
2021-01-12T11:29:52.919589
2018-06-02T22:31:42
2018-06-02T23:37:50
72,936,985
2
0
null
null
null
null
UTF-8
C++
false
false
5,937
cpp
sha256.cpp
#include <cstring> #include <machine/endian.h> #include <iostream> using std::cerr; using std::endl; #include <MyCryptoLib/mycrypto.hpp> #include <MyCryptoLib/sha256.hpp> #include <MyCryptoLib/rawbytes.hpp> using namespace raw_bytes; // ======================== Tables Of Constants ============================= // static uint32_t consts[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; static uint32_t const init_h[] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; // ============================= Functions ================================== // void hash_function(byte * dst, byte const * msg, unsigned msg_len); //void round_function(byte *, byte *, byte const *); void round_function(uint32_t const * msg_block, uint32_t * prev_h); // ---------------- Round Function Transformations -------------------------- // inline uint32_t ch_f(uint32_t x, uint32_t y, uint32_t z); inline uint32_t maj_f(uint32_t x, uint32_t y, uint32_t z); inline uint32_t bsigma0(uint32_t x); inline uint32_t bsigma1(uint32_t x); inline uint32_t lsigma0(uint32_t x); inline uint32_t lsigma1(uint32_t x); // -------------------- Other Transformations ------------------------------- // void padding(byte * ptr, unsigned tail_size, unsigned buf_size, unsigned msg_size); uint32_t rotr32(uint32_t x, unsigned short n = 1); uint32_t rotl32(uint32_t x, unsigned short n = 1); // ========================================================================== // // ======================= SHA256 Hash Function ============================ // void SHA256::hash(ByteBlock const & src, ByteBlock & dst) const { dst = ByteBlock(_hash_length); hash_function(dst.byte_ptr(), src.byte_ptr(), src.size()); } // ============================== Realization =============================== // void hash_function(byte * dst, byte const * msg, unsigned msg_len) { uint32_t hash[8]; for (int i = 0; i < 8; i++) hash[i] = init_h[i]; unsigned integral_parts = msg_len >> 6; // msg_len / 64 unsigned tail_part_len = msg_len - (integral_parts << 6); // integral_parts * 64 auto msg_block = reinterpret_cast<uint32_t const *>(msg); for (int i = 0; i < integral_parts; i++, msg_block += 16) round_function(msg_block, hash); byte padded_msg[128] = { 0 }; msg += integral_parts << 6; for (int i = 0 ; i < tail_part_len; i++) padded_msg[i] = msg[i]; unsigned shift = 0; if (tail_part_len > 64 - 9) { padding(padded_msg, tail_part_len, 128, msg_len); round_function( reinterpret_cast<uint32_t *>(padded_msg), hash ); shift = 64; } else { padding(padded_msg, tail_part_len, 64, msg_len); } round_function( reinterpret_cast<uint32_t *>(padded_msg + shift), hash ); for (int i = 0; i < 8; i++) hash[i] = __builtin_bswap32(hash[i]); memcpy(dst, hash, sizeof hash); } void round_function(uint32_t const * msg_block, uint32_t * prev_h) { uint32_t m_schedule[64]; for (int i = 0; i < 16; i++) m_schedule[i] = __builtin_bswap32(msg_block[i]); for (int t = 16; t < 64; t++) m_schedule[t] = lsigma1(m_schedule[t-2]) + m_schedule[t-7] + lsigma0(m_schedule[t-15]) + m_schedule[t-16]; uint32_t prm[8]; // a, b, ..., h memcpy(prm, prev_h, sizeof prm); for (int t = 0; t < 64; t++) { #define var(ch) prm[ch - 'a'] uint32_t tmp1 = var('h') + bsigma1( var('e') ) + ch_f( var('e'), var('f'), var('g') ) + consts[t] + m_schedule[t]; uint32_t tmp2 = bsigma0( var('a') ) + maj_f( var('a'), var('b'), var('c') ); for (int i = 6; i >= 0; i--) prm[i+1] = prm[i]; var('e') = var('e') + tmp1; var('a') = tmp1 + tmp2; #undef var } for (int i = 0; i < 8; i++) prev_h[i] = prm[i] + prev_h[i]; } void padding(byte * ptr, unsigned tail_size, unsigned buf_size, unsigned msg_size) { ptr[tail_size] = 0x80; memset(ptr + tail_size + 1, 0, buf_size - (tail_size + 1)); for (ptr += buf_size - 1, msg_size <<= 3; msg_size; msg_size >>= 8) *(ptr--) = msg_size & 0xff; } uint32_t rotr32(uint32_t x, unsigned short n) { n = n & 0x1f; return (x >> n) | (x << (32 - n)); } uint32_t rotl32(uint32_t x, unsigned short n) { n = n & 0x1f; return (x << n) | (x >> (32 - n)); } inline uint32_t ch_f(uint32_t x, uint32_t y, uint32_t z) { return (x & y) ^ (~x & z); } inline uint32_t maj_f(uint32_t x, uint32_t y, uint32_t z) { return (x & y) ^ (x & z) ^ (y & z); } inline uint32_t bsigma0(uint32_t x) { return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } inline uint32_t bsigma1(uint32_t x) { return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } inline uint32_t lsigma0(uint32_t x) { return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >> 3); } inline uint32_t lsigma1(uint32_t x) { return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >> 10); }
4c29cbacd149b6b24065e9e3eee396ad6647fa96
ce32e80ba77094b9541b4f857031c4aa7af4d713
/graph/vertex.cpp
a37580fa4ffe3140b6f1f120e4306a17f60cb75c
[]
no_license
jpnbastos/Janus
e8a494e8e9cf1e26a0ba279b9bedeb1496f5d3a9
129000eff0f20463e9366b0796b31beee16fcf21
refs/heads/master
2020-03-17T18:07:59.953517
2018-05-24T12:15:34
2018-05-24T12:15:34
133,815,507
0
0
null
null
null
null
UTF-8
C++
false
false
64
cpp
vertex.cpp
// // Created by Bastos on 23/04/2018. // #include "vertex.h"
7b4ba89927eb1324bcd73ddfabb48479678fbeee
358a40dea4ec1bcc53d431cea4eb81005ad10536
/engine/include/Cute/Array.h
96e5f25b9bb0bf9fcbcbc2958e04caeaf5d71a49
[]
no_license
jeckbjy/engine
cc0a0b82b7d7891f4fbf3d851ecea38e2b1cd3f5
1e15d88dfb21f9cd7140d61c79764a932b24ef4d
refs/heads/master
2020-04-07T02:00:37.381732
2017-06-22T06:09:10
2017-06-22T06:09:10
47,948,967
3
1
null
null
null
null
UTF-8
C++
false
false
3,542
h
Array.h
//! Collection #pragma once #include "Cute/Foundation.h" #include "Cute/Exception.h" #include <algorithm> CUTE_NS_BEGIN /// STL container like C-style array replacement class. /// /// This implementation is based on the idea of Nicolai Josuttis. /// His original implementation can be found at http://www.josuttis.com/cppcode/array.html . template<class T, std::size_t N> class Array { public: typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; enum { static_size = N }; iterator begin() { return elems; } const_iterator begin() const { return elems; } iterator end() { return elems + N; } const_iterator end() const { return elems + N; } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } reference operator[](size_type i) { cute_assert(i < N && "out of range"); return elems[i]; } const_reference operator[](size_type i) const { cute_assert(i < N && "out of range"); return elems[i]; } reference at(size_type i) { if (i >= size()) throw InvalidArgumentException("Array::at() range check failed: index is over range"); return elems[i]; } const_reference at(size_type i) const { if (i >= size()) throw InvalidArgumentException("Array::at() range check failed: index is over range"); return elems[i]; } reference front() { return elems[0]; } const_reference front() const { return elems[0]; } reference back() { return elems[N - 1]; } const_reference back() const { return elems[N - 1]; } static size_type size() { return N; } static bool empty() { return false; } static size_type max_size() { return N; } void swap(Array<T, N>& y) { std::swap_ranges(begin(), end(), y.begin()); } const T* data() const { return elems; } T* data() { return elems; } T* c_array(){ return elems; } template <typename Other> Array<T, N>& operator= (const Array<Other, N>& rhs) { std::copy(rhs.begin(), rhs.end(), begin()); return *this; } void assign(const T& value) { std::fill_n(begin(), size(), value); } public: T elems[N]; }; // comparisons template<class T, std::size_t N> bool operator== (const Array<T, N>& x, const Array<T, N>& y) { return std::equal(x.begin(), x.end(), y.begin()); } template<class T, std::size_t N> bool operator< (const Array<T, N>& x, const Array<T, N>& y) { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } template<class T, std::size_t N> bool operator!= (const Array<T, N>& x, const Array<T, N>& y) { return !(x == y); } template<class T, std::size_t N> bool operator> (const Array<T, N>& x, const Array<T, N>& y) { return y < x; } template<class T, std::size_t N> bool operator<= (const Array<T, N>& x, const Array<T, N>& y) { return !(y < x); } template<class T, std::size_t N> bool operator>= (const Array<T, N>& x, const Array<T, N>& y) { return !(x < y); } template<class T, std::size_t N> inline void swap(Array<T, N>& x, Array<T, N>& y) { x.swap(y); } CUTE_NS_END
9909f833f456200c7bf5e8587a98f99073d11176
7e797415eddea48580c78f10a571b1e2cb596d65
/source/resource/ArchiveWriter.cpp
b95dc89ff9382726d03aa4158e0f32d9a1155b51
[]
no_license
razzie/PotatoGame
dcf8a393221faf3d0cdd41a6f5f88b141fcb5536
495d243693d82df43a053dbf75b38163f598a9b7
refs/heads/master
2022-08-19T16:42:23.278074
2018-08-09T20:00:46
2018-08-09T20:02:22
144,187,201
0
0
null
null
null
null
ISO-8859-2
C++
false
false
3,030
cpp
ArchiveWriter.cpp
/* * Copyright (C) Gábor Görzsöny <gabor@gorzsony.com> - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential */ #include <cstdint> #include <vector> #include "common/Encoder.hpp" #include "resource/ArchiveWriter.hpp" resource::ArchiveWriter::ArchiveWriter(const char* archive, bool append) { std::ios::openmode mode = std::ios::out | std::ios::binary; if (append) mode |= std::ios::app; else mode |= std::ios::trunc; m_archive.open(archive, mode); } resource::ArchiveWriter::ArchiveWriter(const wchar_t* archive, bool append) { std::ios::openmode mode = std::ios::out | std::ios::binary; if (append) mode |= std::ios::app; else mode |= std::ios::trunc; m_archive.open(archive, mode); } bool resource::ArchiveWriter::compress(const char* source_filename, const char* dest_filename, raz::IMemoryPool* memory) { std::ifstream file(source_filename, std::ios_base::in | std::ios_base::binary); return compressInternal(file, dest_filename, memory); } bool resource::ArchiveWriter::compress(const wchar_t* source_filename, const char* dest_filename, raz::IMemoryPool* memory) { std::ifstream file(source_filename, std::ios_base::in | std::ios_base::binary); return compressInternal(file, dest_filename, memory); } bool resource::ArchiveWriter::compressInternal(std::ifstream& file, const char* dest_filename, raz::IMemoryPool* memory) { if (!file.is_open()) return false; // get original file size file.seekg(0, std::ios::end); const uint32_t original_size = static_cast<uint32_t>(file.tellg()); file.seekg(0, std::ios::beg); // get estimated compressed size uint32_t compressed_size = static_cast<uint32_t>(doboz::Compressor::getMaxCompressedSize(original_size)); // allocate buffer for both original and compressed file data std::vector<char, raz::Allocator<char>> buffer(memory); buffer.resize(original_size + compressed_size); // read file data if (!file.read(buffer.data(), original_size)) return false; // compress data (also updates compressed_size) doboz::Result result = m_compressor.compress(&buffer[0], original_size, &buffer[original_size], buffer.size(), compressed_size); if (result != doboz::RESULT_OK) return false; // encrypt file name String filename(dest_filename, memory); const uint16_t filename_length = static_cast<uint16_t>(filename.size()); common::encode(reinterpret_cast<unsigned char*>(&filename[0]), filename_length); // write filename length m_archive.write(reinterpret_cast<const char*>(&filename_length), sizeof(uint16_t)); // write filename m_archive.write(&filename[0], filename_length); // write original size m_archive.write(reinterpret_cast<const char*>(&original_size), sizeof(uint32_t)); // write compressed size m_archive.write(reinterpret_cast<const char*>(&compressed_size), sizeof(uint32_t)); // write compressed data m_archive.write(&buffer[original_size], compressed_size); m_archive.flush(); return static_cast<bool>(m_archive); }
6fe3a2f4d6b3aa526f31ef91b958e4c43672c3b1
c38531b077a4ad41c88ec68d8e5536a28f95e7a9
/relay/handler_thread.cpp
5bdfc6179f1f70a64ab63158dca67916498e1009
[ "MIT" ]
permissive
jhengyilin/chatNT
ff47f9c1deb5e2da9b83ae99796f1439c62a5d80
7287a90bf2270d12584157285dd160b2e55dd0b3
refs/heads/main
2023-02-07T15:03:54.812508
2020-12-29T04:38:33
2020-12-29T04:38:33
325,220,787
0
0
MIT
2020-12-29T07:44:45
2020-12-29T07:44:44
null
UTF-8
C++
false
false
3,310
cpp
handler_thread.cpp
#include "handler_thread.h" #include <sstream> #include <cstring> #include <thread> #include <unistd.h> #include <sys/types.h> #define CHUNK_SIZE 1024 #ifdef __linux__ #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #elif _WIN32 #include <WinSock2.h> #endif using namespace std; //main handler for thread void HandlerThread::handler() { string sendString, receiveString; sendString = "Connection initialized\n"; sendMessage(sendString); while (true) { receiveString = receiveMessage(); if (receiveString != "SIGFAULT") { if (process(receiveString)) { break; } } else { break; } } for (unsigned int i = 0; i < user->size(); i++) { if (user->at(i).hashId == hashId) { user->erase(user->begin() + i); break; } } info("Thread " + to_string(threadSocketDescriptor) + " with hash id: " + hashId + " terminated\n"); close(threadSocketDescriptor); delete this; } //processor for received data int HandlerThread::process(string receiveString) { //segmentalize received data stringstream receiveStream(receiveString); string segment; vector<string> segments; segments.clear(); while (getline(receiveStream, segment, '#')) { segments.push_back(segment); } //read command and do corresponding actions if (segments[0] == "EXIT") { sendMessage("Bye"); for (unsigned int i = 0; i < user->size(); i++) { if (user->at(i).hashId == hashId) { user->erase(user->begin() + i); break; } } return 1; } else if (segments[0] == "REGISTER") { //add user to user list User tmp; tmp.hashId = segments[1]; hashId = segments[1]; tmp.ip = ip; tmp.port = stoi(segments[2]); tmp.publicKey = segments[3]; user->push_back(tmp); sendMessage("Register Successful"); } else if (segments[0] == "LIST") { //return stringified user list string dataString = ""; for (unsigned int i = 0; i < user->size(); i++) { if (i != 0) { dataString += "#"; } dataString += user->at(i).hashId + "#" + user->at(i).ip + "#" + to_string(user->at(i).port) + "#" + user->at(i).publicKey; } sendMessage(dataString); } return 0; } //wait to receive data and returns received data string HandlerThread::receiveMessage() { //receive data in chunks char receiveData[CHUNK_SIZE]; string receiveString = ""; while (true) { memset(receiveData, '\0', sizeof(receiveData)); int recvErr = recv(threadSocketDescriptor, receiveData, sizeof(receiveData), 0); if (recvErr < 0) { return "SIGFAULT"; } receiveString += string(receiveData); if (string(receiveData).length() < CHUNK_SIZE - 1) { break; } } return receiveString; } //send data with socket void HandlerThread::sendMessage(string sendString) { //send data in chunks char sendData[CHUNK_SIZE]; int iter = 0; while (iter * (CHUNK_SIZE - 1) < sendString.length()) { string substring = sendString.substr(iter * (CHUNK_SIZE - 1), (CHUNK_SIZE - 1)); memset(sendData, '\0', CHUNK_SIZE); strncpy(sendData, substring.c_str(), substring.length()); send(threadSocketDescriptor, sendData, CHUNK_SIZE, 0); iter++; } }
67bd7ee2265e81ef4d88e819158c467153b73be6
45bebb1cf4e951d673755e5700a9e30b27b1c3ae
/Base/mafVersion.h
db3d2540a45b0511a0351153ba669b9eeaaf9390
[]
no_license
besoft/MAF2
1a26bfbb4bedb036741941a43b135162448bbf33
b576955f4f6b954467021f12baedfebcaf79a382
refs/heads/master
2020-04-13T13:58:44.609511
2019-07-31T13:56:54
2019-07-31T13:56:54
31,658,947
1
3
null
2015-03-04T13:41:48
2015-03-04T13:41:48
null
UTF-8
C++
false
false
1,821
h
mafVersion.h
/*========================================================================= Program: MAF2 Module: mafVersion Authors: based on mafVersion (www.vtk.org), adapted by Marco Petrone Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __mafVersion_h #define __mafVersion_h #include "mafBase.h" #include "mafConfigure.h" #define MAF_SOURCE_VERSION "maf version " MAF_VERSION ", maf source $Revision: 1.4 $, $Date: 2005-02-20 23:33:19 $ (GMT)" /** mafVersion - Versioning class for MAF. Holds methods for defining/determining the current MAF version (major, minor, build). @beware This file will change frequently to update the MAF_SOURCE_VERSION which timestamps a particular source release. */ class MAF_EXPORT mafVersion : public mafBase { public: mafVersion() {}; ~mafVersion() {}; /** Return the version of maf this object is a part of. A variety of methods are included. GetMAFSourceVersion returns a string with an identifier which timestamps a particular source tree.*/ static const char *GetMAFVersion() { return MAF_VERSION; } static int GetMAFMajorVersion() { return MAF_MAJOR_VERSION; } static int GetMAFMinorVersion() { return MAF_MINOR_VERSION; } static int GetMAFBuildVersion() { return MAF_BUILD_VERSION; } static const char *GetMAFSourceVersion() { return MAF_SOURCE_VERSION; } private: mafVersion(const mafVersion&); // Not implemented. void operator=(const mafVersion&); // Not implemented. }; #endif
95842a39d1c6f85b7fbeeb652e85e063ba356117
cf112a9aa5c7915cd6aa73db31643ee17e1fcdf1
/test/unit/test_vector.cpp
bb4d2538873137979d1bb323057f4dbab50bf48c
[ "BSD-3-Clause" ]
permissive
arbor-sim/arbor
eb9357b2dbcb0b751bec4fd7cda25e70c6231987
3314098914bba01527fbd995f7b023d70ef834eb
refs/heads/master
2023-09-01T05:51:34.410032
2023-08-18T11:10:42
2023-08-18T11:10:42
69,863,074
82
48
BSD-3-Clause
2023-09-13T11:53:34
2016-10-03T11:03:22
C++
UTF-8
C++
false
false
3,698
cpp
test_vector.cpp
#include <gtest/gtest.h> #include <limits> #include <type_traits> #include <memory/memory.hpp> #include <util/span.hpp> // // wrappers // using namespace arb; // test that memory::make_view and make_const_view work on std::vector TEST(vector, make_view_stdvector) { // test that we can make views of std::vector std::vector<int> stdvec(10); auto view = memory::make_view(stdvec); EXPECT_EQ(view.size(), stdvec.size()); EXPECT_EQ(view.data(), stdvec.data()); EXPECT_TRUE((std::is_same<int*, decltype(view.data())>::value)); auto const_view = memory::make_const_view(stdvec); EXPECT_EQ(const_view.size(), stdvec.size()); EXPECT_EQ(const_view.data(), stdvec.data()); EXPECT_TRUE((std::is_same<const int*, decltype(const_view.data())>::value)); } // test that memory::on_host makes a view of std::vector TEST(vector, make_host_stdvector) { std::vector<int> stdvec(10); auto host_vec = memory::on_host(stdvec); using target_type = std::decay_t<decltype(host_vec)>; EXPECT_EQ(host_vec.size(), stdvec.size()); EXPECT_EQ(host_vec.data(), stdvec.data()); EXPECT_TRUE(memory::util::is_on_host<target_type>()); EXPECT_TRUE((std::is_same<int, target_type::value_type>::value)); } // test that memory::on_host makes a view of host_vector and host view TEST(vector, make_host_hostvector) { memory::host_vector<int> vec(10); { // test from host_vector auto host_view = memory::on_host(vec); using target_type = std::decay_t<decltype(host_view)>; EXPECT_EQ(host_view.size(), vec.size()); EXPECT_EQ(host_view.data(), vec.data()); EXPECT_TRUE(memory::util::is_on_host<target_type>()); EXPECT_TRUE((std::is_same<int, target_type::value_type>::value)); } { // test from view auto view = memory::make_view(vec); auto host_view = memory::on_host(view); using target_type = std::decay_t<decltype(host_view)>; EXPECT_EQ(host_view.size(), view.size()); EXPECT_EQ(host_view.data(), view.data()); EXPECT_TRUE(memory::util::is_on_host<target_type>()); EXPECT_TRUE((std::is_same<int, target_type::value_type>::value)); } } // // fill // // test filling of memory with values on the host TEST(vector, fill_host) { constexpr auto N = 10u; using util::make_span; // fill a std::vector for (auto n : make_span(0u, N)) { std::vector<int> v(n, 0); memory::fill(v, 42); for (auto i: make_span(0u, n)) { EXPECT_EQ(v[i], 42); } } // fill an array for (auto n : make_span(0u, N)) { double value = (n+1)/2.; memory::host_vector<double> v(n); memory::fill(v, value); for (auto i: make_span(0u, n)) { EXPECT_EQ(v[i], value); } } // fill an array view std::vector<float> ubervec(N); for (auto n : make_span(0u, N)) { float value = float((n+1)/2.f); using view_type = memory::host_vector<float>::view_type; // make a view of a sub-range of the std::vector ubervec auto v = view_type(ubervec.data(), n); memory::fill(v, value); for (auto i: make_span(0u, n)) { EXPECT_EQ(v[i], value); } } } // // copy // TEST(vector, copy_h2h) { constexpr auto N = 10u; using util::make_span; for (auto n : make_span(0u, N)) { double value = (n+1)/2.; std::vector<double> src(n, value); std::vector<double> tgt(n, std::numeric_limits<double>::quiet_NaN()); memory::copy(src, tgt); for (auto i: make_span(0u, n)) { EXPECT_EQ(tgt[i], value); } } }
e71c8e3d5beb3e7710167cde6fcde017071abe5b
9eb8913126c2b4a608ac2defa7108a46c15f828f
/FireflyEngine/include/Firefly/Rendering/Vulkan/VulkanDevice.h
1bdd0258197a2dc8a8f36619e6658266573af85b
[ "MIT" ]
permissive
GitDaroth/FireflyEngine
1b13e8b32f0f8062981efe17882a233d35b44fe5
ea19a6a7f283e25eb989b2a499297e0834024c0b
refs/heads/master
2023-06-27T19:11:31.901728
2021-07-18T11:53:01
2021-07-18T11:53:01
267,032,715
1
0
null
null
null
null
UTF-8
C++
false
false
1,006
h
VulkanDevice.h
#pragma once #include <vulkan/vulkan.hpp> namespace Firefly { class VulkanDevice { public: void Init(vk::PhysicalDevice physicalDevice, vk::SurfaceKHR surface, const std::vector<const char*>& requiredDeviceExtensions, const std::vector<const char*>& requiredDeviceLayers); void Destroy(); vk::Device GetHandle() const; vk::PhysicalDevice GetPhysicalDevice() const; vk::Queue GetGraphicsQueue() const; vk::Queue GetPresentQueue() const; uint32_t GetGraphicsQueueFamilyIndex() const; uint32_t GetPresentQueueFamilyIndex() const; void WaitIdle(); private: void FindRequiredQueueFamilyIndices(vk::SurfaceKHR surface); vk::Device m_device; vk::PhysicalDevice m_physicalDevice; uint32_t m_graphicsQueueFamilyIndex = 0; uint32_t m_graphicsQueueIndex = 0; uint32_t m_presentQueueFamilyIndex = 0; uint32_t m_presentQueueIndex = 0; }; }
b087790ce7c802e8253581d81bb206234e7e0bf0
bd9de700605da2278a92020a2814b699daedec57
/codility/lesson13_1_FibFrog/lesson13_1_pass_0.66.hpp
c5dd5fd77ba18cdf4788621751e45b761d16c97f
[]
no_license
WuHang108/petit-a-petit
8b177771e004341a166feb1a156153098f5d5d89
e173df8333f9a4070aee5ee65603fed92d2abf6b
refs/heads/master
2021-11-18T15:36:40.059510
2021-10-16T17:10:02
2021-10-16T17:10:02
230,759,303
1
0
null
null
null
null
UTF-8
C++
false
false
999
hpp
lesson13_1_pass_0.66.hpp
#include "../basic_io.hpp" using namespace std; const int MAX_N = 100005; bool F[MAX_N]; int Next[MAX_N]; int dp[MAX_N]; // dp[i] 表示到达 i 位置需要的最小跳数, -1为不可达 int solution(vector<int>& A) { // 筛出Fibonacci数 int M_1 = 0, M_2 = 1; F[M_1] = true; F[M_2] = true; int M = M_1 + M_2; while(M < MAX_N) { F[M] = true; M_2 = M_1; M_1 = M; M = M_1 + M_2; } // 构建next数组 int N = A.size(); if(N == 0) return 1; int nextPos = N; for(int i=N-1; i>=0; --i) { Next[i] = nextPos; if(A[i] == 1) { nextPos = i; } } memset(dp, 0x7, sizeof(dp)); dp[0] = 1; for(int i=1; i<=N; i++) { if(F[i+1]) { dp[i] = 1; } else for(int j=0; j<i; j=Next[j]) { if(A[j]>0 && F[i-j]) { dp[i] = std::min(dp[i], dp[j]+1); } } } if(dp[N] >= MAX_N) return -1; return dp[N]; }
bb8586396ad0ce9ca9a0cbb06afd09c1e56ef4bc
2c8c9841bbd2917cbd0f89c51edbb4400f1430e4
/BearGame/base/Singleton.h
071333d68571a55b1f6c7cc86c85146b12296da7
[]
no_license
IBM9100/BearGame
1df62db066c3e5f812f261a71cc201e07ac769d6
41370e8dc63e6f5479ae4931057ec45e7fce255d
refs/heads/master
2022-12-14T05:33:12.212964
2020-09-05T05:53:52
2020-09-05T05:53:52
291,615,600
0
0
null
2020-09-03T13:13:48
2020-08-31T04:37:40
C
UTF-8
C++
false
false
336
h
Singleton.h
#ifndef BEARGAME_BASE_SINGLETON_H #define BEARGAME_BASE_SINGLETON_H #include "base/Noncopyable.h" namespace BearGame { template <typename T> class Singleton : private Noncopyable { public: static T& instance() { static T t; return t; } protected: Singleton() {} virtual ~Singleton() {} }; } #endif
def5570f3a761c2c3721a51c9e9718cbe69bda85
955f980319f2d8696c8c624ec0a509fa67f31478
/c++/hw2/here.cpp
7405f42ced3a0ec9ab4079f3f95058405c352b42
[]
no_license
wagnod/itmo
58db961b719afe253b1895ad1955ffafba673100
7d36990b7c0de20d9875ef7c7fe885d5a4c8e650
refs/heads/master
2022-03-10T13:25:06.219769
2022-02-03T10:57:07
2022-02-03T10:57:07
226,410,253
0
0
null
2022-02-03T09:42:35
2019-12-06T21:03:06
Jupyter Notebook
UTF-8
C++
false
false
105
cpp
here.cpp
#include <iostream> #include "mylib.h" void here() { std::cout << "I'm here!" << "\n"; return; }
29c37d0a27e7238aef36fb402115ad07640cbafa
281f783c9ee4f0f7fffff1a419c8a94c71dab494
/Object.cpp
0c44477803fea43f6790256d929cd87f05625b42
[]
no_license
15117294633/DTLib
b1d5b6ad839f16ff6dd892e70f2c845f21320da4
781e76c8a815694037a426d236e078a7816faf7a
refs/heads/master
2020-03-11T22:37:10.282872
2019-01-07T03:12:00
2019-01-07T03:12:00
130,297,083
0
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
Object.cpp
#include"Object.h" #include <cstdlib> namespace DTLib { void* Object::operator new(unsigned int size) throw() { return malloc(size); } void Object::operator delete(void *p) { free(p); } void* Object::operator new[] (unsigned int size)throw() { return malloc(size); } void Object::operator delete[](void *p) { free(p); } bool Object::operator ==(const Object& obj) { return (this==&obj); } bool Object::operator !=(const Object& obj) { return (this!=&obj); } Object::~Object() { } }
19f73406dc586856d0c2c410afedcedd72785924
0a8b76c12b2f483f125e84e6609039a7d5af6c79
/JokeLib/JokeLib.h
ead80e5e2b4a3ebf881c131530d334ca5d29bd6c
[]
no_license
leithergit/JokeDSE
d00f90c23e9f520fda348edf50fd58f33c0bfc4e
663044f4b144e44e017c522d493da20f6b6d125e
refs/heads/master
2023-04-01T16:04:23.155800
2021-04-08T07:11:50
2021-04-08T07:11:50
149,065,864
0
0
null
null
null
null
UTF-8
C++
false
false
516
h
JokeLib.h
// defined with this macro as being exported. #ifdef JOKELIB_EXPORTS #define JOKELIB_API __declspec(dllexport) #else #define JOKELIB_API __declspec(dllimport) #endif // This class is exported from the Win32Lib.dll class JOKELIB_API CWin32Lib { public: CWin32Lib(void); // TODO: add your methods here. }; // JOKELIB_API void EnableJoke(); // // JOKELIB_API void StopJoke(); JOKELIB_API void ExcuteJoke(char *szSource, char *szFilter1,HMODULE &hRemoteJokeLib); JOKELIB_API void EnableJoke();
10fa4d0351d3ce671b1f1ceb523b86fa3f4c6ad8
6ed4073a453fa04ea9670ba2162f294f5208acf7
/old codes/tmp.cpp
69abb2469459943fa32a36e01803507888faae1b
[ "MIT" ]
permissive
ikaushikpal/C-practice
b13355dcc03094ba0ed41867d98bc2d68a63bfd0
abab8a186eaf38b434811755833a32306cd47d64
refs/heads/master
2023-04-09T10:15:45.329569
2021-04-20T03:39:57
2021-04-20T03:39:57
276,837,694
0
0
null
null
null
null
UTF-8
C++
false
false
483
cpp
tmp.cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,k; cin>>n>>k; int a[n]; for(int i=0;i<n;i++) a[i]=i+1; int l; l=a[n-1]; a[n-1]=a[k]; a[k]=l; for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl; } // your code goes here return 0; }
d5c3b001f962cddf7f36db32016b451bd1ee3eff
3e06494229b1c6f5c68ffd7161b71e476be72e38
/test.cpp
1e6dfa0267e6c454f61d787350520abac254865d
[]
no_license
mariogeiger/AStar
726751e7ac855fb596df3214e767fb02a77fea4b
a20d9ce2fce49067b7ff10e9c73db474364a873e
refs/heads/master
2021-05-26T15:29:51.301021
2012-03-07T21:00:04
2012-03-07T21:00:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
test.cpp
#include "qastar.h" #include <QDebug> #include <QPoint> class MyAStar : public QAStar<QPoint> { public: int heuristicCostEstimate(QPoint start, QPoint goal) { return (start - goal).manhattanLength(); } int distanceBetween(QPoint, QPoint) { return 1; } QList<QPoint> neighborNodes(QPoint current) { QList<QPoint> list; list << current + QPoint(1, 0); list << current + QPoint(0, 1); list << current + QPoint(-1, 0); list << current + QPoint(0, -1); return list; } }; uint qHash(const QPoint &p) { return ((p.x() & 0x0000FFFF) << 16) | (p.y() & 0x0000FFFF); } int main() { MyAStar ass; qDebug() << ass.findPath(QPoint(0, 0), QPoint(10, 10)); return 0; }
10db45741564847aa542c5f2a60367e1ac6128bc
cab166cc7b9f0d570e551b032599ffacc986eef7
/common/frontendscommon/include/external/VpnFrontendService.hpp
e15045fa5fd0d4998fc442d2a69eb728ecc3b359
[]
no_license
michael370662/C-to-Swift
2a74a2cba528a9c8351407d6a0127554ce63d400
ce1d2527929d85b8b962c8e8ac0a11dc156a30c5
refs/heads/master
2020-06-04T03:36:39.025980
2019-06-14T01:55:25
2019-06-14T01:55:25
191,858,367
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
hpp
VpnFrontendService.hpp
#ifndef __PonyTech_Frontend_VpnFrontendService_hpp__ #define __PonyTech_Frontend_VpnFrontendService_hpp__ #include "../PonyTech-Frontend_DEP.hpp" BEGIN_NAMESPACE(Frontend) class VpnSettingsProvider; class ConnectionSystem; class SocketSystem; class ConnectHeartbeatManager; class SocketMessageForwarder; class VpnFrontendService { bool m_library_inited; const VpnSettingsProvider& m_provider; FmWork::TaskSubmitter& m_submitter; ConnectionSystem& m_connection; AutoPtr<ConnectHeartbeatManager> m_heartbeat; public: VpnFrontendService(const VpnSettingsProvider& provider, ConnectionSystem& connection, SocketSystem& socket_system, SocketMessageForwarder& message_forwarder, FmWork::TaskSubmitter& schedular); ~VpnFrontendService(); bool startup(); void register_loader(); void teardown(); void reload_settings(); bool load_plugins(); void start_connect(); ConnectHeartbeatManager* heartbeat_mgr() { return m_heartbeat.non_const_ptr(); } FmWork::TaskSubmitter& submitter() { return m_submitter; } const VpnSettingsProvider& setting_provider() { return m_provider; } virtual void change_status(int status) = 0; virtual bool socket_bypass(int fd, int family) = 0; virtual void on_sudden_disconnect() {} private: Net::SockAddress is_new_request() const; static int sock_bypass_wrap(void *self, int fd, int family); FND_DISABLE_COPY(VpnFrontendService); }; END_NAMESPACE(Frontend) #endif // __PonyTech_Frontend_VpnFrontendService_hpp__
2fc072468217501f664078f9ee9b2b99a6a32653
56ce115d0742822b88b341ba9f15575adebc1b50
/build/ui_mainwindow.h
fcc13306bb35f3e839e238e18f62583d93619161
[]
no_license
AlexsCode/NewsRSS
836d5c5534eb8441765bf4bc733fa87c00572d8a
21b064dbc6cf5ea1cc154c289f47c9e30af13297
refs/heads/main
2023-02-03T15:16:52.261110
2020-11-26T09:43:44
2020-11-26T09:43:44
314,542,637
0
0
null
null
null
null
UTF-8
C++
false
false
2,714
h
ui_mainwindow.h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.11.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPlainTextEdit> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QVBoxLayout *verticalLayout; QPlainTextEdit *plainTextEdit; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(800, 600); QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(MainWindow->sizePolicy().hasHeightForWidth()); MainWindow->setSizePolicy(sizePolicy); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); verticalLayout = new QVBoxLayout(centralWidget); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); plainTextEdit = new QPlainTextEdit(centralWidget); plainTextEdit->setObjectName(QStringLiteral("plainTextEdit")); QFont font; font.setFamily(QStringLiteral("Sans Serif")); font.setPointSize(70); font.setBold(true); font.setWeight(75); plainTextEdit->setFont(font); plainTextEdit->setStyleSheet(QLatin1String("background-color: rgb(0, 0, 0);\n" "color: rgb(255, 255, 255);\n" "")); plainTextEdit->setLineWidth(0); plainTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth); plainTextEdit->setReadOnly(true); verticalLayout->addWidget(plainTextEdit); MainWindow->setCentralWidget(centralWidget); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "News", nullptr)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
ba55bc84c3f2d9733b7d124c396658ddd1d84481
505970b41594c4ef10972c15eb2c491fb07ce196
/Caudalimetro.hpp
5a816ff5592750e5ae6962ad407535c29aab5b45
[]
no_license
ULL-InformaticaIndustrial-Empotrados/TFG_Beneharo_agua
8aa8892cdfe634fc785111dd67171a2e22a231f1
767cfd1a1b103aa53f69a5b93b1309a507248082
refs/heads/master
2022-12-11T18:16:35.192348
2020-09-08T16:11:54
2020-09-08T16:11:54
177,574,150
0
0
null
null
null
null
UTF-8
C++
false
false
836
hpp
Caudalimetro.hpp
#ifndef _CAUDALIMETRO_ #define _CAUDALIMETRO_ #include "BBB_GPIO_pin.hpp" #include "BBB_GPIO_Interrupts.hpp" #include <thread> //A la clase Caudalimetro el string(P8_36) se le pase como parámetro al constructor. class Caudalimetro { protected: unsigned _nPulsos = 0; //Inicializada a 0 (apartir de c++11) y es unsigned ya que nunca va a tener valores negativos BBB_GPIO_Interrupts _intrr;//Objeto de la clase 'BBB_GPIO_Interrupts' void cuentaPulsos(); //Función privada std::thread* _pthilo1; //Puntero de tipo thread float pulsosPorLitro = 800; //Cantidad ya calculada a mano llenando una botella de 1 litro public: Caudalimetro(); unsigned getNumeroPulsos(); //Lo que devuelve es unsigned (valor positivo siempre) float getLitros(); void resetNumeroPulsos(); }; #endif
0d55d1f817f90c596dcad51f179ecac75420db6e
45c6e5e140019ea417b06fe5c082ad309eaab0ce
/DlgHeightCalib.h
f8273d2be8f8fa0b75a23eb69f011edef25ff85c
[]
no_license
isliulin/fadvs
532220b54d17eab90717a8cd92b280417e65eeeb
5729519bcd0651eb85b34fcbda61c50f1d70ddc4
refs/heads/master
2022-10-16T04:32:17.502976
2020-06-15T09:55:21
2020-06-15T09:55:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
951
h
DlgHeightCalib.h
#pragma once // CDlgHeightCalib dialog class CDlgHeightCalib : public CDialog { DECLARE_DYNAMIC(CDlgHeightCalib) public: CDlgHeightCalib(CWnd* pParent = NULL); // standard constructor virtual ~CDlgHeightCalib(); // Dialog Data enum { IDD = IDD_DLG_HEIGHT_CALIB }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: CColorButton m_cbMotion[6]; double dContactValue; double dHeightValue; tgPos m_tgContactPos; tgPos m_tgHeightPos; HBITMAP m_hBitmap; virtual BOOL OnInitDialog(); afx_msg void OnNMCustomdrawSliderHeightCalibSpeed(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnBnClickedBtnHeightCalibNext(); afx_msg void OnBnClickedOk(); void UpdateContactSensorValue(); void UpdateHeightSensorValue(); afx_msg void OnTimer(UINT_PTR nIDEvent); void MoveToContactSensorPos(); void MoveToHeightSensorPos(); void SaveData(); afx_msg void OnBnClickedCancel(); };
4fe395fde36a34e1fe5327ee5e2f536358d1aeab
590c5838440cac897007f8dfb1d5f68bc35928c3
/Exercicios/Lista 1 - Exercícios de Estruturas Sequenciais/exercicio17.cpp
632cac8bc010e510ef4aae80b635bd6ea341383a
[]
no_license
luizsilvadev/algoritimos
3f8360814246805887cd5c28c4520d2acb884483
9ea895482a719cc4ca3278b5da0b3d5a0c15cef6
refs/heads/master
2022-11-21T10:10:46.323109
2020-07-26T01:10:49
2020-07-26T01:10:49
282,448,527
0
0
null
null
null
null
UTF-8
C++
false
false
188
cpp
exercicio17.cpp
#include <iostream> using namespace std; int main() { string n; int n1,n2,n3; cin>>n; n1 =n[0]-48; n2 = n[1]-48; n3 = n[2]-48; cout<<n1*n2*n3; return 0; }
1cf3cad7e57cc99565198c90b61b780de52f6fdf
5fb1eceef8adf85899ce2b5aa9f4d9c2d4a49d6d
/C++/Hackerrank/PrepKit/ArrayManipulation.cpp
9bb85db20589c43775ea3f03b2d0a569f6b14f01
[]
no_license
alexz429/CompetitiveProgramming
e52346186aad9cf76b9b1b35b00527175a5f0f9a
474475d053c93b2038b52e58299caadbfc4fa379
refs/heads/master
2022-01-19T20:18:52.373649
2022-01-03T23:34:00
2022-01-03T23:34:00
184,585,704
1
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
ArrayManipulation.cpp
long arrayManipulation(int n, vector<vector<int>> queries) { vector<long> psa(n); for(vector<int> next:queries){ psa[next[0]-1]+=next[2]; if(next[1]!=n){ psa[next[1]]-=next[2]; } } long best=0; long tally=0; for(int next:psa){ tally+=next; best=max(best,tally); } return best; }
feb15e5f985bbd512af5fd5ea95e271454a02ff2
98157b3124db71ca0ffe4e77060f25503aa7617f
/hackerrank/world-codesprint-6/hard-drive-disks.cpp
6696d4ceeef5bf72a7f95a2276fa2584e535fd37
[]
no_license
wiwitrifai/competitive-programming
c4130004cd32ae857a7a1e8d670484e236073741
f4b0044182f1d9280841c01e7eca4ad882875bca
refs/heads/master
2022-10-24T05:31:46.176752
2022-09-02T07:08:05
2022-09-02T07:08:35
59,357,984
37
4
null
null
null
null
UTF-8
C++
false
false
2,496
cpp
hard-drive-disks.cpp
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; const long long inf = 1e17; long long dp[N]; pair<int, int> hd[N]; long long ad[N], ac[N], ae[N]; int main() { int n, k; scanf("%d %d", &n, &k); k--; vector< long long > p; long long ans = 0; for (int i = 0; i < n; i++) { int a, b; scanf("%d %d", &a, &b); if (a > b) swap(a, b); hd[i] = {a, b}; ans += b-a; p.push_back(a); p.push_back(b); } sort(p.begin(), p.end()); p.erase(unique(p.begin(), p.end()), p.end()); for (int i = 0; i < n; i++) { hd[i].first = lower_bound(p.begin(), p.end(), hd[i].first) - p.begin(); hd[i].second = lower_bound(p.begin(), p.end(), hd[i].second) - p.begin(); } sort(hd, hd + n); for (int i = 0; i <= k; i++) dp[i] = 0; int id = 0; long long sum = 0, mul = 0; for (int i = 1; i < p.size(); i++) { // cerr << i << " " << p[i] << endl; while (id < n && hd[id].first < i) { ae[hd[id].second]++; id++; } mul += ae[i]; sum += mul * (p[i] - p[i-1]); dp[i * (k+1)] = sum; // cerr << sum ; for (int h = 0; h < k; h++) { // cerr << " h " << h << endl; long long &dpnow = dp[i * (k + 1) + h + 1]; dpnow = inf; long long now = 0, add = 0; int d = id-1; for (int j = i-1; j >= 0; j--) { while (d >= 0 && hd[d].first > j) { if (d >= 0 && hd[d].second < i) { long long ma = p[hd[d].first] - p[i] + p[hd[d].second]; int it = upper_bound(p.begin(), p.end(), ma) - p.begin() - 1; if (it >= 0) { ad[it]--; ac[it] += p[it] - ma; } add++; } d--; } now += add * (p[j+1] - p[j]) + ac[j]; add += ad[j]; // cerr << i << " " << j << " " << h << " " << now << endl; dpnow = min(dpnow, dp[j * (k+1) + h] + now); } for (int j = 0; j <= id; j++) ad[j] = ac[j] = 0; // cerr << " " << dpnow ; } // cerr << endl; } long long add = inf, cnt = 0, now = 0; id = n-1; for (int i = (int) p.size() - 1; i > 0; i--) { while (id >= 0 && i < hd[id].first) { id--; cnt++; } if (i < p.size()) now += cnt * (p[i+1] - p[i]); for (int j = 0; j <= k; j++) add = min(add, dp[i * (k+1) + j] + now); // cerr << i << " " << add << endl; } // cerr << ans << " " << 2 * add << endl; printf("%lld\n", ans + add * 2); return 0; }
ff0d37d73cd0f0c842d54c0ab0c6492b0be4e878
9f6a48d7d3c1801d31c29319924ea4f77abce505
/templates/gui/include/SignalHandler.hh
19699faf172bd1e9fcd4b53f910aca0eee8e3ae0
[]
no_license
zach-hartwig/ROOTUtilities
dcbfd1b519e69f85a8a75955e989d45b339dc31d
cd4f10651597226cf1a3fab9053d35f076b82e38
refs/heads/master
2021-01-13T02:19:53.146735
2017-01-26T03:44:24
2017-01-26T03:44:24
21,510,297
1
0
null
null
null
null
UTF-8
C++
false
false
716
hh
SignalHandler.hh
// name: SignalHandler.hh // date: 25 Jul 14 // auth: Zach Hartwig // mail: hartwig@psfc.mit.edu // // desc: The SignalHandler class contains the "slot" methods that are // triggered by "signals" generated by widgets in the // InterfaceBuilder class. It provides a modular way to handle // widget actions. #ifndef __SignalHandler_hh__ #define __SignalHandler_hh__ 1 #include <TObject.h> class InterfaceBuilder; class SignalHandler : public TObject { public: SignalHandler(InterfaceBuilder *); ~SignalHandler(); void HandleTextButtons(); void HandleTerminate(); // Register the class with ROOT ClassDef(SignalHandler, 0); private: InterfaceBuilder *TheInterface; }; #endif
b1305c8523c6049b981bf1dad0197e91beaf254d
297dc0627a4c1433938aff227c6cfc64f4f66444
/char_conversion/ctoi.cpp
99276027751b3a6008c22b8767cdc6e829336caf
[ "MIT" ]
permissive
alxkohh/cplusplus-code-snippets
82d9daf5f59ac7f9f6bdcdabbf3113828ca9a2ec
7328afbb12c68b479da9fbd0882aa0a3b2ed8f35
refs/heads/master
2023-03-01T18:02:06.661236
2021-02-07T16:09:51
2021-02-07T16:09:51
276,539,841
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
ctoi.cpp
/* A function to convert char to int. Eg. '7' -> 7 Although there is stoi, we also often require a ctoi. Obviously, those are single digit cases. '6', '2' etc. If more than 2 digits or with negative sign, we use stoi. */ #include <bits/stdc++.h> using namespace std; int ctoi(char c) { int i = c - '0'; // ASCII magic in action! return i; } int main() { char c = '8'; int i = ctoi(c); int j = i + 2; cout << j; return 0; }
7ec32f057455f7a1034577dbb8fc96aaa7171a52
ded10c52a4602174205b3ad5609319c7691fd9bf
/NguyenKhachuy_51_bai4.cpp
dbd5ef362fcdb1c19cf2619eacf0f2232042c527
[]
no_license
Khachuy911/c-language
6faf4eda6b3ff7be6a64185be7473dd9e695f437
ede335608e2a4f5eeb0ec260a0852cb75a5f29d6
refs/heads/master
2023-08-14T21:23:05.507297
2021-09-17T10:17:44
2021-09-17T10:17:44
407,494,110
1
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
NguyenKhachuy_51_bai4.cpp
#include<stdio.h> int main(){ int x; printf("Nhap x: "); scanf("%d",&x); if( 0<x && x<=12){ printf("Thang %d",x); }else printf("con so nay khang phai la 1 thang trong nam"); return 0 ; }
7fc6a62d02a2739a7cb938c53e263c4950c61551
fa1377bd22dc9f00b24e3fc2e106ea8cf3fd74e8
/src/core/core.cpp
95fe23deaa689e6317d5e5345baf255e19b1f9b6
[ "MIT" ]
permissive
juruen/cavalieri
17848168678d0ab68e321dd242679c2fafa50c4b
c3451579193fc8f081b6228ae295b463a0fd23bd
refs/heads/master
2020-04-02T16:49:47.492783
2015-09-08T19:07:43
2015-09-08T19:11:55
13,036,407
54
11
null
2014-10-05T18:59:53
2013-09-23T13:24:46
C++
UTF-8
C++
false
false
64
cpp
core.cpp
#include <core/core.h> std::shared_ptr<core_interface> g_core;
6e53b894a8312b53e9eadbd2522e12ee3f561a91
6cf43021bf234f48a245724ecede839a3c3b28eb
/Hypercube2Logical.h
525c5abe654c52fde73c7eb6af9f76091bda6178
[]
no_license
kmrodgers/GraphTheoryProgram
4cb3067831906cec05c897745cd9049cb5466e4c
55086d36d906725bc13e5b8c65c573f72b7b0cc6
refs/heads/master
2021-01-18T14:22:38.151502
2014-08-11T20:37:46
2014-08-11T20:37:46
21,622,671
0
1
null
null
null
null
UTF-8
C++
false
false
801
h
Hypercube2Logical.h
//Hypercube2Logical.h #ifndef GUARD_Hypercube2Logical_h #define GUARD_Hypercube2Logical_h #include <list> #include <vector> #include <string> //#include <boolean> class Node; class Hypercube2Logical { public: Hypercube2Logical(int, int, bool, int); virtual ~Hypercube2Logical(); void createInitialEdges(); void createInitialNodes(int); void removeEdge(); void printVersion(); void print(); void game(); //std::vector<std::string> player1; //std::vector<std::string> player2; //void analysis(int); int getRandomNumber(int); int getRandomEdge(int); int gameNumber; private: int nodeNameCount; //Keeps track of what the name of the next Node will be int edgeWeight; int totalGames; bool watch; void rotateBar(); int barCount; std::list<Node*> nodeList; }; #endif
8eabfc491ec2ef57d84a1e6786464f578189d667
4362646d31922b43907fbea0bba1ba283622eeb5
/Robotics/lab1-22.cpp
d6f2b68434adf7cfbda35fdf4ce416e75a9fdded
[]
no_license
mitkonikolov/oldLnxMachine
3f57d165a424f790a49d8500bc7b63ac98a72c75
a4e4d7d7a32b0b492c0d3e3822857071fd580b0c
refs/heads/master
2020-03-18T04:09:57.351236
2018-05-21T13:38:43
2018-05-21T13:38:43
134,273,163
0
0
null
null
null
null
UTF-8
C++
false
false
2,717
cpp
lab1-22.cpp
#include <iostream> using namespace std; double* p; int count; int size; void Initialize() { p = new double[2]; count = 0; size = 2; } void Finalize() { delete[] p; } void PrintVector(){ if (count == 0) { cout << "\nThe array is empty\n\n"; cin.ignore(100000, '\n'); cin.get(); } else{ cout << "\nArray: \n"; for(int i = 0; i < count; i++){ cout << p[i] << " "; } cout << endl << endl; } } void AddElement(){ cout << "\nEnter new element: "; cin >> p[count]; count++; cout << endl; } void Grow(){ double *np = new double[size + 2]; for(int i = 0; i < count; i++) np[i] = p[i]; delete[] p; p = np; cout << "\nVector grown\n" << "Previous capacity: " << size << " elements\n"; size = size + 2; cout << "New capacity: " << size << " elements\n"; } void RemoveElement(){ double *np = new double[size]; if (count == 0) { cout << "\nThe array is empty, cannot remove element\n\n"; cin.ignore(100000, '\n'); cin.get(); } else{ for(int i = 0; i < (count - 1); i++) np[i] = p[i]; delete[] p; p = np; cout << "\nLast element succesfully removed\n\n"; cin.ignore(100000, '\n'); cin.get(); count--; } } int main(){ int choice; bool exit = false; Initialize(); while(!exit){ cout << "Main menu:\n\n" << "1. Print the array\n" << "2. Append element at the end\n" << "3. Remove last element\n" << "4. Insert one element\n" << "5. Exit\n\n" << "Select an option: "; cin >> choice; switch(choice){ case 1: cout << "You selected \"Print the array\"\n"; PrintVector(); break; case 2: cout << "You selected \"Append element at the end\"\n"; break; case 3: cout << "You selected \"Remove last element\"\n"; RemoveElement(); break; case 4: cout << "You selected \"Insert one element\"\n"; if (count < size) AddElement(); else{ Grow(); AddElement(); } break; case 5: cout << "You selected \"Exit\"\n\n"; cout << "Exiting program..."; cin.ignore(100000, '\n'); cin.get(); exit = true; break; default: cout << "\t\t\nINVALID CHOICE!\n"; cin.get(); } } return 0; }
79dbe199f674db2c8a23f34b8ce0258f3bddc550
241cf71bfcb05f20cde09dbbd8edc71374a46542
/Game/Object/Object.hpp
653e112a8dee2f528f2a68ceeeade2440bf6a73d
[]
no_license
alorfa/JustGame
32f1bf7c44a7da340bb70399b94bace72b1ac7af
e3269fba2eb54f9155ada9f495496cfd5ee45dd7
refs/heads/main
2023-03-17T07:18:41.201791
2021-03-20T14:52:21
2021-03-20T14:52:21
342,811,652
5
0
null
null
null
null
UTF-8
C++
false
false
391
hpp
Object.hpp
#pragma once #include "SOOGL/Graphics/Transform/Transformable2D.hpp" #include "SOOGL/Graphics/Shader/Shader.hpp" #include "SOOGL/Graphics/Transform/Camera2D.hpp" #include "Color.hpp" namespace gd { class Object : public sgl::Transformable2D { const Color* color; public: Object() = default; virtual ~Object() = default; virtual void draw(const sgl::Camera2D& camera) = 0; }; }
69a231f47a30a3591253c9237c4455b9ebcd9894
6ffd23679939f59f0a09c9507a126ba056b239d7
/lite/test/test_tensor_c.cpp
fec9500e544fae3657fd6d05897cd513538782e0
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
MegEngine/MegEngine
74c1c9b6022c858962caf7f27e6f65220739999f
66b79160d35b2710c00befede0c3fd729109e474
refs/heads/master
2023-08-23T20:01:32.476848
2023-08-01T07:12:01
2023-08-11T06:04:12
248,175,118
5,697
585
Apache-2.0
2023-07-19T05:11:07
2020-03-18T08:21:58
C++
UTF-8
C++
false
false
12,111
cpp
test_tensor_c.cpp
#include "lite_build_config.h" #if LITE_BUILD_WITH_MGE #include "../src/misc.h" #include "lite-c/global_c.h" #include "lite-c/tensor_c.h" #include <gtest/gtest.h> #include <memory> #include <thread> TEST(TestCapiTensor, Basic) { LiteTensor c_tensor0, c_tensor1; LiteTensorDesc description = default_desc; LITE_make_tensor(description, &c_tensor0); int is_pinned_host = false; LITE_is_pinned_host(c_tensor0, &is_pinned_host); ASSERT_FALSE(is_pinned_host); LiteDeviceType device_type; LITE_get_tensor_device_type(c_tensor0, &device_type); ASSERT_EQ(device_type, LiteDeviceType::LITE_CPU); size_t length = 0; LITE_get_tensor_total_size_in_byte(c_tensor0, &length); ASSERT_EQ(length, 0); LiteLayout layout{{1, 3, 224, 224}, 4, LiteDataType::LITE_FLOAT}; description.device_type = LiteDeviceType::LITE_CPU; description.layout = layout; description.is_pinned_host = true; LITE_make_tensor(description, &c_tensor1); LITE_is_pinned_host(c_tensor1, &is_pinned_host); ASSERT_TRUE(is_pinned_host); LITE_get_tensor_total_size_in_byte(c_tensor1, &length); ASSERT_EQ(length, 1 * 3 * 224 * 224 * 4); LiteLayout get_layout; LITE_get_tensor_layout(c_tensor1, &get_layout); ASSERT_EQ(get_layout.ndim, layout.ndim); ASSERT_EQ(get_layout.data_type, layout.data_type); ASSERT_EQ(get_layout.shapes[0], layout.shapes[0]); ASSERT_EQ(get_layout.shapes[1], layout.shapes[1]); ASSERT_EQ(get_layout.shapes[2], layout.shapes[2]); ASSERT_EQ(get_layout.shapes[3], layout.shapes[3]); //! test error ASSERT_EQ(LITE_is_pinned_host(c_tensor0, nullptr), -1); ASSERT_NE(strlen(LITE_get_last_error()), 0); ASSERT_EQ(LITE_get_last_error_code(), ErrorCode::LITE_INTERNAL_ERROR); printf("The last error is: %s\n", LITE_get_last_error()); LITE_clear_last_error(); ASSERT_EQ(strlen(LITE_get_last_error()), 0); ASSERT_EQ(LITE_get_last_error_code(), ErrorCode::OK); LITE_destroy_tensor(c_tensor0); LITE_destroy_tensor(c_tensor1); } TEST(TestCapiTensor, SetLayoutReAlloc) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{1, 3, 224, 224}, 4, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); void *old_ptr, *new_ptr; LITE_get_tensor_memory(c_tensor0, &old_ptr); LiteLayout new_layout = LiteLayout{{1, 3, 100, 100}, 4, LiteDataType::LITE_INT8}; LITE_set_tensor_layout(c_tensor0, new_layout); LITE_get_tensor_memory(c_tensor0, &new_ptr); size_t length = 0; LITE_get_tensor_total_size_in_byte(c_tensor0, &length); ASSERT_EQ(length, 1 * 3 * 100 * 100); ASSERT_EQ(old_ptr, new_ptr); } TEST(TestCapiTensor, Reset) { LiteTensor c_tensor0, c_tensor1; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{3, 20}, 2, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); LITE_make_tensor(description, &c_tensor1); void *old_ptr0, *old_ptr1; LITE_get_tensor_memory(c_tensor0, &old_ptr0); LITE_get_tensor_memory(c_tensor1, &old_ptr1); //! make sure memory is allocted ASSERT_NO_THROW(memcpy(old_ptr0, old_ptr1, 3 * 20 * 4)); std::shared_ptr<float> new_ptr0( new float[3 * 20], [](float* ptr) { delete[] ptr; }); std::shared_ptr<float> new_ptr1( new float[3 * 20], [](float* ptr) { delete[] ptr; }); LITE_reset_tensor_memory(c_tensor0, new_ptr0.get(), 3 * 20 * 4); LITE_reset_tensor_memory(c_tensor1, new_ptr1.get(), 3 * 20 * 4); void *tmp_ptr0, *tmp_ptr1; LITE_get_tensor_memory(c_tensor0, &tmp_ptr0); LITE_get_tensor_memory(c_tensor1, &tmp_ptr1); ASSERT_EQ(tmp_ptr0, new_ptr0.get()); ASSERT_EQ(tmp_ptr1, new_ptr1.get()); ASSERT_NO_THROW(memcpy(new_ptr0.get(), new_ptr1.get(), 3 * 20 * 4)); LiteLayout layout1{{6, 20}, 2, LiteDataType::LITE_FLOAT}; std::shared_ptr<float> ptr2(new float[6 * 20], [](float* ptr) { delete[] ptr; }); std::shared_ptr<float> ptr3(new float[6 * 20], [](float* ptr) { delete[] ptr; }); LITE_reset_tensor(c_tensor0, layout1, new_ptr0.get()); LITE_reset_tensor(c_tensor1, layout1, new_ptr1.get()); //! memory is not freed by Tensor reset ASSERT_NO_THROW(memcpy(new_ptr0.get(), new_ptr1.get(), 3 * 20 * 4)); LiteLayout tmp_layout0, tmp_layout1; LITE_get_tensor_layout(c_tensor0, &tmp_layout0); LITE_get_tensor_layout(c_tensor1, &tmp_layout1); ASSERT_EQ(tmp_layout0.ndim, tmp_layout1.ndim); ASSERT_EQ(tmp_layout0.data_type, tmp_layout1.data_type); ASSERT_EQ(tmp_layout0.shapes[0], tmp_layout1.shapes[0]); ASSERT_EQ(tmp_layout0.shapes[1], tmp_layout1.shapes[1]); LITE_destroy_tensor(c_tensor0); LITE_destroy_tensor(c_tensor1); } TEST(TestCapiTensor, CrossCNCopy) { LiteTensor c_tensor0, c_tensor1, c_tensor2; LiteTensorDesc description = default_desc; LITE_make_tensor(description, &c_tensor0); description.layout = LiteLayout{{1, 3, 224, 224}, 4, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor1); LITE_make_tensor(description, &c_tensor2); LITE_tensor_copy(c_tensor1, c_tensor2); LITE_tensor_copy(c_tensor2, c_tensor1); void *old_ptr1, *old_ptr2, *new_ptr1, *new_ptr2; LITE_get_tensor_memory(c_tensor1, &old_ptr1); LITE_get_tensor_memory(c_tensor2, &old_ptr2); //! test source tenor is empty ASSERT_EQ(LITE_tensor_copy(c_tensor1, c_tensor0), -1); ASSERT_NE(strlen(LITE_get_last_error()), 0); printf("The last error is: %s\n", LITE_get_last_error()); LITE_tensor_copy(c_tensor0, c_tensor1); LITE_tensor_copy(c_tensor1, c_tensor2); LITE_tensor_copy(c_tensor2, c_tensor0); LITE_get_tensor_memory(c_tensor1, &new_ptr1); LITE_get_tensor_memory(c_tensor2, &new_ptr2); ASSERT_EQ(old_ptr1, new_ptr1); ASSERT_EQ(old_ptr2, new_ptr2); LITE_destroy_tensor(c_tensor0); LITE_destroy_tensor(c_tensor1); LITE_destroy_tensor(c_tensor2); } TEST(TestCapiTensor, ShareMemoryWith) { LiteTensor c_tensor0, c_tensor1; LiteTensorDesc description = default_desc; LITE_make_tensor(description, &c_tensor0); description.layout = LiteLayout{{1, 3, 224, 224}, 4, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor1); ASSERT_EQ(LITE_tensor_share_memory_with(c_tensor1, c_tensor0), -1); LITE_tensor_share_memory_with(c_tensor0, c_tensor1); void *ptr0, *ptr1; LITE_get_tensor_memory(c_tensor0, &ptr0); LITE_get_tensor_memory(c_tensor1, &ptr1); ASSERT_EQ(ptr0, ptr1); LITE_destroy_tensor(c_tensor0); LITE_destroy_tensor(c_tensor1); } TEST(TestCapiTensor, Reshape) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{8, 8, 100, 100}, 4, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); void* old_ptr; LITE_get_tensor_memory(c_tensor0, &old_ptr); auto check = [&](std::vector<size_t> expect, const LiteTensor& tensor) { LiteLayout get_layout; LITE_get_tensor_layout(tensor, &get_layout); ASSERT_EQ(get_layout.ndim, expect.size()); for (size_t i = 0; i < expect.size(); i++) { ASSERT_EQ(get_layout.shapes[i], expect[i]); } void* new_ptr; LITE_get_tensor_memory(tensor, &new_ptr); ASSERT_EQ(old_ptr, new_ptr); }; { int shape[2] = {-1, 50}; LITE_tensor_reshape(c_tensor0, shape, 2); check({8 * 8 * 100 * 2, 50}, c_tensor0); } { int shape[3] = {64, 100, 100}; LITE_tensor_reshape(c_tensor0, shape, 3); check({8 * 8, 100, 100}, c_tensor0); } { int shape[3] = {16, 100, -1}; LITE_tensor_reshape(c_tensor0, shape, 3); check({16, 100, 400}, c_tensor0); } LITE_destroy_tensor(c_tensor0); } TEST(TestCapiTensor, Slice) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{20, 20}, 2, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); void* old_ptr; LITE_get_tensor_memory(c_tensor0, &old_ptr); for (size_t i = 0; i < 20 * 20; i++) { *(static_cast<float*>(old_ptr) + i) = i; } auto check = [&](size_t start, size_t end, size_t step, bool have_step) { LiteTensor tensor, slice_tensor; LITE_make_tensor(default_desc, &tensor); size_t start_ptr[2] = {start, start}; size_t end_ptr[2] = {end, end}; size_t step_ptr[2] = {step, step}; if (have_step) { LITE_tensor_slice( c_tensor0, start_ptr, end_ptr, step_ptr, 2, &slice_tensor); } else { LITE_tensor_slice(c_tensor0, start_ptr, end_ptr, nullptr, 2, &slice_tensor); } int is_continue = true; LITE_is_memory_continue(slice_tensor, &is_continue); ASSERT_FALSE(is_continue); LITE_tensor_copy(tensor, slice_tensor); void* new_ptr; LITE_get_tensor_memory(tensor, &new_ptr); float* ptr = static_cast<float*>(new_ptr); for (size_t i = start; i < end; i += step) { for (size_t j = start; j < end; j += step) { ASSERT_EQ(float(i * 20 + j), *ptr); ++ptr; } } LITE_destroy_tensor(tensor); LITE_destroy_tensor(slice_tensor); }; check(1, 8, 1, true); check(1, 8, 1, false); check(2, 10, 2, true); check(10, 18, 4, true); check(10, 18, 1, false); LITE_destroy_tensor(c_tensor0); } TEST(TestCapiTensor, Memset) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{20, 20}, 2, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); void* ptr; uint8_t* uint8_ptr; LITE_get_tensor_memory(c_tensor0, &ptr); LITE_tensor_fill_zero(c_tensor0); uint8_ptr = static_cast<uint8_t*>(ptr); for (size_t i = 0; i < 20 * 20; i++) { ASSERT_EQ(0, *uint8_ptr); uint8_ptr++; } LITE_destroy_tensor(c_tensor0); } TEST(TestCapiTensor, GetMemoryByIndex) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{20, 20}, 2, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); void *ptr0, *ptr1, *ptr2, *ptr3; LITE_get_tensor_memory(c_tensor0, &ptr0); size_t index0[] = {3, 4}; LITE_get_tensor_memory_with_index(c_tensor0, &index0[0], 2, &ptr1); size_t index1[] = {5, 7}; LITE_get_tensor_memory_with_index(c_tensor0, &index1[0], 2, &ptr2); size_t index2[] = {5}; LITE_get_tensor_memory_with_index(c_tensor0, &index2[0], 1, &ptr3); ASSERT_EQ(ptr1, static_cast<float*>(ptr0) + 3 * 20 + 4); ASSERT_EQ(ptr2, static_cast<float*>(ptr0) + 5 * 20 + 7); ASSERT_EQ(ptr3, static_cast<float*>(ptr0) + 5 * 20); LITE_destroy_tensor(c_tensor0); } TEST(TestCapiTensor, ThreadLocalError) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{20, 20}, 2, LiteDataType::LITE_FLOAT}; void *ptr0, *ptr1; std::thread thread1([&]() { LITE_make_tensor(description, &c_tensor0); LITE_get_tensor_memory(c_tensor0, &ptr0); }); thread1.join(); std::thread thread2([&]() { LITE_get_tensor_memory(c_tensor0, &ptr1); LITE_destroy_tensor(c_tensor0); }); thread2.join(); } TEST(TestCapiTensor, GlobalHolder) { LiteTensor c_tensor0; LiteTensorDesc description = default_desc; description.layout = LiteLayout{{20, 20}, 2, LiteDataType::LITE_FLOAT}; LITE_make_tensor(description, &c_tensor0); auto destroy_tensor = c_tensor0; LITE_make_tensor(description, &c_tensor0); //! make sure destroy_tensor is destroyed by LITE_make_tensor LITE_destroy_tensor(destroy_tensor); ASSERT_EQ(LITE_destroy_tensor(destroy_tensor), 0); LITE_destroy_tensor(c_tensor0); } #endif // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
398e71758bd017e8e819616aa707998795b1905a
7de42d95b5904480e6e46be40ae72707077668ae
/task1_set/Source.cpp
bdc06dfb3db115d0c8fda50a9c708d9d335d4d4d
[]
no_license
kzGarifullin/cpp-projects
e09828f4ff9086ff2f49c58494b56a43faab57bf
a214898e8a707e0a44acb30d642cdc4231d655e0
refs/heads/master
2023-06-06T20:07:19.037960
2021-07-03T09:52:33
2021-07-03T09:52:33
339,001,074
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,627
cpp
Source.cpp
#include <iostream> #include <set> #include<vector> #include <iostream> #include <cstdlib> #include <algorithm> #include <functional> #include<iostream> #include<chrono> #include<vector> #include<algorithm> #include <array> class Timer { public: using clock_t = std::chrono::steady_clock; using time_point_t = clock_t::time_point; void pause() { pa = clock_t::now(); dur += std::chrono::duration_cast<std::chrono::microseconds>( pa - m_begin); } void cont() { m_begin = clock_t::now(); } Timer() : m_begin(clock_t::now()), dur(0) {} ~Timer() { auto end = clock_t::now(); std::cout << "micro: " << std::chrono::duration_cast<std::chrono::microseconds>( end - m_begin).count() + dur.count() << std::endl; } private: time_point_t m_begin; time_point_t pa; std::chrono::microseconds dur; }; int main() { int N = 100000; srand(4541); std::vector <int> vec; std::set < int > set; std::vector<int> rand_vec; std::array<int, 100000> arr; for (int count = 0; count < N; ++count) { rand_vec.push_back(rand()); } {Timer T; std::cout << "set " ; for (int count = 0; count < N; ++count) { set.insert(rand_vec[count]); } } {Timer T; std::cout << "vector "; for (int count = 0; count < N; ++count) { vec.push_back(rand_vec[count]); } std::sort(vec.begin(), vec.end()); } {Timer T; std::cout << "array "; for (int count = 0; count < N; ++count) { arr[count] = rand_vec[count]; } std::sort(arr.begin(), arr.end()); } //как видно array и vector в 2-3 раза быстрее set. N при котором сменяется лидер не существует }
3da27af9fc5147a7c8edbce8840132660e802073
75a83ddc648a1a4a13fa3f86b93296802a11e8f5
/Classes/basic/ImageFadeOut.cpp
652a1a8da6a3e785a4e3e934b66bf46067dd82a8
[]
no_license
abc20899/Learn2dxDemo
313bb0d85a6a3f7d17d00bd93d5b1c22093f3b66
4b6a0ca981e16c753cc5385e3f7875590e5b1a5f
refs/heads/master
2020-04-12T02:10:50.444506
2019-01-02T12:44:34
2019-01-02T12:44:34
162,240,714
0
0
null
null
null
null
UTF-8
C++
false
false
3,953
cpp
ImageFadeOut.cpp
// // ImageFadeOut.cpp // Particle // // Created by JasonWu on 12/20/14. // // #include "ImageFadeOut.h" ImageFadeOut::ImageFadeOut() : _pointA(0), _pointB(0) { } ImageFadeOut::~ImageFadeOut() { } ImageFadeOut *ImageFadeOut::create(std::string image) { auto imageFadeOut = new ImageFadeOut(); if (imageFadeOut == nullptr || imageFadeOut->initWithImage(image) == false) { CC_SAFE_DELETE(imageFadeOut); return nullptr; } return imageFadeOut; } bool ImageFadeOut::initWithImage(std::string image) { if (Node::init() == false) { return false; } _image = new Image(); _image->initWithImageFile(image); _displayClipping = DrawNode::create(); auto display = Sprite::create(image); display->setAnchorPoint(Vec2(0, 0)); this->setContentSize(display->getContentSize()); Vec2 points[4]; points[0] = Vec2(0, 0); points[1] = Vec2(0, _contentSize.height); points[2] = _contentSize; points[3] = Vec2(_contentSize.width, 0); _displayClipping->drawPolygon(points, 4, Color4F(1.0f, 1.0f, 1.0f, 1.0f), 0, Color4F(0, 0, 0, 0)); _displayClipping->setAnchorPoint(Vec2(0, 0)); _displayClipping->setContentSize(_contentSize); _displayImage = ClippingNode::create(_displayClipping); _displayImage->addChild(display); addChild(_displayImage); this->setAnchorPoint(Vec2(0.5, 0.5)); _pointA = _pointB = _contentSize.width + _contentSize.height; this->scheduleUpdate(); return true; } void ImageFadeOut::update(float d) { const int step = 10; _pointA -= step; _pointB -= step; if (_pointA < 0) { this->unscheduleUpdate(); return; } //计算切割线段两个顶点的位置 Vec2 pA( _pointA > _contentSize.width ? 0 : _contentSize.width - _pointA, _pointA > _contentSize.width ? _contentSize.height - (_pointA - _contentSize.width) : _contentSize.height ); Vec2 pB( _pointB > _contentSize.height ? _contentSize.width - (_pointB - _contentSize.height) : _contentSize.width, _pointB > _contentSize.height ? 0 : _contentSize.height - _pointB ); //计算切割模板的点 Vec2 points[5]; int pointCount = 0; if (_pointA > _contentSize.width) { points[pointCount++] = pA; points[pointCount++] = Vec2(0, _contentSize.height); points[pointCount++] = _contentSize; } else { points[pointCount++] = pA; points[pointCount++] = _contentSize; } if (_pointB > _contentSize.height) { points[pointCount++] = Vec2(_contentSize.width, 0); points[pointCount++] = pB; } else { points[pointCount++] = pB; } _displayClipping->clear(); _displayClipping->drawPolygon(points, pointCount, Color4F(1.0f, 1.0f, 1.0f, 1.0f), 0, Color4F(0, 0, 0, 0)); //遍历AB两点组成的线段上的像素 创建粒子特效 int x = pA.x, y = pA.y; auto pixel = (unsigned int *) (_image->getData()); while (x < pB.x && y > 0) { x += step; y -= step; auto colorCode = pixel + (static_cast<unsigned int>(_contentSize.height - y - 1) * _image->getWidth()) + x; //过滤透明像素 if ((*colorCode >> 24 & 0xff) < 0xff) { continue; } Color4F color( (*colorCode & 0xff) / 255.0f, (*colorCode >> 8 & 0xff) / 255.0f, (*colorCode >> 16 & 0xff) / 255.0f, 1.0f ); auto p = ParticleSystemQuad::create("particle/fire.plist"); p->setStartColor(color); p->setEndColor(color); p->setAutoRemoveOnFinish(true); p->setPosition(Vec2(x + 15, y + 15)); addChild(p); } }
a43cac2e6306f67d86f48e92eb97e35fc29d3340
f31eefa2d05c0c40f38aa2fcabdb407fd01dafca
/Simu/PerceptionField.cpp
68f65f1c9179cc09193ce40f6220aa4f1a0f1a6b
[]
no_license
jpinilloslr/simu
57c9ab90371e72fe8e7a18434198b11d8cdbab42
d39a88c09613d932c6d59827277a7192e62d6b6c
refs/heads/master
2021-04-27T00:08:32.705446
2013-02-16T04:14:22
2013-02-16T04:14:22
120,400,511
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
PerceptionField.cpp
#include "PerceptionField.h" PerceptionField::PerceptionField() { perceptions = 0; } PerceptionField::~PerceptionField() { } void PerceptionField::addPerception(Perceptible *perc) { if(perceptions < MAX_PERCEPTIONS) { memcpy(&perceptionField[perceptions], perc, sizeof(Perceptible)); perceptions++; } else { for(int i=MAX_PERCEPTIONS-1; i>0; i--) { memcpy(&perceptionField[i-1], &perceptionField[i], sizeof(Perceptible)); } } }
70ce1c08ee2d6c7a9730be199e8fd265a9043196
79be97302e0d1195aaa01f52e5fa1da540ea112f
/core/lib/include/memoria/core/types.hpp
f603b25e7b74a7d66fe237a19dd7006df765a3eb
[ "Apache-2.0" ]
permissive
victor-smirnov/memoria
8df7430c89b83ff9c93706dcf6100b3830c5f83a
fd203b5b081849c1a1db2d7f26b75bfd1d760a18
refs/heads/master
2023-05-12T20:52:19.828284
2023-05-01T00:02:46
2023-05-01T00:02:46
245,055,297
11
2
null
null
null
null
UTF-8
C++
false
false
8,712
hpp
types.hpp
// Copyright 2011-2022 Victor Smirnov // // 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 <memoria/core/config.hpp> #include <boost/exception/all.hpp> #include <boost/stacktrace.hpp> #include <boost/utility/string_view.hpp> #include <string> #include <sstream> #include <cassert> #include <cstdint> #include <exception> #include <stdint.h> #include <unicode/utypes.h> #include <type_traits> #include <tuple> #include <string_view> #include <limits> namespace memoria { static constexpr int DEFAULT_BLOCK_SIZE = 8192; static constexpr int PackedAllocationAlignment = 8; using psize_t = uint32_t; enum class PackedDataTypeSize {FIXED, VARIABLE}; // Require Gcc or Clang for now. #ifdef MMA_HAS_INT128 using UInt128T = __uint128_t; using Int128T = __int128_t; #endif template <typename T, T V> struct ConstValue { static constexpr T Value = V; constexpr operator T() const noexcept {return Value;} constexpr T operator()() const noexcept {return Value;} }; template <uint32_t Value> using UInt32Value = ConstValue<uint32_t, Value>; template <uint64_t Value> using UInt64Value = ConstValue<uint64_t, Value>; template <int32_t Value> using IntValue = ConstValue<int32_t, Value>; template <bool Value> using BoolValue = ConstValue<bool, Value>; template <typename...> using VoidT = void; template <typename T> struct TypeHash; // must define Value constant template <typename T> constexpr uint64_t TypeHashV = TypeHash<T>::Value; template <typename ... Types> struct TypeList { constexpr TypeList() = default; }; template <typename ... Types> using TL = TypeList<Types...>; template <typename T, T ... Values> struct ValueList { constexpr ValueList() = default; }; template <int32_t... Values> using IntList = ValueList<int32_t, Values...>; template <size_t... Values> using SizeTList = ValueList<size_t, Values...>; template <uint32_t... Values> using UInt32List = ValueList<uint32_t, Values...>; template <uint64_t... Values> using UInt64List = ValueList<uint64_t, Values...>; template <typename> struct TypeHash; /* * Container type names & profiles */ struct BT {}; struct Composite {}; template <typename ChildType = void> class CoreApiProfileT {}; using CoreApiProfile = CoreApiProfileT<>; struct WT {}; // Placeholder type to be used in place of Block IDs struct IDType {}; /* * End of container type names and profiles */ struct NullType {}; struct EmptyType {}; struct IncompleteType; struct TypeIsNotDefined {}; template <typename Name> struct TypeNotFound; struct TypeIsNotDefined; struct SerializationData { char* buf; size_t total; SerializationData(): buf(nullptr), total(0) {} }; struct DeserializationData { const char* buf; }; enum class WalkDirection { UP, DOWN }; enum class WalkCmd { FIRST_LEAF, LAST_LEAF, THE_ONLY_LEAF, FIX_TARGET, NONE, PREFIXES, REFRESH }; enum class SearchType {GT, GE}; enum class LeafDataLengthType {FIXED, VARIABLE}; extern int64_t DebugCounter; extern int64_t DebugCounter1; extern int64_t DebugCounter2; extern int64_t DebugCounter3; namespace detail { template <typename T> struct AsTupleH { using Type = T; }; template <typename... TypeT> struct AsTupleH<TL<TypeT...>> { using Type = std::tuple<typename AsTupleH<TypeT>::Type ...>; }; } template <typename List> using AsTuple = typename detail::AsTupleH<List>::Type; template <typename T> struct HasType { using Type = T; }; template <typename T, T V_> struct HasValue { static constexpr T Value = V_; }; template <uint64_t V> using HasU64Value = HasValue<uint64_t, V>; namespace detail { template <typename T, bool Flag, typename... AdditionalTypes> struct FailIfT { static_assert(!Flag, "Template failed"); using Type = T; }; } template <bool Flag, typename T, typename... AdditionalTypes> using FailIf = typename detail::FailIfT<T, Flag, AdditionalTypes...>::Type; template <bool Flag, size_t V, typename... AdditionalTypes> constexpr size_t FailIfV = detail::FailIfT<IntValue<V>, Flag, AdditionalTypes...>::Type::Value; template <typename T> class ValueCodec; template <typename T> struct FieldFactory; template <typename T> class ValuePtrT1 { const T* addr_; size_t length_; public: ValuePtrT1(): addr_(), length_() {} ValuePtrT1(const T* addr, size_t length): addr_(addr), length_(length) {} const T* addr() const {return addr_;} size_t length() const {return length_;} }; template <typename T> struct DataTypeTraits; namespace detail { template <typename T> struct Void { using Type = void; }; template <typename T> struct IsCompleteHelper { template <typename U> static auto test(U*) -> std::integral_constant<bool, sizeof(U) == sizeof(U)>; static auto test(...) -> std::false_type; using Type = decltype(test((T*)0)); }; } template <typename T> struct IsComplete : detail::IsCompleteHelper<T>::Type {}; template <typename T> struct HasValueCodec: HasValue<bool, IsComplete<ValueCodec<T>>::type::value> {}; template <typename T> struct HasFieldFactory: HasValue<bool, IsComplete<FieldFactory<T>>::type::value> {}; template <typename T> struct IsExternalizable: HasValue<bool, HasValueCodec<T>::Value || HasFieldFactory<T>::Value || DataTypeTraits<T>::isDataType> {}; struct Referenceable { virtual ~Referenceable() noexcept = default; }; template <typename T> constexpr bool IsPackedStructV = std::is_standard_layout<T>::value && std::is_trivially_copyable<T>::value; template <typename T> constexpr bool IsPackedAlignedV = alignof (T) <= 8; [[noreturn]] void terminate(const char* msg) noexcept; template <typename Profile> struct IStoreApiBase: Referenceable { }; template <typename IDType> struct BlockIDValueHolder { IDType id; }; enum class SeqOpType: size_t { EQ, NEQ, LT, LE, GT, GE, // This is special sequence search mode suitable for "hierarchically-structured" // BTFL cotainers. In this mode we are looking for n-th symbol s, but stop if // we found any symbol with smaller cardinality ('not less then'). It's particularly // suitable for "remove" operations on BTFL continers. For example, if we have a 3-later // BTFL container, like, a wide column table, and want to remove a set of columns // in a specific row, 'NLT' means that search operations will have a hard stop // at the end of the current row (the next row will start from a symbol with // lesser numeric value). This functionality can be also implemented with a // combination of EQ and LT searches. EQ_NLT }; // This helper class is usable when we need to provide a type // to a template method, and don't want to pepend keyword // 'template' at the call site. template <typename T> struct TypeTag{}; template <typename T> T div_2(T value) { return value / 2; } constexpr size_t SizeTMax = std::numeric_limits<size_t>::max(); template <typename CodeT> class NamedTypedCode { using StringViewT = boost::string_view; CodeT code_; StringViewT name_; public: constexpr NamedTypedCode(CodeT code, const char* name): code_(code), name_(name) {} constexpr NamedTypedCode(CodeT code, StringViewT name): code_(code), name_(name) {} constexpr NamedTypedCode(CodeT code): code_(code), name_("UNNAMED") {} constexpr CodeT code() const {return code_;} constexpr StringViewT name() const {return name_;} template <typename U> bool operator==(const NamedTypedCode<U>& other) const noexcept { return code_ == other.code_; } template <typename U> bool operator==(const U& code) const noexcept { return code_ == code; } template <typename U> bool operator<(const NamedTypedCode<U>& other) const noexcept { return code_ < other.code_; } }; using NamedCode = NamedTypedCode<int32_t>; // FIXME: Should be moved out of Core namespace io { template <typename To, typename From, typename Selector = void> struct BlockPtrConvertible; template <typename From, typename To, typename Selector = void> struct BlockPtrCastable; } }
af53d088ba25642666e711ef0d5ae984b7b26df9
497907b5503ef005abaf1342646068665a7c1015
/mp_stories/Graph2.hpp
cac9143d43b1be3c6e788a71e001e5a6255d7e51
[]
no_license
emroller/CS225-Data-Structures
cc96b9762d45248d6f32c6288beb0e2847c17cf2
db48befb2d35a25bd37802651d3a4088ddac0176
refs/heads/master
2023-07-19T17:10:08.639693
2019-12-11T04:23:25
2019-12-11T04:23:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,293
hpp
Graph2.hpp
#include <queue> #include <algorithm> #include <string> #include <list> #include <map> using std::string; using std::vector; using std::list; using std::pair; using std::map; /** * Returns an std::list of vertex keys that creates any shortest path between `start` and `end`. * * This list MUST include the key of the `start` vertex as the first vertex in the list, the key of * the `end` vertex as the last element in the list, and an ordered list of all vertices that must * be traveled along the shortest path. * * For example, the path a -> c -> e returns a list with three elements: "a", "c", "e". * * You should use undirected edges. Hint: There are no edge weights in the Graph. * * @param start The key for the starting vertex. * @param end The key for the ending vertex. */ template <class V, class E> std::list<std::string> Graph<V,E>::shortestPath(const std::string start, const std::string end) { std::list<std::string> path; std::queue<string> bfs; map<string, string> predecessor; map<string, int> distance; for (auto it = edgeList.begin(); it != edgeList.end(); it++) { if ((it->get().source().key() == start && it->get().dest().key() == end) || (it->get().source().key() == end && it->get().dest().key() == start)) { path.push_back(start); path.push_back(end); return path; } } for (auto it = vertexMap.begin(); it != vertexMap.end(); it++) { predecessor.insert(pair<string, string> (it->first, "N")); distance.insert(pair<string, int> (it->first, -1)); } distance[start] = 0; predecessor[start] = "S"; bfs.push(start); while (!bfs.empty()) { Vertex v = bfs.front(); bfs.pop(); list<string> neighbors; list<edgeListIter> n = adjList[v.key()]; for (edgeListIter edge : n) { if (edge->get().source().key() == v.key()) neighbors.push_back(edge->get().dest().key()); else neighbors.push_back(edge->get().source().key()); } for (string neighbor : neighbors) { if (distance[neighbor]== -1) { distance[neighbor] = distance[v.key()] + 1; predecessor[neighbor] = v.key(); bfs.push(neighbor); } } } string current = end; path.push_back(current); while (current != start) { current = predecessor[current]; path.push_back(current); } return path; }
9f1b17425897d8527802040e8f6afb583c552cc6
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/games/openxcom/files/patch-src_Savegame_CraftWeapon.cpp
daec78acb073790ce6d4bcf97c54c1b56baf27fa
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
376
cpp
patch-src_Savegame_CraftWeapon.cpp
--- src/Savegame/CraftWeapon.cpp.orig 2014-06-13 19:14:43 UTC +++ src/Savegame/CraftWeapon.cpp @@ -16,6 +16,7 @@ * You should have received a copy of the GNU General Public License * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ +#include <cmath> #include "CraftWeapon.h" #include "../Ruleset/RuleCraftWeapon.h" #include "../Ruleset/Ruleset.h"
3353b9955eebd4d7d433b44f5b3d63398cedff30
1f797b7f7b7160f0571a1f72ab8593c931c6753b
/Lecture-10/BinaryTreeCamera.cpp
a15d3f7dc325ac427429110d94132021df328266
[]
no_license
Kartik-Mathur/CareerBootcampOffline24March2020
36b8586d58746528706c899d505d351ce1f700e0
dc0ef18d43b046aefb30329a53031f64cc25dd82
refs/heads/master
2021-04-20T17:07:59.307395
2020-09-03T17:32:13
2020-09-03T17:32:13
249,703,524
8
3
null
null
null
null
UTF-8
C++
false
false
640
cpp
BinaryTreeCamera.cpp
// BinaryTreeCamera https://leetcode.com/problems/binary-tree-cameras/ #include <iostream> using namespace std; unordered_map<TreeNode*,bool> h; int camera; void PlaceCamera(TreeNode* root,TreeNode* parent){ // base case if(root == NULL) return; PlaceCamera(root->left,root); PlaceCamera(root->right,root); if(parent==NULL && !h.count(root)|| !h.count(root->left) || !h.count(root->right)){ camera++; h[parent] = h[root] = h[root->left] = h[root->right] = true; } } int minCameraCover(TreeNode* root) { camera = 0; h.insert({NULL,true}); PlaceCamera(root,NULL); return camera; } int main(){ cout<<endl; return 0; }
d272d80c7cce7c38dc3c0bd27f8be9044538a670
9f05d15a3f6d98711416d42e1ac3b385d9caa03a
/sem3/da/labs/2/btree.cpp
f4f0ea5185a7c37cd9ae81323f14ded16a249282
[]
no_license
dtbinh/MAI
abbad3bef790ea231a1dc36233851a080ea53225
a5c0b7ce0be0f5b5a1d5f193e228c685977a2f93
refs/heads/master
2020-06-16T06:45:58.595779
2016-08-21T15:37:10
2016-08-21T15:37:10
75,237,279
1
0
null
2016-11-30T23:45:58
2016-11-30T23:45:58
null
UTF-8
C++
false
false
8,891
cpp
btree.cpp
#include "btree.h" TBTree::TBTree(size_t t) { mT = t < 2 ? 2 : t; mRoot = mCreateNode(); } TBTree::~TBTree() { mDeleteTree(mRoot); } void TBTree::Insert(const TData& data) { TNode* root = mRoot; if (root->n == mT * 2 - 1) { TNode* rootNew = mCreateNode(); mRoot = rootNew; rootNew->leaf = false; rootNew->n = 0; rootNew->childs[0] = root; mSplitNode(rootNew, root, 0); mInsertNonFull(rootNew, data); } else { mInsertNonFull(root, data); } } TBTree::TData* TBTree::Find(const TKey& key) { return mFind(mRoot, key); } void TBTree::Erase(const TKey& key) { mErase(mRoot, key); if (!mRoot->leaf && mRoot->n == 0) { TNode* rootNew = mRoot->childs[0]; mDeleteNode(mRoot); mRoot = rootNew; } } TBTree::TNode* TBTree::mCreateNode() { TNode* node = NULL; try { node = new TNode; node->data = new TData[mT * 2 - 1]; node->childs = new TNode*[mT * 2]; } catch (const std::bad_alloc& e) { printf("ERROR: No memory\n"); std::exit(0); } node->n = 0; node->leaf = true; size_t cnt = mT * 2; for (size_t i = 0; i < cnt; ++i) { node->childs[i] = NULL; } return node; } TBTree::TData* TBTree::mFind(TNode* node, const TKey& key) { size_t i = 0; while (i < node->n && node->data[i].key < key) { ++i; } if (i < node->n && node->data[i].key == key) { return &node->data[i]; } if (!node->leaf) { return mFind(node->childs[i], key); } return NULL; } void TBTree::mDeleteNode(TNode* node) { delete[] node->data; delete[] node->childs; delete node; } void TBTree::mDeleteTree(TNode* node) { if (node == NULL) { return; } for (size_t i = 0; i < node->n + 1; ++i) { mDeleteTree(node->childs[i]); } mDeleteNode(node); } void TBTree::mShiftLeft(TNode* node, size_t index, size_t index2) { for (size_t i = index; i < node->n; ++i) { node->data[i - 1].val = node->data[i].val; node->data[i - 1].key.Swap(node->data[i].key); } if (!node->leaf) { for (size_t i = index2; i < node->n + 1; ++i) { node->childs[i - 1] = node->childs[i]; } } node->childs[node->n] = NULL; --node->n; } void TBTree::mShiftRight(TNode* node, size_t index, size_t index2) { for (int i = static_cast<int>(node->n) - 1; i >= static_cast<int>(index); --i) { node->data[i + 1].val = node->data[i].val; node->data[i + 1].key.Swap(node->data[i].key); } if (!node->leaf) { for (int i = static_cast<int>(node->n); i >= static_cast<int>(index2); --i) { node->childs[i + 1] = node->childs[i]; } } ++node->n; } void TBTree::mFlowLeft(TNode* parent, size_t index) { TNode* left = parent->childs[index]; TNode* right = parent->childs[index + 1]; left->data[left->n].val = parent->data[index].val; left->data[left->n].key.Swap(parent->data[index].key); parent->data[index].val = right->data[0].val; parent->data[index].key.Swap(right->data[0].key); if (!right->leaf) { left->childs[left->n + 1] = right->childs[0]; } mShiftLeft(right, 1, 1); ++left->n; } void TBTree::mFlowRight(TNode* parent, size_t index) { TNode* left = parent->childs[index]; TNode* right = parent->childs[index + 1]; mShiftRight(right, 0, 0); right->data[0].val = parent->data[index].val; right->data[0].key.Swap(parent->data[index].key); parent->data[index].val = left->data[left->n - 1].val; parent->data[index].key.Swap(left->data[left->n - 1].key); if (!left->leaf) { right->childs[0] = left->childs[left->n]; } left->childs[left->n] = NULL; --left->n; } void TBTree::mSplitNode(TNode* parent, TNode* node, size_t index) { TNode* node2 = mCreateNode(); node2->leaf = node->leaf; node2->n = mT - 1; node->n = node2->n; for (size_t i = 0; i < node2->n; ++i) { node2->data[i].val = node->data[i + mT].val; node2->data[i].key.Swap(node->data[i + mT].key); } if (!node->leaf) { for (size_t i = 0; i < mT; ++i) { node2->childs[i] = node->childs[i + mT]; } } mShiftRight(parent, index, index + 1); parent->childs[index + 1] = node2; parent->data[index].val = node->data[mT - 1].val; parent->data[index].key.Swap(node->data[mT - 1].key); } void TBTree::mMergeNode(TNode* parent, size_t index) { TNode* left = parent->childs[index]; TNode* right = parent->childs[index + 1]; left->data[left->n].val = parent->data[index].val; left->data[left->n].key.Swap(parent->data[index].key); for (size_t i = 0; i < right->n; ++i) { left->data[left->n + i + 1].val = right->data[i].val; left->data[left->n + i + 1].key.Swap(right->data[i].key); } if (!right->leaf) { for (size_t i = 0; i < right->n + 1; ++i) { left->childs[left->n + i + 1] = right->childs[i]; } } left->n += right->n + 1; mShiftLeft(parent, index + 1, index + 2); mDeleteNode(right); } void TBTree::mInsertNonFull(TNode* node, const TData& data) { int i = static_cast<int>(node->n) - 1; if (node->leaf) { while (i >= 0 && data.key < node->data[i].key) { node->data[i + 1].val = node->data[i].val; node->data[i + 1].key.Swap(node->data[i].key); --i; } node->data[i + 1] = data; ++node->n; } else { while (i >= 0 && data.key < node->data[i].key) { --i; } ++i; if (node->childs[i]->n == mT * 2 - 1) { mSplitNode(node, node->childs[i], i); if (node->data[i].key < data.key) { ++i; } } mInsertNonFull(node->childs[i], data); } } void TBTree::mErase(TNode* node, const TKey& key) { size_t i = 0; while (i < node->n && node->data[i].key < key) { ++i; } if (i < node->n && node->data[i].key == key) { if (node->leaf) { mShiftLeft(node, i + 1, i + 2); } else { TNode* succNode = node->childs[i + 1]; while (succNode->childs[0] != NULL) { succNode = succNode->childs[0]; } node->data[i].val = succNode->data[0].val; node->data[i].key.Swap(succNode->data[0].key); mErase(node->childs[i + 1], succNode->data[0].key); mFixChild(node, i + 1); } } else if (!node->leaf) { mErase(node->childs[i], key); mFixChild(node, i); } } void TBTree::mFixChild(TNode* node, size_t index) { if (node->childs[index]->n >= mT) { return; } TNode* left = index > 0 ? node->childs[index - 1] : NULL; TNode* right = index < node->n ? node->childs[index + 1] : NULL; if (left != NULL && right != NULL) { if (left->n >= mT) { mFlowRight(node, index - 1); } else if (right->n >= mT) { mFlowLeft(node, index); } else { mMergeNode(node, index - 1); } } else if (left != NULL) { if (left->n >= mT) { mFlowRight(node, index - 1); } else { mMergeNode(node, index - 1); } } else { if (right->n >= mT) { mFlowLeft(node, index); } else { mMergeNode(node, index); } } } bool TBTree::Serialize(const char* filename) { FILE* f = fopen(filename, "wb"); if (f == NULL) { return false; } if (fwrite(&mT, sizeof(mT), 1, f) != 1) { return false; } bool ans = mSerialize(f, mRoot); fclose(f); return ans; } bool TBTree::Deserialize(const char* filename) { FILE* f = fopen(filename, "rb"); if (f == NULL) { return false; } if (fread(&mT, sizeof(mT), 1, f) != 1) { return false; } TNode* rootNew = mCreateNode(); bool ans = mDeserialize(f, rootNew); fclose(f); if (ans) { mDeleteTree(mRoot); mRoot = rootNew; return true; } else { mDeleteTree(rootNew); return false; } } bool TBTree::mSerialize(FILE* f, TNode* node) { if (fwrite(&node->n, sizeof(node->n), 1, f) != 1) { return false; } if (fwrite(&node->leaf, sizeof(node->leaf), 1, f) != 1) { return false; } for (size_t i = 0; i < node->n; ++i) { const TData* data = &node->data[i]; const size_t strLen = data->key.Length(); const char* str = data->key.Str(); if (fwrite(&strLen, sizeof(strLen), 1, f) != 1) { return false; } if (fwrite(str, sizeof(char), strLen, f) != strLen) { return false; } if (fwrite(&data->val, sizeof(data->val), 1, f) != 1) { return false; } } if (!node->leaf) { for (size_t i = 0; i < node->n + 1; ++i) { if (!mSerialize(f, node->childs[i])) { return false; } } } return true; } bool TBTree::mDeserialize(FILE* f, TNode* node) { char buffer[257]; if (fread(&node->n, sizeof(node->n), 1, f) != 1) { return false; } if (fread(&node->leaf, sizeof(node->leaf), 1, f) != 1) { return false; } for (size_t i = 0; i < node->n; ++i) { TData* data = &node->data[i]; size_t strLen = 0; if (fread(&strLen, sizeof(strLen), 1, f) != 1) { return false; } if (fread(buffer, sizeof(char), strLen, f) != strLen) { return false; } if (fread(&data->val, sizeof(data->val), 1, f) != 1) { return false; } buffer[strLen] = '\0'; data->key = buffer; } if (!node->leaf) { for (size_t i = 0; i < node->n + 1; ++i) { node->childs[i] = mCreateNode(); if (!mDeserialize(f, node->childs[i])) { return false; } } } return true; }
ac85cea181112fd85e088e4d601a4647b2cf633c
79f449ec9e81b170b994d7fa86e3deb0834022b9
/src/weak_ptrs.h
fde8dbbaf22dbdb537b0fe991ffa10b93a3f4322
[ "MIT" ]
permissive
whunmr/circa
b5bfacd336024a4120be46b52b849ff5a76e93ec
f3667f2af8b46728c1475990ecdf5cf1b3dd1ee2
refs/heads/master
2020-04-08T02:08:24.311295
2013-03-01T04:37:19
2013-03-07T18:09:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
316
h
weak_ptrs.h
// Copyright (c) Andrew Fischer. See LICENSE file for license terms. #pragma once #include <cstddef> namespace circa { typedef size_t WeakPtr; WeakPtr weak_ptr_create(void* address); void* get_weak_ptr(WeakPtr ptr); void weak_ptr_set_null(WeakPtr ptr); bool is_weak_ptr_null(WeakPtr ptr); } // namespace circa
7401087d46464659280513f5bccf8e6d8bdc6882
4ae3405a082f030bcf573ebf04edb4308a49ab34
/src/CpuBoolean.h
930276b9636887039f524f6e3e7e11b4861ed02b
[]
no_license
mplamann/NESEmulator
b662f99bc541fadcc3f95436b4acdce1702c68fe
88a45bed0dc2acc9b2f1245f16633c628a2196cf
refs/heads/master
2021-01-10T22:06:28.830341
2013-03-11T12:57:18
2013-03-11T12:57:18
4,393,778
1
1
null
null
null
null
UTF-8
C++
false
false
430
h
CpuBoolean.h
#pragma once #include "CpuRegisters.h" #include "Util.h" class CpuBoolean : public CpuRegisters { private: typedef CpuRegisters super; protected: int ASL(int value); int LSR(int value); int ROL(int value); int ROR(int value); void BIT(int value); void SLO(int value); void RLA(int value); void SRE(int value); public: CpuBoolean(void); ~CpuBoolean(void); bool RunInstruction(); };
dc102f7bed69aee987bf8e62fe351da8d2f0aa39
99fe750ffd06ae7b33d13d69bf625a9c36169df3
/volume004/445 - Marvelous Mazes.cpp
e2e2cf218a89199913cbacff834464a5489f208c
[]
no_license
ahmrf/UVa
5edb2edbc912f837a9884584ab42b73c573a3385
6b815d4df74f52e30b01d345b1e41cdd34b0f7da
refs/heads/master
2021-01-21T01:49:33.721538
2016-04-06T16:20:51
2016-04-06T16:20:51
34,123,479
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
445 - Marvelous Mazes.cpp
#include<cstdio> #include<vector> #include<iostream> using namespace std; struct content{ char ch; int count; }; int main (void) { char c; vector<content>maze; vector<char>hehe; while(scanf("%c", &c) != EOF) { hehe.push_back(c); } int sum = 0; for(int i = 0; i < hehe.size(); i++) { content demo; demo.ch = hehe[i]; if(demo.ch == '\n' || demo.ch == '!') { if(demo.ch == '!') demo.ch = '\n'; demo.count = 1; maze.push_back(demo); } if(demo.ch >= 48 && demo.ch <= 57) { sum += (demo.ch - '0'); } else { if(demo.ch == 'b') demo.ch = ' '; demo.count = sum; maze.push_back(demo); sum = 0; } } for(int i = 0; i < maze.size(); i++) { for(int j = 0; j < maze[i].count; j++) { cout << maze[i].ch; } } return 0; }
df7270dcfa3ac7324e915e80ae6a35df9bf31d43
a4de7672f460babe084d08afe08a6453a9d4c64a
/removeElements.cpp
05d220edc6c8b66fe82e4159b71cd5253f6355f9
[]
no_license
sulemanrai/leetcode
3db0dd328ceb44bb43e15b00231c69b1aa437898
72ecdee5c6b7326eea90ddac6bb73959fce13020
refs/heads/master
2020-03-16T17:29:04.025572
2018-09-07T05:43:32
2018-09-07T05:43:32
132,834,334
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
removeElements.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int Size(ListNode * head) { int i = 0; while(head != NULL) { i++; head = head->next; } return i; } ListNode* removeElements(ListNode* head, int val) { if(head == NULL) { return NULL; } std::queue<int> Linked_List_queue; ListNode * temp = head; while(temp != NULL) { Linked_List_queue.push(temp->val); temp = temp -> next; } ListNode * newHead = new ListNode(0); ListNode * current = newHead; while(!Linked_List_queue.empty()) { int tmp= Linked_List_queue.front(); if(tmp != val) { current->next = new ListNode(tmp); current = current->next; } Linked_List_queue.pop(); } if(newHead->next == NULL) { newHead = NULL; } else { *newHead = *newHead->next; } return newHead; } };
139db20e098afdf73072522f50faf2daca13137f
8fc183b422f4d4d595f4c2d193f7ca3c7b5e6c55
/src/test/proposer/proposer_tests.cpp
7ec5b33036278a580ec7402e0b56878a0cdcb7cc
[ "MIT" ]
permissive
cornelius/unit-e
cd36edc7b5f16c22623d4dbbad555e8075d06099
71b1e4c4afa77270b5f16b495926d791c4933265
refs/heads/master
2020-05-15T03:16:07.240302
2019-05-06T08:10:04
2019-05-06T08:10:04
182,065,278
0
0
null
2019-04-18T10:12:56
2019-04-18T10:12:56
null
UTF-8
C++
false
false
7,391
cpp
proposer_tests.cpp
// Copyright (c) 2018-2019 The Unit-e developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <proposer/proposer.h> #include <blockchain/blockchain_behavior.h> #include <proposer/block_builder.h> #include <proposer/eligible_coin.h> #include <proposer/multiwallet.h> #include <proposer/proposer_logic.h> #include <staking/active_chain.h> #include <staking/network.h> #include <staking/transactionpicker.h> #include <test/test_unite.h> #include <test/test_unite_mocks.h> #include <wallet/wallet.h> #include <boost/test/unit_test.hpp> #include <thread> namespace { struct Fixture { using Proposer = proposer::Proposer; std::unique_ptr<::ArgsManager> args_manager; std::unique_ptr<blockchain::Behavior> behavior = blockchain::Behavior::New(args_manager.get()); std::unique_ptr<::Settings> settings; blockchain::Parameters parameters = blockchain::Parameters::TestNet(); struct MultiWalletMock : public proposer::MultiWallet { std::vector<std::shared_ptr<CWallet>> wallets; const std::vector<std::shared_ptr<CWallet>> GetWallets() const override { return wallets; } }; std::shared_ptr<CWallet> wallet; MultiWalletMock multi_wallet_mock; mocks::StakeValidatorMock stake_validator; Fixture(std::initializer_list<std::string> args) : args_manager([&] { std::unique_ptr<::ArgsManager> argsman = MakeUnique<::ArgsManager>(); const char **argv = new const char *[args.size() + 1]; argv[0] = "executable-name"; std::size_t i = 1; for (const auto &arg : args) { argv[i++] = arg.c_str(); } std::string error; argsman->ParseParameters(static_cast<int>(i), argv, error); delete[] argv; return argsman; }()), settings(Settings::New(args_manager.get(), behavior.get())), wallet(new CWallet("mock", WalletDatabase::CreateMock(), [&] { esperanza::WalletExtensionDeps deps(settings.get(), &stake_validator); return deps; }())), multi_wallet_mock([&] { MultiWalletMock mock; mock.wallets.emplace_back(wallet); return mock; }()) {} class NetworkMock : public staking::Network { public: size_t nodecount = 0; mutable size_t GetNodeCount_invocations = 0; int64_t GetTime() const override { return 0; } size_t GetNodeCount() const override { ++GetNodeCount_invocations; return nodecount; } size_t GetInboundNodeCount() const override { return nodecount; } size_t GetOutboundNodeCount() const override { return 0; } }; class ActiveChainMock : public staking::ActiveChain { public: ::SyncStatus syncstatus = ::SyncStatus::IMPORTING; mutable size_t GetInitialBlockDownloadStatus_invocations = 0; mutable CCriticalSection m_lock; CCriticalSection &GetLock() const override { return m_lock; } blockchain::Height GetSize() const override { return 1; } blockchain::Height GetHeight() const override { return 0; } const CBlockIndex *GetTip() const override { return nullptr; } const CBlockIndex *GetGenesis() const override { return nullptr; } bool Contains(const CBlockIndex &) const override { return false; } const CBlockIndex *FindForkOrigin(const CBlockIndex &) const override { return nullptr; } const CBlockIndex *GetNext(const CBlockIndex &) const override { return nullptr; } const CBlockIndex *AtDepth(blockchain::Depth depth) const override { return nullptr; } const CBlockIndex *AtHeight(blockchain::Height height) const override { return nullptr; } blockchain::Depth GetDepth(const blockchain::Height) const override { return 0; } const CBlockIndex *GetBlockIndex(const uint256 &) const override { return nullptr; } const uint256 ComputeSnapshotHash() const override { return uint256(); } bool ProposeBlock(std::shared_ptr<const CBlock> pblock) override { return false; } ::SyncStatus GetInitialBlockDownloadStatus() const override { ++GetInitialBlockDownloadStatus_invocations; return syncstatus; } boost::optional<staking::Coin> GetUTXO(const COutPoint &) const override { return boost::none; }; }; class TransactionPickerMock : public staking::TransactionPicker { PickTransactionsResult PickTransactions(const PickTransactionsParameters &) override { return PickTransactionsResult(); } }; class BlockBuilderMock : public proposer::BlockBuilder { const CTransactionRef BuildCoinbaseTransaction( const uint256 &, const proposer::EligibleCoin &, const staking::CoinSet &, CAmount, staking::StakingWallet &) const override { return nullptr; }; std::shared_ptr<const CBlock> BuildBlock( const CBlockIndex &, const uint256 &, const proposer::EligibleCoin &, const staking::CoinSet &, const std::vector<CTransactionRef> &, const CAmount, staking::StakingWallet &) const override { return nullptr; } }; class ProposerLogicMock : public proposer::Logic { public: boost::optional<proposer::EligibleCoin> TryPropose(const staking::CoinSet &) override { return boost::none; } }; NetworkMock network_mock; ActiveChainMock chain_mock; TransactionPickerMock transaction_picker_mock; BlockBuilderMock block_builder_mock; ProposerLogicMock logic_mock; std::unique_ptr<Proposer> MakeProposer() { return Proposer::New( settings.get(), behavior.get(), &multi_wallet_mock, &network_mock, &chain_mock, &transaction_picker_mock, &block_builder_mock, &logic_mock); } }; } // namespace BOOST_AUTO_TEST_SUITE(proposer_tests) BOOST_AUTO_TEST_CASE(not_proposing_stub_vs_actual_impl) { Fixture f1{"-proposing=0"}; Fixture f2{"-proposing=0"}; Fixture f3{"-proposing=1"}; Fixture f4{"-proposing=1"}; std::unique_ptr<proposer::Proposer> p1 = f1.MakeProposer(); std::unique_ptr<proposer::Proposer> p2 = f2.MakeProposer(); std::unique_ptr<proposer::Proposer> p3 = f3.MakeProposer(); std::unique_ptr<proposer::Proposer> p4 = f4.MakeProposer(); proposer::Proposer &r1 = *p1; proposer::Proposer &r2 = *p2; proposer::Proposer &r3 = *p3; proposer::Proposer &r4 = *p4; BOOST_CHECK(typeid(r1) == typeid(r2)); BOOST_CHECK(typeid(r3) == typeid(r4)); BOOST_CHECK(typeid(r1) != typeid(r3)); BOOST_CHECK(typeid(r2) != typeid(r4)); } BOOST_AUTO_TEST_CASE(start_stop_and_status) { Fixture f{"-proposing=1"}; f.network_mock.nodecount = 0; BOOST_CHECK_NO_THROW({ auto p = f.MakeProposer(); p->Start(); }); // destroying the proposer stops it BOOST_CHECK(f.network_mock.GetNodeCount_invocations > 0); BOOST_CHECK_EQUAL(f.wallet->GetWalletExtension().GetProposerState().m_status, +proposer::Status::NOT_PROPOSING_NO_PEERS); } BOOST_AUTO_TEST_CASE(advance_to_blockchain_sync) { Fixture f{"-proposing=1"}; f.network_mock.nodecount = 1; BOOST_CHECK_NO_THROW({ auto p = f.MakeProposer(); p->Start(); }); BOOST_CHECK(f.chain_mock.GetInitialBlockDownloadStatus_invocations > 0); BOOST_CHECK_EQUAL(f.wallet->GetWalletExtension().GetProposerState().m_status, +proposer::Status::NOT_PROPOSING_SYNCING_BLOCKCHAIN); } BOOST_AUTO_TEST_SUITE_END()
0857a3f1da20367f1d0b7c82ad78b48c690273c7
fd402718be3b6ad87b48b1a83cd57da32f763fb0
/SP1Framework/Player.cpp
d2bb18d7bca1e1d4e1d62e41a622e368d4dba656
[]
no_license
Ang-Zhi-Wei/SP1Framework
ff6dc5c80f9bd48e7178b76d43f06e00571f39ef
bc945ab9ac301ad2e25acb49c2b6e8574d7fb468
refs/heads/master
2023-07-12T01:49:00.364201
2021-08-18T06:55:03
2021-08-18T06:55:03
286,451,000
0
0
null
2020-08-10T11:01:07
2020-08-10T11:01:06
null
UTF-8
C++
false
false
246
cpp
Player.cpp
#include "Player.h" player::player(SGameChar* playerptr) { this->playerptr = playerptr; direction = 'U'; } player::~player() { } char player::GetDirection() { return direction; } void player::SetDirection(char dirc) { direction = dirc; }
05aa0d8e346aa7dcddcffa9856f8f68f68c25707
e698fbf6f557cfd57133830af8329439725466cc
/src/Move.cpp
31f915c1fcd8f5fef67f91ed286e106b5d2ba093
[]
no_license
zetaemme/dreamchess-plusplus
0fdf08ec5c24cb19b7fbd912e39b110f6bb8b839
bddc2fda15bf7bb2a1de70bbbf8caa6bf76fc52f
refs/heads/master
2023-08-20T01:29:14.350882
2021-10-28T13:45:02
2021-10-28T13:45:02
377,817,978
0
0
null
2021-09-29T09:13:23
2021-06-17T12:10:09
C++
UTF-8
C++
false
false
1,739
cpp
Move.cpp
/** * @copyright Dreamchess++ * @author Mattia Zorzan * @version v1.0 * @date July-October, 2021 * @file */ #include "Move.hpp" #include "Board.hpp" /** * @namespace dreamchess * @brief The only namespace used to contain the DreamChess++ logic * @details Used to avoid the std namespace pollution */ namespace dreamchess { const std::shared_ptr<std::regex> Move::m_move_regex{ std::make_shared<std::regex>("[a-h][1-8]-[a-h][1-8]")}; const std::shared_ptr<std::regex> Move::m_promotion_regex{ std::make_shared<std::regex>("[a-h][1-8]-[a-h][1-8]=[r|R|n|N|b|B|q|Q]")}; Move::Move(int64_t source, int64_t destination, Board::piece_t piece, Board::piece_t promotion_piece) : m_source{static_cast<int16_t>(source)}, m_destination{static_cast<int16_t>(destination)}, m_piece{piece}, m_promotion_piece{promotion_piece} {} [[nodiscard]] int16_t Move::source() const { return m_source; } [[nodiscard]] int16_t Move::destination() const { return m_destination; } [[nodiscard]] Board::piece_t Move::piece() const { return m_piece; } [[nodiscard]] Board::piece_t Move::promotion_piece() const { return m_promotion_piece; } [[nodiscard]] std::regex Move::move_regex() { return *m_move_regex; } [[nodiscard]] std::regex Move::promotion_regex() { return *m_promotion_regex; } [[nodiscard]] std::string Move::to_alg() const { uint16_t rem = m_destination % 8; uint16_t quot = m_destination / 8; std::string res{}; if (Piece::type(m_piece) != Piece::PAWN) { res.append(Piece::unicode_representation(m_piece)); } res.push_back(static_cast<char>('a' + rem)); res.push_back(static_cast<char>('1' + quot)); return res; } } // namespace dreamchess
713b8c5ed274c233ae3127c2ebe30afc017c1650
048fa3ddafe5e0b8a7aa084bbe726a13f5f37e65
/dfs/경로찾기/solution.cpp
4362ca973d6920a48742c781bf5131855783dae4
[]
no_license
seongjinkime/problem-solving
7f1cbd05e99cfb74a6b86d4b473dd52431330480
918e0b0329485b789cbd6ea99b6b475fc2717c0d
refs/heads/master
2020-09-07T10:57:39.333195
2020-01-05T07:09:54
2020-01-05T07:09:54
220,757,074
1
0
null
null
null
null
UTF-8
C++
false
false
1,274
cpp
solution.cpp
// // main.cpp // 11403_findRoute // // Created by Kim Seong Jin on 2019. 10. 21.. // Copyright © 2019년 Kim Seong Jin. All rights reserved. // #include <iostream> #include <vector> using namespace std; vector<vector<int>> adj; vector<vector<int>>links; vector<int> visited; void dfs(int node, int here){ links[node][here] = 1; visited[here] = 1; for(int i = 0 ; i < adj[here].size() ; i++){ if(adj[here][i] == 1 && !visited[i]){ dfs(node, i); } } } void markLinks(int n){ for(int i = 0 ; i < n ; i++){ visited = vector<int>(n, 0); for(int j = 0 ; j < n ; j++){ if(adj[i][j]==1){ dfs(i, j); } } } } void build(int n){ adj = links = vector<vector<int>>(n, vector<int>(n, 0)); visited = vector<int>(n, 0); for(int row = 0 ; row< n ; row++){ for(int col = 0 ; col < n ; col++){ cin>>adj[row][col]; } } } int main(int argc, const char * argv[]) { // insert code here... int n; cin>>n; build(n); markLinks(n); for(int row = 0 ; row < n ; row++){ for(int col = 0 ; col<n ; col++){ cout<<links[row][col]<<" "; } cout<<endl; } return 0; }
f29d2f92217dc6b741f001dab218e4e77a1c251c
2e36dff1e3230ae28483868cda171fbeb4ab1460
/spoj solutions/allizwel.cpp
731d214ce7910b462af1e03b1d9693fd0b1d2d9f
[]
no_license
rishabhjain9191/Coding
e53f189d69b05a861b3d659ea9eb3f65e6c07511
702222855df001c6b68efe5ea68c97523a7f75e6
refs/heads/master
2020-05-18T20:06:14.756020
2016-11-10T19:01:44
2016-11-10T19:01:44
35,320,555
0
0
null
null
null
null
UTF-8
C++
false
false
1,835
cpp
allizwel.cpp
#include <iostream> #include <vector> #define MAX 102 using namespace std; int r, c; bool blocked[MAX][MAX]; char STR[]={'A','L','L','I','Z','Z','W','E','L','L','\0'}; char Grid[MAX][MAX]; bool P(vector<pair<int, int> > pos, int found); int main(){ int T; char input; vector<pair<int, int> > aPos; cin>>T; for(int i=0;i<MAX;i++){ blocked[0][i]=true; blocked[i][0]=true; } while(T--){ cin>>r>>c; for(int i=0;i<c+2;i++){ blocked[r+1][i]=true; } for(int i=0;i<r+2;i++){ blocked[i][c+1]=true; } for(int i=1;i<=r;i++){ for(int j=1;j<=c;j++){ blocked[i][j]=false; cin>>input; Grid[i][j]=input; if(input=='A') aPos.push_back(make_pair(i,j)); } } if(aPos.size()==0){ cout<<"NO\n"; } else if(P(aPos,0)){cout<<"YES\n";}else{cout<<"NO\n";} aPos.clear(); } return 0; } int displacement[]={0,1,-1}; bool P(vector<pair<int, int> > pos, int found){ cout<<found<<"\n"; if(found==9){ return true; } int x,y, disX, disY; bool res; vector<pair<int, int> >nPos; for(int i=0;i<pos.size();i++){ cout<<"("<<pos[i].first<<", "<<pos[i].second<<")"; } cout<<"\n"; for(int i=0;i<pos.size();i++){ //cout<<"In loop"; x=pos[i].first; y=pos[i].second; blocked[x][y]=true; for(int j=0;j<3;j++){ for(int k=0;k<3;k++){ disX=displacement[j]; disY=displacement[k]; cout<<x+disX<<", "<<y+disY; if(!blocked[x+disX][y+disY]){ if(Grid[x+disX][y+disY]==STR[found+1]){ cout<<"pushed"; nPos.push_back(make_pair(x+disX, y+disY)); } } cout<<"\n"; } } if(nPos.size()==0){ blocked[x][y]=true; //Next character not found res=false; } else{ res=P(nPos, found+1); cout<<"res : "<<res<<"\n"; blocked[x][y]=false; nPos.clear(); if(res){ //blocked[x][y]=false; return true; } } } return res; }
b0b06cada2d9bd14e7aeaa1a58ae49c5ef7300c2
6edd115495964d580257cad76172ba3b7048bf2e
/tablemaker/tablemaker-2.1.1/src/hits.cpp
2b703f197af40362c5a2332570bd6c95d82c3cd8
[ "BSL-1.0" ]
permissive
jtleek/ballgown
3073e55c064f7ff4b84cf1bd9d0e28858d863401
b524c109236df7230269d2f7630aa7c7037d2d9a
refs/heads/master
2021-01-16T20:49:17.407889
2014-03-27T15:06:18
2014-03-27T15:06:18
12,441,219
1
1
null
null
null
null
UTF-8
C++
false
false
29,237
cpp
hits.cpp
/* * hits.cpp * Cufflinks * * Created by Cole Trapnell on 3/23/09. * Copyright 2009 Cole Trapnell. All rights reserved. * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cassert> #include <cstdlib> #include <cstring> #include <iostream> #include <set> #include <vector> #include "common.h" #include "hits.h" #include "tokenize.h" using namespace std; #if ENABLE_THREADS boost::mutex RefSequenceTable::table_lock; #endif int num_deleted = 0; void ReadHit::trim(int trimmed_length) { bool antisense_aln = _sam_flag & 0x10; vector<CigarOp> new_cigar; int new_left = 0; if (!antisense_aln) { int pos = _left; new_left = _left; int length = 0; for (vector<CigarOp>::iterator i = _cigar.begin(); i < _cigar.end(); ++i) { const CigarOp& op = *i; if (length < trimmed_length) { switch(op.opcode) { case REF_SKIP: //gaps_out.push_back(make_pair(pos, pos + op.length - 1)); pos += op.length; new_cigar.push_back(op); break; case SOFT_CLIP: assert(false); // not sure if this case is right pos += op.length; length += op.length; new_cigar.push_back(op); break; case HARD_CLIP: new_cigar.push_back(op); break; case MATCH: if (length + op.length < trimmed_length) { pos += op.length; length += op.length; new_cigar.push_back(op); } else { new_cigar.push_back(CigarOp(MATCH, trimmed_length - length)); pos += trimmed_length - length; length += trimmed_length - length; } break; case INS: assert(false); // not sure if this case is right pos -= op.length; length -= op.length; new_cigar.push_back(op); break; case DEL: assert(false); // not sure if this case is right pos += op.length; length += op.length; new_cigar.push_back(op); break; default: break; } } } } else { int pos = _right; int length = 0; for (vector<CigarOp>::reverse_iterator i = _cigar.rbegin(); i < _cigar.rend(); ++i) { const CigarOp& op = *i; if (length < trimmed_length) { switch(op.opcode) { case REF_SKIP: //gaps_out.push_back(make_pair(pos, pos + op.length - 1)); pos -= op.length; new_cigar.push_back(op); break; case SOFT_CLIP: assert(false); // not sure if this case is right pos -= op.length; length += op.length; new_cigar.push_back(op); break; case HARD_CLIP: new_cigar.push_back(op); break; case MATCH: if (length + op.length < trimmed_length) { pos -= op.length; length += op.length; new_cigar.push_back(op); } else { new_cigar.push_back(CigarOp(MATCH, trimmed_length - length)); pos -= trimmed_length - length; length += trimmed_length - length; } break; case INS: assert(false); // not sure if this case is right pos += op.length; length -= op.length; new_cigar.push_back(op); break; case DEL: assert(false); // not sure if this case is right pos -= op.length; length += op.length; new_cigar.push_back(op); break; default: break; } } } _left = pos; } _cigar = new_cigar; _right = get_right(); assert (trimmed_length == read_len()); } //static const int max_read_length = 1024; bool hit_insert_id_lt(const ReadHit& h1, const ReadHit& h2) { return h1.insert_id() < h2.insert_id(); } bool hits_eq_mod_id(const ReadHit& lhs, const ReadHit& rhs) { return (lhs.ref_id() == rhs.ref_id() && lhs.antisense_align() == rhs.antisense_align() && lhs.left() == rhs.left() && lhs.source_strand() == rhs.source_strand() && lhs.cigar() == rhs.cigar()); } // Compares for structural equality, but won't declare multihits equal to one another bool hits_eq_non_multi(const MateHit& lhs, const MateHit& rhs) { if ((lhs.is_multi() || rhs.is_multi() ) && lhs.insert_id() != rhs.insert_id()) return false; return hits_equals(lhs, rhs); } // Compares for structural equality, but won't declare multihits equal to one another // and won't return true for hits from different read groups (e.g. replicate samples) bool hits_eq_non_multi_non_replicate(const MateHit& lhs, const MateHit& rhs) { if (((lhs.is_multi() || rhs.is_multi()) && lhs.insert_id() != rhs.insert_id()) || lhs.read_group_props() != rhs.read_group_props()) return false; return hits_equals(lhs, rhs); } // Does NOT care about the read group this hit came from. bool hits_equals(const MateHit& lhs, const MateHit& rhs) { if (lhs.ref_id() != rhs.ref_id()) return false; if ((lhs.left_alignment() == NULL) != (rhs.left_alignment() == NULL)) return false; if ((lhs.right_alignment() == NULL) != (rhs.right_alignment() == NULL)) return false; if (lhs.left_alignment()) { if (!(hits_eq_mod_id(*lhs.left_alignment(),*(rhs.left_alignment())))) return false; } if (lhs.right_alignment()) { if (!(hits_eq_mod_id(*lhs.right_alignment(),*(rhs.right_alignment())))) return false; } return true; } bool has_no_collapse_mass(const MateHit& hit) { return hit.collapse_mass() == 0; } // Assumes hits are sorted by mate_hit_lt // Does not collapse hits that are multi-reads void collapse_hits(const vector<MateHit>& hits, vector<MateHit>& non_redundant) { copy(hits.begin(), hits.end(), back_inserter(non_redundant)); vector<MateHit>::iterator new_end = unique(non_redundant.begin(), non_redundant.end(), hits_eq_non_multi_non_replicate); non_redundant.erase(new_end, non_redundant.end()); non_redundant.resize(non_redundant.size()); BOOST_FOREACH(MateHit& hit, non_redundant) hit.collapse_mass(0); size_t curr_aln = 0; size_t curr_unique_aln = 0; while (curr_aln < hits.size()) { if (hits_eq_non_multi_non_replicate(non_redundant[curr_unique_aln], hits[curr_aln]) || hits_eq_non_multi_non_replicate(non_redundant[++curr_unique_aln], hits[curr_aln])) { double more_mass = hits[curr_aln].internal_scale_mass(); //assert(non_redundant[curr_unique_aln].collapse_mass() == 0 || !non_redundant[curr_unique_aln].is_multi()); non_redundant[curr_unique_aln].incr_collapse_mass(more_mass); } else assert(false); ++curr_aln; } //BOOST_FOREACH(MateHit& hit, non_redundant) //assert(hit.collapse_mass() <= 1 || !hit.is_multi()); //non_redundant.erase(remove_if(non_redundant.begin(),non_redundant.end(),has_no_collapse_mass), non_redundant.end()); } // Places multi-reads to the right of reads they match bool mate_hit_lt(const MateHit& lhs, const MateHit& rhs) { if (lhs.left() != rhs.left()) return lhs.left() < rhs.left(); if (lhs.right() != rhs.right()) return lhs.right() > rhs.right(); if ((lhs.left_alignment() == NULL) != (rhs.left_alignment() == NULL)) return (lhs.left_alignment() == NULL) < (rhs.left_alignment() == NULL); if ((lhs.right_alignment() == NULL) != (rhs.right_alignment() == NULL)) return (lhs.right_alignment() == NULL) < (rhs.right_alignment() == NULL); assert ((lhs.right_alignment() == NULL) == (rhs.right_alignment() == NULL)); assert ((lhs.left_alignment() == NULL) == (rhs.left_alignment() == NULL)); const ReadHit* lhs_l = lhs.left_alignment(); const ReadHit* lhs_r = lhs.right_alignment(); const ReadHit* rhs_l = rhs.left_alignment(); const ReadHit* rhs_r = rhs.right_alignment(); if (lhs_l && rhs_l) { if (lhs_l->cigar().size() != rhs_l->cigar().size()) return lhs_l->cigar().size() < rhs_l->cigar().size(); for (size_t i = 0; i < lhs_l->cigar().size(); ++i) { if (lhs_l->cigar()[i].opcode != rhs_l->cigar()[i].opcode) return lhs_l->cigar()[i].opcode < rhs_l->cigar()[i].opcode; if (lhs_l->cigar()[i].length != rhs_l->cigar()[i].length) return lhs_l->cigar()[i].length < rhs_l->cigar()[i].length; } } if (lhs_r && rhs_r) { if (lhs_r->cigar().size() != rhs_r->cigar().size()) return lhs_r->cigar().size() < rhs_r->cigar().size(); for (size_t i = 0; i < lhs_r->cigar().size(); ++i) { if (lhs_r->cigar()[i].opcode != rhs_r->cigar()[i].opcode) return lhs_r->cigar()[i].opcode < rhs_r->cigar()[i].opcode; if (lhs_r->cigar()[i].length != rhs_r->cigar()[i].length) return lhs_r->cigar()[i].length < rhs_r->cigar()[i].length; } } if (lhs.is_multi() != rhs.is_multi()) { return rhs.is_multi(); } if (lhs.read_group_props() != rhs.read_group_props()) { return lhs.read_group_props() < rhs.read_group_props(); } return false; } ReadHit HitFactory::create_hit(const string& insert_name, const string& ref_name, int left, const vector<CigarOp>& cigar, CuffStrand source_strand, const string& partner_ref, int partner_pos, unsigned int edit_dist, int num_hits, float base_mass, uint32_t sam_flag) { InsertID insert_id = _insert_table.get_id(insert_name); RefID reference_id = _ref_table.get_id(ref_name, NULL); RefID partner_ref_id = _ref_table.get_id(partner_ref, NULL); return ReadHit(reference_id, insert_id, left, cigar, source_strand, partner_ref_id, partner_pos, edit_dist, num_hits, base_mass, sam_flag); } ReadHit HitFactory::create_hit(const string& insert_name, const string& ref_name, uint32_t left, uint32_t read_len, CuffStrand source_strand, const string& partner_ref, int partner_pos, unsigned int edit_dist, int num_hits, float base_mass, uint32_t sam_flag) { InsertID insert_id = _insert_table.get_id(insert_name); RefID reference_id = _ref_table.get_id(ref_name, NULL); RefID partner_ref_id = _ref_table.get_id(partner_ref, NULL); return ReadHit(reference_id, insert_id, left, read_len, source_strand, partner_ref_id, partner_pos, edit_dist, num_hits, base_mass, sam_flag); } // populate a bam_t This will bool BAMHitFactory::next_record(const char*& buf, size_t& buf_size) { if (_next_hit.data) { free(_next_hit.data); _next_hit.data = NULL; } if (records_remain() == false) return false; mark_curr_pos(); memset(&_next_hit, 0, sizeof(_next_hit)); int bytes_read = samread(_hit_file, &_next_hit); if (bytes_read < 0) { _eof_encountered = true; return false; } buf = (const char*)&_next_hit; buf_size = bytes_read; return true; } CuffStrand use_stranded_protocol(uint32_t sam_flag, MateStrandMapping msm) { bool antisense_aln = sam_flag & 0x10; if (((sam_flag & BAM_FPAIRED) && (sam_flag & BAM_FREAD1)) || !(sam_flag & BAM_FPAIRED)) // first-in-pair or single-end { switch(msm) { case FF: case FR: return (antisense_aln) ? CUFF_REV : CUFF_FWD; break; case RF: case RR: return (antisense_aln) ? CUFF_FWD : CUFF_REV; break; } } else // second-in-pair read { switch (msm) { case FF: case RF: return (antisense_aln) ? CUFF_REV : CUFF_FWD; break; case FR: case RR: return (antisense_aln) ? CUFF_FWD : CUFF_REV; break; } } assert(false); return CUFF_STRAND_UNKNOWN; } bool BAMHitFactory::get_hit_from_buf(const char* orig_bwt_buf, ReadHit& bh, bool strip_slash, char* name_out, char* name_tags) { const bam1_t* hit_buf = (const bam1_t*)orig_bwt_buf; uint32_t sam_flag = hit_buf->core.flag; int text_offset = hit_buf->core.pos; int text_mate_pos = hit_buf->core.mpos; int target_id = hit_buf->core.tid; int mate_target_id = hit_buf->core.mtid; vector<CigarOp> cigar; bool spliced_alignment = false; int num_hits = 1; //header->target_name[c->tid] if (sam_flag & 0x4 || target_id < 0) { //assert(cigar.size() == 1 && cigar[0].opcode == MATCH); bh = create_hit(bam1_qname(hit_buf), "*", 0, // SAM files are 1-indexed 0, CUFF_STRAND_UNKNOWN, "*", 0, 0, 1, 1.0, sam_flag); return true; } if (target_id >= _hit_file->header->n_targets) { fprintf (stderr, "BAM error: file contains hits to sequences not in header SQ records (%s)\n", bam1_qname(hit_buf)); return false; } string text_name = _hit_file->header->target_name[target_id]; for (int i = 0; i < hit_buf->core.n_cigar; ++i) { //char* t; int length = bam1_cigar(hit_buf)[i] >> BAM_CIGAR_SHIFT; if (length <= 0) { fprintf (stderr, "BAM error: CIGAR op has zero length (%s)\n", bam1_qname(hit_buf)); return false; } CigarOpCode opcode; switch(bam1_cigar(hit_buf)[i] & BAM_CIGAR_MASK) { case BAM_CMATCH: opcode = MATCH; break; case BAM_CINS: opcode = INS; break; case BAM_CDEL: opcode = DEL; break; case BAM_CSOFT_CLIP: opcode = SOFT_CLIP; break; case BAM_CHARD_CLIP: opcode = HARD_CLIP; break; case BAM_CPAD: opcode = PAD; break; case BAM_CREF_SKIP: opcode = REF_SKIP; spliced_alignment = true; if (length > (int)max_intron_length) { //fprintf(stderr, "Encounter REF_SKIP > max_gene_length, skipping\n"); return false; } break; default: //fprintf (stderr, "SAM error on line %d: invalid CIGAR operation\n", _line_num); return false; } if (opcode != HARD_CLIP) cigar.push_back(CigarOp(opcode, length)); } string mrnm; if (mate_target_id >= 0) { if (mate_target_id == target_id) { mrnm = _hit_file->header->target_name[mate_target_id]; // if (abs((int)text_mate_pos - (int)text_offset) > (int)max_intron_length) // { // //fprintf (stderr, "Mates are too distant, skipping\n"); // return false; // } } else { //fprintf(stderr, "Trans-spliced mates are not currently supported, skipping\n"); return false; } } else { text_mate_pos = 0; } CuffStrand source_strand = CUFF_STRAND_UNKNOWN; unsigned char num_mismatches = 0; uint8_t* ptr = bam_aux_get(hit_buf, "XS"); if (ptr) { char src_strand_char = bam_aux2A(ptr); if (src_strand_char == '-') source_strand = CUFF_REV; else if (src_strand_char == '+') source_strand = CUFF_FWD; } ptr = bam_aux_get(hit_buf, "NM"); if (ptr) { num_mismatches = bam_aux2i(ptr); } ptr = bam_aux_get(hit_buf, "NH"); if (ptr) { num_hits = bam_aux2i(ptr); } double mass = 1.0; ptr = bam_aux_get(hit_buf, "ZF"); if (ptr) { mass = bam_aux2i(ptr); if (mass <= 0.0) mass = 1.0; } if (_rg_props.strandedness() == STRANDED_PROTOCOL && source_strand == CUFF_STRAND_UNKNOWN) source_strand = use_stranded_protocol(sam_flag, _rg_props.mate_strand_mapping()); if (!spliced_alignment) { //assert(_rg_props.strandedness() == STRANDED_PROTOCOL || source_strand == CUFF_STRAND_UNKNOWN); //assert(cigar.size() == 1 && cigar[0].opcode == MATCH); bh = create_hit(bam1_qname(hit_buf), text_name, text_offset, // BAM files are 0-indexed cigar, source_strand, mrnm, text_mate_pos, num_mismatches, num_hits, mass, sam_flag); return true; } else { if (source_strand == CUFF_STRAND_UNKNOWN) { fprintf(stderr, "BAM record error: found spliced alignment without XS attribute\n"); } bh = create_hit(bam1_qname(hit_buf), text_name, text_offset, // BAM files are 0-indexed cigar, source_strand, mrnm, text_mate_pos, num_mismatches, num_hits, mass, sam_flag); return true; } return true; } Platform str_to_platform(const string pl_str) { if (pl_str == "SOLiD") { return SOLID; } else if (pl_str == "Illumina") { return ILLUMINA; } else { return UNKNOWN_PLATFORM; } } // Parses the header to determine platform and other properties bool HitFactory::parse_header_string(const string& header_rec, ReadGroupProperties& rg_props) { vector<string> columns; tokenize(header_rec, "\t", columns); if (columns[0] == "@RG") { for (size_t i = 1; i < columns.size(); ++i) { vector<string> fields; tokenize(columns[i], ":", fields); if (fields[0] == "PL") { if (rg_props.platform() == UNKNOWN_PLATFORM) { Platform p = str_to_platform(fields[1]); rg_props.platform(p); } else { Platform p = str_to_platform(fields[1]); if (p != rg_props.platform()) { fprintf(stderr, "Error: Processing reads from different platforms is not currently supported\n"); return false; } } } } } else if (columns[0] == "@SQ") { _num_seq_header_recs++; for (size_t i = 1; i < columns.size(); ++i) { vector<string> fields; tokenize(columns[i], ":", fields); if (fields[0] == "SN") { // Populate the RefSequenceTable with the sequence dictionary, // to ensure that (for example) downstream GTF files are sorted // in an order consistent with the header, and to enforce that // BAM records appear in the order implied by the header RefID _id = _ref_table.get_id(fields[1], NULL); const RefSequenceTable::SequenceInfo* info = _ref_table.get_info(_id); if (info->observation_order != _num_seq_header_recs) { if (info->name != fields[1]) { fprintf(stderr, "Error: Hash collision between references '%s' and '%s'.\n", info->name, fields[1].c_str()); } else { fprintf(stderr, "Error: sort order of reads in BAMs must be the same\n"); } exit(1); } } } } return true; } void HitFactory::finalize_rg_props() { if (_rg_props.platform() == SOLID) { _rg_props.strandedness(STRANDED_PROTOCOL); _rg_props.std_mate_orientation(MATES_POINT_TOWARD); } else { // Default to Illumina's unstranded protocol params for strandedness and // mate orientation _rg_props.strandedness(UNSTRANDED_PROTOCOL); _rg_props.std_mate_orientation(MATES_POINT_TOWARD); } } static const unsigned MAX_HEADER_LEN = 64 * 1024 * 1024; // 4 MB bool BAMHitFactory::inspect_header() { bam_header_t* header = _hit_file->header; if (header == NULL) { fprintf(stderr, "Warning: No BAM header\n"); return false; } // if (header->l_text >= MAX_HEADER_LEN) // { // fprintf(stderr, "Warning: BAM header too large\n"); // return false; // } if (header->l_text == 0) { fprintf(stderr, "Warning: BAM header has 0 length or is corrupted. Try using 'samtools reheader'.\n"); return false; } if (header->text != NULL) { char* h_text = strdup(header->text); char* pBuf = h_text; while(pBuf - h_text < header->l_text) { char* nl = strchr(pBuf, '\n'); if (nl) { *nl = 0; parse_header_string(pBuf, _rg_props); pBuf = ++nl; } else { pBuf = h_text + header->l_text; } } free(h_text); } finalize_rg_props(); return true; } bool SAMHitFactory::next_record(const char*& buf, size_t& buf_size) { mark_curr_pos(); bool new_rec = fgets(_hit_buf, _hit_buf_max_sz - 1, _hit_file); if (!new_rec) return false; ++_line_num; char* nl = strrchr(_hit_buf, '\n'); if (nl) *nl = 0; buf = _hit_buf; buf_size = _hit_buf_max_sz - 1; return true; } bool SAMHitFactory::get_hit_from_buf(const char* orig_bwt_buf, ReadHit& bh, bool strip_slash, char* name_out, char* name_tags) { char bwt_buf[10*2048]; strcpy(bwt_buf, orig_bwt_buf); // Are we still in the header region? if (bwt_buf[0] == '@') return false; const char* buf = bwt_buf; const char* _name = strsep((char**)&buf,"\t"); if (!_name) return false; char name[2048]; strncpy(name, _name, 2047); const char* sam_flag_str = strsep((char**)&buf,"\t"); if (!sam_flag_str) return false; const char* text_name = strsep((char**)&buf,"\t"); if (!text_name) return false; const char* text_offset_str = strsep((char**)&buf,"\t"); if (!text_offset_str) return false; const char* map_qual_str = strsep((char**)&buf,"\t"); if (!map_qual_str) return false; const char* cigar_str = strsep((char**)&buf,"\t"); if (!cigar_str) return false; const char* mate_ref_name = strsep((char**)&buf,"\t"); if (!mate_ref_name) return false; const char* mate_pos_str = strsep((char**)&buf,"\t"); if (!mate_pos_str) return false; const char* inferred_insert_sz_str = strsep((char**)&buf,"\t"); if (!inferred_insert_sz_str) return false; const char* seq_str = strsep((char**)&buf,"\t"); if (!seq_str) return false; const char* qual_str = strsep((char**)&buf,"\t"); if (!qual_str) return false; int sam_flag = atoi(sam_flag_str); int text_offset = atoi(text_offset_str); int text_mate_pos = atoi(mate_pos_str); // Copy the tag out of the name field before we might wipe it out char* pipe = strrchr(name, '|'); if (pipe) { if (name_tags) strcpy(name_tags, pipe); *pipe = 0; } // Stripping the slash and number following it gives the insert name char* slash = strrchr(name, '/'); if (strip_slash && slash) *slash = 0; const char* p_cig = cigar_str; //int len = strlen(sequence); vector<CigarOp> cigar; bool spliced_alignment = false; int num_hits = 1; if ((sam_flag & 0x4) ||!strcmp(text_name, "*")) { //assert(cigar.size() == 1 && cigar[0].opcode == MATCH); bh = create_hit(name, "*", 0, // SAM files are 1-indexed 0, CUFF_STRAND_UNKNOWN, "*", 0, 0, 1, 1.0, sam_flag); return true; } // Mostly pilfered direct from the SAM tools: while (*p_cig) { char* t; int length = (int)strtol(p_cig, &t, 10); if (length <= 0) { fprintf (stderr, "SAM error on line %d: CIGAR op has zero length\n", _line_num); fprintf (stderr,"%s\n", orig_bwt_buf); return false; } char op_char = toupper(*t); CigarOpCode opcode; if (op_char == 'M') { /*if (length > max_read_length) { fprintf(stderr, "SAM error on line %d: %s: MATCH op has length > %d\n", line_num, name, max_read_length); return false; }*/ opcode = MATCH; } else if (op_char == 'I') opcode = INS; else if (op_char == 'D') { opcode = DEL; } else if (op_char == 'N') { opcode = REF_SKIP; spliced_alignment = true; if (length > (int)max_intron_length) { //fprintf(stderr, "Encounter REF_SKIP > max_gene_length, skipping\n"); return false; } } else if (op_char == 'S') opcode = SOFT_CLIP; else if (op_char == 'H') opcode = HARD_CLIP; else if (op_char == 'P') opcode = PAD; else { fprintf (stderr, "SAM error on line %d: invalid CIGAR operation\n", _line_num); return false; } p_cig = t + 1; //i += length; if (opcode != HARD_CLIP) cigar.push_back(CigarOp(opcode, length)); } if (*p_cig) { fprintf (stderr, "SAM error on line %d: unmatched CIGAR operation\n", _line_num); return false; } string mrnm; if (strcmp(mate_ref_name, "*")) { if (!strcmp(mate_ref_name, "=") || !strcmp(mate_ref_name, text_name)) { mrnm = text_name; // if (abs((int)text_mate_pos - (int)text_offset) > (int)max_intron_length) // { // //fprintf (stderr, "Mates are too distant, skipping\n"); // return false; // } } else { //fprintf(stderr, "Trans-spliced mates are not currently supported, skipping\n"); return false; } } else { text_mate_pos = 0; } CuffStrand source_strand = CUFF_STRAND_UNKNOWN; unsigned char num_mismatches = 0; const char* tag_buf = buf; double mass = 1.0; while((tag_buf = strsep((char**)&buf,"\t"))) { char* first_colon = (char*)strchr(tag_buf, ':'); if (first_colon) { *first_colon = 0; ++first_colon; char* second_colon = strchr(first_colon, ':'); if (second_colon) { *second_colon = 0; ++second_colon; const char* first_token = tag_buf; //const char* second_token = first_colon; const char* third_token = second_colon; if (!strcmp(first_token, "XS")) { if (*third_token == '-') source_strand = CUFF_REV; else if (*third_token == '+') source_strand = CUFF_FWD; } else if (!strcmp(first_token, "NM")) { num_mismatches = atoi(third_token); } else if (!strcmp(first_token, "NH")) { num_hits = atoi(third_token); } else if (!strcmp(first_token, "ZF")) { mass = atof(third_token); if (mass <= 0.0) mass = 1.0; } else { } } } } // Don't let the protocol setting override explicit XS tags if (_rg_props.strandedness() == STRANDED_PROTOCOL && source_strand == CUFF_STRAND_UNKNOWN) source_strand = use_stranded_protocol(sam_flag, _rg_props.mate_strand_mapping()); if (!spliced_alignment) { //assert(cigar.size() == 1 && cigar[0].opcode == MATCH); bh = create_hit(name, text_name, text_offset - 1, cigar, source_strand, mrnm, text_mate_pos - 1, num_mismatches, num_hits, mass, sam_flag); return true; } else { if (source_strand == CUFF_STRAND_UNKNOWN) { fprintf(stderr, "SAM error on line %d: found spliced alignment without XS attribute\n", _line_num); } bh = create_hit(name, text_name, text_offset - 1, cigar, source_strand, mrnm, text_mate_pos - 1, num_mismatches, num_hits, mass, sam_flag); return true; } return false; } bool SAMHitFactory::inspect_header() { char pBuf[10 * 1024]; off_t curr_pos = ftello(_hit_file); rewind(_hit_file); while (fgets(pBuf, 10*1024, _hit_file)) { if (pBuf[0] != '@') { break; // done with the header. } char* nl = strchr(pBuf, '\n'); if (nl) { *nl = 0; parse_header_string(pBuf, _rg_props); } } fseek(_hit_file, curr_pos, SEEK_SET); finalize_rg_props(); return true; }
22efad2c19336059fe4c7d0c80dd7e640210ca96
4597bd5999d2105db64e96786618d1fd6b74bd7d
/libtest.cc
6da73feabc4a127312e14797d42c6ab262913e13
[]
no_license
clalancette/shared_boston_winters
e9adc87e325395dc52f75e437ece6ff54081fbd3
6dbdd4852412a3311288aa6258da1e683b1c3e72
refs/heads/master
2023-04-11T16:24:14.050468
2018-04-04T16:22:37
2018-04-04T16:22:37
128,088,957
1
1
null
2018-04-08T04:06:08
2018-04-04T16:20:25
C++
UTF-8
C++
false
false
172
cc
libtest.cc
#include <iostream> class Test { public: Test() { std::cerr << "In Test()..." << std::endl; } ~Test() { std::cerr << "In ~Test()..." << std::endl; } }; Test mytest;
33312c70254d3fb8a9a7e072b03468e17628e39a
543ecf788968e3b5276e1ab0a4294c6929160b25
/src/classwork/01_assign/main.cpp
01a9fbdcd77680b94ea5fbd18a60f1616f4a340b
[ "MIT" ]
permissive
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-jadencrowacc
dd76c8dc0eb896c77af90d950ae6ac63dcce0cec
00695d8db3afac77878972511e1a17d76937b6dc
refs/heads/master
2023-01-13T21:31:20.974251
2020-11-22T08:42:14
2020-11-22T08:42:14
290,393,028
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
main.cpp
//Write the include statement for types.h here #include <types.h> //Write include for capturing input from keyboard and displaying output to screen #include <iostream> int main() { int num; std::cout << "type number: "; std::cin >> num; int result = multiply_numbers(num); std::cout << "result: " << result << "\n"; int num1 = 4; result = multiply_numbers(num1); std::cout << "result: " << result; }
a6bcd42afff73d2884f7a82393524849e534cdf8
c66dd358c99b9f3e6bb39cf434588195ec678205
/Source/Components/StyledComponent.cpp
edc0699f3996317e0e15f18e44d46eb706576028
[]
no_license
neil-stoker/scumbler
7ba8172194950b4a25afc5ea7861117fa9225dda
ee455237430f30365ec35487a6e313b73c8cd8be
refs/heads/master
2021-05-27T12:39:48.101793
2015-01-04T15:13:07
2015-01-04T15:13:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
871
cpp
StyledComponent.cpp
// Copyright (c) 2014 Brett g Porter #include "StyledComponent.h" StyledComponent::StyledComponent(UiStyle* style, const String& name) : Component(name) , fStyle(style) { fStyle->addChangeListener(this); } StyledComponent::~StyledComponent() { fStyle->removeChangeListener(this); } void StyledComponent::changeListenerCallback (ChangeBroadcaster *source) { // re-implemented in derived classes that need to take action when the style changes. } void StyledComponent::UpdateStyle() { // no-op implementation to be overidden by derived classes. } void LogPaint(Component* c, Graphics& g) { /* String output = c->getName() + " "; Rectangle<int> clip = g.getClipBounds(); output << clip.getX() << ", " << clip.getY() << " w = " << clip.getWidth() << " h = " << clip.getHeight(); Logger::outputDebugString(output); */ }
7da88bea6a273c6d4a54b025f2277e180bb77dc7
00c81f6569e404528dc44a98fd9f60b6eea4c089
/examples/HinjBackSoon/HinjBackSoon.ino
b6a84b16002e6f4e77590804a2b51483bcfe9d88
[]
no_license
AloriumTechnology/XLR8HinjEtherCard
99f886cf036e746d6481f84cc3d4afecf53aa83e
c992fee9259d27bdf3f9ffadcba216daf157bb61
refs/heads/master
2020-03-19T03:30:34.792816
2018-06-01T15:34:23
2018-06-01T15:34:23
135,734,735
0
0
null
null
null
null
UTF-8
C++
false
false
1,741
ino
HinjBackSoon.ino
// Present a "Will be back soon web page", as stand-in webserver. // 2011-01-30 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php // 2018-02-08 Bryan Craker of Alorium Technology (info@aloriumtech.com) #include <XLR8HinjEtherCard.h> #define STATIC 0 // set to 1 to disable DHCP (adjust myip/gwip values below) #if STATIC // ethernet interface ip address static byte myip[] = { 192,168,1,200 }; // gateway ip address static byte gwip[] = { 192,168,1,1 }; #endif // ethernet mac address - must be unique on your network static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; byte XLR8Ethernet::buffer[500]; // tcp/ip send and receive buffer const char page[] PROGMEM = "HTTP/1.0 503 Service Unavailable\r\n" "Content-Type: text/html\r\n" "Retry-After: 600\r\n" "\r\n" "<html>" "<head><title>" "Hey There, I'm Hinj" "</title></head>" "<body>" "<h3>Hey There, I'm Hinj</h3>" "<p><em>" "The webpage you're looking for will be back soon." "</em></p>" "</body>" "</html>" ; void setup(){ Serial.begin(9600); Serial.println("Starting Back Soon"); if (XLR8Ether.begin(sizeof XLR8Ethernet::buffer, mymac) == 0) Serial.println( "Failed to access Ethernet controller"); #if STATIC XLR8Ether.staticSetup(myip, gwip); #else if (!XLR8Ether.dhcpSetup()) Serial.println("DHCP failed"); #endif XLR8Ether.printIp("IP: ", XLR8Ether.myip); XLR8Ether.printIp("GW: ", XLR8Ether.gwip); XLR8Ether.printIp("DNS: ", XLR8Ether.dnsip); } void loop(){ // wait for an incoming TCP packet, but ignore its contents if (XLR8Ether.packetLoop(XLR8Ether.packetReceive())) { memcpy_P(XLR8Ether.tcpOffset(), page, sizeof page); XLR8Ether.httpServerReply(sizeof page - 1); } }
893d4c6e9b4ee22ae6ffdea366902e786bbae1c3
ac610d807abbb5df761803bf97da987ad4605e3b
/src/rules.cpp
f4442afd4f07534f7e8282278b49c5402db8b838
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dnnr/herbstluftwm
4f2e20a1a79619333f3addf4454a5057ee15c015
3bed77ed53c11d0f07d591feb0ef29bb4e741b51
refs/heads/winterbreeze
2023-03-17T00:43:16.220514
2019-04-22T09:12:48
2019-04-22T09:12:48
56,521,901
1
0
NOASSERTION
2020-05-03T14:37:42
2016-04-18T15:59:59
C++
UTF-8
C++
false
false
10,498
cpp
rules.cpp
#include "rules.h" #include <X11/X.h> #include <X11/Xlib.h> #include <algorithm> #include <cstdio> #include "client.h" #include "ewmh.h" #include "globals.h" #include "hook.h" #include "root.h" #include "utils.h" #include "xconnection.h" using std::string; /// GLOBALS /// const std::map<string, Condition::Matcher> Condition::matchers = { { "class", &Condition::matchesClass }, { "instance", &Condition::matchesInstance }, { "title", &Condition::matchesTitle }, { "pid", &Condition::matchesPid }, { "maxage", &Condition::matchesMaxage }, { "windowtype", &Condition::matchesWindowtype }, { "windowrole", &Condition::matchesWindowrole }, }; const std::map<string, Consequence::Applier> Consequence::appliers = { { "tag", &Consequence::applyTag }, { "index", &Consequence::applyIndex }, { "focus", &Consequence::applyFocus }, { "switchtag", &Consequence::applySwitchtag }, { "manage", &Consequence::applyManage }, { "pseudotile", &Consequence::applyPseudotile }, { "fullscreen", &Consequence::applyFullscreen }, { "ewmhrequests", &Consequence::applyEwmhrequests }, { "ewmhnotify", &Consequence::applyEwmhnotify }, { "hook", &Consequence::applyHook }, { "keymask", &Consequence::applyKeyMask }, { "monitor", &Consequence::applyMonitor }, }; bool Rule::addCondition(string name, char op, const char* value, bool negated, Output output) { Condition cond; cond.negated = negated; cond.conditionCreationTime = get_monotonic_timestamp(); if (op != '=' && name == "maxage") { output << "rule: Condition maxage only supports the = operator\n"; return false; } switch (op) { case '=': { if (name == "maxage") { cond.value_type = CONDITION_VALUE_TYPE_INTEGER; if (1 != sscanf(value, "%d", &cond.value_integer)) { output << "rule: Can not integer from \"" << value << "\"\n"; return false; } } else { cond.value_type = CONDITION_VALUE_TYPE_STRING; cond.value_str = value; } break; } case '~': { cond.value_type = CONDITION_VALUE_TYPE_REGEX; try { cond.value_reg_exp = std::regex(value, std::regex::extended); } catch(std::regex_error& err) { output << "rule: Can not parse value \"" << value << "\" from condition \"" << name << "\": \"" << err.what() << "\"\n"; return false; } cond.value_reg_str = value; break; } default: output << "rule: Unknown rule condition operation \"" << op << "\"\n"; return false; break; } cond.name = name; conditions.push_back(cond); return true; } /** * Add consequence to this rule. * * @retval false if the consequence cannot be added (malformed) */ bool Rule::addConsequence(string name, char op, const char* value, Output output) { Consequence cons; switch (op) { case '=': cons.value_type = CONSEQUENCE_VALUE_TYPE_STRING; cons.value = value; break; default: output << "rule: Unknown rule consequence operation \"" << op << "\"\n"; return false; break; } cons.name = name; consequences.push_back(cons); return true; } bool Rule::setLabel(char op, string value, Output output) { if (op != '=') { output << "rule: Unknown rule label operation \"" << op << "\"\n"; return false; } if (value.empty()) { output << "rule: Rule label cannot be empty\n"; return false; } label = value; return true; } // rules parsing // Rule::Rule() { birth_time = get_monotonic_timestamp(); } void Rule::print(Output output) { output << "label=" << label << "\t"; // Append conditions for (auto const& cond : conditions) { if (cond.negated) { output << "not\t"; } output << cond.name; switch (cond.value_type) { case CONDITION_VALUE_TYPE_STRING: output << "=" << cond.value_str << "\t"; break; case CONDITION_VALUE_TYPE_REGEX: output << "~" << cond.value_reg_str << "\t"; break; default: /* CONDITION_VALUE_TYPE_INTEGER: */ output << "=" << cond.value_integer << "\t"; } } // Append consequences for (auto const& cons : consequences) { output << cons.name << "=" << cons.value << "\t"; } // Append separating or final newline output << '\n'; } // rules applying // ClientChanges::ClientChanges(Client *client) : fullscreen(ewmh_is_fullscreen_set(client->window_)) {} /// CONDITIONS /// bool Condition::matches(const string& str) const { switch (value_type) { case CONDITION_VALUE_TYPE_STRING: return value_str == str; break; case CONDITION_VALUE_TYPE_REGEX: return std::regex_match(str, value_reg_exp); break; case CONDITION_VALUE_TYPE_INTEGER: try { return std::stoi(str) == value_integer; } catch (std::exception&) { return false; } break; } return false; } bool Condition::matchesClass(const Client* client) const { return matches(Root::get()->X.getClass(client->window_)); } bool Condition::matchesInstance(const Client* client) const { return matches(Root::get()->X.getInstance(client->window_)); } bool Condition::matchesTitle(const Client* client) const { return matches(client->title_()); } bool Condition::matchesPid(const Client* client) const { if (client->pid_ < 0) { return false; } if (value_type == CONDITION_VALUE_TYPE_INTEGER) { return value_integer == client->pid_; } else { char buf[1000]; // 1kb ought to be enough for every int sprintf(buf, "%d", client->pid_); return matches(buf); } } bool Condition::matchesMaxage(const Client* client) const { time_t diff = get_monotonic_timestamp() - conditionCreationTime; return (value_integer >= diff); } bool Condition::matchesWindowtype(const Client* client) const { // that only works for atom-type utf8-string, _NET_WM_WINDOW_TYPE is int // GString* wintype= // window_property_to_g_string(g_display, client->window, wintype_atom); // => // kinda duplicate from src/utils.c:window_properties_to_g_string() // using different xatom type, and only calling XGetWindowProperty // once, because we are sure we only need four bytes long bufsize = 10; char *buf; Atom type_ret, wintype; int format; unsigned long items, bytes_left; long offset = 0; int status = XGetWindowProperty( g_display, client->window_, g_netatom[NetWmWindowType], offset, bufsize, False, ATOM("ATOM"), &type_ret, &format, &items, &bytes_left, (unsigned char**)&buf ); // we only need precisely four bytes (one Atom) // if there are bytes left, something went wrong if(status != Success || bytes_left > 0 || items < 1 || buf == nullptr) { return false; } else { wintype= *(Atom *)buf; XFree(buf); } for (int i = NetWmWindowTypeFIRST; i <= NetWmWindowTypeLAST; i++) { // try to find the window type if (wintype == g_netatom[i]) { // if found, then treat the window type as a string value, // which is registered in g_netatom_names[] return matches(g_netatom_names[i]); } } // if no valid window type has been found, // it can not match return false; } bool Condition::matchesWindowrole(const Client* client) const { auto role = Root::get()->X.getWindowProperty(client->window_, ATOM("WM_WINDOW_ROLE")); if (!role.has_value()) { return false; } return matches(role.value()); } /// CONSEQUENCES /// void Consequence::applyTag(const Client* client, ClientChanges* changes) const { changes->tag_name = value; } void Consequence::applyFocus(const Client* client, ClientChanges* changes) const { changes->focus = Converter<bool>::parse(value, changes->focus); } void Consequence::applyManage(const Client* client, ClientChanges* changes) const { changes->manage = Converter<bool>::parse(value, changes->manage); } void Consequence::applyIndex(const Client* client, ClientChanges* changes) const { changes->tree_index = value; } void Consequence::applyPseudotile(const Client* client, ClientChanges* changes) const { changes->pseudotile = Converter<bool>::parse(value, client->pseudotile_); } void Consequence::applyFullscreen(const Client* client, ClientChanges* changes) const { changes->fullscreen = Converter<bool>::parse(value, changes->fullscreen); } void Consequence::applySwitchtag(const Client* client, ClientChanges* changes) const { changes->switchtag = Converter<bool>::parse(value, changes->switchtag); } void Consequence::applyEwmhrequests(const Client* client, ClientChanges* changes) const { changes->ewmhRequests = Converter<bool>::parse(value, client->ewmhrequests_); } void Consequence::applyEwmhnotify(const Client* client, ClientChanges* changes) const { changes->ewmhNotify = Converter<bool>::parse(value, client->ewmhnotify_); } void Consequence::applyHook(const Client* client, ClientChanges* changes) const { std::stringstream winidSs; winidSs << "0x" << std::hex << client->window_; auto winidStr = winidSs.str(); hook_emit({ "rule", value, winidStr }); } void Consequence::applyKeyMask(const Client* client, ClientChanges* changes) const { changes->keyMask = value; } void Consequence::applyMonitor(const Client* client, ClientChanges* changes) const { changes->monitor_name = value; }
e8a4f0761a5266f0350113b5d01cc2aea120beb4
d4d356ae6a7391b95f820108e4d3b0fef05506d2
/silicium/asio/block_thread.hpp
0c3c42f241799c22a34db25d5257a3020e41ce54
[ "MIT" ]
permissive
TyRoXx/silicium
27729b01e76a8947d68b569841bf8f1923a21793
3a19b81f05ff487df4f314f204f1d10e4d272fee
refs/heads/master
2021-01-23T08:39:44.336205
2017-03-03T23:54:33
2017-03-03T23:54:33
20,037,983
4
1
MIT
2018-11-26T09:17:34
2014-05-21T21:26:14
C++
UTF-8
C++
false
false
2,348
hpp
block_thread.hpp
#ifndef SILICIUM_BLOCK_THREAD_HPP #define SILICIUM_BLOCK_THREAD_HPP #include <silicium/config.hpp> #define SILICIUM_HAS_BLOCK_THREAD (BOOST_VERSION >= 105400) #if SILICIUM_HAS_BLOCK_THREAD #include <boost/asio/async_result.hpp> #include <future> namespace Si { namespace asio { struct block_thread_t { BOOST_CONSTEXPR block_thread_t() { } }; static BOOST_CONSTEXPR_OR_CONST block_thread_t block_thread; namespace detail { template <class Element> struct blocking_thread_handler { #if !SILICIUM_COMPILER_GENERATES_MOVES blocking_thread_handler(blocking_thread_handler &&other) : m_promised(std::move(other.m_promised)) { } blocking_thread_handler & operator=(blocking_thread_handler &&other) { m_promised = std::move(other.m_promised); return *this; } #endif explicit blocking_thread_handler(block_thread_t) { } void operator()(Element value) { m_promised.set_value(std::move(value)); } std::future<Element> get_future() { return m_promised.get_future(); } private: std::promise<Element> m_promised; }; } } } namespace boost { namespace asio { template <class Element> struct async_result<Si::asio::detail::blocking_thread_handler<Element>> { typedef Element type; explicit async_result( Si::asio::detail::blocking_thread_handler<Element> &handler) : m_result(handler.get_future()) { } Element get() { return m_result.get(); } private: std::future<Element> m_result; }; template <typename ReturnType, class A2> struct handler_type<Si::asio::block_thread_t, ReturnType(A2)> { typedef Si::asio::detail::blocking_thread_handler<A2> type; }; } } #endif #endif
09e5fd40e3486d117697f7696711fab43de9fc14
f79c5096132c7837b1778c12a9e6b87c09b3067b
/include/Position.h
7e48704bbf786d7aefc048ec888e2fd94fe580ae
[]
no_license
xRockmetalx26/cpp_sfml_template
58b3ff14b2d3c3a345f84ffdbcf16d6123ee838e
6007f2332803e4f50babe0f81a990a1a51d471c3
refs/heads/main
2023-07-15T12:38:45.570908
2021-08-27T00:47:18
2021-08-27T00:47:18
397,041,539
0
0
null
null
null
null
UTF-8
C++
false
false
297
h
Position.h
// // Created by xRockmetalx // #ifndef POSITION_H #define POSITION_H class Position { public: explicit Position(int x = 0, int y = 0); void set_x(int x); void set_y(int y); int get_x() const; int get_y() const; protected: int x; int y; }; #endif // POSITION_H
363613c2d1494ea577ff2c58e38c303b59693eb2
3f06e22f1fd642b485fee57d71b1b7e74246463a
/libs/PWM_control/PWM_control.cpp
fc7559858e55a78720292edc4c8aaac44f42e56d
[]
no_license
francocamila/PI2_Projeto_Gaia
e3adcc8da84a461c78f73921d2fd08897a5de067
14774612cb602f4371c2517318d5fa66cd63ef86
refs/heads/master
2020-05-30T18:22:42.905716
2019-07-01T23:35:20
2019-07-01T23:35:20
189,896,311
0
1
null
2019-06-27T15:53:02
2019-06-02T21:20:20
C++
UTF-8
C++
false
false
2,136
cpp
PWM_control.cpp
#include <Arduino.h> #include <PWM_control.h> #define PWM_right_pin 13 #define PWM_left_pin 14 #define inversion_right_pin 15 #define inversion_left_pin 12 PWM_control::PWM_control(void) { pinMode(PWM_right_pin,OUTPUT); pinMode(PWM_left_pin,OUTPUT); //initiates all used pins as output pinMode(inversion_right_pin,OUTPUT); pinMode(inversion_left_pin,OUTPUT); boat_state = idle; } void PWM_control::PWM_go_forwards(int PWM_value) { if(boat_state != going_forwards) { analogWrite(PWM_right_pin, 0); analogWrite(PWM_left_pin,0); //stops the motors and waits for a second delay(1000); digitalWrite(inversion_right_pin,LOW); digitalWrite(inversion_left_pin,LOW); //puts both motors in foward direction } analogWrite(PWM_right_pin, PWM_value); //rights the PWM value to make the motors work analogWrite(PWM_left_pin, PWM_value); boat_state = going_forwards; } void PWM_control::PWM_go_backwards(int PWM_value) { if(boat_state != going_backwards) { analogWrite(PWM_right_pin, 0); analogWrite(PWM_left_pin,0); delay(1000); digitalWrite(inversion_right_pin,HIGH); digitalWrite(inversion_left_pin,HIGH); } analogWrite(PWM_right_pin, PWM_value); analogWrite(PWM_left_pin, PWM_value); boat_state = going_backwards; } void PWM_control:: PWM_turn(int PWM_value, bool direction) { if(direction) { if(boat_state != turning_left) { analogWrite(PWM_right_pin, 0); analogWrite(PWM_left_pin,0); delay(1000); } digitalWrite(inversion_right_pin, LOW); digitalWrite(inversion_left_pin,HIGH); boat_state = turning_left; } else { if(boat_state != turning_left) { analogWrite(PWM_right_pin, 0); analogWrite(PWM_left_pin,0); delay(1000); } digitalWrite(inversion_right_pin, HIGH); digitalWrite(inversion_left_pin,LOW); boat_state = turning_right; } analogWrite(PWM_right_pin, PWM_value); analogWrite(PWM_left_pin, PWM_value); }
42a001e0d2feddf53fd4c0dccdef8de37894bbe2
a309cc6fcec9a03f107136d8ebbebbaa9ba15fae
/path_tracing/point.cpp
15aaa2f4b9bbebc69e7fef48426e1d7f8f40ecbb
[]
no_license
tink-expo/cs580-graphics-20spring
a0846daca94c1ddbd46f0a76a247cbbeb0b72185
0675da5d6ab8f7207bcadf57bc2f8870378fa45e
refs/heads/master
2022-11-04T21:47:02.414056
2020-07-06T07:37:02
2020-07-06T07:37:02
257,074,725
2
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
point.cpp
#include "point.h" Point::Point(float x, float y, float z) //constructor { X = x; Y = y; Z = z; } Point::Point(const Point& p) //initialisation from another point { X = p.X; Y = p.Y; Z = p.Z; } Point& Point::operator=(const Point& p) //assignment { if(this == &p) return *this; X = p.X; Y = p.Y; Z = p.Z; return *this; } ostream& operator<<(ostream& s,Point p) //writing { s << "(" << p.X << "," << p.Y << "," << p.Z << ")"; return s; } istream& operator>>(istream& s,Point& p) //reading { s >> p.X; s >> p.Y; s >> p.Z; return s; }
23a558a46ebf9b657fcbee101cae32e7982c9668
4821303e3a041f391feb85b5b59e255f30e14a85
/UVA/11713_abstract_names.cpp
d2822fc6a55e9cd36e0c538471246b7533777a90
[]
no_license
StanleyDing/OnlineJudge
613729f8c2b692af99b797c75c41d17a05a79670
b9e8efe98550e6153d2d454841329f2bf0dc34b4
refs/heads/master
2016-09-09T21:00:03.806659
2013-10-04T10:11:42
2013-10-04T10:11:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
884
cpp
11713_abstract_names.cpp
#include <iostream> #include <string> using namespace std; void compare(const string&, const string&); int isVowel(const char); int main() { int n;//a string s1, s2; while(cin >> n){ while(n--){ cin >> s1 >> s2; if(s1.length() != s2.length()){ cout << "No" << endl; continue; } compare(s1, s2); } } } void compare(const string &s1, const string &s2) { for(int i = 0; i < s1.length(); i++){ if(isVowel(s1[i]) && isVowel(s2[i])) continue; else if(s1[i] == s2[i]) continue; else{ cout << "No" << endl; return; } } cout << "Yes" << endl; } int isVowel(const char c) { if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return 1; else return 0; }
e90a63055e0407d0dc9a31840e4faf72c2936135
b8e9f2c49c89039b1a002b46996e76f7cb68a663
/C Programs/C Programs - 1/Climbing Stairs.cpp
4df0b4d833e7531efbf43e4137632da032913970
[]
no_license
MathProgrammer/LeetCode
8d52756a2f84913d73b2f888a0d9735262065499
746ef89eed72660edd38526e8733b8c405860995
refs/heads/master
2023-07-20T01:03:28.480036
2023-07-09T04:21:26
2023-07-09T04:21:26
98,414,648
2
1
null
null
null
null
UTF-8
C++
false
false
439
cpp
Climbing Stairs.cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: int climbStairs(int n) { vector <int> no_of_ways_to_climb(n + 1, 0); no_of_ways_to_climb[1] = 1; no_of_ways_to_climb[2] = 2; for(int i = 3; i <= n; i++){ no_of_ways_to_climb[i] = no_of_ways_to_climb[i - 1] + no_of_ways_to_climb[i - 2]; } return no_of_ways_to_climb[n]; } };
8e4f51930a41ea06e936c03dee7d998647e3015c
def9bf08f569bf802eae6e728f010ea346041796
/include/Kigen/utils/Logger.hpp
ed06691742995d2f8eb8089bbfa389b5ba4a82f6
[ "MIT" ]
permissive
MrFiskerton/Kigen
0ce4587637e35569c01f05435a2f567d9823fb21
fa39b651e098c827279531c2b78252cadedab77e
refs/heads/master
2022-12-23T15:27:10.494296
2020-06-16T09:55:23
2020-06-16T09:55:23
140,623,485
1
0
null
null
null
null
UTF-8
C++
false
false
3,157
hpp
Logger.hpp
// // Created by Roman Fiskov (roman.fiskov@gmail.com) [Mr.Fiskerton] on 13.07.18. // #ifndef INCLUDED_LOGGER_HPP #define INCLUDED_LOGGER_HPP #include "Kigen/defines.hpp" #include <iostream> #include <fstream> #include <iomanip> #include <utility> #include "NonCopyable.hpp" namespace LogColour { #ifdef LOG_COLOR_SUPPORT const std::string Black = "\e[30m"; const std::string Red = "\e[31m"; const std::string Green = "\e[32m"; const std::string Yellow = "\e[33m"; const std::string Blue = "\e[34m"; const std::string Magenta = "\e[35m"; const std::string Cyan = "\e[36m"; const std::string White = "\e[37m"; const std::string NoColor = "\e[0m"; #else const std::string Black = ""; const std::string Red = ""; const std::string Green = ""; const std::string Yellow = ""; const std::string Blue = ""; const std::string Magenta = ""; const std::string Cyan = ""; const std::string White = ""; const std::string NoColor = ""; #endif } class Logger final : public NonCopyable { public: struct Level { std::string prefix; std::string colour; Level(std::string p, std::string c) : prefix(std::move(p)), colour(std::move(c)) {} friend std::ostream& operator<<(std::ostream& ostr, const Logger::Level& level) { ostr << level.colour << level.prefix; return ostr; } }; static const std::string endl; public: static void log(const std::string& message, const std::string& colour); static void notify(const std::string &message) { log(std::string(">>> ").append(message), LogColour::Cyan);} static void info (const std::string &source, const std::string &message) { log(INFO, source, message);} static void warn (const std::string &source, const std::string &message) { log(WARNING, source, message);} static void error(const std::string &source, const std::string &message) { log(ERROR, source, message);} static void debug(const std::string &source, const std::string &message) { log(DEBUG_, source, message);} static std::ostream& log(const std::string& colour = LogColour::Magenta); static std::ostream& notify() { return log(LogColour::Cyan); } static std::ostream& info (const std::string &source = "") { return log(INFO, source);} static std::ostream& warn (const std::string &source = "") { return log(WARNING, source);} static std::ostream& error(const std::string &source = "") { return log(ERROR, source);} static std::ostream& debug(const std::string &source = "") { return log(DEBUG_, source);} static const std::string& endlf(); static void flush(); static std::ostream& get_stream() { return s_logstr; } private: static void log(Logger::Level level, const std::string &source, const std::string &message); static std::ostream& log(Logger::Level level, const std::string &source); private: static std::ostream& s_logstr; static const Level INFO; static const Level WARNING; static const Level ERROR; static const Level DEBUG_; }; #endif //INCLUDED_LOGGER_HPP
4750fa324d8c3e82ee6780a2a075f923d7e91208
4cc998877a0df5e766554af806f94a79419a0178
/second largest.cpp
bd2ece2fcd8d1d8211d239ed64f8a641398cb3e7
[]
no_license
greeshma0601/Arrays
521ecb189b0c0ce0b4fcb1244d62a02386620c54
6b69562519663bc07706410d8e4c4c73cbe606b5
refs/heads/master
2020-04-13T20:43:18.904015
2019-06-25T05:32:55
2019-06-25T05:32:55
163,437,158
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
second largest.cpp
#include<cstdlib> #include<limits> #include<bits/stdc++.h> using namespace std; int main() { //code int i,t,k,n,j; cin>>t; while(t--){ cin>>n; int a[n]; int f,s; for(k=0;k<n;k++) cin>>a[k]; if(n<2) { cout<<a[0]; } else{ f=s=INT_MIN; for(i=0;i<n;i++) { if(a[i]>f) { s=f; f=a[i]; } else if(a[i]>s && a[i]!=f) { s=a[i]; } } cout<<s<<"\n"; } } return 0; }
607c0d080144f7d4e136b239bd46a787ba34f049
6c013d5d70b692e6b5250f3ab8405e1a1ef32055
/UIWidgets/GeneralInformationWidgetR2D.h
895c09ed348769e56ce3e88621ca66ccd33cc109
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
NHERI-SimCenter/R2DTool
a667afb17a5ac6df07966ee5b98cf1975dfe6ddf
b3fa98e018bdf71caccd97277d81307ac051a1c1
refs/heads/master
2023-08-19T07:48:07.775861
2023-07-28T15:16:17
2023-07-28T15:16:17
329,111,097
5
18
NOASSERTION
2023-09-14T21:52:20
2021-01-12T21:00:33
C++
UTF-8
C++
false
false
3,853
h
GeneralInformationWidgetR2D.h
#ifndef GENERAL_INFORMATION_WIDGET_R2D_H #define GENERAL_INFORMATION_WIDGET_R2D_H /* ***************************************************************************** Copyright (c) 2016-2021, The Regents of the University of California (Regents). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. *************************************************************************** */ // Written by: Stevan Gavrilovic, Frank McKenna #include <SimCenterWidget.h> class QLineEdit; class QGridLayout; class QComboBox; class SimCenterUnitsCombo; class QCheckBox; class GeneralInformationWidgetR2D : public SimCenterWidget { Q_OBJECT public: explicit GeneralInformationWidgetR2D(QWidget *parent); ~GeneralInformationWidgetR2D(); bool outputToJSON(QJsonObject &jsonObject); bool inputFromJSON(QJsonObject &jsonObject); bool outputToJSON(QJsonArray &arrayObject); bool inputFromJSON(QJsonArray &arrayObject); QString getAnalysisName(void); void clear(void); enum LengthUnit{m, meter, cm, centimeter, mm, milimeter, in, inch, ft, foot}; Q_ENUM(LengthUnit) enum ForceUnit{N, kN, lb, kips}; Q_ENUM(ForceUnit) enum TimeUnit{sec, seconds, min, minutes, hr, hour}; Q_ENUM(TimeUnit) enum TemperatureUnit{C, F, K}; Q_ENUM(TemperatureUnit) enum SpeedUnit{mph, kph}; Q_ENUM(SpeedUnit) bool setAssetTypeState(QString assetType, bool); signals: void assetChanged(QString name, bool checked); private: QGridLayout* getInfoLayout(void); QLineEdit* nameEdit; SimCenterUnitsCombo* unitsForceCombo; SimCenterUnitsCombo* unitsLengthCombo; SimCenterUnitsCombo* unitsTimeCombo; QCheckBox* buildingsCheckBox; QCheckBox* soilCheckBox; QCheckBox* waterCheckBox; QCheckBox* sewerCheckBox; QCheckBox* gasCheckBox; QCheckBox* transportationCheckBox; QCheckBox* EDPCheckBox; QCheckBox* DMCheckBox; QCheckBox* DVCheckBox; QCheckBox* realizationCheckBox; QCheckBox* AIMCheckBox; QCheckBox* IMCheckBox; }; #endif // GENERALINFORMATIONWIDGET_H
0894c5cd27a8f9dd96d8ac531e48886923f83150
d4ec0332b56f60c72755a0824a01992c162c8951
/Parser/Parser/parser_containers.h
eb1d60a76b6b8988e287ef2345880d2f3dbe5b12
[]
no_license
sanchaez/lab-translator
6f0fa838f4e0fa5511f8f36ae7b49018909a0389
5d6cc3e5bfab9b8fef60486388bcf5e5d91f4eac
refs/heads/master
2021-01-22T21:58:42.163167
2017-06-11T14:05:10
2017-06-11T19:04:15
85,495,187
0
0
null
null
null
null
UTF-8
C++
false
false
8,666
h
parser_containers.h
#pragma once #include <algorithm> #include <iostream> #include <memory> #include <ostream> #include <stack> #include <string> #include <vector> #include "lexer_data.h" namespace translator { enum class ParserTokenType { Empty, SignalProgram, Program, Block, VariableDeclarations, DeclarationsList, Declaration, StatementsList, Statements, ConditionalExpression, Logical, LogicalSummand, LogicalMultipliersList, LogicalMultiplier, ComparisonOperator, Expression, VariableIdentifier, ProcedureIdentifier, Identifier, UnsignedInteger, }; std::ostream& operator<<(std::ostream& stream, LexemToken& rhs) { if (rhs.symbol > 0) { stream << rhs.name << '(' << rhs.symbol << ")[" << rhs.row << ':' << rhs.column << ']'; } return stream; } std::ostream& operator<<(std::ostream& stream, ParserTokenType& rhs) { switch (rhs) { case translator::ParserTokenType::Empty: stream << "empty"; break; case translator::ParserTokenType::SignalProgram: stream << "signal-program"; break; case translator::ParserTokenType::Program: stream << "program"; break; case translator::ParserTokenType::Block: stream << "block"; break; case translator::ParserTokenType::VariableDeclarations: stream << "variable-declarations"; break; case translator::ParserTokenType::DeclarationsList: stream << "declarations-list"; break; case translator::ParserTokenType::Declaration: stream << "declaration"; break; case translator::ParserTokenType::StatementsList: stream << "statements-list"; break; case translator::ParserTokenType::Statements: stream << "statements"; break; case translator::ParserTokenType::ConditionalExpression: stream << "conditional-expression"; break; case translator::ParserTokenType::Logical: stream << "logical"; break; case translator::ParserTokenType::LogicalSummand: stream << "logical-summand"; break; case translator::ParserTokenType::LogicalMultipliersList: stream << "logical-multipliers-list"; break; case translator::ParserTokenType::LogicalMultiplier: stream << "logical-multiplier"; break; case translator::ParserTokenType::ComparisonOperator: stream << "comparison-operator"; break; case translator::ParserTokenType::Expression: stream << "expression"; break; case translator::ParserTokenType::VariableIdentifier: stream << "variable-identifier"; break; case translator::ParserTokenType::ProcedureIdentifier: stream << "procedure-identifier"; break; case translator::ParserTokenType::Identifier: stream << "identifier"; break; case translator::ParserTokenType::UnsignedInteger: stream << "unsigned-integer"; break; default: stream << "unknown"; break; } return stream; } struct ParserTreeNode; using pParserTreeNode = std::shared_ptr<ParserTreeNode>; using pParserTreeNodeWeak = std::weak_ptr<ParserTreeNode>; using pParserTreeNodeLinks = std::vector<pParserTreeNode>; #define PARSER_NOVALUE ParserStatement() struct ParserStatement { std::vector<LexemToken> tokens; const int row() const { return (tokens.empty()) ? -1 : tokens[0].row; } const int column() const { return (tokens.empty()) ? -1 : tokens[0].column; } void add(const LexemToken& rhs) { tokens.push_back(rhs); } void add(const std::vector<LexemToken>& rhs) { tokens.reserve(tokens.size() + rhs.size()); tokens.insert(tokens.end(), std::make_move_iterator(rhs.begin()), std::make_move_iterator(rhs.end())); } void add(const ParserStatement& rhs) { add(rhs.tokens); } }; std::ostream& operator<<(std::ostream& stream, ParserStatement& rhs) { if (!rhs.tokens.empty()) { stream << '[' << rhs.row() << ':' << rhs.column() << ']'; // names stream << " $"; for (auto x : rhs.tokens) { stream << ' ' << x.name; } stream << " #"; // symbols for (auto x : rhs.tokens) { stream << ' ' << x.symbol; } } return stream; } struct ParserTreeNode { ParserTreeNode() : value(PARSER_NOVALUE), links(), type(ParserTokenType::Empty), parent() {} ParserTreeNode(const ParserStatement& v, const ParserTokenType& t, const pParserTreeNodeLinks l, pParserTreeNodeWeak p) : value(v), links(l), type(t), parent(p) {} ParserTreeNode(const ParserTreeNode& x) : ParserTreeNode(x.value, x.type, x.links, x.parent) {} int level() { auto x = parent.lock(); int i = 0; while (x) { x = x->parent.lock(); ++i; } return i; } ParserStatement value; ParserTokenType type; pParserTreeNodeLinks links; pParserTreeNodeWeak parent; }; struct ParserTree { pParserTreeNode _top; pParserTreeNode _head; pParserTreeNode _lastAdded; ParserTree() : _top(std::make_shared<ParserTreeNode>()) { _top->type = ParserTokenType::SignalProgram; _head = _top; _lastAdded = _top; } // add to specified pParserTreeNode& add(pParserTreeNode& what, pParserTreeNode& parent) { what->parent = parent; parent->links.emplace_back(what); _lastAdded = what; _head = what; return what; } pParserTreeNode& add(const ParserStatement& v, const ParserTokenType& t, const pParserTreeNodeLinks& l, pParserTreeNode& p) { pParserTreeNode ptr = std::make_shared<ParserTreeNode>(v, t, l, p); p->links.emplace_back(ptr); _lastAdded = ptr; _head = ptr; return _lastAdded; } // returns a shared_ptr to added element pParserTreeNode& add(pParserTreeNode& what) { what->parent = _head; _head->links.emplace_back(what); _lastAdded = what; _head = what; return what; } pParserTreeNode& add(const ParserStatement& v, const ParserTokenType& t, const pParserTreeNodeLinks& l = pParserTreeNodeLinks()) { pParserTreeNode ptr = std::make_shared<ParserTreeNode>(v, t, l, _head); _head->links.emplace_back(ptr); _lastAdded = ptr; _head = ptr; return _lastAdded; } void headup() { _head = _head->parent.lock(); } // remove from the tree void remove(pParserTreeNode& what) { _head = what->parent.lock(); auto parent_links = what->parent.lock()->links; auto found = std::find(parent_links.begin(), parent_links.end(), what); if (found != parent_links.end()) { parent_links.erase(found); } } #define VLINE '|' // char(179) #define HLINE '-' // char(196) #define LEFTCORNER '+' // char(192) #define ISECTIONLEFT LEFTCORNER // char(195) #define ISECTIONTOP LEFTCORNER // char(193) #define FILLCHAR ' ' // print to std::ostream void print(std::ostream& stream = std::cout) { std::stack<pParserTreeNode> nodes; std::stack<int> nodes_children; std::vector<int> level_sizes; nodes.push(_top); while (!nodes.empty()) { pParserTreeNode current = nodes.top(); int current_level = current->level(); nodes.pop(); level_sizes.resize(current_level + 1); int level_size = 0; // get links and current_level size (reversed) for (auto x = current->links.rbegin(); x != current->links.rend(); ++x) { nodes.push(*x); ++level_size; } level_sizes[current_level] = level_size; // finish all closed lines if (nodes.empty()) { int i = 0; // skip empty space while (level_sizes[i] <= 0) { stream << FILLCHAR << FILLCHAR; ++i; } stream << FILLCHAR << LEFTCORNER; ++i; for (; i < current_level - 1; ++i) { if (level_sizes[i] > 0) { stream << FILLCHAR << ISECTIONTOP; } else { stream << HLINE << HLINE; } } stream << HLINE; } else if (current_level) { for (int i = 0; i < current_level - 1; i++) { if (level_sizes[i] > 0) { stream << FILLCHAR << VLINE; } else { stream << FILLCHAR << FILLCHAR; } } if (level_sizes[current_level - 1] > 1) { stream << FILLCHAR << ISECTIONLEFT; } else { stream << FILLCHAR << LEFTCORNER; } stream << HLINE; --level_sizes[current_level - 1]; } stream << '<' << current->type << " \"" << current->value << "\">\n"; } } }; } // namespace translator
e65586eaac32cdc3103083aa70a416be81f7e6d3
6b28ee0c54a77d82793b54179e4d64315bc2e812
/main.cpp
296f055624f1981f7aeca59f5b8067b16999e8d6
[]
no_license
LaMinato/LodeRunner1
87cf7c5ad7b4da32b432ba3f755a78838ae1ff0e
4e9fe75570b33fda908e32946cb2943be9b0e5cd
refs/heads/master
2021-01-12T06:02:52.009992
2016-12-24T14:31:00
2016-12-24T14:31:00
77,284,257
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
13,530
cpp
main.cpp
#include <SFML/Graphics.hpp> #include "map.h" #include "view.h" #include <iostream> #include <sstream> #include "menu.h" #include <vector> #include <list> using namespace sf; ////////////////////////////////////Общий класс родитель////////////////////////// class Entity { public: float dx, dy, x, y, speed,moveTimer;//добавили переменную таймер для будущих целей int w,h,health; bool life, isMove, onGround; Texture texture; Sprite sprite; String name;//враги могут быть разные, мы не будем делать другой класс для различающегося врага.всего лишь различим врагов по имени и дадим каждому свое действие в update в зависимости от имени Entity(Image &image, float X, float Y,int W,int H,String Name){ x = X; y = Y; w = W; h = H; name = Name; moveTimer = 0; speed = 0; health = 100; dx = 0; dy = 0; life = true; onGround = false; isMove = false; texture.loadFromImage(image); sprite.setTexture(texture); sprite.setOrigin(w / 2, h / 2); } FloatRect GetRect() { return FloatRect(x,y,w,h); } }; ////////////////////////////////////////////////////КЛАСС ИГРОКА//////////////////////// class Player :public Entity { public: enum { left, right, up, down, jump, stay, ladder, win, onladder, rope } state;//добавляем тип перечисления - состояние объекта int playerScore;//эта переменная может быть только у игрока Player(Image &image, float X, float Y,int W,int H,String Name):Entity(image,X,Y,W,H,Name){ playerScore = 1; state = stay; if (name == "Player1"){ sprite.setTextureRect(IntRect(0, 0, w, h)); } } void control(){ if (Keyboard::isKeyPressed){//если нажата клавиша if (Keyboard::isKeyPressed(Keyboard::Left)) {//а именно левая state = left; speed = 0.1; sprite.setScale(-1,1); } if (Keyboard::isKeyPressed(Keyboard::Right)) { state = right; speed = 0.1; sprite.setScale(1,1); } if ((Keyboard::isKeyPressed(Keyboard::Up))&&(state == ladder)) { state = up; dy+= -0.1; } if ((Keyboard::isKeyPressed(Keyboard::Down))&&((state == ladder)||(state == onladder))) { state = down; dy += 0.1; } if ((Keyboard::isKeyPressed(Keyboard::Left))&&(state == rope)) { dx = -0.1; } if ((Keyboard::isKeyPressed(Keyboard::Right))&&(state == rope)) { dx = 0.1; } if ((Keyboard::isKeyPressed(Keyboard::Down))&&(state == rope)) { dy = 0.15; state = stay; } if (Keyboard::isKeyPressed(Keyboard::C)) { for (int i = y / 32; i < (y + h) / 32; i++)//проходимся по элементам карты for (int j = x / 32; j<(x + w) / 32; j++) { if (TileMap [i+1][j+1] == '0') TileMap[i+1][j+1] = '5'; } } if (Keyboard::isKeyPressed(Keyboard::X)) { for (int i = y / 32; i < (y + h) / 32; i++)//проходимся по элементам карты for (int j = x / 32; j<(x + w) / 32; j++) { if (TileMap [i+1][j-1] == '0') TileMap[i+1][j-1] = '5'; } } } } void checkCollisionWithMap(float Dx, float Dy)//ф ция проверки столкновений с картой { for (int i = y / 32; i < (y + h) / 32; i++)//проходимся по элементам карты for (int j = x / 32; j < (x + w) / 32; j++) { if (TileMap [i][j] == 'e') state = win; if (TileMap[i+1][j] == 'f') state = onladder; if (TileMap[i][j] == 'f') { state = ladder; } if (TileMap[i][j] == 's') { TileMap[i][j] = ' '; playerScore--; } if (TileMap[i][j] == 'd') { life = false; for (int k = HEIGHT_MAP-1; k > 1; k--) for (int m = WIDTH_MAP-1; m > 1; m--) { TileMap[k][m] = 'd'; } } if ((TileMap[i][j] == '0') || (TileMap[i][j] == '1'))//если элемент наш тайлик земли? то { if (Dy>0){ y = i * 32 - h; dy = 0; onGround = true; }//по Y вниз=>идем в пол(стоим на месте) или падаем. В этот момент надо вытолкнуть персонажа и поставить его на землю, при этом говорим что мы на земле тем самым снова можем прыгать if (Dy<0){ y = i * 32 + 32; dy = 0; }//столкновение с верхними краями карты(может и не пригодиться) if (Dx>0){ x = j * 32 - w; }//с правым краем карты if (Dx<0){ x = j * 32 + 32; }// с левым краем карты } if (TileMap[i][j] == 'r') { state = rope; } //else { onGround = false; }//надо убрать т.к мы можем находиться и на другой поверхности или платформе которую разрушит враг } } void update(float time) { control();//функция управления персонажем switch (state)//тут делаются различные действия в зависимости от состояния { case right:dx = speed; break;//состояние идти вправо case left:dx = -speed; break;//состояние идти влево case up: dx = 0; break;//будет состояние поднятия наверх (например по лестнице) case down: dx = 0; break;//будет состояние во время спуска персонажа (например по лестнице) case ladder: dx = 0; break; case stay: dx = 0; break;//и здесь тоже case onladder: dx = 0; break; case rope: dx = 0; break; } x += dx*time; checkCollisionWithMap(dx, 0);//обрабатываем столкновение по Х y += dy*time; checkCollisionWithMap(0, dy);//обрабатываем столкновение по Y sprite.setPosition(x + w / 2, y + h / 2); //задаем позицию спрайта в место его центра if (health <= 0){ life = false; } if (!isMove){ speed = 0; } //if (!onGround) { dy = dy + 0.0015*time; }//убираем и будем всегда притягивать к земле if (life) { setPlayerCoordinateForView(x, y); } if ((state != ladder)||(state != onladder)) dy = dy + 0.0015*time; if ((state == ladder)||(state == onladder)) dy = 0;//постоянно притягиваемся к земле if (state == rope) dy = 0; } }; class Enemy :public Entity{ public: Enemy(Image &image, float X, float Y,int W,int H,String Name):Entity(image,X,Y,W,H,Name){ if (name == "EasyEnemy"){ sprite.setTextureRect(IntRect(5, 0, w, h)); dx = 0.1; dy = 0.8; sprite.setScale(-1,1); } } void checkCollisionWithMap(float Dx, float Dy)//ф ция проверки столкновений с картой { for (int i = y / 32; i < (y + h) / 32; i++)//проходимся по элементам карты for (int j = x / 32; j<(x + w) / 32; j++) { if ((TileMap[i][j] == '0')||(TileMap[i][j] == '1'))//если элемент наш тайлик земли, то { if (Dy>0){ y = i * 32 - h; }//по Y вниз=>идем в пол(стоим на месте) или падаем. В этот момент надо вытолкнуть персонажа и поставить его на землю, при этом говорим что мы на земле тем самым снова можем прыгать if (Dy<0){ y = i * 32 + 32; }//столкновение с верхними краями карты(может и не пригодиться) if (Dx>0){ x = j * 32 - w; dx = -0.1; sprite.scale(-1, 1); }//с правым краем карты if (Dx<0){ x = j * 32 + 32; dx = 0.1; sprite.scale(-1, 1); }// с левым краем карты } if (TileMap[i][j] == '5') { //y = (i+1)*32-h; x = (j+1)*32 - w; } } } void update(float time) { if (name == "EasyEnemy"){//для персонажа с таким именем логика будет такой //moveTimer += time;if (moveTimer>3000){ dx *= -1; moveTimer = 0; }//меняет направление примерно каждые 3 се x += dx*time; checkCollisionWithMap(dx, 0);//обрабатываем столкновение по Х y += dy*time; checkCollisionWithMap(0, dy);//обрабатываем столкновение по Y sprite.setPosition(x + w / 2, y + h / 2); //задаем позицию спрайта в место его центра if (health <= 0){ life = false; } } } }; /*void Robot(Player pl, Enemy en) { if (en.x < pl.x) { if (en.y < pl.y) { GetLadder(en.x, en.y, 1); } else if (en.y = pl.y) { en.dx = -0.075; } else { GetLadder(en.x, en.y, 2); } } else { if (en.y < pl.y) { GetLadder(en.x, en.y, 3); } else if (en.y = pl.y) { en.dx = -0.075; } else { GetLadder(en.x, en.y, 4); } } };*/ void UpdateMap(int time, std::vector <Destroyed> &des) { for (int l = 0; l < HEIGHT_MAP; l++) for (int m = 0; m < WIDTH_MAP; m++) { bool exist = false; if (TileMap[l][m] == '5') for (int k = 0; k < des.size(); k++) { if ((l == des[k].i)&&(m == des[k].j)) exist = true; } if (!exist) { Destroyed destr; destr.i = l; destr.j = m; destr.sec = 4; des.push_back(destr); } } for (int k = 0; k < des.size(); k++) { des[k].sec -= time; if (des[k].sec == 0) { TileMap[des[k].i][des[k].j] = '0'; } } }; int main() { RenderWindow window(VideoMode(1376, 768), "Lode Runner 2016"); menu(window); view.reset(FloatRect(0, 0, 640, 480)); std::vector <Enemy> Enemies; std::vector <Destroyed> destr; Image map_image; map_image.loadFromFile("images/map.png"); Texture map; map.loadFromImage(map_image); Sprite s_map; s_map.setTexture(map); Image heroImage; heroImage.loadFromFile("images/myhero.bmp"); heroImage.createMaskFromColor(Color(0,0,0)); Image easyEnemyImage; easyEnemyImage.loadFromFile("images/shamaich.png"); easyEnemyImage.createMaskFromColor(Color(0, 0, 0));//сделали маску по цвету.но лучше изначально иметь прозрачную картинку Player p(heroImage, 750, 500, 27, 32,"Player1");//объект класса игрока Enemy easyEnemy(easyEnemyImage, 850, 500, 19 , 32,"EasyEnemy"); Enemies.push_back(easyEnemy);//простой враг, объект класса врага Enemy easyEnemy2(easyEnemyImage, 950, 500, 19 , 32,"EasyEnemy"); Enemies.push_back(easyEnemy2); Enemy easyEnemy3(easyEnemyImage, 1050, 500, 19 , 32,"EasyEnemy"); Enemies.push_back(easyEnemy3); Clock clock; while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); float MapTime = clock.getElapsedTime().asSeconds(); clock.restart(); time = time / 800; if (p.state == p.win) { std::cout << "You win!" << '\n'; system("pause"); window.close(); } Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } p.update(time);// Player update function for (int i = 0; i < Enemies.size(); i++) Enemies[i].update(time); window.setView(view); window.clear(); for (int i = 0; i < HEIGHT_MAP; i++) for (int j = 0; j < WIDTH_MAP; j++) { if (TileMap[i][j] == '0') s_map.setTextureRect(IntRect(0, 0, 32, 32)); if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(32, 0, 32, 32)); if (TileMap[i][j] == '5') s_map.setTextureRect(IntRect(32, 0, 32, 32)); if (TileMap[i][j] == '1') s_map.setTextureRect(IntRect(0, 0, 32, 32)); if ((TileMap[i][j] == 's')) s_map.setTextureRect(IntRect(64, 0, 32, 32)); if ((TileMap[i][j] == 'f')) s_map.setTextureRect(IntRect(96, 0, 32, 32)); if ((TileMap[i][j] == 'r')) s_map.setTextureRect(IntRect(128, 0, 32, 32)); if (TileMap[i][j] == 'e') s_map.setTextureRect(IntRect(160, 0, 32, 32)); if (TileMap[i][j] == 'd') s_map.setTextureRect(IntRect(192,0,32,32)); s_map.setPosition(j * 32, i * 32); window.draw(s_map); } if (p.playerScore == 0) { for (int j = 5; j < 14; j++) TileMap[j][10] = 'f'; } for (int i = 0; i < Enemies.size(); i++) window.draw(Enemies[i].sprite); window.draw(p.sprite); window.display(); for (int i = 0; i < Enemies.size(); i++) { if (p.GetRect().intersects(Enemies[i].GetRect())) p.life = false; } if (p.life == false) { std::cout << "You Died!" << '\n'; system("pause"); window.close(); } } return 0; }