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
beea0e3c5d00d478817b2bc743dd897cdc060774
bbe4ea490a469950b7a71240593cd53a3ac7ee4c
/IGRV_src/Main.cpp
019ddfb13b47c63b0c098994ab8a0a0bc96e2d2a
[]
no_license
SunHaozhe/CG-Rendering-modeling
82c9135f82aa9b10664de92a112ed2ab160af3ee
85786b0f3bf1ffe34153119457f6bb336f21332a
refs/heads/master
2021-09-12T12:57:33.332989
2018-01-27T15:13:15
2018-01-27T15:13:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,538
cpp
Main.cpp
// -------------------------------------------------------------------------- // Copyright(C) 2009-2016 // Tamy Boubekeur // // Permission granted to use this code only for teaching projects and // private practice. // // Do not distribute this code outside the teaching assignements. // All rights reserved. // -------------------------------------------------------------------------- #include <GL/glew.h> #include <GL/glut.h> #include <iostream> #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include <algorithm> #include <time.h> #include <set> #include "Vec3.h" #include "Camera.h" #include "GLProgram.h" #include "Exception.h" #include "LightSource.h" #include "Ray.h" #include "Vec4.h" using namespace std; static const unsigned int DEFAULT_SCREENWIDTH = 1024; static const unsigned int DEFAULT_SCREENHEIGHT = 768; static const string DEFAULT_MESH_FILE ("../mesh_collection/max_50K.off"); static const string appTitle ("Informatique Graphique & Realite Virtuelle - Travaux Pratiques - Algorithmes de Rendu"); static const string myName ("Haozhe Sun"); static GLint window; static unsigned int FPS = 0; static bool fullScreen = false; static Camera camera; static Mesh mesh; GLProgram * glProgram; GLProgram * toonProgram; GLProgram * toon_outlines_Program; GLProgram * bvhProgram; static std::vector<Vec4f> colorResponses; // Cached per-vertex color response, updated at each frame static std::vector<LightSource> lightSources; static BVH * big_bvh; static unsigned int currentDeep = 0; std::vector<Vec3f> BVH::bvh_positions; std::vector<unsigned int> BVH::bvh_indices; unsigned int BVH::deep_count = 0; //speeds of interactions //static float lightMoveSpeed = 0.5f; static float alphaSpeed = 0.02f; static float F0Speed = 0.01f; //static float kd = M_PI; //coefficient diffusion //static float ks = 1; //coefficient specular //static float fd = kd / M_PI; //Lambert BRDF (diffusion) //static float s = 1; //shininess static float alpha = 0.5f; //roughness static float F0 = 0.5f; //Fresnel refraction index, dependent on material static int nb_samples_AO = 20; //number of sample of rays in one point when calculating AO static float radius_AO = 0.6f; //radius of rays when calculating AO static bool microFacet = false; //Blinn-Phong BRDF / micro facet BRDF static bool ggx = false; //Cook-Torrance micro facet BRDF / GGX micro facet BRDF static bool schlick = false; //Approximation of Schlick for GGX micro facet BRDF static bool perVertexShadow = true; //Shadow mode (true by default) static bool renderShadowOnlyInInit = true; //Render shadow only in the beginning of the program or in every frame ( calls of function renderScene() ) static bool perVertexAO = true; //Ambient occlusion mode (true by default) static bool cartoon_mode = false; //cartoon mode static bool renderMode = false; //coefficients for attenuation, aq the coefficient for d^2, al the coefficient for d, ac the constant coefficient, where d means the distance between the vertex and the light source //static const float ac = 0; //static const float al = 1; //static const float aq = 0; void printUsage () { std::cerr << std::endl<< appTitle << std::endl << "Author: " << myName << std::endl << std::endl << "Usage: ./main [<file.off>]" << std::endl << "Commands:" << std::endl << "------------------" << std::endl << " ?: Print help" << std::endl << " w: Toggle wireframe mode" << std::endl << " <drag>+<left button>: rotate model" << std::endl << " <drag>+<right button>: move model" << std::endl << " <drag>+<middle button>: zoom" << std::endl << " <f>: full screen mode"<< std::endl << " <w>: skeleton mode"<< std::endl << " <c>: Blinn-Phong mode for specular reflection"<< std::endl << " <v>: Cook-Torrance micro facet mode for specular reflection"<< std::endl << " <b>: GGX micro facet mode (Smith) for specular reflection"<< std::endl << " <n>: GGX micro facet mode (approximation of Schlick) for specular reflection"<< std::endl << " <j>: increase roughness alpha for micro facet mode"<< std::endl << " <k>: decrease roughness alpha for micro facet mode"<< std::endl << " <y>: increase Fresnel refraction index F0 for micro facet mode"<< std::endl << " <u>: decrease Fresnel refraction index F0 for micro facet mode"<< std::endl << " <s>: active shadow mode (per vertex shadow)"<< std::endl << " <o>: active Ambient occlusion mode (per vertex AO)"<< std::endl << " <l>: visualize Bounding Bolume Hierarchy (BVH), increase depth of visualization"<< std::endl << " <m>: visualize Bounding Bolume Hierarchy (BVH), decrease depth of visualization"<< std::endl << " <t>: active cartoon mode"<< std::endl << " <0>: reload the original model"<< std::endl << " <1>: topological Laplace filtre with step size of 0.1"<< std::endl << " <2>: topological Laplace filtre with step size of 0.5"<< std::endl << " <3>: topological Laplace filtre with step size of 1.0"<< std::endl << " <4>: geometric Laplace filtre with step size of 0.1"<< std::endl << " <5>: geometric Laplace filtre with step size of 0.5"<< std::endl << " <6>: geometric Laplace filtre with step size of 1.0"<< std::endl << " <7>: simplification 16*16*16 with a uniform grid"<< std::endl << " <8>: simplification 32*32*32 with a uniform grid"<< std::endl << " <9>: simplification 64*64*64 with a uniform grid"<< std::endl << " <a>: adaptive simplification with 5 as max number per leaf"<< std::endl << " <z>: adaptive simplification with 20 as max number per leaf"<< std::endl << " <g>: Loop subdivision"<< std::endl << " <q>, <esc>: Quit" << std::endl << std::endl; } void addPlane(Mesh & mesh){ //Parameters unsigned int nb_per_row = 22; float z = - 1.2f; // offset XY-plane float l = 0.125f; // l^2 = area of a square float first_square_originX = - 1.4f; float first_square_originY = - 1.6f; unsigned int nb_squares_plane = nb_per_row * nb_per_row; unsigned int first_index = mesh.positions().size(); for(unsigned int i = 0; i <= nb_per_row; i++){ for(unsigned int j = 0; j <= nb_per_row; j++){ mesh.positions().push_back( Vec3f(first_square_originX + j * l, first_square_originY + i * l, z) ); } } for(unsigned int k = 0; k < nb_squares_plane; k++){ unsigned int i = k / nb_per_row; //row number unsigned int j = k % nb_per_row; //column number unsigned int index0 = first_index + i * (nb_per_row + 1) + j; unsigned int index1 = first_index + (i + 1) * (nb_per_row + 1) + j; unsigned int index2 = first_index + (i + 1) * (nb_per_row + 1) + j + 1; unsigned int index3 = first_index + i * (nb_per_row + 1) + j + 1; mesh.triangles().push_back( Triangle(index3, index1, index0) ); mesh.triangles().push_back( Triangle(index3, index2, index1) ); } mesh.recomputeNormals(); } void computePerVertexAO (unsigned int numOfSamples, float radius, const Mesh& mesh){ srand((unsigned)time(0)); unsigned int mesh_size = mesh.positions().size(); for(unsigned int i = 0; i < mesh_size; i++){ Vec3f p = mesh.positions()[i]; Vec3f n = mesh.normals()[i]; float mark = 0.0f; unsigned int k = 0; while(true){ float random_variable1 = (float)rand() / (RAND_MAX); float random_variable2 = (float)rand() / (RAND_MAX); float random_variable3 = (float)rand() / (RAND_MAX); int sign1 = rand() % 2; int sign2 = rand() % 2; int sign3 = rand() % 2; random_variable1 = (sign1 == 0) ? random_variable1 : - random_variable1; random_variable2 = (sign2 == 0) ? random_variable2 : - random_variable2; random_variable3 = (sign3 == 0) ? random_variable3 : - random_variable3; Vec3f direction = Vec3f(random_variable1, random_variable2, random_variable3); if( length(direction) > 1.0 ) continue; if( ( dot(direction, n) / ( length(direction) * length(n) ) ) < 0.7f ) continue; k++; direction.normalize(); direction = direction * radius; Ray ray(p, direction); if( ray.isIntersected(mesh, big_bvh) ) mark += 1.0f; if(k == numOfSamples) break; } colorResponses[i][0] = (float)(mark / numOfSamples); } } void computePerVertexShadow(const Mesh& mesh){ unsigned int ls_size = 1; unsigned int mesh_size = mesh.positions().size(); //loop on light sources for(unsigned int k = 0; k < ls_size; k++){ Vec3f lightPosition = lightSources[k].getPosition(); //loop on triangles of the mesh for(unsigned int i = 0; i < mesh_size; i++){ Vec3f origin = mesh.positions()[i]; Vec3f direction = lightPosition - origin; Ray ray(origin + direction * 0.00001f, direction); if( ray.isIntersected(mesh, big_bvh) ){ colorResponses[i][3] = 0.0f; }else{ colorResponses[i][3] = 1.0f; } } } } void init (const char * modelFilename) { glewExperimental = GL_TRUE; glewInit (); // init glew, which takes in charges the modern OpenGL calls (v>1.2, shaders, etc) glCullFace (GL_BACK); // Specifies the faces to cull (here the ones pointing away from the camera) glEnable (GL_CULL_FACE); // Enables face culling (based on the orientation defined by the CW/CCW enumeration). glDepthFunc (GL_LESS); // Specify the depth test for the z-buffer glEnable (GL_DEPTH_TEST); // Enable the z-buffer in the rasterization glEnableClientState (GL_VERTEX_ARRAY); glEnableClientState (GL_NORMAL_ARRAY); glEnableClientState (GL_COLOR_ARRAY); glEnable (GL_NORMALIZE); glLineWidth (2.0); // Set the width of edges in GL_LINE polygon mode glClearColor (0.0f, 0.0f, 0.0f, 1.0f); // Background color mesh.loadOFF (modelFilename); if(renderMode) addPlane(mesh); //adds a plane colorResponses.resize (mesh.positions().size()); camera.resize (DEFAULT_SCREENWIDTH, DEFAULT_SCREENHEIGHT); try { glProgram = GLProgram::genVFProgram ("Simple GL Program", "shader.vert", "shader.frag"); // Load and compile pair of shaders toonProgram = GLProgram::genVFProgram ("Cartoon GL Program", "shader_cartoon.vert", "shader_cartoon.frag"); toon_outlines_Program = GLProgram::genVFProgram ("Outline GL Program", "shader_outline_cartoon.vert", "shader_outline_cartoon.frag"); bvhProgram = GLProgram::genVFProgram ("BVH GL Program", "shader_bvh.vert", "shader_bvh.frag"); glProgram->use (); // Activate the shader program } catch (Exception & e) { cerr << e.msg () << endl; } unsigned int deep_count1 = 0; big_bvh = BVH::buildBVH( mesh.triangles(), mesh, deep_count1); cout << "BVH has been built." << '\n'; cout << "deep_count of BVH is " << BVH::deep_count << '\n'; /* if(octreeMode == true){ vector<unsigned int> ind(mesh.positions().size()); for(unsigned int k = 0; k < mesh.positions().size(); k++){ ind[k] = k; } float max_float = numeric_limits<float>::max(); float min_float = - ( numeric_limits<float>::max() - 1); Vec3f max_point = Vec3f(min_float, min_float, min_float); Vec3f min_point = Vec3f(max_float, max_float, max_float); getMinMax(min_point, max_point, mesh); octreeRoot = OctreeNode::buildOctree(min_point, max_point, ind, mesh); }*/ //8 light sources maximum lightSources.resize(8); lightSources[0] = LightSource(Vec3f(0.0f, 0.0f, 5.0f), Vec3f(4.0f, 2.0f, 3.0f)); lightSources[0].activeLightSource(); //lightSources[1] = LightSource(Vec3f(1.0f, 1.0f, 1.0f), Vec3f(1.0f, 0.9f, 0.8f)); //lightSources[1].activeLightSource(); //lightSources[2] = LightSource(Vec3f(-2.0f, -1.0f, -1.0f), Vec3f(1.0f, 0.8f, 1.0f)); //lightSources[2].activeLightSource(); if(renderShadowOnlyInInit == true && renderMode == true){ if(perVertexAO == true) computePerVertexAO(nb_samples_AO, radius_AO, mesh); if(perVertexShadow == true) computePerVertexShadow(mesh); } } /* float G1Schlick(Vec3f w, Vec3f n){ float k = alpha * sqrt(2.0f / M_PI); return dot(n, w) / (dot(n, w) * (1 - k) + k); } float G1Smith(Vec3f w, float alpha2, Vec3f n){ return 2 * dot(n, w) / (dot(n, w) + sqrt(alpha2 + (1 - alpha2) * pow(dot(n, w), 2))); } float microFacetFs(Vec3f n, Vec3f wi, Vec3f wo, Vec3f wh){ float nwh2 = pow(dot(n, wh), 2); float F = F0 + (1 - F0) * pow(1 - max(0.0f, dot(wi, wh)), 5); if(ggx == false){ //Cook-Torrance micro facet mode float alpha2 = pow(alpha, 2); float D = exp((nwh2 - 1.0f) / (alpha2 * nwh2)) / (pow(nwh2, 2) * alpha2 * M_PI); float shading = 2 * (dot(n, wh) * dot(n, wi)) / dot(wo, wh); float masking = 2 * (dot(n, wh) * dot(n, wo)) / dot(wo, wh); float G = min(1.0f, min(shading, masking)); return (D * F * G) / (4 * dot(n, wi) * dot(n, wo)); }else{ //GGX micro facet mode float alphap = alpha; float alphap2 = pow(alphap, 2); float alpha2 = pow(alpha, 2); float D = alphap2 / (M_PI * pow(1.0f + (alphap2 - 1) * nwh2, 2)); float G; if(schlick == false) G = G1Smith(wi, alpha2, n) * G1Smith(wo, alpha2, n); else G = G1Schlick(wi, n) * G1Schlick(wo, n); //approximation of Schlick return (D * F * G) / (4 * dot(n, wi) * dot(n, wo)); } } // the following color response shall be replaced with a proper reflectance evaluation/shadow test/etc. // This function is not compatible with shadow mode void updatePerVertexColorResponse () { for (unsigned int i = 0; i < colorResponses.size (); i++){ colorResponses[i] = Vec3f (0.f, 0.f, 0.f); for(unsigned int lightIndex = 0; lightIndex < lightSources.size(); lightIndex++){ if(lightSources[lightIndex].isActive()){ LightSource lighSource = lightSources[lightIndex]; Vec3f x = mesh.positions()[i]; //coordinates of this vertex Vec3f n = mesh.normals()[i]; //normal vector of this vertex Vec3f cameraPosition; camera.getPos(cameraPosition); Vec3f wo = (cameraPosition - x); wo.normalize(); Vec3f wi = (lighSource.getPosition() - x); wi.normalize(); Vec3f Li = lighSource.getColor(); Vec3f wh = (wi + wo); wh.normalize(); //half vector float fs; if(microFacet == false) fs = ks * pow(dot(n, wh), s); //Blinn-Phong BRDF (specular) else fs = microFacetFs(n, wi, wo, wh); //Micro facet Cook-Torrance BRDF (specular) float f = fd + fs; float d = (lighSource.getPosition() - x).length(); //distance between the vertex x and the light source float attenuation = 1 / (ac + al * d + aq * d * d); colorResponses[i] += Li * f * max(dot(n, wi), 0.0f) * attenuation; } } } } */ void renderScene () { //updatePerVertexColorResponse (); GLfloat lightPos[3 * 8]; GLfloat lightCol[3 * 8]; GLint nb_light_active = 0; for(unsigned int i = 0; i < 8; i++){ LightSource lightSource = lightSources[i]; if(lightSource.isActive() == true){ lightPos[3 * i + 0] = lightSource.getPosition()[0]; lightPos[3 * i + 1] = lightSource.getPosition()[1]; lightPos[3 * i + 2] = lightSource.getPosition()[2]; lightCol[3 * i + 0] = lightSource.getColor()[0]; lightCol[3 * i + 1] = lightSource.getColor()[1]; lightCol[3 * i + 2] = lightSource.getColor()[2]; nb_light_active++; } } if( cartoon_mode == false ){ glProgram->use (); GLint variableLocationPos = glProgram->getUniformLocation("lightPositions"); GLint variableLocationCol = glProgram->getUniformLocation("lightColors"); glUniform3fv (variableLocationPos, nb_light_active, lightPos); glUniform3fv (variableLocationCol, nb_light_active, lightCol); glProgram->setUniform1i("numberOfLightActive", nb_light_active); //glProgram->setUniform1f("ac", ac); //glProgram->setUniform1f("al", al); //glProgram->setUniform1f("aq", aq); //glProgram->setUniform1f("ks", ks); //glProgram->setUniform1f("fd", fd); //glProgram->setUniform1f("s", s); glProgram->setUniform1f("alpha", alpha); glProgram->setUniform1f("F0", F0); glProgram->setUniform1i("microFacet", microFacet); glProgram->setUniform1i("ggx", ggx); glProgram->setUniform1i("schlick", schlick); glProgram->setUniform1i("perVertexShadow", perVertexShadow); glProgram->setUniform1i("perVertexAO", perVertexAO); glProgram->setUniform1i("renderMode", renderMode); }else{ glCullFace (GL_FRONT); toon_outlines_Program->use(); glVertexPointer (3, GL_FLOAT, sizeof (Vec3f), (GLvoid*)(&(mesh.positions()[0]))); glNormalPointer (GL_FLOAT, 3*sizeof (float), (GLvoid*)&(mesh.normals()[0])); glColorPointer (4, GL_FLOAT, sizeof (Vec4f), (GLvoid*)(&(colorResponses[0]))); glDrawElements (GL_TRIANGLES, 3*mesh.triangles().size(), GL_UNSIGNED_INT, (GLvoid*)((&mesh.triangles()[0]))); glCullFace (GL_BACK); toonProgram->use(); GLint variableLocationPos = toonProgram->getUniformLocation("lightPositions"); glUniform3fv (variableLocationPos, nb_light_active, lightPos); toonProgram->setUniform1i("numberOfLightActive", nb_light_active); toonProgram->setUniform1i("perVertexShadow", perVertexShadow); toonProgram->setUniform1i("perVertexAO", perVertexAO); } if(renderShadowOnlyInInit == false){ if(perVertexShadow == true) computePerVertexShadow(mesh); } colorResponses.resize(4 * mesh.positions().size()); glVertexPointer (3, GL_FLOAT, sizeof (Vec3f), (GLvoid*)(&(mesh.positions()[0]))); glNormalPointer (GL_FLOAT, 3*sizeof (float), (GLvoid*)&(mesh.normals()[0])); glColorPointer (4, GL_FLOAT, sizeof (Vec4f), (GLvoid*)(&(colorResponses[0]))); glDrawElements (GL_TRIANGLES, 3*mesh.triangles().size(), GL_UNSIGNED_INT, (GLvoid*)((&mesh.triangles()[0]))); bvhProgram->use(); glVertexPointer (3, GL_FLOAT, sizeof (Vec3f), (GLvoid*)(&(BVH::bvh_positions[0]))); glDrawElements (GL_LINES, BVH::bvh_indices.size(), GL_UNSIGNED_INT, (GLvoid*)((&BVH::bvh_indices[0]))); } void reshape(int w, int h) { camera.resize (w, h); } void display () { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera.apply (); renderScene (); glFlush (); glutSwapBuffers (); } void key (unsigned char keyPressed, int x, int y) { switch (keyPressed) { case 'f': if (fullScreen) { glutReshapeWindow (camera.getScreenWidth (), camera.getScreenHeight ()); fullScreen = false; } else { glutFullScreen (); fullScreen = true; } break; case 'q': case 27: exit (0); break; case 'w': GLint mode[2]; glGetIntegerv (GL_POLYGON_MODE, mode); glPolygonMode (GL_FRONT_AND_BACK, mode[1] == GL_FILL ? GL_LINE : GL_FILL); break; break; case 'c': microFacet = false; glProgram->setUniform1i("microFacet", microFacet); break; case 'v': microFacet = true; ggx = false; glProgram->setUniform1i("microFacet", microFacet); glProgram->setUniform1i("ggx", ggx); break; case 'b': microFacet = true; ggx = true; schlick = false; glProgram->setUniform1i("microFacet", microFacet); glProgram->setUniform1i("ggx", ggx); glProgram->setUniform1i("schlick", schlick); break; case 'n': microFacet = true; ggx = true; schlick = true; glProgram->setUniform1i("microFacet", microFacet); glProgram->setUniform1i("ggx", ggx); glProgram->setUniform1i("schlick", schlick); break; //roughness case 'j': alpha = min((alpha + alphaSpeed), 1.0f); glProgram->setUniform1f("alpha", alpha); break; case 'k': alpha = max((alpha - alphaSpeed), alphaSpeed); glProgram->setUniform1f("alpha", alpha); break; //Fresnel refraction index, dependent on material case 'y': F0 = min((F0 + F0Speed), 1.0f); glProgram->setUniform1f("F0", F0); break; case 'u': F0 = max((F0 - F0Speed), 0.0f); glProgram->setUniform1f("F0", F0); break; case 's': perVertexShadow = ! perVertexShadow; break; case 'o': perVertexAO = ! perVertexAO; break; case 't': cartoon_mode = ! cartoon_mode; break; case 'l': if( currentDeep <= BVH::deep_count ){ currentDeep++; big_bvh->drawBVH(currentDeep); } break; case 'm': if( currentDeep > 0 ){ currentDeep--; big_bvh->drawBVH(currentDeep); } break; case 48: //0 mesh.reloadOFF (); if(renderMode) addPlane(mesh); //adds a plane break; case 49: //1 mesh.topologicalLaplacianFilter(0.1f); break; case 50: //2 mesh.topologicalLaplacianFilter(0.5f); break; case 51: // 3 mesh.topologicalLaplacianFilter(1.0f); break; case 52: //4 mesh.geometricLaplacianFilter(0.1f); break; case 53: //5 mesh.geometricLaplacianFilter(0.5f); break; case 54: //6 mesh.geometricLaplacianFilter(1.0f); break; case 55: //7 mesh.simplify(16); break; case 56: //8 mesh.simplify(32); break; case 57: //9 mesh.simplify(64); break; case 'g': mesh.subdivide(); break; case 'a': mesh.simplifyAdaptiveMesh(5); break; case 'z': mesh.simplifyAdaptiveMesh(20); break; default: printUsage (); break; } } void specialKey(GLint key, GLint x, GLint y){ switch (key) { case GLUT_KEY_UP: break; case GLUT_KEY_DOWN: break; case GLUT_KEY_LEFT: break; case GLUT_KEY_RIGHT: break; default: break; } } void mouse (int button, int state, int x, int y) { camera.handleMouseClickEvent (button, state, x, y); } void motion (int x, int y) { camera.handleMouseMoveEvent (x, y); } void idle () { static float lastTime = glutGet ((GLenum)GLUT_ELAPSED_TIME); static unsigned int counter = 0; counter++; float currentTime = glutGet ((GLenum)GLUT_ELAPSED_TIME); if (currentTime - lastTime >= 1000.0f) { FPS = counter; counter = 0; static char winTitle [128]; unsigned int numOfTriangles = mesh.triangles ().size (); sprintf (winTitle, "Number Of Triangles: %d - FPS: %d", numOfTriangles, FPS); string title = appTitle + " - By " + myName + " - " + winTitle; glutSetWindowTitle (title.c_str ()); lastTime = currentTime; } glutPostRedisplay (); } int main (int argc, char ** argv) { if (argc > 2) { printUsage (); exit (1); } glutInit (&argc, argv); glutInitDisplayMode (GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize (DEFAULT_SCREENWIDTH, DEFAULT_SCREENHEIGHT); window = glutCreateWindow (appTitle.c_str ()); init (argc == 2 ? argv[1] : DEFAULT_MESH_FILE.c_str ()); glutIdleFunc (idle); glutReshapeFunc (reshape); glutDisplayFunc (display); glutKeyboardFunc (key); glutSpecialFunc(specialKey); glutMotionFunc (motion); glutMouseFunc (mouse); printUsage (); glutMainLoop (); return 0; }
07e55745eed6b0ca4ca8971facb3fb0c9d091822
6158ef4be6194f49de72f43c65493482d92cc35b
/src/core/cart/MapperList.h
42618344369174cb353ae850bbcf77ff5bf2aae2
[]
no_license
WesUnwin/nes-emulator
b47edc4cca9b3e93ab0038ad9fa52c41581cd315
7bf81f4a5d37e2224a64f18d02b691cd9e4a008f
refs/heads/master
2021-09-07T19:51:23.318475
2018-02-28T04:59:07
2018-02-28T04:59:07
100,424,032
0
0
null
null
null
null
UTF-8
C++
false
false
343
h
MapperList.h
#ifndef CART_MAPPERLIST_H #define CART_MAPPERLIST_H #include "iNesRom.h" #include "iNesFileFormatException.h" #include "CartMapper.h" #include "Mapper0.h" #include "Mapper1.h" class MapperList { public: MapperList(); ~MapperList(); static CartMapper* constructMapper(int iNesMapperNum, iNesRom* rom); }; #endif
1b0b4f12dbe65410c280e7fefe71f9b307beea9e
0e989193660bc9ccb2c50cb69deccfe2ba54b6ad
/src/main.cpp
f7838cd4a4b605e2a7b48754f6e0b009e7d7a421
[ "Apache-2.0" ]
permissive
buffetboy2001/cppmanifest
d513f0c07578f2e3a6dffd91236e352210081675
4edfca713deebc53c7c0281fa09e524fe8c3758f
refs/heads/master
2021-01-20T20:14:40.526446
2017-09-14T01:22:24
2017-09-14T01:22:24
61,448,090
0
1
Apache-2.0
2018-02-20T14:37:57
2016-06-18T18:55:19
CMake
UTF-8
C++
false
false
1,177
cpp
main.cpp
// // Created by Stuart to test cppmanifest. This is NOT needed to use cppmanifest! // #include "include/cppmanifest.h" using namespace std; int main(int argc, char* argv[]) { cout << "Starting logging" << endl; cout << "Build version: " << cppmanifest::getVersion() << endl; cout << "Created-by: " << cppmanifest::getUserName() << endl; cout << "Created-on: " << cppmanifest::getBuildTimeStamp() << endl; cout << "Built with GCC version: " << cppmanifest::getBuildCompilerVersion() << endl; cout << "Built on system name: " << cppmanifest::getBuildSystemName() << endl; cout << "Built on system processor: " << cppmanifest::getBuildSystemProcessor() << endl; cout << "Built with system ver: " << cppmanifest::getBuildSystemVersion() << endl; cout << "Built with system ver: " << cppmanifest::getBuildHostName() << endl; cout << "Built from git branch: " << cppmanifest::getGitBranch() << endl; if (cppmanifest::getGitIsClean()) cout << "Built from git hash: " << cppmanifest::getGitHash() << endl; else cout << "Built from git hash: " << cppmanifest::getGitHash() << "-DIRTY" << endl; }
b8082614f9230e2bf9e74f92696af9d9088238f3
d67b2232d540f7f9ec26519f7c01dc860225d99f
/Data Structure/Day7/PracticeForxm/Tree.cpp
8a748a239a2a3964169cff97691d11f989196918
[]
no_license
lalit47/Codes
b5b33ee626041218f8c5d75975985f6c55096931
9018bdbf524d58a4e8b758f12b7682eaf603a64c
refs/heads/master
2022-09-20T08:34:51.123267
2020-05-25T02:49:28
2020-05-25T02:49:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
843
cpp
Tree.cpp
#include<iostream> using namespace std; struct tree { int data; struct tree *left; struct tree *right; }; void traversal1(tree *root) { if (root != NULL ) { traversal1(root->left); cout<<root->data<<" "; traversal1(root->right); } } int main() { struct tree *t1=new tree(); t1->data=100; t1->left=NULL; t1->right=NULL; struct tree *t2=new tree(); t2->data=90; t2->left=NULL; t2->right=NULL; t1->left=t2; struct tree *t3=new tree(); t3->data=180; t3->left=NULL; t3->right=NULL; t1->right=t3; struct tree *t4=new tree(); t4->data=95; t4->left=NULL; t4->right=NULL; t2->right=t4; struct tree *t5=new tree(); t5->data=160; t5->left=NULL; t5->right=NULL; t3->right=t5; struct tree *t6=new tree(); t6->data=750; t6->left=NULL; t6->right=NULL; t3->right=t6; traversal1(t1); return 0; }
ce9056a038ee0b8d7b8de2910ba6cb3165efda78
58cb3bda08b4b1a6c3440edd48866317b1a95f5a
/src/gui/controllerwidget.cpp
53a747a01d62e2f919ffe3a55fdf2a454525fce5
[]
no_license
lutris/virtualjaguar
1adff5064b572366e5963d3eeb4dc44df31a3dde
1b6d726df3245de60106274cd8b607c35fc5ed3d
refs/heads/master
2020-05-20T09:40:25.614504
2014-04-14T21:10:22
2014-04-14T21:10:22
14,670,731
3
2
null
null
null
null
UTF-8
C++
false
false
7,197
cpp
controllerwidget.cpp
// // controllerwidget.cpp: A widget for changing "Controller" configuration // // Part of the Virtual Jaguar Project // (C) 2011 Underground Software // See the README and GPLv3 files for licensing and warranty information // // JLH = James Hammons <jlhamm@acm.org> // // WHO WHEN WHAT // --- ---------- ------------------------------------------------------------ // JLH 07/20/2011 Created this file // #include "controllerwidget.h" #include "joystick.h" #include "gamepad.h" #include "keygrabber.h" // These tables are used to convert Qt keycodes into human readable form. Note that // a lot of these are just filler. char ControllerWidget::keyName1[96][16] = { "Space", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "$61", "$62", "$63", "$64", "$65", "$66", "$67", "$68", "$69", "$6A", "$6B", "$6C", "$6D", "$6E", "$6F", "$70", "$71", "$72", "$73", "$74", "$75", "$76", "$77", "$78", "$79", "$7A", "{", "|", "}", "~" }; char ControllerWidget::keyName2[64][16] = { "Esc", "Tab", "BTab", "BS", "Ret", "Ent", "Ins", "Del", "Pause", "Prt", "SRq", "Clr", "$C", "$D", "$E", "$F", "Hm", "End", "Lf", "Up", "Rt", "Dn", "PgU", "PgD", "$18", "$19", "$1A", "$1B", "$1C", "$1D", "$1E", "$1F", "Shf", "Ctl", "Mta", "Alt", "Cap", "Num", "ScL", "$27", "$28", "$29", "$2A", "$2B", "$2C", "$2D", "$2E", "$2F", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16" }; char ControllerWidget::hatName[4][16] = { "Up", "Rt", "Dn", "Lf" }; char ControllerWidget::axisName[2][8] = { "+", "-" }; // This is hard-coded crap. It's crap-tastic! // These are the positions to draw the button names at, ordered by the BUTTON_* sequence // found in joystick.h. int ControllerWidget::buttonPos[21][2] = { { 74, 32 }, { 71, 67 }, { 53, 49 }, { 93, 49 }, { 110, 200 }, { 110, 175 }, { 110, 151 }, { 110, 126 }, { 148, 200 }, { 148, 175 }, { 148, 151 }, { 148, 126 }, { 186, 200 }, { 186, 175 }, { 186, 151 }, { 186, 126 }, { 234, 31 }, { 216, 51 }, { 199, 71 }, { 164-11, 101-30 }, { 141-11, 108+13-30 } }; ControllerWidget::ControllerWidget(QWidget * parent/*= 0*/): QWidget(parent), controllerPic(":/res/controller.png"), widgetSize(controllerPic.size()), keyToHighlight(-1), mouseDown(false) { // Seems we have to pad this stuff, otherwise it clips on the right side widgetSize += QSize(4, 4); // We want to know when the mouse is moving over our widget... setMouseTracking(true); //nope //setFixedSize(widgetSize); } ControllerWidget::~ControllerWidget() { } QSize ControllerWidget::sizeHint(void) const { return widgetSize; } QSizePolicy ControllerWidget::sizePolicy(void) const { return QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } void ControllerWidget::paintEvent(QPaintEvent * /*event*/) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.drawImage(QPoint(0, 0), controllerPic); // Bump up the size of the default font... QFont font = painter.font(); font.setPixelSize(15); font.setBold(true); painter.setFont(font); // painter.setPen(QColor(48, 255, 255, 255)); // This is R,G,B,A painter.setPen(QColor(0, 0, 0, 255)); // This is R,G,B,A painter.setBrush(QBrush(QColor(48, 255, 255, 255))); // First, draw black oversize line, then dot, then colored line QPen blackPen(QColor(0, 0, 0, 255)); blackPen.setWidth(4); QPen colorPen(QColor(48, 255, 255, 255)); colorPen.setWidth(2); QLine line(QPoint(141-11, 100-30), QPoint(141-11, 108+5-30)); painter.setPen(blackPen); painter.drawLine(line); blackPen.setWidth(1); painter.setPen(blackPen); painter.drawEllipse(QPoint(141-11, 100-30), 4, 4); painter.setPen(colorPen); painter.drawLine(line); for(int i=BUTTON_FIRST; i<=BUTTON_LAST; i++) { if (keyToHighlight == i) { painter.setPen(QColor(255, 48, 255, 255)); // This is R,G,B,A font.setPixelSize(mouseDown ? 15 : 18); painter.setFont(font); } else { painter.setPen(QColor(48, 255, 255, 255)); // This is R,G,B,A font.setPixelSize(15); painter.setFont(font); } if (keys[i] < 0x80) DrawBorderedText(painter, buttonPos[i][0], buttonPos[i][1], QString(keyName1[keys[i] - 0x20])); else if ((keys[i] & 0xFFFFFF00) == 0x01000000) { DrawBorderedText(painter, buttonPos[i][0], buttonPos[i][1], QString(keyName2[keys[i] & 0x3F])); } #if 1 else if (keys[i] & JOY_BUTTON) { DrawBorderedText(painter, buttonPos[i][0], buttonPos[i][1], QString("JB%1").arg(keys[i] & JOY_BUTTON_MASK)); } else if (keys[i] & JOY_HAT) { DrawBorderedText(painter, buttonPos[i][0], buttonPos[i][1], QString("j%1").arg(hatName[keys[i] & JOY_BUTTON_MASK])); } else if (keys[i] & JOY_AXIS) { DrawBorderedText(painter, buttonPos[i][0], buttonPos[i][1], QString("JA%1%2").arg((keys[i] & JOY_AXISNUM_MASK) >> 1).arg(axisName[keys[i] & JOY_AXISDIR_MASK])); } #endif else DrawBorderedText(painter, buttonPos[i][0], buttonPos[i][1], QString("???")); } } void ControllerWidget::mousePressEvent(QMouseEvent * /*event*/) { mouseDown = true; update(); } void ControllerWidget::mouseReleaseEvent(QMouseEvent * /*event*/) { mouseDown = false; // Spawning the keygrabber causes leaveEvent() to be called, so we need to save this int keyToHighlightSave = keyToHighlight; KeyGrabber keyGrab(this); keyGrab.SetKeyText(keyToHighlightSave); keyGrab.exec(); int key = keyGrab.key; if (key != Qt::Key_Escape) { keys[keyToHighlightSave] = key; emit(KeyDefined(keyToHighlightSave, key)); } keyToHighlight = keyToHighlightSave; update(); } void ControllerWidget::mouseMoveEvent(QMouseEvent * event) { if (mouseDown) return; // Save the current closest item int keyToHighlightOld = keyToHighlight; // Set up closest distance (this should be large enough) double closest = 1e9; for(int i=BUTTON_FIRST; i<=BUTTON_LAST; i++) { // We loop through the button text positions, to see which one is closest. double distX = (double)(event->x() - buttonPos[i][0]); double distY = (double)(event->y() - buttonPos[i][1]); double currentDistance = sqrt((distX * distX) + (distY * distY)); if (currentDistance < closest) { closest = currentDistance; keyToHighlight = i; } } if (keyToHighlightOld != keyToHighlight) update(); } void ControllerWidget::leaveEvent(QEvent * /*event*/) { keyToHighlight = -1; update(); } void ControllerWidget::DrawBorderedText(QPainter & painter, int x, int y, QString text) { // Text is drawn centered at (x, y) as well, using a bounding rect for the purpose. QRect rect(0, 0, 60, 30); QPen oldPen = painter.pen(); painter.setPen(QColor(0, 0, 0, 255)); // This is R,G,B,A for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++) { rect.moveCenter(QPoint(x + i, y + j)); painter.drawText(rect, Qt::AlignCenter, text); } } painter.setPen(oldPen); rect.moveCenter(QPoint(x, y)); painter.drawText(rect, Qt::AlignCenter, text); }
420dee997aced72b77deffed681d9da0c99cc857
c7f3db94cc3d69cd9a2ae24aa3c69cd767b28672
/must_rma/src/externals/typeart/lib/passes/instrumentation/InstrumentationHelper.cpp
1f329f0ba01d1f5af9f63d4a10a27e974f68e94f
[ "BSD-3-Clause" ]
permissive
RWTH-HPC/must-rma-correctness22-supplemental
10683ff20339098a45a35301dbee6b31d74efaec
04cb9fe5f0dcb05ea67880209accf19c5e0dda25
refs/heads/main
2023-04-14T20:48:36.684589
2022-08-10T20:28:43
2022-11-18T03:33:05
523,105,966
0
0
null
null
null
null
UTF-8
C++
false
false
2,229
cpp
InstrumentationHelper.cpp
// TypeART library // // Copyright (c) 2017-2022 TypeART Authors // Distributed under the BSD 3-Clause license. // (See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/BSD-3-Clause) // // Project home: https://github.com/tudasc/TypeART // // SPDX-License-Identifier: BSD-3-Clause // #include "InstrumentationHelper.h" #include "support/Logger.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #include "llvm/Support/Casting.h" namespace typeart { using namespace llvm; InstrumentationHelper::InstrumentationHelper() = default; InstrumentationHelper::~InstrumentationHelper() = default; llvm::SmallVector<llvm::Type*, 8> InstrumentationHelper::make_signature(const llvm::ArrayRef<llvm::Value*>& args) { llvm::SmallVector<llvm::Type*, 8> types; for (auto* val : args) { types.push_back(val->getType()); } return types; } llvm::Type* InstrumentationHelper::getTypeFor(IType id) { auto& c = module->getContext(); switch (id) { case IType::ptr: return Type::getInt8PtrTy(c); case IType::function_id: return Type::getInt32Ty(c); case IType::extent: return Type::getInt64Ty(c); case IType::type_id: [[fallthrough]]; case IType::alloca_id: return Type::getInt32Ty(c); case IType::stack_count: return Type::getInt32Ty(c); default: LOG_WARNING("Unknown IType selected."); return nullptr; } } llvm::ConstantInt* InstrumentationHelper::getConstantFor(IType id, size_t value) { const auto make_int = [&]() -> Optional<ConstantInt*> { auto itype = dyn_cast_or_null<IntegerType>(getTypeFor(id)); if (itype == nullptr) { LOG_FATAL("Pointer for the constant type is null, need aborting..."); return None; } return ConstantInt::get(itype, value); }; return make_int().getValue(); } void InstrumentationHelper::setModule(llvm::Module& m) { module = &m; } llvm::Module* InstrumentationHelper::getModule() const { return module; } } // namespace typeart
6b15ed5f2005a3af5ab6ef946a783e761c537ae0
65e7c147e50a1ae17269c73c79bf885e3f9b1e30
/TribesAscendSDK/HeaderDump/UTGame.UTSkelControl_SpinControl.h
05e52b8fa8f6a0b4a9aea3ba2fbd8d69c800307f
[]
no_license
indiecore/TASDK
05134d7722c941f8e69bbe5bd20616dcc31dd9d5
b1e7061f0e3695e74cd1bf94b6be38b287f2f2ba
refs/heads/master
2020-12-25T03:39:55.801138
2013-07-31T13:36:10
2013-07-31T13:36:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
164
h
UTGame.UTSkelControl_SpinControl.h
#pragma once #include "UDKBase.UDKSkelControl_SpinControl.h" namespace UnrealScript { class UTSkelControl_SpinControl : public UDKSkelControl_SpinControl { }; }
8ce1e6f68bfe755e24596bb7d0a50446f5a3a99e
28f4fb78ba6a1635b23201efa21e891fb8683e32
/mudduinodemo/mudduinodemo.ino
efac01453f961e04b8a771c2af6c7dc1e3635b08
[]
no_license
adobke/e11
bbf1484f50e983b75fd6b06c140964d400252cc9
92d8058f153290a7ce873ba04d2de5fff7a6532d
refs/heads/master
2020-04-15T12:14:15.132960
2013-11-04T02:21:58
2013-11-04T02:21:58
6,399,569
0
0
null
null
null
null
UTF-8
C++
false
false
7,429
ino
mudduinodemo.ino
#define leftneg 9 #define leftpos 8 #define leftenable 6 #define rightneg 7 #define rightpos 12 #define rightenable 11 #define maxCorrThres 21 // threshold for determining if detected sequence is the gold code. const boolean PT = true; //false pushes yellow #define looplen 217 // 31 * 7 One big array for all our values #define LEN 31 int GCLED = 5; int REFLECT_PIN = A4; // for gc detection int PHOTO_PIN = A5; // for gc detection const long LOOP_TIME = 250; // number of microseconds per loop //int DIST_PIN_FRONT = 0; //int DIST_PIN_SIDE = 3; int raw_distance_front = 0; int raw_distance_side = 0; int gc1[31] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1}; int gc2[31] = { 1,1,0,0,0,1,1,1,1,1,1,1,0,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0}; int gc3[31] = { 0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,1,1,0,1,0,1,0,1,1,1,0}; int gc4[31] = { 1,0,1,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1,0,0,0,0,1,1,1,0,1}; int gc5[31] = { 0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,1}; int gc6[31] = { 1,1,1,0,0,0,1,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0}; int gc7[31] = { 0,1,1,0,0,1,1,0,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,0,1,1,1,1,0,1,0}; int gc8[31] = { 1,0,0,1,0,1,1,1,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1}; void setup() { pinMode(leftneg, OUTPUT); pinMode(leftpos, OUTPUT); pinMode(leftenable, OUTPUT); pinMode(rightneg, OUTPUT); pinMode(rightpos, OUTPUT); pinMode(rightenable, OUTPUT); pinMode(GCLED,OUTPUT); pinMode(PHOTO_PIN,INPUT); pinMode(REFLECT_PIN,INPUT); // pinMode(DIST_PIN_FRONT, INPUT); // pinMode(DIST_PIN_SIDE, INPUT); //pinMode(6,OUTPUT); pinMode(2,OUTPUT); Serial.begin(115200); Serial.println("Hi there!!!!"); } int gcnum=0; void loop() { int magic = 500; int reflect = analogRead(REFLECT_PIN); Serial.println(reflect); if (reflect > magic + 50) go(35,125); else if (reflect < magic - 50) go(125,35); else go(125,125); // while(true) // { // //go(-255,255); // // //raw_distance_front = analogRead(DIST_PIN_FRONT); // //raw_distance_side = analogRead(DIST_PIN_SIDE); // // // analogWrite(10,150); // // int gcnum = goldcode(); //get the number of the beacon seen. Serial.println("gc found: " + gcnum); // Serial.println(gcnum); // int test = analogRead( PHOTO_PIN ); // Serial.println(test ); // delay(10); if (gcnum>0) { digitalWrite(GCLED,HIGH); press(); //delay(10); } else { digitalWrite(GCLED,LOW); delay(50); } // delay(50); // ///* // Serial.println(raw_distance_front); // Serial.println("^"); // Serial.println(raw_distance_side); // if (raw_distance_front<450) // { // digitalWrite(GCLED,HIGH); // if (raw_distance_side>500) // { // digitalWrite(6,HIGH); // go(150,255); // delay(10); // } // else if (raw_distance_side>450) // { // digitalWrite(6,LOW); // go(255,255); // delay(10); // } // else // { // digitalWrite(6,HIGH); // go(255,150); // delay(10); // } // } // else // { // digitalWrite(GCLED,LOW); // go(-100,255); // delay(10); // } // // // if( digitalRead(7) ) // { // go(200,-200); // } // else // { // go(-200,200); // } //*/ // } } void cheer() { go(0,0); } void press() { go(125,0); delay(1400); go(-125,0); delay(1000); } // GOLD CODE STUFF void wrap_dest(int A[], int ALEN) // Shift an array to the left and wrap around { int a0 = A[ALEN-1]; for(int i = (ALEN-1); i> 0; i--) { A[i]=A[i-1]; } A[0]=a0; } int correlate( int A[], int B[], int ALEN) // Correlate two codes 31 or -31 is best { int score=0; for(int i = 0; i<ALEN; i++) { if(A[i]==B[i]) { score++; } else { score--; } } return score; } int correlateGoldCodes( int GC1[], int GC2[], int ALEN) //returns the max correlation { int maxcorr = 0; for(int i = 0;i<ALEN;i++) { int corr = correlate(GC1,GC2,ALEN); if (abs(corr) > abs(maxcorr)) // We want to detect ~-31 or ~31 { maxcorr=corr; } wrap_dest(GC2,ALEN); } return maxcorr; } void binaryize(int ledInput[]) //Find average value. Change all values in array to { // 1 if higher, 0 if lower long average=0; for(int i = 0; i < looplen; i++) { average += ledInput[i]; } average = average / looplen; for(int i = 0; i < looplen; i++) { if(ledInput[i]<average) { ledInput[i]=1; } else { ledInput[i]=0; } } } void averagize(int ledInput[]) // Takes the 31 by 7 array and average the columns { int average=0; for(int i = 0; i < LEN; i++) { average = 0; for(int n = 0; n < 7; n++) { average += ledInput[i + 31*n]; } if(average>4) { ledInput[i]=1; } else { ledInput[i]=0; } } } boolean checkcorr(int ledInput[],int gc[]) //Check if given code is detected { int maxcorr = correlateGoldCodes(ledInput,gc,31); if (abs(maxcorr)>=maxCorrThres) { if(PT&&(maxcorr>0)) //If maxcorr is positive and above threshold then we see a blue beacon { return true; } if(!PT&&(maxcorr<0)) // If corr is negative then we see a yellow beacon { return true; } return false; } else { // Serial.println(" This is probably not the gold code :("); return false; } } int goldcode() { long curr_time = 0; // the current time // the next time we want to take some action... long next_time = micros() + LOOP_TIME; int ledInput[looplen] = { }; int counter = 0; while(true) { curr_time = micros(); // get current time... if (curr_time > next_time) // is it time yet? { next_time = next_time + LOOP_TIME; ledInput[counter++]=analogRead( PHOTO_PIN ); // Serial.println(ledInput[counter-1]); } if(counter==216) break; } if(counter==(216)) { // printArray(ledInput, LEN); // Serial.println(" AA"); binaryize(ledInput); // printArray(ledInput, LEN); averagize(ledInput); // printArray(ledInput, LEN); if (checkcorr(ledInput,gc1)) { // Serial.println(" This is probably the gold code. yay :)"); return 1; } else if(checkcorr(ledInput,gc2)) { // Serial.println(" This is probably not the gold code :("); return 2; } else if(checkcorr(ledInput,gc3)) { // Serial.println(" This is probably not the gold code :("); return 3; } else if(checkcorr(ledInput,gc4)) { // Serial.println(" This is probably not the gold code :("); return 4; } else if(checkcorr(ledInput,gc5)) { // Serial.println(" This is probably not the gold code :("); return 5; } else if(checkcorr(ledInput,gc6)) { // Serial.println(" This is probably not the gold code :("); return 6; } else if(checkcorr(ledInput,gc7)) { // Serial.println(" This is probably not the gold code :("); return 7; } else if(checkcorr(ledInput,gc8)) { // Serial.println(" This is probably not the gold code :("); return 8; } else { return 0; } } }
5f1ea5d5ab1adabd5cb135a3d10b367301de0edf
050c8a810d34fe125aecae582f9adfd0625356c6
/strmatch/main.cpp
2299ad21982ace136f2386b7da04386c5438f567
[]
no_license
georgerapeanu/c-sources
adff7a268121ae8c314e846726267109ba1c62e6
af95d3ce726325dcd18b3d94fe99969006b8e138
refs/heads/master
2022-12-24T22:57:39.526205
2022-12-21T16:05:01
2022-12-21T16:05:01
144,864,608
11
0
null
null
null
null
UTF-8
C++
false
false
917
cpp
main.cpp
#include <cstdio> #include <cstring> #include <vector> using namespace std; FILE *f=fopen("strmatch.in","r"); FILE *g=fopen("strmatch.out","w"); int F[2000005],N,M; char A[2000005]; char B[2000005]; vector<int> V; int nr; int kmp() { F[1]=0; for(int i=2;i<=N;i++) { int k=F[i-1]; while(k&&A[k+1]!=A[i])k=F[k]; if(A[k+1]==A[i])k++; F[i]=k; } int j=0; for(int i=1;i<=M;i++) { while(j&&A[j+1]!=B[i])j=F[j]; if(A[j+1]==B[i])j++; if(j==N) { j=F[j]; nr++; if(nr>1000)continue; V.push_back(i-N); } } return j; } int main() { fgets(A+1,2000005,f);N=strlen(A+1);N-=(A[N]=='\n'); fgets(B+1,2000005,f);M=strlen(B+1);M-=(B[M]=='\n'); kmp(); fprintf(g,"%d\n",nr); for(auto it:V) fprintf(g,"%d ",it); fclose(f); fclose(g); return 0; }
2f25f7ccda7e512dd20c3aa9c24b73f2f08fe4b2
eded0885c3c439f96d31a76bc392039120b70069
/ros_ws/src/robot_soccer/game_control/gamecontroller.cpp
09ededfadea829d34bba806e717bde2099a02459
[]
no_license
snydergo/RobotSoccer_TheFirstOrder
aa7ec38a7ea1bf15a64ba27644c03d3fde5b1de8
92e3f92f77c18ba876adc41802d357deb81032a7
refs/heads/master
2021-01-21T13:17:49.070315
2016-04-29T22:23:13
2016-04-29T22:23:13
49,161,587
3
1
null
2016-04-07T20:06:56
2016-01-06T21:06:22
Python
UTF-8
C++
false
false
9,504
cpp
gamecontroller.cpp
#include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atof */ #include <sstream> #include <iostream> #include <string> #include <fstream> #include <ros/ros.h> #include <robot_soccer/gameparam.h> #include <std_msgs/String.h> using namespace std; std::string parseColor() { string newValue; cin >> newValue; if (newValue != ":") { cout << "### invalid parameter assingment ###" << endl; return ""; } cin >> newValue; if (newValue == "green" || newValue == "blue" || newValue == "purple" || newValue == "red" || newValue == "orange" || newValue == "yellow" || newValue == "pink") { return newValue; } else { cout << "### invalid color ###" << endl; return ""; } } int main(int argc, char** argv) { std::cout << "RUNNING GAME CONTROLLER" << std::endl; ros::init(argc, argv, "game_controller"); ros::NodeHandle n; ros::Publisher gameStatePub = n.advertise<robot_soccer::gameparam>("game_state", 5); ros::Publisher gameCommandPub = n.advertise<std_msgs::String>("game_cmd", 5); bool paramValid = false; bool cmdValid = false; std_msgs::String gameCommand; robot_soccer::gameparam gameParam; ifstream cache; cache.open("src/robot_soccer/game_control/values.txt"); if (cache.is_open()) { cout << "loading cached values" << endl; cache >> gameParam.ally1_color; cache >> gameParam.ally2_color; cache >> gameParam.enemy1_color; cache >> gameParam.enemy2_color; cache >> gameParam.ball_color; cache >> gameParam.field_pos; cache >> gameParam.ally_robot_count; cache >> gameParam.enemy_robot_count; int temp; cache >> temp; gameParam.show_video = (temp != 0); cache.close(); } else { gameParam.ally1_color = string("green"); gameParam.ally2_color = string("purple"); gameParam.enemy1_color = string("orange"); gameParam.enemy2_color = string("blue"); gameParam.ball_color = string("pink"); gameParam.field_pos = string("home"); gameParam.ally_robot_count = 1; gameParam.enemy_robot_count = 0; gameParam.show_video = true; } while (ros::ok()) { paramValid = false; while (!paramValid && !cmdValid) { cout << "Input parameter or command:" << endl; string parameterName; cin >> parameterName; if(parameterName == "help"){ cout << "--- valid (paramter : value) pairs ---" << endl << "ally1_color : green, blue, purple, red, orange, yellow" << endl << "ally2_color : green, blue, purple, red, orange, yellow" << endl << "enemy1_color : green, blue, purple, red, orange, yellow" << endl << "enemy2_color : green, blue, purple, red, orange, yellow" << endl << "ball_color : pink, yellow" << endl << "field_pos : home, away" << endl << "ally_robot_count : [0-2]" << endl << "enemy_robot_count : [0-2]" << endl << "show_video : true, t, false, f"<< endl << endl << "--- valid commands ---" << endl << "stop (stop robot)" << endl << "start (begin AI state machine)" << endl << "mark (move to starting mark)" << endl << "update (force update of latest paramter values)" << endl << endl << "type 'quit' or 'q' to quit" << endl << endl; } else if (parameterName == "ally1_color") { string color = parseColor(); if (color != "") { gameParam.ally1_color = color; paramValid = true; } } else if (parameterName == "ally2_color") { string color = parseColor(); if (color != "") { gameParam.ally2_color = color; paramValid = true; } } else if (parameterName == "enemy1_color") { string color = parseColor(); if (color != "") { gameParam.enemy1_color = color; paramValid = true; } } else if (parameterName == "enemy2_color") { string color = parseColor(); if (color != "") { gameParam.enemy2_color = color; paramValid = true; } } else if (parameterName == "ball_color") { string color = parseColor(); if (color != "") { gameParam.ball_color = color; paramValid = true; } } else if (parameterName == "field_pos") { string pos; cin >> pos; if (pos != ":") { cout << "### invalid assignment operator ###" << endl; continue; } cin >> pos; if (pos == "home" || pos == "away") { gameParam.field_pos = pos; paramValid = true; } } else if (parameterName == "ally_robot_count") { string pos; cin >> pos; if (pos != ":") { cout << "### invalid assignment operator ###" << endl; continue; } cin >> pos; int robotCount; try{ robotCount = stoi(pos); }catch(...){ std::cout << "### invalid robot count ###\n"; continue; } if (robotCount >= 0 && robotCount <= 2) { gameParam.ally_robot_count = robotCount; paramValid = true; } else { std::cout << "### current configuration only supports 0-2 ally robots ###\n"; continue; } } else if (parameterName == "enemy_robot_count") { string pos; cin >> pos; if (pos != ":") { cout << "### invalid assignment operator ###" << endl; continue; } cin >> pos; int robotCount; try{ robotCount = stoi(pos); }catch(...){ std::cout << "### invalid robot count ###\n"; continue; } if (robotCount >= 0 && robotCount <= 2) { gameParam.enemy_robot_count = robotCount; paramValid = true; } else { std::cout << "### current configuration only supports 0-2 enemy robots ###\n"; continue; } } else if (parameterName == "show_video") { string pos; cin >> pos; if (pos != ":") { cout << "### invalid assignment operator ###" << endl; continue; } cin >> pos; if (pos == "true" || pos == "t") { gameParam.show_video = true; paramValid = true; } else if (pos == "false" || pos == "f") { gameParam.show_video = false; paramValid = true; } else { std::cout << "### show_video can only be true or false ###" << endl; continue; } } else if (parameterName == "update" || parameterName == "u") { paramValid = true; } else if (parameterName == "stop") { gameCommand.data = "stop"; cmdValid = true; } else if (parameterName == "start") { gameCommand.data = "start"; cmdValid = true; } else if (parameterName == "mark") { gameCommand.data = "mark"; cmdValid = true; } else if (parameterName == "quit" || parameterName == "q") { return 0; } else { cout << "### Invalid Parameter or Command ###" << endl; } } if (paramValid) { gameStatePub.publish(gameParam); ofstream cache; cache.open("src/robot_soccer/game_control/values.txt"); if (cache.is_open()) { cache << gameParam.ally1_color << "\n"; cache << gameParam.ally2_color.data() << "\n"; cache << gameParam.enemy1_color << "\n"; cache << gameParam.enemy2_color << "\n"; cache << gameParam.ball_color << "\n"; cache << gameParam.field_pos << "\n"; cache << gameParam.ally_robot_count << "\n"; cache << gameParam.enemy_robot_count << "\n"; cache << (int)gameParam.show_video << "\n"; cache.close(); } paramValid = false; } if (cmdValid) { gameCommandPub.publish(gameCommand); cmdValid = false; } } }
e65ff46385f79d0fb6d97f909f1cb855ef8d6892
88e265f3f0bfb269a8df7717d4a3b303941dc7b0
/Hill_Kelly_SourceCode/CHAP10/FIG10_29.CPP
f1a97e5bbf61a7db255c04f4f376fd903a716772
[]
no_license
rcparent17/opengl
0699afb41d7fb84db22d64f776e086aa7ecf11be
56c63c9364f0b25c5f2de0da52da39340e899f1b
refs/heads/master
2020-04-17T04:39:42.407464
2019-02-25T05:06:43
2019-02-25T05:06:43
166,239,831
0
0
null
null
null
null
UTF-8
C++
false
false
451
cpp
FIG10_29.CPP
void floodFill(short x ,short y, short intColor) // Start at (x, y); change all pixels of intColor to newColor. // assume drawing color is newColor // 4-connected version { if(getPixel(x,y) == intColor) { setPixel(x, y); // change its color floodFill(x - 1, y, intColor); // fill left floodFill(x + 1, y, intColor); // fill right floodFill(x, y + 1, intColor); // fill down floodFill(x, y - 1, intColor) // fill up } }
d0b4713e264026040f535306493da374e8113f90
65881271497c9c1d17df008fe1fe5671b78e8560
/Castlevania/Game/Board.h
cc02ebeb2a17adb2c4aad43b73102dac5ccf0868
[]
no_license
phntrg121/Castlevania
7ecfcf717cdf0b85a8ac30316d322bd006ae6399
1bc67723520b9ccf5387a18e5d81d0bac7538fa2
refs/heads/master
2022-11-20T19:36:51.383184
2020-07-25T01:03:12
2020-07-25T01:03:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,555
h
Board.h
#pragma once #include "..\Framework\Texture.h" #include "..\Framework\Graphics.h" #include "Objects\Item.h" #include "Objects\Weapons\Whip.h" #include "Objects\Weapons\SubWeapon.h" class Board { private: static Board* _instance; LPTEXTURE texture; float x, y; int score; int time; int stage; int heart; int life; int playerhp; int enemyhp; int shot; int whip; int subweapon; DWORD tickcount; bool timeout; DWORD playerdeadtime; DWORD playerdeadtimestart; bool gameover; int selectchoice; bool victory; DWORD victorytime; DWORD victorytimestart; bool done; DWORD donetime; DWORD donetimestart; bool pause; RECT GetCharRect(char c, float x, float y); void DrawByChar(char c, float x, float y, int alpha = 255); void Draw(std::string text, float x, float y, int alpha = 255); void Reset(); public: Board(); static Board* GetInstance(); void LoadTexture(); void SetStage(int i) { stage = i > 0 ? i : 1; } void GetSimonData(Whip* whip, SubWeapon* sub); void PlayerHit(int damage); void PlayerDie(); int GetPlayerHp() { return playerhp; } void BossHit(int damage); int GetBossHp() { return enemyhp; } bool IsPaused() { return pause; } void GamePause(); void GameResume(); void RenderGameover(); bool IsGameOver() { return gameover; } bool IsDone() { return done; } void ConfirmSelection(); void ChangeSelection(); void ItemClaimed(LPITEM item); void AddScore(int score) { this->score += score; } void SubWeaponUsed(int n) { heart -= n; } void Update(DWORD dt); void Render(); };
3d0ab71390a77cf786a8397c51da08942b7d6a9f
a109d6d3331e927a75f30d0eb8b0179cbcf790d6
/Sketch.ino
2f020005b9ca873c968b3b47956a95ee1f17432b
[]
no_license
torgeir/vise-hvordan-github-funker
e22bb1d020040b9a6c267e8cdf5b4ba91a30660e
d0b38f003db9027de559554932ee68fa3595dc11
refs/heads/master
2021-01-10T22:41:29.266166
2017-03-08T11:36:52
2017-03-08T11:36:52
32,449,194
0
0
null
null
null
null
UTF-8
C++
false
false
33
ino
Sketch.ino
int i = 0; void loop() { i++; }
637d3692038cd06a16d579ce053cb4273cd864a9
aadf288b40c29b37bd57f05e9f94515276274e0c
/A-5/q_6.cpp
c94ec21d0805f28fcf80d9f9c45d11d3ba6d913e
[]
no_license
VatsalBatra/CPP_Assignments
04a44ece2860e7c68aab0e05f12b2b8a90abd294
c90ec19d467f383d9986c80dc418a74c8a46ff8c
refs/heads/master
2021-06-24T07:23:42.040372
2017-09-10T10:56:31
2017-09-10T10:56:31
103,022,421
0
0
null
null
null
null
UTF-8
C++
false
false
501
cpp
q_6.cpp
#include<iostream> using namespace std; void insertion_sort(int a[],int n){ if(n <=1){ return; } insertion_sort(a,n-1); int last = a[n-1]; int j=n-2; while(j>=0 && a[j] > last ){ a[j+1] =a[j]; j--; } a[j+1] =last; } int main(){ int arr[100]; int x; cout<<"enter number of array enteries:"; cin>>x; cout<<"enter the array to be sorted:"; for(int i=0;i<x;i++){ cin>>arr[i]; } insertion_sort(arr,x); for (int i=0;i<x;i++){ cout<<" "<<arr[i]<<endl; } return 0; }
15fb1a0e7e708a758930f58d24e59a97d19b826d
a81c6131b3688bebb839e7c68cb2f29043332629
/cnf_gen/clausecounter.cpp
c52b5e3213de0acf0c9183fd1531edc88d2c9cf9
[]
no_license
SmallLars/ma-sha256
40cd682fb66c8dc2acfd320187a0818a46c1200d
71ff02fda09766fd72c9ca6812d870d8f564078b
refs/heads/master
2021-05-04T10:31:21.851050
2017-06-17T11:18:19
2017-06-17T11:18:19
52,981,239
2
1
null
2017-06-17T11:18:20
2016-03-02T17:11:00
C++
UTF-8
C++
false
false
709
cpp
clausecounter.cpp
#include <vector> #include <stdio.h> #include <stdlib.h> #include "cryptominisat4/cryptominisat.h" #include "common/dimacsparser.h" using std::cout; using std::flush; using std::vector; using namespace CMSat; int main(int argc, const char* argv[]) { if (argc != 2) { cout << "Usage: clausecounter <FILE>" << "\n"; return 0; } unsigned int clauses = 0; unsigned int counter = 0; DimacsParser parser(argv[1]); vector<Lit> clause; while (parser.getNextClause(clause, true)) { clauses++; counter += clause.size(); cout << "\r" << clauses << "/" << counter << " : " << counter / (double) clauses; } cout << "\n"; return 0; }
00fc126c92d3eba0ac802cee7d5fc30a6e41c529
02c92550bdb7b5696d7a54bde93f95670c4132a5
/ejercicio2.cpp
8a6e2ae5d0b1c0439df84aead7b7c2ca6cd17eb2
[]
no_license
ChrMlg/FP_laboratorio7_00110219
6a680c5cfa88294c8ff00ba30969af26169faecb
6a4d7cf8145071da782a2f0aa9fcb964f6065170
refs/heads/master
2020-08-14T03:01:45.828451
2019-10-22T04:19:30
2019-10-22T04:19:30
215,086,000
0
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
ejercicio2.cpp
#include <iostream> using namespace std; int main(){ //solicitud de cantidad de casos int n=0; cout << "Digite numero de casos "<<endl;cin >> n; //processo que se repite segun la cantidad de casos asignados for (int i = 1;i<=n;i++){ int a=0; int b=0; //solicitud de valores cout << "Caso " << i << ": "<<endl; cout << "Primer numero:"<<endl; cin >> a; cout << "Segundo numero:"<<endl; cin >> b; //menor if (a<b){ cout << a << " es menor a " << b << endl; } //mayor if (a>b){ cout << a << " es mayor a " << b << endl; } //igual if (a==b){ cout << a << " es igual a " << b << endl; } } return 0; }
ea25f622ac201bb7b2ce767509e3e45ab68ff62a
4e9d28e319ee58dd120fda27f5bd695e09bac620
/DataAnalysis/widget_heatmap.h
b6f3c248dfcf83ca3b681e8b0ff353ef3803eccb
[]
no_license
Lvisual/GraduateProject
f73aa64baac3a0b073abd344d8e1866b06ad81c8
25e508aa144960a7934054f9e887cfe71769da0e
refs/heads/master
2020-03-09T01:29:32.411440
2018-05-01T15:44:15
2018-05-01T15:44:15
128,515,956
0
0
null
null
null
null
UTF-8
C++
false
false
686
h
widget_heatmap.h
#ifndef WIDGET_HEATMAP_H #define WIDGET_HEATMAP_H #include <QWidget> #include <QApplication> #include <QLabel> #include <QComboBox> #include <QVBoxLayout> #include <QHBoxLayout> #include <QString> #include <QPushButton> #include "heatmap.h" #include "basestation/formtitle.h" class Widget_HeatMap : public QWidget { Q_OBJECT public: explicit Widget_HeatMap(QWidget *parent=0); ~Widget_HeatMap(); HeatMap *heatMap; FormTitle *title; QWidget *widget1; QWidget *widget_area; QLabel *label_area; QComboBox *combobox_area; QPushButton *button_export; public slots: void pic_export(); void data_change(); }; #endif // WIDGET_HEATMAP_H
4518ef2ac72b74b5814947ac5a0c5f35dfa4bfa6
bac9f410bdf1c779f95795a9c64a397c9df88715
/W4H2.ino.ino
ae75fb0d9005e86781484ab794f9dd30e8cd0183
[]
no_license
kk4090311/-esp32-wk4
4fd6377ab38915f51dc7b45e8ad6cff4a482c544
eada320a9d9c00c13f91810c5ee362782f9c7c5d
refs/heads/main
2023-08-25T01:30:17.263252
2021-10-16T17:07:17
2021-10-16T17:07:17
417,892,906
0
0
null
null
null
null
UTF-8
C++
false
false
2,211
ino
W4H2.ino.ino
#include <Servo.h> //匯入函式庫 Servo myservo; // 建立伺服馬達控制 bool win=0; const int servoPin = 13; //用常態變數設定pin腳位,與之前define方式差不多 int pos = 90; //角度初始在中間,設定為90度 const int led_pin = 27; int win_staus = 1; const int Button1_Pin = 12, Button2_Pin = 14; //紀錄兩按鈕腳位 bool btn1_Pressed = false, btn2_Pressed = false; //紀錄兩按鈕按壓狀態 void setup() { Serial.begin(115200);//序列阜連線速率(鮑率) myservo.attach(servoPin); // 將伺服馬達連接的GPIO pin連接伺服物件 myservo.write(pos); //角度初始在中間,設定為90度 pinMode(led_pin,OUTPUT); pinMode(Button1_Pin, INPUT); pinMode(Button2_Pin, INPUT); digitalWrite(led_pin,LOW); } void loop() { int btn1_val=digitalRead(Button1_Pin); int btn2_val=digitalRead(Button2_Pin); if (win==0)//no win { /* if (btn1_val==1) { Serial.print(",btn1="); Serial.println(btn1_val); } if (btn2_val==1) { Serial.print(",btn2="); Serial.println(btn2_val); } delay(20); */ //Player 1 if(btn1_val == HIGH && btn1_Pressed == false) { btn1_Pressed = true; pos += 5; //角度加五度 } else if(btn1_val == LOW && btn1_Pressed == true) { btn1_Pressed = false; } //Player 2 if(btn2_val == HIGH && btn2_Pressed == false) { btn2_Pressed = true; pos -= 5; //角度減五度 } else if(btn2_val == LOW && btn2_Pressed == true) { btn2_Pressed = false; } Serial.println(pos); myservo.write(pos); //設定角度 if (pos==0||pos==180) { win=1; } } else { if( btn1_val == HIGH && btn2_val == HIGH) { win=0; pos=90; win_staus=0; } DoWin(); } } void DoWin() { digitalWrite(led_pin,win_staus); if(win_staus== 1) win_staus=0; else win_staus=1; delay(500-300*win_staus); }
6f1ddcdf05222bafc1d2b96517196c761c4244fc
4ef55d3911b2f5797c84b862a616c3c02f0c0951
/Code/quickfix/ConsoleApplication2/Transaction.cpp
e33feecd6efaf2e8da10791f47dba8fe738392b3
[ "BSD-2-Clause" ]
permissive
GhostatSpirit/StockExchangeSimulator
65aad0411401fa335a80aee447868ee77b4b95be
d22cdbe7b70b838baf7930dfc769d460de15e172
refs/heads/master
2021-01-09T09:36:38.206696
2016-07-24T18:16:08
2016-07-24T18:16:08
63,987,758
1
0
null
null
null
null
UTF-8
C++
false
false
2,317
cpp
Transaction.cpp
#include "Transaction.h" #include "error.h" using namespace std; Transaction::Transaction(Order& sell_order, Order& buy_order) :sellOrder(sell_order), buyOrder(buy_order) { // validate the symbol, price, quantity of the two orders, // if valid, store the symbol, price, quantity if (sellOrder.getSymbol() != buyOrder.getSymbol()) { error("Transaction: constructor: symbol not match"); } symbol = sellOrder.getSymbol(); if (sellOrder.getLastExecutedQuantity() != buyOrder.getLastExecutedQuantity()) { error("Transaction: constructor: lastExecutedQuantity not match"); } quantity = sellOrder.getLastExecutedQuantity(); if (sellOrder.getLastExecutedPrice() != buyOrder.getLastExecutedPrice()) { error("Transaction: constructor: lastExecutedPrice not match"); } price = sellOrder.getLastExecutedPrice(); // store the buyer and seller seller = sellOrder.getOwner(); buyer = buyOrder.getOwner(); valid = true; //update UTC time of this transaction _time.setCurrent(); } void Transaction::validate() { if (sellOrder.getSymbol() != buyOrder.getSymbol()) { error("Transaction: constructor: symbol not match"); } symbol = sellOrder.getSymbol(); if (sellOrder.getLastExecutedQuantity() != buyOrder.getLastExecutedQuantity()) { error("Transaction: constructor: lastExecutedQuantity not match"); } quantity = sellOrder.getLastExecutedQuantity(); if (sellOrder.getLastExecutedPrice() != buyOrder.getLastExecutedPrice()) { error("Transaction: constructor: lastExecutedPrice not match"); } price = sellOrder.getLastExecutedPrice(); // store the buyer and seller seller = sellOrder.getOwner(); buyer = buyOrder.getOwner(); valid = true; //update UTC time of this transaction _time.setCurrent(); } ostream & operator<<(ostream & ostream, Transaction & transaction) { const string marker = "> "; ostream << marker << "TRANSACTION OF: " << transaction.getSymbol() << "|" << "TIME: " << transaction._time.getString() << endl; ostream << marker << "PRICE: " << std::setw(10) << transaction.getPrice() << "|"; ostream << "QUANTITY: " << std::setw(10) << transaction.getQuantity() << "|"; ostream << "SELLER: " << std::setw(10) << transaction.getSeller() << "|"; ostream << "BUYER: " << std::setw(10) << transaction.getBuyer() << "|"; ostream << endl; return ostream; }
361de9a4b0735c804bb9c63b6dd3c32933007706
882a20fdf88ec1598b1e0031c2f21f521fbbb3f6
/duff2/Source/PropertyPageDuplicates.cpp
35e9d2b466f06da6fd2c1c7dabcbd1abc2f8b53a
[]
no_license
presscad/duff
39fb6db6884c0e46f7b2862842334915ec17375e
eabfd1aa440883cbd5fd172aa9c10e2b6902d068
refs/heads/master
2021-04-17T09:16:21.042836
2012-01-30T22:42:40
2012-01-30T22:42:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,835
cpp
PropertyPageDuplicates.cpp
// DuplicatesPropertyPage.cpp : implementation file // #include "stdafx.h" #include "duff.h" #include "PropertyPageDuplicates.h" #include "duffdlg.h" #include "TextClipboard.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDuplicatesPropertyPage property page IMPLEMENT_DYNCREATE(CDuplicatesPropertyPage, CResizablePage) CDuplicatesPropertyPage::CDuplicatesPropertyPage() : CResizablePage(CDuplicatesPropertyPage::IDD) { //{{AFX_DATA_INIT(CDuplicatesPropertyPage) //}}AFX_DATA_INIT } CDuplicatesPropertyPage::~CDuplicatesPropertyPage() { } void CDuplicatesPropertyPage::DoDataExchange(CDataExchange* pDX) { CResizablePage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDuplicatesPropertyPage) DDX_Control(pDX, IDC_DUPLICATE_LIST, m_DupeList); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDuplicatesPropertyPage, CResizablePage) //{{AFX_MSG_MAP(CDuplicatesPropertyPage) ON_WM_SIZE() ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDuplicatesPropertyPage message handlers BOOL CDuplicatesPropertyPage::OnInitDialog() { CResizablePage::OnInitDialog(); // anchor dialog items AddAnchor(IDC_DUPLICATE_LIST_FRAME, TOP_LEFT,BOTTOM_RIGHT); AddAnchor(IDC_DUPLICATE_LIST, TOP_LEFT,BOTTOM_RIGHT); AddAnchor(IDC_SELECTED_SIZE, BOTTOM_LEFT); AddAnchor(IDC_STATIC_SELECTED_SIZE, BOTTOM_LEFT); AddAnchor(IDC_TOTAL_CHECKED, BOTTOM_LEFT); AddAnchor(IDC_STATIC_CHECKED, BOTTOM_LEFT); AddAnchor(IDC_TOTAL_SIZE, BOTTOM_LEFT); AddAnchor(IDC_TOTAL_SELECTED, BOTTOM_LEFT); AddAnchor(IDC_TOTAL_COUNT, BOTTOM_LEFT); AddAnchor(IDC_STATIC_SELECTED, BOTTOM_LEFT); AddAnchor(IDC_STATIC_COUNT, BOTTOM_LEFT); AddAnchor(IDC_STATIC_SIZE, BOTTOM_LEFT); AddAnchor(IDC_STATIC_MARKED_SIZE, BOTTOM_LEFT); AddAnchor(IDC_MARKED_SIZE, BOTTOM_LEFT); AddAnchor(IDC_TOTAL_DUPE_SIZE, BOTTOM_LEFT); AddAnchor(IDC_STATIC_TOTAL_DUPE_SIZE, BOTTOM_LEFT); AddAnchor(IDC_TOTAL_DUPLICATES, BOTTOM_LEFT); AddAnchor(IDC_STATIC_DUPLICATES, BOTTOM_LEFT); // // set up list info controls m_DupeList.SetTotalCheckedCtrl( (CEdit*)GetDlgItem(IDC_TOTAL_CHECKED) ); m_DupeList.SetTotalCountCtrl( (CEdit*)GetDlgItem(IDC_TOTAL_COUNT) ); m_DupeList.SetTotalBytesCtrl( (CEdit*)GetDlgItem(IDC_TOTAL_SIZE) ); m_DupeList.SetNumSelectedCtrl( (CEdit*)GetDlgItem(IDC_TOTAL_SELECTED) ); m_DupeList.SetSelectedBytesCtrl( (CEdit*)GetDlgItem(IDC_SELECTED_SIZE) ); m_DupeList.SetMarkedBytesCtrl( (CEdit*)GetDlgItem(IDC_MARKED_SIZE) ); m_DupeList.SetTotalDuplicateCtrl( (CEdit*)GetDlgItem(IDC_TOTAL_DUPLICATES) ); m_DupeList.SetDuplicateBytesCtrl( (CEdit*)GetDlgItem(IDC_TOTAL_DUPE_SIZE) ); // return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // let parent dialog know of keystrokes BOOL CDuplicatesPropertyPage::PreTranslateMessage(MSG* pMsg) { bool ret; if ( IsDialogMessage( pMsg ) ) { if ( TranslateAccelerator ( GetSafeHwnd(),((CDuffDlg*)GetParent()->GetParent())->m_hAccel,pMsg) ) { TranslateMessage(pMsg); DispatchMessage(pMsg); ret = false; } ret = true; } else { ret = ( CWnd::PreTranslateMessage( pMsg ) != 0); } return ret; } void CDuplicatesPropertyPage::LoadSettings() { // MessageBox("loading settings"); } void CDuplicatesPropertyPage::SaveSettings() { // MessageBox("save settings"); } void CDuplicatesPropertyPage::AddItem(CFileInfo *pFileInfo) { m_DupeList.AddItem(pFileInfo); } ULONGLONG CDuplicatesPropertyPage::GetNumFiles() { return m_DupeList.GetTotalFilesCounter(); } void CDuplicatesPropertyPage::UpdateListMarks() { m_DupeList.UpdateListMarks(); }
596aa7d839bc218e7e83f8b83c974e560b26a5ea
cd67a57944b5871e4a412706b4365a7d48f63243
/include/a2b/translator.h
2a83d8e666d8ed3837691e81609d9c8b80d1e033
[ "MIT" ]
permissive
0x656b694d/a2b
43c73bc6674286c502cdd50194a2aa522c4044cc
6febe9cc02ed46b5ccbea14b95a3d9fa5da28d44
refs/heads/master
2021-03-24T14:04:30.358927
2018-04-16T08:47:45
2018-04-16T08:47:45
123,925,238
0
0
null
null
null
null
UTF-8
C++
false
false
7,473
h
translator.h
/* * Model Translation Utility * * https://github.com/0x656b694d/a2b * */ #include <list> #include <tuple> #include <boost/mpl/at.hpp> #include <boost/mpl/find.hpp> #include <boost/mpl/list.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/size.hpp> #include <boost/mpl/transform.hpp> namespace a2b { namespace internal { /* * Transforming boost::mpl to std::tuple */ template <typename SEQ, size_t N> struct vector_at : boost::mpl::at_c<SEQ, N> {}; template <typename... TYPES, size_t N> struct vector_at<std::tuple<TYPES...>, N> : std::tuple_element<N, std::tuple<TYPES...>> {}; template <typename SEQ, size_t N, typename... ARGS> struct convert_helper : convert_helper<SEQ, N-1, typename vector_at<SEQ, N-1>::type, ARGS...> {}; template <typename SEQ, typename... ARGS> struct convert_helper<SEQ, 0, ARGS...> { typedef std::tuple<ARGS...> type; }; template <typename SEQ> using Tuplified = convert_helper<SEQ, boost::mpl::size<SEQ>::value>; /* * Transforming a type list to a type list of containers of the internal types, * i.e. boost::mpl::list<T> -> boost::mpl::list<std::list<T>> */ template<typename T, template<class...> class C> using Listified = typename boost::mpl::transform<T, C<boost::mpl::_1>>::type; template<typename F, typename Tuple, std::size_t N> class TupleVisitor { public: explicit TupleVisitor(F& f): _func(f) {} void accept(Tuple const& t) { TupleVisitor<F, Tuple, N-1>(_func).accept(t); _func(std::get<N-1>(t)); } void reverse_accept(Tuple const& t) { _func(std::get<N-1>(t)); TupleVisitor<F, Tuple, N-1>(_func).reverse_accept(t); } private: F &_func; }; template<typename F, typename Tuple> class TupleVisitor<F, Tuple, 1> { public: explicit TupleVisitor(F& f): _func(f) {} void accept(Tuple const& t) { _func(std::get<0>(t)); } void reverse_accept(Tuple const& t) { _func(std::get<0>(t)); } private: F &_func; }; template<typename F, template<class...> class C> class Applicator { public: explicit Applicator(F& f): _func(f) {} template<typename D> void operator()(C<D> const& x) const { for (D const& d: x) { _func(d); } } template<typename D> void operator()(C<D>& x) const { for (D& d: x) { _func(d); } } private: F &_func; }; template<template<class...> class C, typename F, typename... Args> F& visit(std::tuple<Args...> const& t, F& f) { using tmp = TupleVisitor<Applicator<F, C>, decltype(t), sizeof...(Args)>; Applicator<F, C> a(f); tmp(a).accept(t); return f; } template<template<class...> class C, typename F, typename... Args> F& visit(std::tuple<Args...>& t, F& f) { using tmp = TupleVisitor<Applicator<F, C>, decltype(t), sizeof...(Args)>; Applicator<F, C> a(f); tmp(a).accept(t); return f; } template<template<class...> class C, typename F, typename... Args> F& reverse_visit(std::tuple<Args...> const& t, F& f) { using tmp = TupleVisitor<Applicator<F, C>, decltype(t), sizeof...(Args)>; Applicator<F, C> a(f); tmp(a).reverse_accept(t); return f; } template<template<class...> class C, typename F, typename... Args> F& reverse_visit(std::tuple<Args...>& t, F& f) { using tmp = TupleVisitor<Applicator<F, C>, decltype(t), sizeof...(Args)>; Applicator<F, C> a(f); tmp(a).reverse_accept(t); return f; } } // internal template<typename ListifiedModel, template<class...> class C> class Instance { public: using listified_type = ListifiedModel; using value_type = typename internal::Tuplified<listified_type>::type; template<typename ...T> using container_type = C<T...>; template<typename T> C<T>& get() { return std::get<Index<T>::value>(_value); } template<typename T> C<T> const& get() const { return std::get<Index<T>::value>(_value); } template<typename T> value_type& add(T const& value) { std::get<Index<T>::value>(_value).push_back(value); return _value; } value_type const& getValue() const { return _value; } value_type& getValue() { return _value; } template<typename F> void visit(F& f) { internal::visit<container_type>(_value, f); } template<typename F> void visit(F& f) const { internal::visit<container_type>(_value, f); } template<typename F> void reverse_visit(F& f) { internal::reverse_visit<container_type>(_value, f); } template<typename F> void reverse_visit(F& f) const { internal::reverse_visit<container_type>(_value, f); } private: template<typename T> struct Index { static size_t const value = boost::mpl::distance< typename boost::mpl::begin<listified_type>::type, typename boost::mpl::find<listified_type, C<T>>::type>::value; }; value_type _value; }; template<typename UserTranslator, typename Model, template<class...> class C = std::list, typename V = Instance<internal::Listified<Model, C>, C>> class Translator { public: using value_type = V; using result_type = V&; using model_type = Model; using base_type = Translator<UserTranslator, Model, C, V>; template<typename ...T> using container_type = C<T...>; // Generic translators template<typename T> result_type translate(T const&) const { throw std::runtime_error(std::string("Missing translation for ") + typeid(T).name()); } template<template<class...> class CC, typename T> value_type translate(CC<T> const& sequence) && { return translate_sequence(sequence); } template<template<class...> class CC, typename T> result_type translate(CC<T> const& sequence) & { return translate_sequence(sequence); } // end of generic translators template<typename T> result_type add(T const& obj) { _result.add(obj); return _result; } value_type const& getResult() const { return _result; } value_type& getResult() { return _result; } protected: Translator() = default; private: template<typename T> result_type translate_sequence(T const& sequence) { for (auto&& obj: sequence) { static_cast<UserTranslator*>(this)->translate(obj); } return _result; } value_type _result; }; // class Translator template<typename I, typename F> void visit(I const& result, F& f) { internal::visit<I::container_type>(result.getValue(), f); } template<typename I, typename F> void visit(I& result, F& f) { internal::visit<I::template container_type>(result.getValue(), f); } template<typename I, typename F> void reverse_visit(I const& result, F& f) { internal::reverse_visit<I::container_type>(result.getValue(), f); } template<typename I, typename F> void reverse_visit(I& result, F& f) { internal::reverse_visit<I::template container_type>(result.getValue(), f); } struct Visitor {}; template<typename... Args> using model = boost::mpl::list<Args...>; } // namespace a2b
76d1374332a0821e1735bc42d630c52d4f2bd032
8ff6b90b1ce5312ebc1a2ed3579eed5cc102bec0
/clock/platformio/src/sound.cpp
67dc9e4b0cf5aecfedf02b5f1cc8d707aab8f190
[]
no_license
dcowden/battlepoint
a208aef872c5eccff260254c599c6b67fdd0383a
ed13314fb6bb5a1c96301aa9dc4b7997df31a9c3
refs/heads/master
2022-01-20T01:36:01.150910
2021-12-24T22:54:49
2021-12-24T22:54:49
135,941,061
0
1
null
null
null
null
UTF-8
C++
false
false
1,122
cpp
sound.cpp
#include <sound.h> #include "HardwareSerial.h" #include "DFRobotDFPlayerMini.h" HardwareSerial mySoftwareSerial(1); DFRobotDFPlayerMini myDFPlayer; void sound_init(int rx_pin, int tx_pin){ mySoftwareSerial.begin(9600, SERIAL_8N1, rx_pin, tx_pin); // speed, type, RX, TX Serial.begin(115200); Serial.println(); Serial.println(F("DFRobot DFPlayer Mini Demo")); Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)")); if (!myDFPlayer.begin(mySoftwareSerial)) { //Use softwareSerial to communicate with mp3. Serial.println(myDFPlayer.readType(),HEX); Serial.println(F("Unable to begin:")); Serial.println(F("1.Please recheck the connection!")); Serial.println(F("2.Please insert the SD card!")); while(true); } Serial.println(F("DFPlayer Mini online.")); myDFPlayer.setTimeOut(500); //Set serial communictaion time out 500ms myDFPlayer.EQ(DFPLAYER_EQ_NORMAL); myDFPlayer.outputDevice(DFPLAYER_DEVICE_SD); } void sound_play(int sound_id){ myDFPlayer.play(sound_id); } void play_random_startup(){ long r = random(18,25); sound_play(r); }
93891826a57330f8bdc84925e9e6b4f1e245b415
0eb12fdd27a10e7697153cfce43d9c35a70ba578
/StuCPPFirst/main08.cpp
14933acdf4706f9a03c938090f2a4703504d58ad
[]
no_license
VonsName/StuCPPFirst
a180351f52e30b4ecf35726c381e15642cd6e17f
de900889a7986d61ee2c76c303e559bf6b4060d7
refs/heads/master
2020-03-27T10:27:08.691499
2018-09-01T12:19:55
2018-09-01T12:19:55
146,421,075
0
0
null
null
null
null
GB18030
C++
false
false
1,341
cpp
main08.cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <assert.h> using namespace std; class Name { public: Name(); ~Name(); Name(const Name &rn); Name(const char *name); public: char *getName() { return name; } private: char *name; }; Name::Name() { } /** * 拷贝构造函数,自己实现深拷贝 */ Name::Name(const char *src) { assert(src); int len = strlen(src) + 1; name = (char *)malloc(sizeof(char)*len); strcpy(name, src); } Name::Name(const Name &rn) { int len = strlen(rn.name) + 1; name = (char *)malloc(sizeof(char)*len); strcpy(name, rn.name); } Name::~Name() { if (name!=NULL) { free(name); } } /** * 1.当类中没有定义构造函数和拷贝构造函数,C++编译器会默认一个拷贝构造函数和构造函数 * 2.当类中定义了拷贝构造函数,编译器不会提供无参数构造函数 */ int main081(_In_ int argc, _In_reads_(argc) _Pre_z_ char** argv, _In_z_ char** envp) { Name n("lisi"); printf("%s\n", n.getName()); Name n1 = n; printf("%s\n", n1.getName()); Name n3(n1); printf("%s\n", n3.getName()); Name n4("王五"); // n4 = n3;//简单的赋值操作,浅拷贝,n4重新指向了n3,n4原来的内存泄漏,释放内存的时候 //相当于释放了n3两次,程序段错误 重载=号操作符 printf("%s\n", n4.getName()); return 0; }
8b69c69e7af40a65f7d3ec108838a469e0344f9e
f5e2ec3042ee7b186df00cf9cf6598c70f7dfb5f
/16-3sum-closest.cpp
6e843a4af5e77eab30b38df91daa17829a11213f
[]
no_license
gaocegege/MyLeetcode
b911b6de29f26f734ac91033170efe0138521225
7f122b3f83eea1db62cfdca2640bb00ebceb4401
refs/heads/master
2021-01-19T17:47:55.789939
2016-11-01T13:52:38
2016-11-01T13:52:38
32,554,802
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
16-3sum-closest.cpp
#include <iostream> using namespace std; class Solution() { int threeSumClosest(vector<int> &num, int target) { int sz = num.size(); int front = 0; int rear = sz - 1; sort(num.begin(), num.end()); int resSum = num[0] + num[1] + num[2]; int res = abs(resSum - target); for (int i = 0; i < sz; i++) { front = i + 1; rear = sz - 1; if (res == 0) return target; while (front < rear) { int sum = num[i] + num[front] + num[rear]; if (abs(sum - target) < res) { res = abs(sum - target); resSum = sum; } if (sum < target) front++; else if (sum > target) rear--; else break; } } return resSum; } }
43b36c644e18c9462840c106465416a7c77eb32d
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5695413893988352_1/C++/noxwell/contest.cpp
e4b1f3545de1d9a9eaac725307c17d072b401e67
[]
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
5,450
cpp
contest.cpp
#pragma comment (linker, "/STACK:256000000") #define _USE_MATH_DEFINES #define _CRT_NO_DEPRECEATE #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <iomanip> #include <fstream> #include <cstdio> #include <cstdlib> #include <string> #include <cstring> #include <vector> #include <utility> #include <algorithm> #include <functional> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <cmath> #include <queue> #include <memory.h> #include <sstream> #include <cassert> #include <ctime> #include <complex> #include <random> using namespace std; typedef unsigned int uint32; typedef long long int64; typedef unsigned long long uint64; typedef long double ldouble; typedef pair<int, int> pii; typedef pair<int64, int64> pll; typedef pair<pii, pii> piiii; #define pb push_back #define sq(x) ((x)*(x)) #define tmin(x,y,z) (min(min((x),(y)),(z))) #define rand32() (((unsigned int)(rand()) << 16) | (unsigned int)(rand())) #define rand64() (((unsigned int64)(rand32()) << 16) | (unsigned int64)(rand32())) #define bit(mask, b) ((mask >> b) & 1) #define biton(mask, bit) (mask | (((uint32)(1)) << bit)) #define bitoff(mask, bit) (mask & (~(((uint32)(1)) << bit))) #define bitputon(mask, bit) (mask |= (((uint32)(1)) << bit)) #define bitputoff(mask, bit) (mask &= (~(((uint32)(1)) << bit))) #define FAIL() (*((int*)(0)))++ #define INF ((int)(1e9) + 1337) #define LINF ((int64)(1e18)) #define EPS 1e-9 #define PI (3.1415926535897932384626433832795) #define y1 yy1 #define y0 yy0 #define j0 jj0 #define MOD 1000000007LL #define HMOD 1234567913LL #define HBASE 1009 //#define HMOD ((int64)(1e18) + 3LL) //#ifdef _MY_DEBUG //#define HMOD 1000000007 //#endii #define MAX 2000000000 mt19937 ggen; struct trip { int64 dt, a, b; trip() {} trip(int64 a, int64 b) : a(a), b(b) { dt = abs(a - b); } }; bool operator<(const trip &a, const trip &b) { if (a.dt < b.dt) return 1; else if (a.dt == b.dt && a.a < b.a) return 1; else if (a.dt == b.dt && a.a == b.a && a.b < b.b) return 1; else return 0; } int n; string a, b; int64 pw[18]; void init() { pw[0] = 1; for (int i = 1; i < 18; i++) pw[i] = pw[i - 1] * 10; } inline trip get(bool le) { trip res(0, 0); for (int i = 0; i < n; i++) { if(a[n - 1 - i] != '?') res.a += pw[i] * (int64)(a[n - 1 - i] - '0'); if (b[n - 1 - i] != '?') res.b += pw[i] * (int64)(b[n - 1 - i] - '0'); if (a[n - 1 - i] == '?' && le) res.a += pw[i] * 9; if (b[n - 1 - i] == '?' && !le) res.b += pw[i] * 9; } res.dt = abs(res.a - res.b); return res; } void solve() { cin >> a >> b; n = a.size(); bool end = false; trip ans(0, 2e18); for (int i = 0; i < n && !end; i++) { if (a[i] == '?' && b[i] == '?') { trip t; a[i] = '0'; b[i] = '1'; t = get(1); ans = min(ans, t); a[i] = '1'; b[i] = '0'; t = get(0); ans = min(ans, t); a[i] = '0'; b[i] = '0'; } else if (a[i] == '?' && b[i] != '?') { trip t; if (b[i] != '0') { a[i] = b[i] - 1; t = get(1); ans = min(ans, t); } if (b[i] != '9') { a[i] = b[i] + 1; t = get(0); ans = min(ans, t); } a[i] = b[i]; } else if (a[i] != '?' && b[i] == '?') { trip t; if (a[i] != '0') { b[i] = a[i] - 1; t = get(0); ans = min(ans, t); } if (a[i] != '9') { b[i] = a[i] + 1; t = get(1); ans = min(ans, t); } b[i] = a[i]; } else { trip t; if (a[i] != b[i]) end = true; t = get(a[i] <= b[i]); ans = min(ans, t); } } if (!end) { auto t = get(1); ans = min(ans, t); } cout << setw(n) << setfill('0') << ans.a << ' ' << setw(n) << setfill('0') << ans.b; } //void testgen(int n) //{ // ofstream ofs("input.txt", ios_base::out | ios_base::trunc); // mt19937 gen(1337); // uniform_int_distribution<int> dist('a', 'z'); // for (int i = 0; i < n; i++) // ofs << (char)dist(gen); // ofs.close(); //} #define TASK "substr" int main() { //stresstest(50, 100, 70); return 0; //testgen(20000); return 0; ios_base::sync_with_stdio(false); cin.tie(0); #ifdef _MY_DEBUG freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #else //freopen(TASK ".in", "rt", stdin); freopen(TASK ".out", "wt", stdout); #endif //stresstest(); return 0; srand(1313); ggen = mt19937(13); init(); int ts; cin >> ts; for (int i = 0; i < ts; i++) { cout << "Case #" << i + 1 << ": "; solve(); cout << '\n'; } return 0; }
0c83ead2d80644c60cb6b81d5bf61f5648ea715f
e5c991f8509075eac3a8cad5009c36a94e296a3d
/fpga_labs/S05/CH02/HLS/skin_detect/solution1/syn/systemc/AXIvideo2Mat.h
be772039d72ded019b071222564050ce1c35a145
[]
no_license
fdu2020/2020
c18a5c1a76b48baaacbd1cdcecca9e11d0876368
c2ebfff8c77017a10c697edc0ae49ea473ab9efa
refs/heads/master
2022-12-01T07:13:43.717995
2020-08-06T06:36:06
2020-08-06T06:36:06
281,705,104
0
4
null
null
null
null
UTF-8
C++
false
false
10,275
h
AXIvideo2Mat.h
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2018.3 // Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved. // // =========================================================== #ifndef _AXIvideo2Mat_HH_ #define _AXIvideo2Mat_HH_ #include "systemc.h" #include "AESL_pkg.h" namespace ap_rtl { struct AXIvideo2Mat : public sc_module { // Port declarations 39 sc_in_clk ap_clk; sc_in< sc_logic > ap_rst; sc_in< sc_logic > ap_start; sc_out< sc_logic > ap_done; sc_in< sc_logic > ap_continue; sc_out< sc_logic > ap_idle; sc_out< sc_logic > ap_ready; sc_in< sc_lv<32> > AXI_video_strm_V_data_V_dout; sc_in< sc_logic > AXI_video_strm_V_data_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_data_V_read; sc_in< sc_lv<4> > AXI_video_strm_V_keep_V_dout; sc_in< sc_logic > AXI_video_strm_V_keep_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_keep_V_read; sc_in< sc_lv<4> > AXI_video_strm_V_strb_V_dout; sc_in< sc_logic > AXI_video_strm_V_strb_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_strb_V_read; sc_in< sc_lv<1> > AXI_video_strm_V_user_V_dout; sc_in< sc_logic > AXI_video_strm_V_user_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_user_V_read; sc_in< sc_lv<1> > AXI_video_strm_V_last_V_dout; sc_in< sc_logic > AXI_video_strm_V_last_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_last_V_read; sc_in< sc_lv<1> > AXI_video_strm_V_id_V_dout; sc_in< sc_logic > AXI_video_strm_V_id_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_id_V_read; sc_in< sc_lv<1> > AXI_video_strm_V_dest_V_dout; sc_in< sc_logic > AXI_video_strm_V_dest_V_empty_n; sc_out< sc_logic > AXI_video_strm_V_dest_V_read; sc_in< sc_lv<32> > img_rows_V_read; sc_in< sc_lv<32> > img_cols_V_read; sc_out< sc_lv<8> > img_data_stream_0_V_din; sc_in< sc_logic > img_data_stream_0_V_full_n; sc_out< sc_logic > img_data_stream_0_V_write; sc_out< sc_lv<8> > img_data_stream_1_V_din; sc_in< sc_logic > img_data_stream_1_V_full_n; sc_out< sc_logic > img_data_stream_1_V_write; sc_out< sc_lv<8> > img_data_stream_2_V_din; sc_in< sc_logic > img_data_stream_2_V_full_n; sc_out< sc_logic > img_data_stream_2_V_write; // Module declarations AXIvideo2Mat(sc_module_name name); SC_HAS_PROCESS(AXIvideo2Mat); ~AXIvideo2Mat(); sc_trace_file* mVcdFile; sc_signal< sc_logic > ap_done_reg; sc_signal< sc_lv<8> > ap_CS_fsm; sc_signal< sc_logic > ap_CS_fsm_state1; sc_signal< sc_logic > AXI_video_strm_V_data_V_blk_n; sc_signal< sc_logic > ap_CS_fsm_state2; sc_signal< sc_logic > ap_CS_fsm_pp1_stage0; sc_signal< sc_logic > ap_enable_reg_pp1_iter1; sc_signal< bool > ap_block_pp1_stage0; sc_signal< sc_lv<1> > exitcond_reg_512; sc_signal< sc_lv<1> > brmerge_fu_438_p2; sc_signal< sc_logic > ap_CS_fsm_state9; sc_signal< sc_lv<1> > ap_phi_mux_eol_2_phi_fu_387_p4; sc_signal< sc_logic > AXI_video_strm_V_keep_V_blk_n; sc_signal< sc_logic > AXI_video_strm_V_strb_V_blk_n; sc_signal< sc_logic > AXI_video_strm_V_user_V_blk_n; sc_signal< sc_logic > AXI_video_strm_V_last_V_blk_n; sc_signal< sc_logic > AXI_video_strm_V_id_V_blk_n; sc_signal< sc_logic > AXI_video_strm_V_dest_V_blk_n; sc_signal< sc_logic > img_data_stream_0_V_blk_n; sc_signal< sc_logic > ap_enable_reg_pp1_iter2; sc_signal< sc_lv<1> > exitcond_reg_512_pp1_iter1_reg; sc_signal< sc_logic > img_data_stream_1_V_blk_n; sc_signal< sc_logic > img_data_stream_2_V_blk_n; sc_signal< sc_lv<32> > t_V_2_reg_290; sc_signal< sc_lv<1> > eol_1_reg_301; sc_signal< sc_lv<32> > axi_data_V_1_reg_312; sc_signal< sc_lv<1> > eol_reg_323; sc_signal< sc_lv<1> > axi_last_V_2_reg_335; sc_signal< sc_lv<32> > p_Val2_s_reg_348; sc_signal< bool > ap_block_state1; sc_signal< sc_lv<32> > tmp_data_V_reg_483; sc_signal< sc_logic > AXI_video_strm_V_id_V0_status; sc_signal< sc_lv<1> > tmp_last_V_reg_491; sc_signal< sc_lv<1> > exitcond2_fu_413_p2; sc_signal< sc_logic > ap_CS_fsm_state4; sc_signal< sc_lv<32> > i_V_fu_418_p2; sc_signal< sc_lv<32> > i_V_reg_507; sc_signal< sc_lv<1> > exitcond_fu_424_p2; sc_signal< bool > ap_block_state5_pp1_stage0_iter0; sc_signal< bool > ap_predicate_op59_read_state6; sc_signal< bool > ap_block_state6_pp1_stage0_iter1; sc_signal< bool > ap_block_state7_pp1_stage0_iter2; sc_signal< bool > ap_block_pp1_stage0_11001; sc_signal< sc_lv<32> > j_V_fu_429_p2; sc_signal< sc_logic > ap_enable_reg_pp1_iter0; sc_signal< sc_lv<8> > tmp_8_fu_444_p1; sc_signal< sc_lv<8> > tmp_8_reg_525; sc_signal< sc_lv<8> > tmp_4_reg_530; sc_signal< sc_lv<8> > tmp_5_reg_535; sc_signal< bool > ap_block_state9; sc_signal< bool > ap_block_pp1_stage0_subdone; sc_signal< sc_logic > ap_condition_pp1_exit_iter1_state6; sc_signal< sc_lv<1> > axi_last_V_3_reg_360; sc_signal< sc_lv<1> > axi_last_V1_reg_259; sc_signal< sc_logic > ap_CS_fsm_state10; sc_signal< sc_logic > ap_CS_fsm_state3; sc_signal< sc_lv<32> > axi_data_V_3_reg_372; sc_signal< sc_lv<32> > axi_data_V1_reg_269; sc_signal< sc_lv<32> > t_V_reg_279; sc_signal< sc_lv<1> > ap_phi_mux_eol_1_phi_fu_304_p4; sc_signal< sc_lv<32> > ap_phi_mux_axi_data_V_1_phi_fu_315_p4; sc_signal< sc_lv<1> > ap_phi_mux_eol_phi_fu_327_p4; sc_signal< sc_lv<1> > ap_phi_reg_pp1_iter1_axi_last_V_2_reg_335; sc_signal< sc_lv<32> > ap_phi_mux_p_Val2_s_phi_fu_352_p4; sc_signal< sc_lv<32> > ap_phi_reg_pp1_iter1_p_Val2_s_reg_348; sc_signal< sc_logic > ap_CS_fsm_state8; sc_signal< sc_lv<1> > eol_2_reg_384; sc_signal< sc_logic > AXI_video_strm_V_id_V0_update; sc_signal< bool > ap_block_pp1_stage0_01001; sc_signal< sc_lv<1> > sof_1_fu_204; sc_signal< sc_lv<1> > tmp_user_V_fu_404_p1; sc_signal< sc_lv<8> > ap_NS_fsm; sc_signal< sc_logic > ap_idle_pp1; sc_signal< sc_logic > ap_enable_pp1; sc_signal< bool > ap_condition_287; sc_signal< bool > ap_condition_249; static const sc_logic ap_const_logic_1; static const sc_logic ap_const_logic_0; static const sc_lv<8> ap_ST_fsm_state1; static const sc_lv<8> ap_ST_fsm_state2; static const sc_lv<8> ap_ST_fsm_state3; static const sc_lv<8> ap_ST_fsm_state4; static const sc_lv<8> ap_ST_fsm_pp1_stage0; static const sc_lv<8> ap_ST_fsm_state8; static const sc_lv<8> ap_ST_fsm_state9; static const sc_lv<8> ap_ST_fsm_state10; static const sc_lv<32> ap_const_lv32_0; static const bool ap_const_boolean_1; static const sc_lv<32> ap_const_lv32_1; static const sc_lv<32> ap_const_lv32_4; static const bool ap_const_boolean_0; static const sc_lv<1> ap_const_lv1_0; static const sc_lv<32> ap_const_lv32_6; static const sc_lv<32> ap_const_lv32_3; static const sc_lv<1> ap_const_lv1_1; static const sc_lv<32> ap_const_lv32_7; static const sc_lv<32> ap_const_lv32_2; static const sc_lv<32> ap_const_lv32_5; static const sc_lv<32> ap_const_lv32_8; static const sc_lv<32> ap_const_lv32_F; static const sc_lv<32> ap_const_lv32_10; static const sc_lv<32> ap_const_lv32_17; // Thread declarations void thread_ap_clk_no_reset_(); void thread_AXI_video_strm_V_data_V_blk_n(); void thread_AXI_video_strm_V_data_V_read(); void thread_AXI_video_strm_V_dest_V_blk_n(); void thread_AXI_video_strm_V_dest_V_read(); void thread_AXI_video_strm_V_id_V0_status(); void thread_AXI_video_strm_V_id_V0_update(); void thread_AXI_video_strm_V_id_V_blk_n(); void thread_AXI_video_strm_V_id_V_read(); void thread_AXI_video_strm_V_keep_V_blk_n(); void thread_AXI_video_strm_V_keep_V_read(); void thread_AXI_video_strm_V_last_V_blk_n(); void thread_AXI_video_strm_V_last_V_read(); void thread_AXI_video_strm_V_strb_V_blk_n(); void thread_AXI_video_strm_V_strb_V_read(); void thread_AXI_video_strm_V_user_V_blk_n(); void thread_AXI_video_strm_V_user_V_read(); void thread_ap_CS_fsm_pp1_stage0(); void thread_ap_CS_fsm_state1(); void thread_ap_CS_fsm_state10(); void thread_ap_CS_fsm_state2(); void thread_ap_CS_fsm_state3(); void thread_ap_CS_fsm_state4(); void thread_ap_CS_fsm_state8(); void thread_ap_CS_fsm_state9(); void thread_ap_block_pp1_stage0(); void thread_ap_block_pp1_stage0_01001(); void thread_ap_block_pp1_stage0_11001(); void thread_ap_block_pp1_stage0_subdone(); void thread_ap_block_state1(); void thread_ap_block_state5_pp1_stage0_iter0(); void thread_ap_block_state6_pp1_stage0_iter1(); void thread_ap_block_state7_pp1_stage0_iter2(); void thread_ap_block_state9(); void thread_ap_condition_249(); void thread_ap_condition_287(); void thread_ap_condition_pp1_exit_iter1_state6(); void thread_ap_done(); void thread_ap_enable_pp1(); void thread_ap_idle(); void thread_ap_idle_pp1(); void thread_ap_phi_mux_axi_data_V_1_phi_fu_315_p4(); void thread_ap_phi_mux_eol_1_phi_fu_304_p4(); void thread_ap_phi_mux_eol_2_phi_fu_387_p4(); void thread_ap_phi_mux_eol_phi_fu_327_p4(); void thread_ap_phi_mux_p_Val2_s_phi_fu_352_p4(); void thread_ap_phi_reg_pp1_iter1_axi_last_V_2_reg_335(); void thread_ap_phi_reg_pp1_iter1_p_Val2_s_reg_348(); void thread_ap_predicate_op59_read_state6(); void thread_ap_ready(); void thread_brmerge_fu_438_p2(); void thread_exitcond2_fu_413_p2(); void thread_exitcond_fu_424_p2(); void thread_i_V_fu_418_p2(); void thread_img_data_stream_0_V_blk_n(); void thread_img_data_stream_0_V_din(); void thread_img_data_stream_0_V_write(); void thread_img_data_stream_1_V_blk_n(); void thread_img_data_stream_1_V_din(); void thread_img_data_stream_1_V_write(); void thread_img_data_stream_2_V_blk_n(); void thread_img_data_stream_2_V_din(); void thread_img_data_stream_2_V_write(); void thread_j_V_fu_429_p2(); void thread_tmp_8_fu_444_p1(); void thread_tmp_user_V_fu_404_p1(); void thread_ap_NS_fsm(); }; } using namespace ap_rtl; #endif
d4848192be2cebe3c420c01c6580af81f6f4db56
af6838bd0efd21b499dce8a8ed3ca61ff631dfd0
/Module 3 Projects/minmax.cpp
6469af4e68894aac643c951f7069b465724ab921
[]
no_license
EJAtwood/CS-161-Projects
8317925e6bd646cefcccc268e242287f19b39e23
ab0bb076e6beee00374dd4139b9ddb743774490a
refs/heads/master
2020-07-13T06:29:15.465143
2019-08-28T21:17:10
2019-08-28T21:17:10
205,017,536
0
0
null
null
null
null
UTF-8
C++
false
false
1,997
cpp
minmax.cpp
#include <iostream> int main () { int userInteger; //number of integers user wants to inputr int number; //counter variable int userIntEnter; // user input for set of integers int maxNum; //used to assign max value from user int minNum; //used to assign min value from user //disaplys prompt for user std::cout << "How many integers would you like to enter?" << std::endl; std::cin >> userInteger; //action for user std::cout << "Please enter " << userInteger << " integers." << std::endl; //initialized these variables number = 1;//since i initialized at 1, number has to be <= userInteger //I could have initalized at 0 and then number < userInteger maxNum = 0; minNum = 0; /*number is used as a counter variable. Each iteration goes up by one until it matches amount of userInteger which is the amount of integer the user wants to enter */ while (number <= userInteger) { std::cin >> userIntEnter; //gets integer in set of userIntegers and uses to test loop /*number is equal to one means that the counter is at one and only one number has been input by the user. This one number would be the min and max...since there is only one number entered so far */ if (number == 1) maxNum = minNum = userIntEnter; /*If the above if statement is false, then we move here. If the user entered integer is greater than the variable maxNum (so true), then maxNum is assinged this user input value */ if (userIntEnter > maxNum) maxNum = userIntEnter; /*If the above is false, then we move here. If the user entered integer is less than the assigned minNum, minNum is assinged this value */ if (userIntEnter < minNum) minNum = userIntEnter; number++; //adds 1 to variable number as a increment counter } //we ouput the newly assinged variable with their respective asociation, ie min or max value std::cout << "min: " << minNum << std::endl; std::cout << "max: " << maxNum << std::endl; return 0; }
55cf6bd4c0b4a0e66124bcc366d8f38c95e64b68
169251c757f13d19b52ca3443fe4140ee6ceb5a8
/source/2019.08.08/库致远/sequence.cpp
1f908b9e6b881b1962d06b8806f55ce6d82810b3
[]
no_license
kcudcigam/Problems
e394dd75539f69107e2987126036f2638aeaf4e2
a53b473b9a5df5d91da13d52aba1c59ce1bc5a53
refs/heads/master
2023-07-25T06:26:40.350993
2019-08-29T11:24:07
2019-08-29T11:24:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
sequence.cpp
#include<bits/stdc++.h> using namespace std; template <typename T> void read(T &x){ int f=1;x=0;char c=getchar(); for (;!isdigit(c);c=getchar()) if (c=='-') f=-f; for (; isdigit(c);c=getchar()) x=x*10+c-'0'; x*=f; } int n,m,l,r,s,e; long long a[500005],kzy; int main(){ freopen("sequence.in","r",stdin); freopen("sequence.out","w",stdout); read(n);read(m); for (int i=1;i<=m;i++) { read(l);read(r);read(s);read(e); long long k=(e-s)/(r-l+1); for (int j=l;j<=r;j++){ a[j]=a[j]+s; s=s+k; } } for (int i=1;i<=n;i++){ kzy=a[i]^kzy; } cout<<kzy<<endl; return 0; }
c059507b9f15e1df0befd33b279a4f8254ccc20a
fdf8d0ecc667ad5212ad975f1982e0bf33765179
/include/libada/Ada.hpp
214ec64835448a0bd0a54f33d5d12a1ea7930815
[ "BSD-3-Clause" ]
permissive
personalrobotics/libada
55b099568e4c4b543e702b51102579d35c7e1125
f34e88b5d805065e85190fdd526f79875b075fc2
refs/heads/master
2023-04-27T16:29:42.425965
2023-04-15T23:29:27
2023-04-15T23:29:27
127,351,940
7
2
BSD-3-Clause
2023-01-16T21:55:54
2018-03-29T22:01:14
C++
UTF-8
C++
false
false
9,266
hpp
Ada.hpp
#ifndef LIBADA_ADA_HPP_ #define LIBADA_ADA_HPP_ #include <chrono> #include <future> #include <memory> #include <Eigen/Core> #include <aikido/common/ExecutorThread.hpp> #include <aikido/common/RNG.hpp> #include <aikido/constraint/Testable.hpp> #include <aikido/constraint/TestableIntersection.hpp> #include <aikido/constraint/dart/CollisionFree.hpp> #include <aikido/constraint/dart/TSR.hpp> #include <aikido/control/TrajectoryExecutor.hpp> #include <aikido/control/ros/RosJointStateClient.hpp> #include <aikido/io/CatkinResourceRetriever.hpp> #include <aikido/planner/World.hpp> #include <aikido/planner/kunzretimer/KunzRetimer.hpp> #include <aikido/planner/parabolic/ParabolicSmoother.hpp> #include <aikido/robot/ros/RosRobot.hpp> #include <aikido/statespace/dart/MetaSkeletonStateSpace.hpp> #include <aikido/trajectory/Interpolated.hpp> #include <aikido/trajectory/Spline.hpp> #include <aikido/trajectory/Trajectory.hpp> #include <dart/dart.hpp> #include <ros/ros.h> #include <iostream> namespace ada { /// ADA-specific defaults for postprocessors // Default kunz parameters constexpr static double DEFAULT_KUNZ_DEVIATION = 1e-3; constexpr static double DEFAULT_KUNZ_STEP = 1e-3; struct KunzParams : aikido::planner::kunzretimer::KunzRetimer::Params { KunzParams( double _maxDeviation = DEFAULT_KUNZ_DEVIATION, double _timeStep = DEFAULT_KUNZ_STEP) : aikido::planner::kunzretimer::KunzRetimer::Params( _maxDeviation, _timeStep) { // Do nothing. } }; // Default parabolic smoother parameters constexpr static double DEFAULT_SMOOTH_RESOLUTION = 1e-3; constexpr static double DEFAULT_SMOOTH_TOLERANCE = 1e-3; struct SmoothParams : aikido::planner::parabolic::ParabolicSmoother::Params { SmoothParams( double _resolution = DEFAULT_SMOOTH_RESOLUTION, double _tolerance = DEFAULT_SMOOTH_TOLERANCE) : aikido::planner::parabolic::ParabolicSmoother::Params() { aikido::planner::parabolic::ParabolicSmoother::Params:: mFeasibilityCheckResolution = _resolution; aikido::planner::parabolic::ParabolicSmoother::Params:: mFeasibilityApproxTolerance = _tolerance; } }; class Ada final : public aikido::robot::ros::RosRobot { public: /// Inner AdaHand class that implements Aikido's Hand Interface class AdaHand; // Default Parameters #define DEFAULT_THREAD_CYCLE std::chrono::milliseconds(10) #define DEFAULT_ROS_TRAJ_INTERP_TIME 0.1 #define DEFAULT_ROS_TRAJ_GOAL_TIME_TOL 5.0 #define DEFAULT_CONF_OBJ_NS "adaConf" #define DEFAULT_ARM_TRAJ_CTRL "trajectory_controller" #define DEFAULT_HAND_TRAJ_CTRL "hand_controller" #define DEFAULT_EE_NAME "end_effector" #define DEFAULT_URDF \ "package://ada_description/robots_urdf/ada_with_camera.urdf" #define DEFAULT_SRDF \ "package://ada_description/robots_urdf/ada_with_camera.srdf" /// Construct Ada metaskeleton using a URI. /// \param[in] simulation True if running in simulation mode. /// \param[in] env World (either for planning, post-processing, or executing). /// \param[in] confNamespace rosparam namespace of configuration object. /// \param[in] threadCycle Period of self-driven spin thread (ms) /// \param[in] node ROS node. Required for running in real. /// \param[in] rngSeed seed for initializing random generator. /// May be nullptr if simulation is true. /// \param[in] retriever Resource retriever for retrieving Ada Ada(bool simulation, aikido::planner::WorldPtr env = aikido::planner::World::create(), const std::string confNamespace = DEFAULT_CONF_OBJ_NS, const std::chrono::milliseconds threadCycle = DEFAULT_THREAD_CYCLE, const ::ros::NodeHandle* node = nullptr, aikido::common::RNG::result_type rngSeed = std::random_device{}(), const dart::common::ResourceRetrieverPtr& retriever = std::make_shared<aikido::io::CatkinResourceRetriever>()); virtual ~Ada(); /// Simulates up to the provided timepoint. /// Assumes that parent robot is locked. /// \param[in] timepoint Time to simulate to. void step(const std::chrono::system_clock::time_point& timepoint) override; /// Get the arm. aikido::robot::RobotPtr getArm(); /// Get the const arm. aikido::robot::ConstRobotPtr getArm() const; /// Get the hand as an Aikido::Robot aikido::robot::RobotPtr getHandRobot(); /// Get the const hand as an Aikido::Robot aikido::robot::ConstRobotPtr getHandRobot() const; /// Get the hand as an Aikido::Hand std::shared_ptr<AdaHand> getHand(); /// Generates an arm-only trajectory from the given list of configurations. /// Runs through the provided or default postprocessor if enabled. /// \param[in] waypoints Ordered configurations to add to the trajectory, each /// of which is paired with its desired time along the output trajectory. /// \param[in] collisionFree Collision constraint during post-processing ONLY. /// \param[in] trajPostProcessor Optional explicit postprocessor. /// \return Trajectory pointer, or nullptr on error. aikido::trajectory::TrajectoryPtr computeArmJointSpacePath( const std::vector<std::pair<double, Eigen::VectorXd>>& waypoints, const aikido::constraint::dart::CollisionFreePtr& collisionFree, const std::shared_ptr<aikido::planner::TrajectoryPostProcessor> trajPostProcessor = nullptr); // Default to selfCollisionConstraint aikido::trajectory::TrajectoryPtr computeArmJointSpacePath( const std::vector<std::pair<double, Eigen::VectorXd>>& waypoints, const std::shared_ptr<aikido::planner::TrajectoryPostProcessor> trajPostProcessor = nullptr) { return computeArmJointSpacePath( waypoints, getSelfCollisionConstraint(), trajPostProcessor); } /// Sets the default trajectory post-processor /// Also enables automatic post-processing for all planning functions. /// \param[in] velocityLimits Can be arm-only DoF or whole-bot DoF /// Leave blank for MetaSkeleton defaults. /// \param[in] accelerationLimits Can be arm-only DoF or whole-bot DoF /// Leave blank for MetaSkeleton defaults. /// \param[in] params Can be KunzParams() [default], SmoothParams(), or custom template <typename PostProcessor = aikido::planner::kunzretimer::KunzRetimer> void setDefaultPostProcessor( const Eigen::VectorXd& velocityLimits = Eigen::VectorXd(), const Eigen::VectorXd& accelerationLimits = Eigen::VectorXd(), const typename PostProcessor::Params& params = KunzParams()); /// Starts the provided trajectory controllers if not started already. /// Makes sure that no other controllers are running and conflicting /// with the ones we are about to start. /// \return true if all controllers have been successfully switched bool startTrajectoryControllers(); /// Turns off provided trajectory controllers /// \return true if all controllers have been successfully switched bool stopTrajectoryControllers(); /// Opens Ada's hand std::future<void> openHand(); /// Closes Ada's hand std::future<void> closeHand(); /// Get current soft velocity limits Eigen::VectorXd getVelocityLimits(bool armOnly = false) const; /// Get current soft acceleration limits Eigen::VectorXd getAccelerationLimits(bool armOnly = false) const; /// Get Body Node of End Effector dart::dynamics::BodyNodePtr getEndEffectorBodyNode(); private: /// Switches between controllers. /// \param[in] startControllers Controllers to start. /// \param[in] stopControllers Controllers to stop. /// Returns true if controllers successfully switched. bool switchControllers( const std::vector<std::string>& startControllers, const std::vector<std::string>& stopControllers); // Call to spin first to pass current time to step void spin(); // Utility function to (re)-create and set trajectory executors void createTrajectoryExecutor(bool isHand); // True if running in simulation. const bool mSimulation; // Names of the ros trajectory controllers std::string mArmTrajControllerName; std::string mHandTrajControllerName; // Soft velocity and acceleration limits Eigen::VectorXd mSoftVelocityLimits; Eigen::VectorXd mSoftAccelerationLimits; Eigen::VectorXd mDefaultVelocityLimits; Eigen::VectorXd mDefaultAccelerationLimits; // Ros node associated with this robot. ::ros::NodeHandle mNode; // Ros controller service client. std::unique_ptr<::ros::ServiceClient> mControllerServiceClient; // Ros joint state client. std::unique_ptr<aikido::control::ros::RosJointStateClient> mJointStateClient; // Name of the End Effector in the URDF // might differ for different Ada configurations std::string mEndEffectorName; // The robot arm aikido::robot::RobotPtr mArm; // The robot hand as an Aikido Robot aikido::robot::RobotPtr mHandRobot; // Self-driving thread std::unique_ptr<aikido::common::ExecutorThread> mThread; // State Publisher in Simulation ros::Publisher mPub; // Inner Hand Object std::shared_ptr<AdaHand> mHand; }; } // namespace ada #include "detail/Ada-impl.hpp" #include "libada/AdaHand.hpp" #endif // LIBADA_ADA_HPP_
453981d189b701dbe230b0a5e3801f1b27b0f191
7ab3757bde602ebe0b2f9e49d7e1d5f672ee150a
/template/src/libtemplate/Symbol.cpp
147dd11271d5c2bc8efd5854142aa492a56b9850
[ "MIT" ]
permissive
brucelevis/easyeditor
310dc05084b06de48067acd7ef5d6882fd5b7bba
d0bb660a491c7d990b0dae5b6fa4188d793444d9
refs/heads/master
2021-01-16T18:36:37.012604
2016-08-11T11:25:20
2016-08-11T11:25:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
Symbol.cpp
#include "Symbol.h" #include "Sprite.h" namespace etemplate { Symbol::Symbol() { } Symbol::~Symbol() { } void Symbol::Draw(const s2::RenderParams& params, const ee::Sprite* spr) const { } sm::rect Symbol::GetSize(const ee::Sprite* sprite) const { return sm::rect(sm::vec2(0, 0), 200, 200); } void Symbol::LoadResources() { } }
06455570113890a7735f83b9a57ae1a2b3729940
195e0e06d409e663d0a4f3eb964b56d278de7a95
/Escape-From-Ethically-Questionable-Labs/character.cpp
64a1ccc11ad76288dbec36aa21246b420c6146b4
[]
no_license
JasonCFisher/Sample-Coarsework
ee73e6e3a0070a5502da4c88cd00368e418ce50f
1eca8f09117fbd6c4adc5807b33e701c5dca33e7
refs/heads/master
2021-01-19T04:20:16.673570
2016-06-15T22:32:23
2016-06-15T22:32:23
61,242,555
0
0
null
null
null
null
UTF-8
C++
false
false
2,816
cpp
character.cpp
/**************************************************************************** **Program Filename: character.cpp **Author: Jason Fisher **Date: 3/3/2016 **Description: character.cpp File for Final Project **Input: **Output: ****************************************************************************/ #include "character.hpp" //Default Constructor Character::Character() { location = " "; counter = 25; minCounter = 0; maxItems = 2; } //setLocation void Character::setLocation(std::string l) { location = l; } //getLocation std::string Character::getLocation() { return location; } //decCounter - increments counter void Character::decCounter() { counter--; } //getCounter int Character::getCounter() { return counter; } //getMaxCounter int Character::getMinCounter() { return minCounter; } //getMaxItems int Character::getMaxItems() { return maxItems; } //getLabCoatSize int Character::getLabCoatSize() { return labCoat.size(); } //getInventory std::string Character::getInventory(int x) { return labCoat.at(x); } /*************************************************************************** **Function: addItem **Description: adds item to lab coat if lab coat not full **Parameters: std::string i **Pre-Condition: **Post-Condition: ***************************************************************************/ void Character::addItem(std::string i) { if (labCoat.size() < maxItems) { labCoat.push_back(i); std::cout << "Your inventory now contains:" << std::endl; for (int count = 0; count < labCoat.size(); count++) { std::cout << labCoat.at(count) << std::endl; } std::cout << std::endl; } else { std::cout << "Your pockets are already bulging with the things you've " << std::endl; std::cout << "picked up. If you try putting anything else in them they'll probably " << std::endl; std::cout << "burst like someone's chest in Alien. Seriously, enough already. " << std::endl; std::cout << "Go use something if you want to pick up more stuff." << std::endl; } } /*************************************************************************** **Function: removeItem **Description: finds item in inventory and removes **Parameters: std::string i **Pre-Condition: **Post-Condition: ***************************************************************************/ void Character::removeItem(std::string i) { labCoat.erase(find(labCoat.begin(), labCoat.end(), i)); std::cout << "Your inventory now contains:" << std::endl; if (labCoat.size() == 0) { std::cout << "Nothing." << std::endl; } for (int count = 0; count < labCoat.size(); count++) { std::cout << labCoat.at(count) << std::endl; } std::cout << std::endl; }
7fab5422af31ee7ccd57169e7e184e6ce34d2afb
717ee95b70a35672791199458bba9f125f29361a
/third.ino
d1955936e23869f7fa4f38d578b1ec77132a26af
[ "Apache-2.0" ]
permissive
GodofDragons/Smart-Drinks
adf19b511d07054e4b835b0f022208a19a758f5b
284b2af13b6d9233da19baa1ab296c7b4b3da19e
refs/heads/master
2020-04-04T15:09:08.786852
2018-11-04T18:14:58
2018-11-04T18:14:58
156,026,174
0
1
null
null
null
null
UTF-8
C++
false
false
908
ino
third.ino
int trigPin = 10; int echoPin = 9; int pumpPin = 13; int heightInputPin = A4; long duration, distanceCM, height; long heightFill; void setup() { Serial.begin(9600); pinMode (trigPin, OUTPUT); pinMode (echoPin, INPUT); pinMode (heightInputPin, INPUT); pinMode(pumpPin, OUTPUT); long totalHeight = getDistance(); height = analogRead(heightInputPin); heightFill = (totalHeight - height)*0.8; } void loop() { digitalWrite(pumpPin, HIGH); while (getDistance() > heightFill) {} digitalWrite(pumpPin, LOW); exit(0); } long getDistance () { digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distanceCM = microsecondsToCentimeters(duration); return distanceCM; } long microsecondsToCentimeters(long duration) { return (duration / 29.0)/2.0; }
8277801ea2ca90b38c1c9568cf9f1e0c21324441
1164e110181e49c66f1e09fef6a27b5ac8e8621c
/libs/beacon/include/beacon/trusted_dealer.hpp
06b1aac951042df85b4f60d5c2b0a363bc334bd7
[ "Apache-2.0" ]
permissive
fetchai/ledger
3d560d7f75282bc4c4f08c97a9954100bf6e7257
c49fb154ec148518d72d4a8f3d2e9b020160d5dd
refs/heads/master
2021-11-25T06:44:22.761854
2021-11-18T09:21:19
2021-11-18T09:21:19
117,567,381
82
55
Apache-2.0
2021-11-18T09:28:30
2018-01-15T16:15:05
C++
UTF-8
C++
false
false
2,100
hpp
trusted_dealer.hpp
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "beacon/dkg_output.hpp" #include "beacon/notarisation_manager.hpp" #include "crypto/mcl_dkg.hpp" #include <map> #include <set> #include <vector> namespace fetch { namespace beacon { class TrustedDealer { public: using DkgOutput = beacon::DkgOutput; using MuddleAddress = byte_array::ConstByteArray; using DkgKeyInformation = crypto::mcl::DkgKeyInformation; using NotarisationManager = ledger::NotarisationManager; using SharedNotarisationManager = std::shared_ptr<NotarisationManager>; using CabinetNotarisationKeys = std::map<MuddleAddress, NotarisationManager::PublicKey>; TrustedDealer(std::set<MuddleAddress> cabinet, double threshold); DkgOutput GetDkgKeys(MuddleAddress const &address) const; std::pair<SharedNotarisationManager, CabinetNotarisationKeys> GetNotarisationKeys( MuddleAddress const &address); private: std::set<MuddleAddress> cabinet_{}; uint32_t threshold_{0}; std::map<MuddleAddress, uint32_t> cabinet_index_{}; std::vector<DkgKeyInformation> outputs_{}; std::vector<SharedNotarisationManager> notarisation_units_{}; CabinetNotarisationKeys notarisation_keys_{}; }; } // namespace beacon } // namespace fetch
6b29134b1b5a8e20d405eead738cea1cdbe88e0c
2af921e619dead8071ca824bd96a7b9c22a7edd3
/week07/Practise/Exercise1/main.cpp
ee4516cc74b15906fedd076fd23a2360f94ebf56
[]
no_license
green-fox-academy/Soulmast3r01
d1d5fd40b6c40b8d8acd912074dea4302da21c17
3426772fb68cc494853db6c161388825adcf30b9
refs/heads/master
2020-04-02T17:33:41.075636
2019-01-10T16:21:58
2019-01-10T16:21:58
154,662,186
0
0
null
null
null
null
UTF-8
C++
false
false
348
cpp
main.cpp
#include <iostream> #include <vector> int matrixSum(std::vector<std::vector<int>>matrix); int main() { std::cout << "Hello, World!" << std::endl; return 0; } int matrixSum(std::vector<std::vector<int>>matrix) { int counter = 0; for (int i = 0; i <matrix.size(); ++i) { if(i % 2 == 0){ counter + } } }
07acbb6028fe459e8c51242340354c6b30fd0463
7acc93d31b1fad7f0f71625116a7d372ca37c80c
/src/optimization/iSAM2Optimizer.cpp
d93bc6fa1281c0778eb3c20c58e1fd03e23480b7
[ "MIT" ]
permissive
KMS-TEAM/vi_slam
bcb4b4b7393e395d8861e1c4aae24622f0b0d7b0
4cb5ae94bfecef5758f809d84e135e574b4fb860
refs/heads/main
2023-06-14T18:21:14.431529
2021-07-12T17:08:56
2021-07-12T17:08:56
384,636,583
1
1
null
null
null
null
UTF-8
C++
false
false
2,233
cpp
iSAM2Optimizer.cpp
// // Created by cit-industry on 11/07/2021. // #include "vi_slam/optimization/iSAM2Optimizer.h" #include "vi_slam/basics/yaml.h" namespace vi_slam{ namespace optimization{ using namespace datastructures; using namespace gtsam; using namespace std; iSAM2Optimizer::iSAM2Optimizer(std::string& config_path) { basics::Yaml readConfig(config_path); // YAML intrinsics (pinhole): [fu fv pu pv] std::vector<double> cam0_intrinsics(4); cam0_intrinsics = readConfig.get_vec<double>("cam0/resolution"); this->f = (cam0_intrinsics[0] + cam0_intrinsics[1]) / 2; this->cx = cam0_intrinsics[2]; this->cy = cam0_intrinsics[3]; // YAML image resolution parameters (radtan): [k1 k2 r1 r2] vector<double> cam0_resolution(2); cam0_resolution = readConfig.get_vec<double>("cam0/resolution"); this->resolution_x = cam0_resolution[0]; this->resolution_y = cam0_resolution[1]; // YAML extrinsics (distance between 2 cameras and transform between imu and camera)) vector<double> T_cam1(16); T_cam1 = readConfig.get_vec<double>("cam1/T_cn_cnm1"); this->Tx = T_cam1[3]; vector<double> T_cam_imu(16); T_cam_imu = readConfig.get_vec<double>("cam0/T_cam_imu"); gtsam::Matrix4 T_cam_imu_mat_copy(T_cam_imu.data()); T_cam_imu_mat = move(T_cam_imu_mat_copy); // Set K: (fx, fy, s, u0, v0, b) (b: baseline where Z = f*d/b; Tx is negative) this->K.reset(new Cal3_S2Stereo(cam0_intrinsics[0], cam0_intrinsics[1], 0.0, this->cx, this->cy, -this->Tx)); // iSAM2 settings ISAM2Params parameters; parameters.relinearizeThreshold = 0.01; parameters.relinearizeSkip = 1; isam.reset(new ISAM2(parameters)); } iSAM2Optimizer::~iSAM2Optimizer(){}; void iSAM2Optimizer::initializeIMUParameters(Tracking &tracker) { tracker.PreintegrateIMU(); } void iSAM2Optimizer::optimizerVIO_IMU() { } } }
43242fa48e8cd7081bb108455f7c25f19617824b
cd954f06232e3b9fe008f9a6291689e75f179a88
/acwing/算法竞赛进阶指南/0x08-总结与练习/117. 占卜DIY.cpp
bba037beaa813bf59d0dfe3f8832e90752d006b2
[ "MIT" ]
permissive
upupming/algorithm
35446f4b15f3a505041ac65c1dc6f825951d8e99
a3807ba05960b9025e55d668ef95b3375ae71895
refs/heads/master
2023-08-09T03:07:18.047084
2023-08-01T05:57:13
2023-08-01T05:57:13
217,478,998
239
34
MIT
2021-08-13T05:42:26
2019-10-25T07:41:19
C++
UTF-8
C++
false
false
1,194
cpp
117. 占卜DIY.cpp
/* 除了 K 以外,其他牌具有对称性,但是为了进行下标索引,还是需要转为数字 支持放在堆上面,又要从底下抽取一张,可以用 deque 来存储牌 仔细分析一下,放在上面这个过程只需要计数即可,不必真正的放入,可以直接用 vector 就行 模拟一下整个过程即可 */ #include <iostream> #include <map> #include <vector> using namespace std; map<char, int> m{{'A', 1}, {'0', 10}, {'J', 11}, {'Q', 12}, {'K', 13}}; vector<int> d[14]; // 统计正面朝上的数的个数 int cnt[14]; int main() { char ch; int x; for (int i = 1; i <= 13; i++) { for (int j = 0; j < 4; j++) { cin >> ch; x = ch - '0'; if (x >= 2 && x <= 9) d[i].push_back(x); else d[i].push_back(m[ch]); } } for (int i = 0; i < 4; i++) { x = d[13][i]; while (x != 13) { cnt[x]++; int y = d[x].back(); d[x].pop_back(); x = y; } } int ans = 0; for (int i = 1; i <= 12; i++) { ans += (cnt[i] == 4); } cout << ans << endl; return 0; }
968b45a263622c973f78a9ce245321286e8c409b
db6f3e6486ad8367c62163a4f124da185a64ab5d
/include/retdec/loader/loader/segment.h
4e1697c55e3ff76294de98177740c814c66fe705
[ "MIT", "Zlib", "JSON", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0", "BSD-3-Clause", "GPL-2.0-only", "NCSA", "WTFPL", "BSL-1.0", "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
avast/retdec
c199854e06454a0e41f5af046ba6f5b9bfaaa4b4
b9791c884ad8f5b1c1c7f85c88301316010bc6f2
refs/heads/master
2023-08-31T16:03:49.626430
2023-08-07T08:15:07
2023-08-14T14:09:09
113,967,646
3,111
483
MIT
2023-08-17T05:02:35
2017-12-12T09:04:24
C++
UTF-8
C++
false
false
2,349
h
segment.h
/** * @file include/retdec/loader/loader/segment.h * @brief Declaration of segment class. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_LOADER_RETDEC_LOADER_SEGMENT_H #define RETDEC_LOADER_RETDEC_LOADER_SEGMENT_H #include <cstdint> #include <memory> #include <string> #include <vector> #include "retdec/common/range.h" #include "retdec/fileformat/fftypes.h" #include "retdec/fileformat/types/sec_seg/sec_seg.h" #include "retdec/loader/loader/segment_data_source.h" #include "retdec/loader/utils/range.h" namespace retdec { namespace loader { class Segment { public: Segment(const retdec::fileformat::SecSeg* secSeg, std::uint64_t address, std::uint64_t size, std::unique_ptr<SegmentDataSource>&& dataSource); Segment(const Segment& segment); const retdec::fileformat::SecSeg* getSecSeg() const; bool containsAddress(std::uint64_t address) const; std::uint64_t getAddress() const; std::uint64_t getEndAddress() const; std::uint64_t getPhysicalEndAddress() const; std::uint64_t getSize() const; std::uint64_t getPhysicalSize() const; retdec::common::Range<std::uint64_t> getAddressRange() const; retdec::common::Range<std::uint64_t> getPhysicalAddressRange() const; const retdec::common::RangeContainer<std::uint64_t>& getNonDecodableAddressRanges() const; std::pair<const std::uint8_t*, std::uint64_t> getRawData() const; bool hasName() const; const std::string& getName() const; void setName(const std::string& name); bool getBytes(std::vector<unsigned char>& result) const; bool getBytes(std::vector<unsigned char>& result, std::uint64_t addressOffset, std::uint64_t size) const; bool getBits(std::string& result) const; bool getBits(std::string& result, std::uint64_t addressOffset, std::uint64_t bytesCount) const; bool setBytes(const std::vector<unsigned char>& value, std::uint64_t addressOffset); void resize(std::uint64_t newSize); void shrink(std::uint64_t shrinkOffset, std::uint64_t newSize); void addNonDecodableRange(retdec::common::Range<std::uint64_t> range); private: const retdec::fileformat::SecSeg* _secSeg; std::uint64_t _address; std::uint64_t _size; std::unique_ptr<SegmentDataSource> _dataSource; std::string _name; retdec::common::RangeContainer<std::uint64_t> _nonDecodableRanges; }; } // namespace loader } // namespace retdec #endif
bb51459404041d9f19193de92027421f4d91f0fe
20d8e57f4ba8f3984b0eed25be774670f060ef5d
/999_exe/trunk/plugins/web_plugin_factory.cpp
2d389bbe0593c33c2cbec215947e1dbe5f46d4b2
[]
no_license
brBart/project-999
86a4806df73522cd93c6d479a0a73a62ebb9e59c
25859f1f3926feb9e044a865d6c96093943fbe55
refs/heads/master
2020-03-27T20:52:57.499396
2012-04-22T19:16:06
2012-04-22T19:16:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
cpp
web_plugin_factory.cpp
/* * web_plugin_factory.cpp * * Created on: 31/05/2010 * Author: pc */ #include "web_plugin_factory.h" /** * @class PluginFactory * Class in charge of creating or passing widgets to the QWebPage for display. */ /** * Constructs a PluginFactory. */ WebPluginFactory::WebPluginFactory(QObject *parent) : QWebPluginFactory(parent) { } /** * Returns the widget of the passed mime type. */ QObject* WebPluginFactory::create(const QString &mimeType, const QUrl &url, const QStringList &argumentNames, const QStringList &argumentValues) const { if (m_Plugins.contains(mimeType)) { PluginWidget *widget = m_Plugins[mimeType]; widget->init(argumentNames, argumentValues); return dynamic_cast<QObject*>(widget); } else { return NULL; } } /** * Returns a empty list just for compliance. */ QList<QWebPluginFactory::Plugin> WebPluginFactory::plugins() const { QList<QWebPluginFactory::Plugin> plugins; return plugins; } /** * Installs a plugin in the factory. */ void WebPluginFactory::install(QString mimeType, PluginWidget *widget) { m_Plugins[mimeType] = widget; } /** * Removes a plugin from the factory. */ void WebPluginFactory::remove(QString mimeType) { m_Plugins.remove(mimeType); }
1cd1711e02160d9999c683f5bdd1c54ac31e2f4f
b86d4fe35f7e06a1981748894823b1d051c6b2e5
/UVa/10784 Diagonal.cpp
9469d14bb6684df5ab95df5f054be647a8e730f8
[]
no_license
sifat-mbstu/Competitive-Programming
f138fa4f7a9470d979106f1c8106183beb695fd2
c6c28979edb533db53e9601073b734b6b28fc31e
refs/heads/master
2021-06-26T20:18:56.607322
2021-04-03T04:52:20
2021-04-03T04:52:20
225,800,602
1
0
null
null
null
null
UTF-8
C++
false
false
569
cpp
10784 Diagonal.cpp
#include <math.h> #include <stdio.h> int nCr(int n, int r) { if(r>n) { printf("FATAL ERROR"); return 0; } if(n==0 || r==0 || n==r) { return 1; } else { return (int)lround( ((double)n/(double)(n-r)/(double)r) * exp(lgamma(n) - lgamma(n-r) - lgamma(r))); } } int nPr(int n, int r) { if(r>n) {printf("FATAL ERROR"; return 0;} if(n==0 || r==0) { return 1; } else { if (n==r) { r = n - 1; } return (int)lround( ((double)n/(double)(n-r)) * exp(lgamma(n) - lgamma(n-r))); } } int main() { }
0e1b767b7752cadb9706ef25ed02c10eca061bf0
0591bffd540504c2e5fc9bcab71e2c7f833b4787
/i2cs_ping_attiny.ino
75c143e5b01d03e918d9acd2bb0cb1ccfb09ef01
[ "MIT" ]
permissive
omzn/i2cs_ping_attiny
c5459d0094794e3e6370ef3f4300fcd745708bf0
edd42a44b95b09d33e58d3f6fee228a04e872a6a
refs/heads/master
2021-01-10T05:55:42.786993
2016-03-28T13:27:55
2016-03-28T13:27:55
50,355,769
0
0
null
null
null
null
UTF-8
C++
false
false
2,784
ino
i2cs_ping_attiny.ino
/* * Usage write: low_th high_th * read : distance */ #include <TinyWireS.h> // Requires fork by Rambo with onRequest support #include <TinyNewPing.h> // NewPing library modified for ATtiny //#include <EEPROM.h> #define LED_R_PIN (1) #define LED_G_PIN (4) #define TRIG_PIN (3) #define ECHO_PIN (3) //#define EEPROM_THRES_ADDR 0 #define SLAVE_ADDR (0x26) #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. byte distance; // Where the Distance is stored (8 bit unsigned) uint8_t thres[2]; // 0-warn, 1-emerg unsigned long ptime = 0; uint8_t ledstatus = 0; NewPing SensorOne (TRIG_PIN, ECHO_PIN, MAX_DISTANCE); // Define the Sensor bool thres_changed; void setup() { delay(100); // EEPROM.begin(); pinMode(LED_R_PIN, OUTPUT); pinMode(LED_G_PIN, OUTPUT); digitalWrite(LED_R_PIN, LOW); digitalWrite(LED_G_PIN, LOW); // thres[0] = EEPROM.read(EEPROM_THRES_ADDR + 0); // thres[1] = EEPROM.read(EEPROM_THRES_ADDR + 1); // if (thres[0] == 255) { thres[0] = 0; // } // if (thres[1] == 255) { thres[1] = 0; // } TinyWireS.begin(SLAVE_ADDR); // Begin I2C Communication TinyWireS.onRequest(transmit); // When requested, call function transmit() TinyWireS.onReceive(set_thres); } void loop() { //distance = SensorOne.ping_cm(); // Get distance in cm. Could be changed to distance = SensorOne.ping_median(10) / US_ROUNDTRIP_CM; // Take the median of 5 readings // if (thres_changed) { // EEPROM.update(EEPROM_THRES_ADDR + 0, thres[0]); // EEPROM.update(EEPROM_THRES_ADDR + 1, thres[1]); // thres_changed = false; // } delay(30); // Delay to avoid interference from last ping unsigned long t = millis(); if (thres[0] > 0 && thres[1] > 0) { if (distance >= thres[0] && distance < thres[1]) { // normal digitalWrite(LED_R_PIN, LOW); digitalWrite(LED_G_PIN, HIGH); } else if (distance >= thres[0] && distance >= thres[1]) { // low if (t - ptime > 500 || t < ptime) { ledstatus = 1 - ledstatus; digitalWrite(LED_R_PIN, ledstatus); digitalWrite(LED_G_PIN, LOW); ptime = t; } } else { // full digitalWrite(LED_R_PIN, HIGH); digitalWrite(LED_G_PIN, HIGH); } } } void set_thres(uint8_t y) { uint8_t x[16]; int i = 0; if (y < 1) { return; } while (y--) { x[i] = TinyWireS.receive(); // receive byte as a character i++; } if (i > 1) { thres[0] = x[0]; thres[1] = x[1]; // thres_changed = true; } } void transmit() { TinyWireS.send(distance); // Send last recorded distance for current sensor }
d02bdb740222a38c8866609bf4c44340ee9cfe9f
7878f4ca118be351c37ecf33ee449521f37c7012
/ShellProject/computer.h
f4e9d342659210bcf88263039ed9dca860c17087
[]
no_license
Vaerish/My-Linux-File-manager
76602880f16c174130119b80be3b0da10249f9ac
befe054b37a48477b042a2e3976d37884931eff9
refs/heads/master
2021-02-13T17:53:46.147830
2019-12-07T00:38:53
2019-12-07T00:38:53
244,718,502
0
0
null
null
null
null
UTF-8
C++
false
false
63,881
h
computer.h
#include <vector> #include <iostream> #include "node.h" #include <limits> #include <sstream> #include <map> #include <string> #include <random> #include "schedulers.h" #ifndef COMPUTER_H #define COMPUTER_H extern bool doneCore; extern vector<Process> core1; extern vector<Process> core2; extern vector<string> schedHist; extern int schedCh; namespace Shell // { const std::string CMDS[] = {"", "ls", "pwd", "exit", "mkdir", "touch", "cd", "rm", "rmdir", "chmod", "useradd", "chuser", "groupadd", "usermod", "chown", "chgrp", "userdel", "groupdel", "groups", "users", "run", "ps", "kill", "schedHist", "algorithm"}; // Computer class // Represents the OS who controls the file System. class Computer { // Private vars private: // The root File Node* rootFile; // The current Directory the System is looking at Node* curDir; // The current logged in user. User* curUser; // The name of this computer std::string computerName; // Creating lists to track users and groups std::vector<User> user_list; std::vector<std::string> group_list; // FLAG: SET TO FALSE BEFORE USING. DO NOT USE OUTSIDE THE PARSER. bool parser_flag = false; // String used to hold temporary strings std::string temp_string = ""; std::string temp_token = ""; vector<Process> procList; //whether it is in first or second core bool firstCore = true; //States if the current user is in the same group //as the file it is getting permissions from. bool InGroup = false; //String used to hold the permission section that //a specific user refrences to when deciding //if they have permission to do something or not std::string PermissionSection = ""; // Public functions public: // The constructor taking in the computer name Computer(std::string name) { // set the name and call the default constuctor computerName = name; Computer(); } // Deconstructor, make sure we don't have memory leaks :) ~Computer() { //delete curUser; // Delete the root : let its deconstructor handle deleting // the rest of the file system. delete rootFile; // Make sure we clear the pointers to prevent some accidental // pointer to mem we don't own. rootFile = nullptr; curDir = nullptr; curUser = nullptr; } // Main constructor - does the heavy lifting Computer() { // No user to start off with, need to login. curUser = nullptr; // Create the root of the file system. rootFile = new Node("", true, nullptr, 0, "root", "Users"); //Was "root" "root" // If this changes back then in the resetGroup function it would need to change back as well // Set the root's parent to itself - makes it auto handle ../ on root. // simple hack to make my life easier down the line. rootFile->parent = rootFile; // Make the root user. //curUser = new User("root", "root", true); user_list.push_back(User("root", "Users", true)); group_list.push_back("Users"); curUser = &user_list[0]; // set the computer name. computerName = "computer"; // move the current location to the root - this will change depending // on who logs in curDir = rootFile; // create home and root directory rootFile->AddChild(new Node("root", true, rootFile, curUser->Username(), curUser->Group())); rootFile->AddChild(new Node("home", true, rootFile, curUser->Username(), curUser->Group())); } // Running the computer. Handles all operations from here. void run() { // Start the console. console(); } // Private functions private: // Console handles taking in input and outputting correct response. // is what emulates running the shell. void console() { // control var for machine bool looping = true; // storages variables std::string dir; std::string input; // While we haven't quit while(looping) { // Gets current working directory dir = pwd(); //looks for user's name in wd int pos = dir.find(curUser->Username()); // if found, use ~ insead the complete path. if(pos > -1) dir = "~" + dir.substr(pos + curUser->Username().length()); // output the status line. std::cout << curUser->Username() << "@" << computerName << ":" << dir << "#" << " "; // Get input from the user. std::getline(std::cin, input); // Parse it and handle it. looping = parser(input); doneCore = looping; } } //Returns -1 if user cannot be found or returns the index int findUser(const std::string uname) { for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == uname) return i; } return -1; } //Returns -1 id the group cannot be found or returns the index int findGroup(const std::string gname) { for (int i = 0; (unsigned) i < group_list.size(); i++) { if (group_list.at(i) == gname) return i; } return -1; } //Function that sets all of the objects owned by a specified user back to root void resetUser(const std::string uname, Node* file) { if (file->User() == uname) { file->setUser("root"); } // Make sure all child nodes are reset in the same way for (auto child : file->Children()) { resetUser(uname, child.second); } } // Function that sets all of the objects owned by a specific group back to root void resetGroup(const std::string gname, Node* file) { if (file->Group() == gname) { file->setGroup("Users"); } // Make sure all child nodes are reset in the same way for (auto child : file->Children()) { resetGroup(gname, child.second); } } // Parses input. returns true if the console should continue. bool parser(std::string input) { // storage vars for easier manipulation of data. std::stringstream stream(input); std::string command; std::vector<std::string> args; // Using a string stream to quickly break up input on spaces. stream >> command; // get the rest of the input std::string temp; // store it as an argument while(stream >> temp) { args.push_back(temp); } // return the results of commands func return commands(command, args); } // attempts to run a command using the command and the args for it. // returns true if console should keep running. bool commands(std::string command, std::vector<std::string> args) { // Handles ls command if(command == "ls") { // if command has args if(args.size() > 0) { // if it has only the correct arg. if(args.size() == 1 && args[0] == "-l") { // display output PermissionSection = curDir->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(curDir->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('r') != std::string::npos) { for(auto childPair :curDir->Children()) { Node* child = childPair.second; std::cout << child->PermsStr() << " " << child->NumDirs() << " " << child->User() << " " << child->Group() << " " << child->Size() << " " << child->TimeStr() << " " // Adds blue color if it is a dir << (child->isDir ? "\033[34m" : "") << child->name << "\033[0m" << std::endl; } } else { std::cout << "Permission Denied due to not having read permissions" << std::endl; } } else { // otherwise invalid useage std::cout << "Invalid use - For help use: help ls\n"; } } // no args else { PermissionSection = curDir->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(curDir->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('r') != std::string::npos) { // display simple output for(auto child : curDir->Children()) { Node* childSec = child.second; PermissionSection = childSec->PermsStr(); std::cout << (child.second->IsDir() ? "\033[34m" : "") << child.first << "\033[0m "; } // adds a new line at the end only if there was something to print if(curDir->Children().size() > 0) std::cout << std::endl; } else { std::cout << "Permission Denied due to not having read permissions" << std::endl; } } } // Handles pwd command else if(command == "pwd") { // outputs the current directory std::cout << pwd() << std::endl; } // Handles the exit command else if(command == "exit") { // return false to signal ending return false; } // Handles mkdir command else if(command == "mkdir") { // if there are no arguments if(args.size() == 0) { // error std::cout << "Invalid use - For help use: help mkdir\n"; } // else else { PermissionSection = curDir->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; //Print group list for that user InGroup = user_list.at(i).contains(curDir->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { // iterate over arguments for(std::string arg : args) { // Attempt to add new directory if fails output such a message. if(!curDir->AddChild(new Node(arg, true, curDir, curUser->Username(), curUser->Group()))) { std::cout << "mkdir: cannot create directory '" << arg << "': File exits\n"; } } } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } // Handles touch command else if(command == "touch") { // if there are no args if(args.size() == 0) { // error std::cout << "touch: Invalid use - For help use: help touch\n"; } // otherwise attempt do it else { PermissionSection = curDir->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(curDir->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { // iterate over args for(std::string arg : args) { // try to add and if that fails, update the current timestamp if(!curDir->AddChild(new Node(arg, false, curDir, curUser->Username(), curUser->Group()))) { PermissionSection = curDir->children[arg]->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(curDir->children[arg]->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->children[arg]->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { curDir->children[arg]->UpdateTimeStamp(); } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } // Handles cd command else if (command == "cd") { // if no args if(args.size() == 0) { // set current directory to root's home curDir = rootFile->children["root"]; // if their directory doesn't exist anymore, put them at the root. if(curDir == nullptr) curDir = rootFile; } // if there is args and it is more than one else if(args.size() > 1) { // error std::cout << "cd: too many arguments - For help use: help cd\n"; } // else if only one arg else { // attempt to find the file. Node* file = findFile(args[0]); // if file exists and is not a directory error if(file != nullptr) if(!file->isDir) std::cout << "cd: " << args[0] << " Not a directory\n"; else { PermissionSection = file->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(file->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == file->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('x') != std::string::npos || args[0] == ".." || args[0] == "/") { // else set curDir to it curDir = file; } else { std::cout << "Permission Denied due to not having execute permissions" << std::endl; } } // else file isn't real else std::cout << "cd: Directory does not exist\n"; } } // Handles rm command else if (command == "rm") { // if no args if(args.size() == 0) { // error std::cout << "rm: Invalid use - For help use: help rm\n"; } // else if there are args else { PermissionSection = curDir->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(curDir->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { // iterate over them for(auto arg : args) { // try to find the arg Node* file = findFile(arg); // if it doesn't exist, error if(file == nullptr) { std::cout << "rm: File '" << arg << "' not found\n"; } // if file is a directory else if(file->isDir) { // error std::cout << "rm: cannot remove '" << arg << "': Is a directory\n"; } // else is valid so delete else { file->parent->DeleteChild(file); delete file; } } } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } // Handles rmdir command else if (command == "rmdir") { // if there are no args if(args.size() == 0) { // error std::cout << "rm: Invalid use - For help use: help rmdir\n"; } // has args else { PermissionSection = curDir->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(curDir->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == curDir->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { // iterate over args for(auto arg : args) { //find file Node* file = findFile(arg); // if not found if(file == nullptr) { // error std::cout << "rm: File '" << arg << "' not found\n"; } // if file is not a directory else if(!file->isDir) { // error std::cout << "rm: failed to remove '" << arg << "': Not a directory\n"; } // if there is stuff in the file, else if(file->children.size() > 0) { // error std::cout << "rm: failed to remove '" << file->Name() << "': Directory not empty\n"; } // else delete files else { // if we try to delete this directory, move back a directory if(file == curDir) curDir = file->parent; // delete the file if it isn't the root. if(file != rootFile) { file->parent->DeleteChild(file); delete file; } // else error else std::cout << "rm: Permission Denied\n"; } } } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } // Handle chmod command else if(command == "chmod") { // int for conversion int permInt; // if there are more than 2 args if(args.size() > 2) { // error std::cout << "chmod: Too many arguments - For help use: help chmod\n"; } // if args is less 2 else if(args.size() < 2) { // error std::cout << "chmod: Not enough arguments - For help use: help chmod\n"; } else { try { // convert the number to an int permInt = std::stoi(args[0]); // make sure it is a valid if(permInt > 777 || permInt < 0) { // error std::cout << "chmod: Invalid permission number\n"; } else { // iterate over args for(auto arg : args) { // if is the first ignore if(arg == args[0]) continue; // try to find file Node* file = findFile(arg); // if file doesn't exist if(file == nullptr) { // error std::cout << "File '" << arg << "' does not exist\n"; } // else else { PermissionSection = file->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(file->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == file->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { // break up the digit file->perms = { permInt / 100 % 10, permInt / 10 % 10, permInt % 10 }; } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } } } catch(const std::exception&) { std::cout << "chmod: " << args[0] << " invalid Permissions\n"; } } } else if(command == "cat") { // if no args if(args.size() == 0) { // error std::cout << "cat: Invalid use"; } // else if there are args else { // iterate over them for(auto arg : args) { // try to find the arg Node* file = findFile(arg); // if it doesn't exist, error if(file == nullptr) { std::cout << "cat: File '" << arg << "' not found\n"; } // if file is a directory else if(file->isDir) { // error std::cout << "cat: cannot display '" << arg << "': Is a directory\n"; } // else is valid so display else { PermissionSection = file->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(file->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == file->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('r') != std::string::npos) { std::cout << "Fake Fake Fake, blah blah blah is in this file. " << "If you are seeing this then you did have permission to cat the file.\n"; } else { std::cout << "Permission Denied due to not having read permissions" << std::endl; } } } } } // Handles useradd command else if(command == "useradd") { // Creates new user and adds them to Users group & Sets that group as their primary if (args.size() == 1) { // Checking to make sure that this user does not already exist parser_flag = false; for (int i = 0; (unsigned)i < user_list.size(); ++i) { if (user_list.at(i).Username() == args[0]) { parser_flag = true; break; } } // User already exists, send error message if (parser_flag) { std::cout << "Error: User '" << args[0] << "' already exists. Use 'users' command to see list of current users." << std::endl; } // User does not already exist: Create and add to nedded lists. else { user_list.push_back(User(args[0], "Users", false)); curUser = &user_list[0]; //Update curUser pointer after altering vector } } else if (args.size() == 3 && args[0] == "-G") { // Form of "useradd -G <group[,group]> <username>" // Adds new user to all listed groups if possible (group exists). Still sets Users to be default group. // Checking to make sure that this user does not already exist parser_flag = false; for (int i = 0; (unsigned)i < user_list.size(); ++i) { if (user_list.at(i).Username() == args[2]) { parser_flag = true; break; } } // User already exists, send error message if (parser_flag) { std::cout << "Error: User '" << args[2] << "' already exists. Use 'users' command to see list of current users" << std::endl; } else // User does not already exist so create it and add it to all existing groups listed { user_list.push_back(User(args[2], "Users", false)); curUser = &user_list[0]; //Update curUser pointer after altering vector // Search through listed groups and add to all existing ones temp_string = args[1]; while (temp_string.find(",") != std::string::npos) { parser_flag = false; temp_token = temp_string.substr(0, temp_string.find(",")); // Only adds to users groups if the group already exists for (int i = 0; (unsigned) i < group_list.size(); i++) { if (temp_token == group_list.at(i)) { parser_flag = true; user_list.back().addGroup(temp_token); } } // For every group that does not exist, inform the user if (!parser_flag) { std::cout << temp_token << ": This group does not exist. Can only add to existing groups." << std::endl; } temp_string.erase(0, temp_string.find(",") + 1); } parser_flag = false; // Only adds to users groups if the group already exists for (int i = 0;(unsigned) i < group_list.size(); i++) { if (temp_string == group_list.at(i)) { parser_flag = true; user_list.back().addGroup(temp_string); } } // For every group that does not exist, inform the user if (!parser_flag) { std::cout << temp_string << ": This group does not exist. Can only add to existing groups." << std::endl; } } } else { // Else no arguments provided std::cout << "Invalid use - For help use: help useradd\n"; } } // Handles chuser command else if(command == "chuser") { if (args.size() == 1) { // For of "chuser <username>" // Change active user to one indicated if that user exists, otherwise fails // Check that requested user exists parser_flag = false; for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == args[0]) { // Since user exists, change curr user to that parser_flag = true; curUser = &user_list[i]; break; } } if (!parser_flag) { std::cout << args[0] << " not in user list. Can only change to existing users, see help for details." << std::endl; } } // Else no arguments provided else { std::cout << "Invalid use - For help use: help chuser\n"; } } // Handles groupadd command else if(command == "groupadd") { if (args.size() == 1) { // Form of "groupadd <group>" // Creates new group and adds Root user to itself // Checks that the group does not already exists before adding it parser_flag = false; for (int i = 0; (unsigned) i < group_list.size(); i++) { if (group_list.at(i) == args[0]) { parser_flag = true; } } if (parser_flag) { std::cout << args[0] << " already exists" << std::endl; } else { // Adding group to group list group_list.push_back(args[0]); // Adding root to group user_list.at(0).addGroup(args[0]); } } else { // Else no arguments provided std::cout << "Invalid use - For help use: help groupadd\n"; } } // Handles usermod command else if(command == "usermod") { if (args.size() == 3 && args[0] == "-g") { // Must have "usermod -g <group> <username>" format. // Fail if user or group doesnt exist or the user is not part of the group. if (findUser(args[2]) == -1) { std::cout << args[2] << "is not an existing user" << std::endl; } else //Both user and group exist { // Need to check that the user already is part of the group to be able to set it to its primary if (user_list.at(findUser(args[2])).contains(args[1])) { user_list.at(findUser(args[2])).setPrimaryGroup(args[1]); } else { std::cout << "User is not part of " << args[1] << " group, cannot set to primary" << std::endl; } } } else if (args.size() == 4 && args[0] == "-a" && args[1] == "-G") { // Must have "usermod -a -G <group> <username>" format. // Adds indicated user to groups list. Fails if the user or group doesnt already exist. if (findGroup(args[2]) == -1) { std::cout << args[2] << " is not an existing group" << std::endl; } else if (findUser(args[3]) == -1) { std::cout << args[3] << " is not an existing user" << std::endl; } else //Both user and group exist { user_list.at(findUser(args[3])).addGroup(args[2]); // Add group to users group list } } else { // Incorrect number of arguments provided std::cout << "Invalid use - For help use: help usermod\n"; } } else if(command == "chown") { //Changes the owner of the indicated object to the indicated user. Fails if user or object doesnt exist or user doesnt have write permissions. if (args.size() == 2) { Node* file = findFile(args[1]); //Check that the user exists if (findUser(args[0]) == -1) { std::cout << args[0] << " is not an existing user" << std::endl; } //Check that the object exists else if (file == nullptr) { std::cout << args[1] << " is not an existing file or directory" << std::endl; } // Try and switch owner of object else { PermissionSection = file->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(file->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == file->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { //Set owner of object to specified user file->setUser(args[0]); } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } else { std::cout << "Invalid use - For help use: help chown\n"; } } else if(command == "chgrp") { Node* file = findFile(args[1]); //Change group of the indicated object to indicated group. Fails if object or user doesnt exist as well as user not having permissins if (args.size() == 2) { //Check that the group exists if (findGroup(args[0]) == -1) { std::cout << args[0] << " is not an existing group" << std::endl; } //Check that the object exists else if (file == nullptr) { std::cout << args[1] << " is not an existing file or directory" << std::endl; } // Try and switch group of object else { PermissionSection = file->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(file->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == file->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('w') != std::string::npos) { //Set owner of object to specified user file->setGroup(args[0]); } else { std::cout << "Permission Denied due to not having write permissions" << std::endl; } } } else { std::cout << "Invalid use - For help use: help chgrp\n"; } } else if(command == "userdel") { //Removes user from the system if it exists and not root. Any owned objects become Root users property. if (args.size() == 1) { if (args[0] == "root") { std::cout << "Root user cannot be removed" << std::endl; } else if (findUser(args[0]) == -1) { std::cout << args[0] << " is not a current existing user" << std::endl; } else // Not root and an existing user. Valid. { temp_string = curUser->Username(); // Saves current user user_list.erase(user_list.begin() + findUser(args[0]) , user_list.begin() + findUser(args[0]) + 1); curUser = &user_list[findUser(temp_string)]; // Fixes the curUser pointer after altering the users list //Change any objects that were once owned by this user back to root resetUser(args[0], rootFile); } } //Removes listed user from indicated group. Fails if either doen't exist or user is not part of the group, the group is Users, or the user is Root else if (args.size() == 3 && args[0] == "-G") { if (findUser(args[2]) == -1) // Makes sure user exists { std::cout << args[2] << " is not an existing user" << std::endl; } else if (findGroup(args[1]) == -1) // Makes sure group exists { std::cout << args[1] << " is not an existing group" << std::endl; } else if (!user_list.at(findUser(args[2])).contains(args[1])) // Make sure user is part of group { std::cout << args[2] << " is not part of that group" << std::endl; } else if (args[1] == "Users") { std::cout << "Cannot remove User group from any user" << std::endl; } else if (args[2] == "root") { std::cout << "Cannot remove root from any group" << std::endl; } else // Valid, remove user from group { user_list.at(findUser(args[2])).removeGroup(args[1]); } } else { std::cout << "Invalid use - For help use: help userdel\n"; } } else if(command == "groupdel") { //Removes an existing group from the system as long as its not root. All permissions for this group are changed to Users permissions. if (args.size() == 1) { if (args[0] == "root") { std::cout << "Root group cannot be removed" << std::endl; } else if (findGroup(args[0]) == -1) { std::cout << args[0] << " is not a current existing group" << std::endl; } else // Not root and an existing group. Valid. { // Erase group from groups list group_list.erase(group_list.begin() + findGroup(args[0]), group_list.begin() + findGroup(args[0]) + 1); // Erase groups from users group list. If any had this group as primary, set it to Users. for (int i = 0; (unsigned) i < user_list.size(); i++) { user_list.at(i).removeGroup(args[0]); } // Switch permissions of anything belonging to this group to Users group resetGroup(args[0], rootFile); } } else { std::cout << "Invalid use - For help use: help groupdel\n"; } } else if(command == "groups") { parser_flag = false; // Prints out all the groups associated with this user if (args.size() == 1) { for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == args[0]) { parser_flag = true; //Print group list for that user user_list.at(i).printGroupList(); break; } } if (!parser_flag) { std::cout << "User does not exist" << std::endl; } } else { std::cout << "Invalid use - For help use: help groups\n" << std::endl; } } else if(command == "users") { //Prints all known users for (int i = 0; (unsigned)i < user_list.size(); i++) { std::cout << user_list.at(i).Username() << " "; } std::cout << std::endl; } else if(command == "run") { // if no args if(args.size() == 0) { // error std::cout << "run: Invalid use"; } // else if there are args else { // iterate over them for(auto arg : args) { // try to find the arg Node* file = findFile(arg); // if it doesn't exist, error if(file == nullptr) { std::cout << "run: File '" << arg << "' not found\n"; } // if file is a directory else if(file->isDir) { // error std::cout << "run: cannot execute '" << arg << "': Is a directory\n"; } // else is valid so execute else { PermissionSection = file->PermsStr(); //Finds if current User in in same group as object for (int i = 0; (unsigned) i < user_list.size(); i++) { if (user_list.at(i).Username() == curUser->Username()) { parser_flag = true; InGroup = user_list.at(i).contains(file->Group()); } } //Checks if root, owner, same group, or public and assigns PermissionSection accordingly if(curUser->Username() == "root") { PermissionSection = "rwx"; } else if(curUser->Username() == file->User()) { PermissionSection = PermissionSection.substr(1,3); } else if(InGroup) { PermissionSection = PermissionSection.substr(4,3); } else { PermissionSection = PermissionSection.substr(7,3); } if (PermissionSection.find('x') != std::string::npos) { Process p; p.id = file->name; p.startTime = 0; //this will update in the thread as each new process is found by the schedular p.totalTimeNeeded = file->time_run; //this makes it between ten and 50 units long p.user = file->user; if(firstCore) //determines which core the file that needs to be executed will be pushed to { core1.push_back(p); firstCore = false; } else { core2.push_back(p); firstCore = true; } } else { std::cout << "Permission Denied due to not having execute permissions" << std::endl; } } } } } else if(command == "ps") //calls both cores and says what needs to be run as long as it is not done and is currently running { for(unsigned int i = 0; i < core1.size(); i++) { if(!core1[i].isDone && core1[i].timeScheduled != 1) { cout << core1[i].id << " " << core1[i].user << " " << core1[i].startTime << " " << core1[i].timeScheduled << " "<< core1[i].totalTimeNeeded << endl; } } for(unsigned int i = 0; i < core2.size(); i++) { if(!core2[i].isDone&& core1[i].timeScheduled != 1) { cout << core2[i].id << " " << core2[i].user << " " << core2[i].startTime << " " << core2[i].timeScheduled << " "<< core2[i].totalTimeNeeded << endl; } } } else if(command == "kill") { if(args.size() == 0) { // error std::cout << "kill: Invalid use"; } // else if there are args else { // iterate over them for(auto arg : args) { // try to find the arg Node* file = findFile(arg); // if it doesn't exist, error if(file == nullptr) { std::cout << "kill: File '" << arg << "' not found\n"; } // if file is a directory else if(file->isDir) { // error std::cout << "kill: cannot execute '" << arg << "': Is a directory\n"; } // else is valid so execute else { for(unsigned int i = 0; i < core1.size(); i++) { if(core1[i].id == file->name) { core1[i].isDone = true; } } for(unsigned int i = 0; i < core2.size(); i++) { if(core2[i].id == file->name) { core2[i].isDone = true; } } } } } } else if(command == "schedHist") //prints out list of schedHist from point it was called { for(unsigned int i = 0; i < schedHist.size(); i++) { cout << schedHist[i] << endl; } } // Commnad to allow the user to switch simulated execution algorithm else if(command == "algorithm") { for(auto arg : args) //schedCh communicates to threads what current algorithm is being used { if(arg == "RR") { schedCh = 1; } else if(arg == "SPN") { schedCh = 2; } else if(arg == "SRT") { schedCh = 3; } else if(arg == "HRRN") { schedCh = 4; } else if(arg == "FCFS") { schedCh = 5; } else { //list of all available options cout << "In correct Option only available algorithms are " << endl; cout << "RR" << endl; cout << "SPN" << endl; cout << "SRT" << endl; cout << "HRRN" << endl; cout << "FCFS" << endl; cout << "All spelled like above." << endl; } } } else if(command == "help") { if(args.size() == 0 || args[0] == "") { std::cout << "Usage: help cmd : prints help for a given command\n"; std::cout << "Usage: help -a : prints help for all avaliable commands\n"; } else if(args[0] == "-a") { for(std::string cmd : CMDS) { commands("help", std::vector<std::string>{cmd}); } } else if(args[0] == "ls") { std::cout << "Usage: ls : prints files in directory\n"; std::cout << "Usage: ls -l : prints files in directory" << " with extra information\n"; } else if(args[0] == "pwd") { std::cout << "Usage: pwd : prints working file directory\n"; } else if(args[0] == "exit") { std::cout << "Usage: exit : exits console\n"; } else if(args[0] == "mkdir") { std::cout << "Usage: mkdir dir... : makes the directories listed\n"; } else if(args[0] == "touch") { std::cout << "Usage: touch file... :will make a file if " << "doesn't exist\n"; } else if(args[0] == "cd") { std::cout << "Usage: cd dir : changes current working directory\n"; } else if(args[0] == "rm") { std::cout << "Usage: rm file... : removes the files listed\n"; } else if(args[0] == "rmdir") { std::cout << "Usage: rmdir dir... : removes the directories " << "listed\n"; } else if(args[0] == "chmod") { std::cout << "Usage: chmod ### file/dir... : changes permissions" << " of files/directories listed\n"; } else if(args[0] == "useradd") { std::cout << "Usage: useradd <username> : Creates a new user\n"; std::cout << "Usage: useradd -G <group[,group]> <username> : Creates a new user\n"; std::cout << "and adds them to the specified groups\n"; } else if(args[0] == "chuser") { std::cout << "Usage: chuser <username> : Changes to indicated active user\n"; } else if(args[0] == "groupadd") { std::cout << "Usage: groupadd <group> : Creates a new group\n"; } else if(args[0] == "usermod") { std::cout << "Usage: usermod -g <group> <username> : Sets primary group for indicated\n"; std::cout << "user to be indicated group\n"; std::cout << "Usage: usermod -a -G <group> <username> : Add indicated user to indicated group\n"; } else if(args[0] == "chown") { std::cout << "Usage: chown <username> <object> : Change owner of indicated object to indicated user\n"; } else if(args[0] == "chgrp") { std::cout << "Usage: chgrp <group> <object> : Change objects group to indicated group\n"; } else if(args[0] == "userdel") { std::cout << "Usage: userdel -G <group> <username> : Remove the indicated user from the indicated\n"; std::cout << "group\n"; std::cout << "Usage: userdel <username> : Removes indicated user from system\n"; } else if(args[0] == "groupdel") { std::cout << "Usage: groupdel <group> : Remove the group from the system\n"; } else if(args[0] == "groups") { std::cout << "Usage: groups <username> : Lists groups indicated user is part of\n"; } else if(args[0] == "users") { std::cout << "Usage: users : List the known users to the system\n"; } else if(args[0] == "run") { std::cout << "Usage: run <file> : Executes the indicated file\n"; } else if(args[0] == "ps") { std::cout << "Usage: ps : Lists all currently running processes\n"; } else if(args[0] == "kill") { std::cout << "Usage: kill <file> : Terminates indicated files execution\n"; } else if(args[0] == "schedHist") { std::cout << "Usage: schedHist : Outputs the scheduling history\n"; } else if(args[0] == "algorithm") { std::cout << "Usage: algorithms <RR, SPN, SRT, HRRN, FCFS> : Changes the current scheduling algorithm to the indicated algorithm\n"; } else { std::cout << "help: command doesn't exist\n"; } } // else handle no command found else { std::cout << "Command '" << command << "' not found.\n"; } return true; } // returns the current working directory std::string pwd() { std::string dir; // make a new tracker Node* traverse = curDir; // check to see if we are on the root. if(traverse == rootFile) { dir = "/"; } // if we are not, work backwards while(traverse != rootFile) { if(traverse->IsDir()) dir = "/" + traverse->Name() + dir; traverse = traverse->Parent(); } // return directory return dir; } // Finds the file or not, takes a path and returns a pointer // pointer is null if it wasn't found Node* findFile(std::string path) { Node* next = curDir; // stream for parsing std::stringstream pathStream(path); bool succeed = true; // while there exists stuff to parse while(pathStream.peek() != std::char_traits<char>::eof()) { std::string dir; // delimited on / getline(pathStream, dir, '/'); // check if we are looking at the root of the directory if(dir == "" && pathStream.peek() == std::char_traits<char>::eof()) { next = rootFile; } else { // if find .. then go to parent if(dir == "..") { next = next->parent; } // if . then stay else if(dir == ".") { // Nothing needed to do. } // else look for child. else { auto found = next->children.find(dir); succeed = found != next->children.end(); // if looking and didn't find stop if(!succeed) break; else next = next->children[dir]; } } } // return if we found it or no return succeed ? next : nullptr; } }; } #endif
0fb5e65df47d6f63557b31993aed54a24f239bbb
c635ff855ce2fdbae22c402a683af44d41beee44
/Compucell/include/CompuCell3D/CompuCell3D/Field3D/Field3DImpl.h
df57c519641f94a6892dd8d266fa7ee2e43ad3d8
[]
no_license
teinvdlugt/ru-modellenpracticum
d2ff87c6253429c3c5a55a3b60c9e9cdcc6eaf44
d1a1ba344fdddd4cab988cd265d64665b612bbac
refs/heads/master
2022-11-20T19:09:07.504230
2020-07-10T14:32:32
2020-07-10T14:32:32
256,532,365
1
0
null
null
null
null
UTF-8
C++
false
false
5,529
h
Field3DImpl.h
/************************************************************************* * CompuCell - A software framework for multimodel simulations of * * biocomplexity problems Copyright (C) 2003 University of Notre Dame, * * Indiana * * * * This program is free software; IF YOU AGREE TO CITE USE OF CompuCell * * IN ALL RELATED RESEARCH PUBLICATIONS according to the terms of the * * CompuCell GNU General Public License RIDER you can redistribute it * * and/or modify it under the terms of the GNU General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *************************************************************************/ #ifndef FIELD3DIMPL_H #define FIELD3DIMPL_H #include <math.h> #include <CompuCell3D/Boundary/BoundaryStrategy.h> #include <BasicUtils/BasicException.h> #include "Dim3D.h" #include "Field3D.h" namespace CompuCell3D { //indexing macro #define PT2IDX(pt) (pt.x + ((pt.y + (pt.z * dim.y)) * dim.x)) template<class T> class Field3D; /** * Default implementation of the Field3D interface. * */ template<class T> class Field3DImpl : public Field3D<T> { protected: Dim3D dim; T *field; T initialValue; long len; public: /** * @param dim The field dimensions * @param initialValue The initial value of all data elements in the field. */ Field3DImpl(const Dim3D dim, const T &initialValue) : dim(dim),field(0), initialValue(initialValue) { ASSERT_OR_THROW("Field3D cannot have a 0 dimension!!!", dim.x != 0 && dim.y != 0 && dim.z != 0); // Check that the dimensions are not too large. ASSERT_OR_THROW("Field3D dimensions too large!!!", log((double)dim.x)/log(2.0) + log((double)dim.y)/log(2.0) + log((double)dim.z)/log(2.0) <= sizeof(int) * 8); // Allocate and initialize the field len = dim.x * dim.y * dim.z; field = new T[len]; for (unsigned int i = 0; i < len; i++) field[i] = initialValue; } virtual ~Field3DImpl() { if(field){ delete [] field; field=0; } } virtual void set(const Point3D &pt, const T value) { ASSERT_OR_THROW("set() point out of range!", isValid(pt)); field[PT2IDX(pt)] = value; } virtual void resizeAndShift(const Dim3D theDim, Dim3D shiftVec=Dim3D()){ T* field2 = new T[theDim.x*theDim.y*theDim.z]; //first initialize the lattice with initial value for(long int i = 0 ; i < theDim.x*theDim.y*theDim.z ; ++i) field2[i]=initialValue; //then copy old field for (int x = 0; x < theDim.x; x++) for (int y = 0; y < theDim.y; y++) for (int z = 0; z < theDim.z; z++) //if ((x-shiftVec.x < dim.x) && (y-shiftVec.y < dim.y) && (z < dim.z)) //field2[(x+shiftVec.x)+(((y+shiftVec.y)+((z+shiftVec.z)*theDim.y))*theDim.x)] = getQuick(Point3D(x,y,z)); if ((x-shiftVec.x>=0) && (x-shiftVec.x<dim.x) && (y-shiftVec.y>=0) && (y-shiftVec.y<dim.y) && (z-shiftVec.z>=0) && (z-shiftVec.z<dim.z) ){ field2[x+((y+(z*theDim.y))*theDim.x)] = getQuick(Point3D(x-shiftVec.x,y-shiftVec.y,z-shiftVec.z)); } delete [] field; field = field2; dim = theDim; //Set dimension for the Boundary Strategy BoundaryStrategy::getInstance()->setDim(dim); } virtual void setDim(const Dim3D theDim, Dim3D shiftVec=Dim3D()) { this->resizeAndShift(theDim); } T getQuick(const Point3D &pt) const { //return field[PT2IDX(pt)]; return (isValid(pt) ? field[PT2IDX(pt)] : initialValue); } void setQuick(const Point3D &pt,const T _value) { field[PT2IDX(pt)]=_value; } virtual T get(const Point3D &pt) const { return (isValid(pt) ? field[PT2IDX(pt)] : initialValue); } virtual T getByIndex(long _offset) const { return ( ((0<=_offset)&&(_offset<len)) ? field[_offset] : initialValue); } virtual void setByIndex(long _offset, const T _value) { if((0<=_offset)&&(_offset<len)) field[_offset]=_value; } virtual Dim3D getDim() const {return dim;} virtual bool isValid(const Point3D &pt) const { return (0 <= pt.x && pt.x < dim.x && 0 <= pt.y && pt.y < dim.y && 0 <= pt.z && pt.z < dim.z); } }; }; #endif
f0f3926f55539bd99523b991128b86b204a5d070
1489fb78dfe5d612de7f81e3019f70215dad15c9
/discord.cpp
14725321606a4508b53d69db6fc1c00eda0613e2
[]
no_license
Kawa-oneechan/Asspull3X
3222223c676a6b315b4d81c09deb084e1d2d92bb
095a4c347d44695042d095ea72c102a04ec03418
refs/heads/master
2023-09-02T19:44:33.810347
2023-08-29T12:36:43
2023-08-29T12:36:43
209,994,262
27
5
null
2022-06-02T18:34:01
2019-09-21T13:56:29
C
UTF-8
C++
false
false
2,300
cpp
discord.cpp
#include "asspull.h" #include <discord_rpc.h> #include <time.h> namespace Discord { bool enabled = false; const char* ApplicationId = "709359522732441653"; typedef void (WINAPI* INITIALIZEPROC) (const char* applicationId, DiscordEventHandlers* handlers, int autoRegister, const char* optionalSteamId); typedef void (WINAPI* UPDATEPRESENCEPROC) (const DiscordRichPresence* presence); typedef void (WINAPI* CLEARPRESENCEPROC) (void); typedef void (WINAPI* SHUTDOWNPROC) (void); INITIALIZEPROC __Discord_Initialize; UPDATEPRESENCEPROC __Discord_UpdatePresence; CLEARPRESENCEPROC __Discord_ClearPresence; SHUTDOWNPROC __Discord_Shutdown; HMODULE discordDLL = NULL; void SetPresence(char* gameName); void Initialize() { if (!enabled) return; discordDLL = LoadLibraryExA("discord-rpc.dll", NULL, 0); if (discordDLL == NULL) { Log(logWarning, UI::GetString(IDS_DISCORDDLL)); //"Discord is enabled but the DLL isn't here." enabled = false; return; } __Discord_Initialize = (INITIALIZEPROC)GetProcAddress(discordDLL, "Discord_Initialize"); __Discord_UpdatePresence = (UPDATEPRESENCEPROC)GetProcAddress(discordDLL, "Discord_UpdatePresence"); __Discord_ClearPresence = (CLEARPRESENCEPROC)GetProcAddress(discordDLL, "Discord_ClearPresence"); __Discord_Shutdown = (SHUTDOWNPROC)GetProcAddress(discordDLL, "Discord_Shutdown"); DiscordEventHandlers handlers = {}; __Discord_Initialize(ApplicationId, &handlers, 1, nullptr); SetPresence(NULL); } void SetPresence(char* gameName) { if (!enabled) return; WCHAR wName[128] = { 0 }; if (gameName == NULL) wcscpy(wName, UI::GetString(IDS_NOTPLAYING)); else mbstowcs(wName, gameName, ARRAYSIZE(wName)); Log(L"Discord: \"%s\"", wName); DiscordRichPresence discord_presence = {}; discord_presence.details = gameName; discord_presence.startTimestamp = time(NULL); discord_presence.smallImageKey = "a3x"; discord_presence.largeImageText = gameName; char key[32] = {}; for (auto i = 0; i < 32 && gameName[i] != 0; i++) key[i] = (char)tolower(gameName[i]); discord_presence.largeImageKey = key; __Discord_UpdatePresence(&discord_presence); } void Shutdown() { if (!enabled) return; __Discord_ClearPresence(); __Discord_Shutdown(); FreeModule(discordDLL); } }
6f1dbae0185ac7b21428d61b56a4b16f0709d6bc
43dbc05549b8b9ffe067791c2564aeb150f9fe89
/10452 - Marcus.cpp
c94d500cf9547d9d7574eb77ac0ed724a4ca43e9
[]
no_license
maruf-rahad/uva
d985f526d2eec45e34785ef10fb2c8402e7c620b
f8a1e2cf8335f64cbab94461dd3f45bb68e15077
refs/heads/master
2023-02-04T04:36:33.272863
2020-12-27T08:02:42
2020-12-27T08:02:42
292,663,715
1
0
null
null
null
null
UTF-8
C++
false
false
1,542
cpp
10452 - Marcus.cpp
#include<bits/stdc++.h> using namespace std; char letter[7] = {'I','E','H','O','V','A','#'}; char ch[10][10]; int r[4] = {0,0,1,-1}; int c[4] = {1,-1,0,0}; int flag = 0; int flag2 = 0; int n,m; void makestep(int x,int y,int xx,int yy) { if(flag2==1)printf(" "); flag2 = 1; if(abs(x-xx)==1)printf("forth"); else if(yy-y==1)printf("right"); else if(yy-y==-1)printf("left"); } void marcus(int x,int y,int step) { if(flag==1||step==7){ flag = 1; return; } for(int i=0;i<4;i++) { int xx = x+r[i]; int yy = y+c[i]; if(ch[xx][yy]==letter[step]&&xx>=1&&xx<=n&&yy>=1&&yy<=m) { makestep(x,y,xx,yy); // printf("going %d %d\n",xx,yy); if(step==7){ flag = 1; return ; } marcus(xx,yy,++step); } } } int main() { // freopen("output.txt","w",stdout); int a,b,i,j,x,y,t; char str1,str2; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); getchar(); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%c",&ch[i][j]); if(ch[i][j]=='@'){ x = i; y = j; } } getchar(); } flag = 0; flag2 = 0; // for(i=0;i<6;i++)printf("%c \n",letter[i]); // printf("yes\n"); marcus(x,y,0); printf("\n"); } return 0; }
b0641af60704c43c5b20b7bba8ffd80ea03bbe11
065e4598998ce8b78b12dedd48585fb4b2930033
/运算符重载/testVec2d.cpp
1c4a51a2e9e50d3d9bb21d324610a2f0ed1827e7
[]
no_license
zhuzhu18/C-CPP-learning
ace73a997fb79d5ea96536497cf34b6c1c112e56
5852e7f622f49fefb9abdc37bb74bfc8b41ad58a
refs/heads/master
2023-04-27T10:26:33.304376
2023-04-17T00:06:12
2023-04-17T00:06:12
191,556,152
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
382
cpp
testVec2d.cpp
#include <iostream> #include "Vec2D.h" using namespace std; int main() { Vec2D v1{ 2, 3 }, v2{ 3, 4 }; cout << v1.toString() << endl; cout << (v1 + v2).toString() << endl; cout << (2 + v2).toString() << endl; v1 += v2; cout << v1.toString() << endl; v1[0] = 10; // ÐÞ¸Äv1[0] cout << "v1[0] = " << v1[0] << ", v1[1] = " << v1[1] << endl; }
b20575457c231206658ab7352374142e100f7ad6
4044f3d0accc6e75141f9428c1a892bfce6256e9
/src/fix_split_file.cpp
8b7dceaca4adb212b388c4d3c89731e99dab4378
[ "BSD-3-Clause" ]
permissive
OuyangJunyuan/annotate-for-category
48facceb4dc3a9b528944e2ce049992a360efc83
d1816dfdf57e8f98eb2736da89a4b766930bdc77
refs/heads/master
2023-02-24T21:10:53.474735
2021-01-28T10:09:09
2021-01-28T10:09:09
331,904,522
6
0
null
null
null
null
UTF-8
C++
false
false
2,898
cpp
fix_split_file.cpp
// // Created by ou on 2021/1/26. // #include <yaml-cpp/yaml.h> #include <iostream> #include <QFile> #include <QDebug> #include <QDir> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #define CONFIG_FILE "/home/ou/workspace/ros_ws/ironworks_ws/src/tools/my_annotate/config/annodate.yaml" using namespace std; int main() { YAML::Node node; node = YAML::LoadFile(CONFIG_FILE); QString root_path = node["dataset_root"].as<std::string>().c_str(); vector<string> labels, tags; vector<int> labels_num, tags_num; //获取当前进度与标签 YAML::Node node_labels = node["labels"]; for (size_t i = 0; i < node_labels.size(); ++i) { auto it = node_labels[i].begin(); labels.push_back(it->first.as<string>()); labels_num.push_back(it->second.as<uint32_t>()); } YAML::Node node_tags = node["tags"]; for (size_t i = 0; i < node_tags.size(); ++i) { auto it = node_tags[i].begin(); tags.push_back(it->first.as<string>()); tags_num.push_back(it->second.as<uint32_t>()); } vector<string> cate_dir(labels.size()); for (int i = 0; i < labels.size(); ++i) { QFile fp; fp.setFileName(root_path + "/synsetoffset2category.txt"); fp.open(QIODevice::ReadWrite | QIODevice::Text); stringstream ss(fp.readAll().toStdString()); for (int j = 0; j < labels.size(); ++j) { string temp1, temp2; ss >> temp1 >> temp2; if (labels[i] == temp1) { cate_dir[i] = temp2; break; } } fp.close(); } QStringList files[labels.size()]; QDir temp; temp.setFilter(QDir::NoDotAndDotDot | QDir::AllEntries); //否则空文件夹也有2个文件 for (int i = 0; i < labels.size(); i++) { temp.setPath(root_path + "/" + cate_dir[i].c_str() + "/points"); auto lists = temp.entryList(); files[i] = lists; cout << lists.size() << " files in dir <" << temp.path().toStdString() << ">." << endl; } QJsonArray content; for (int i = 0; i < labels.size(); ++i) { if (!files[i].empty()) { string data = "shape_data/" + cate_dir[i] + "/"; auto fp = files[i]; for (int j = 0; j < files[i].size(); ++j) { string name = data + fp[j].toStdString(); content.append(name.c_str()); } } } QJsonDocument doc(content); QFile split; split.setFileName(root_path + "/" + "train_test_split/shuffled_train_file_list.json"); split.open(QIODevice::WriteOnly); QByteArray data = doc.toJson(); split.write(data); split.close(); // // string split_file_path = root_path + "/" + "train_test_split" + "/shuffled_" + "train" + "_file_list.json"; // QString path = split_file_path.c_str(); return 0; }
92c14786c19be5eaa3e852fac64ddf172401bd5b
8508f45dd15ebcad0f9f30c706f78d3524bf833c
/src/OccEdge.cpp
ac7144b746bb47a23fcbb3b0dfb090826da33b50
[]
no_license
ezzieyguywuf/OccWrapper
7812b255d4086904fff2593684bbf4857d2ee151
1284aaec7bf3bbfc58d423764048cdab9062f127
refs/heads/master
2021-07-17T13:57:42.779220
2021-05-19T15:37:13
2021-05-19T15:37:13
124,664,015
3
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
OccEdge.cpp
#include <OccEdge.h> #include <ShapeAnalysis_Edge.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS.hxx> using Occ::Edge; Edge::Edge(const TopoDS_Edge& aEdge) : Shape(aEdge) {} bool Edge::overlaps(const Occ::Edge& anEdge, double tolerance) const { TopoDS_Edge myEdge = TopoDS::Edge(this->getShape()); TopoDS_Edge checkEdge = TopoDS::Edge(anEdge.getShape()); return ShapeAnalysis_Edge().CheckOverlapping(myEdge, checkEdge, tolerance); }
1a7ed657b616d1839c00c060d4b49b0f7647724e
6ec56b18388c28b31d5586a914f1e103b2dc0475
/SkeletonPuzzleSlam/Attachment.h
85b1397fae587ba9aa9a92da53c2d597d5ddaa25
[]
no_license
binhcoding/puzzle-game
404e9755a8b7764cd73358553e374d3de4b87b10
a2aaef4edc00cf9ca3c48e9f65899021b8aa6b60
refs/heads/master
2021-01-10T22:10:08.066970
2015-03-06T02:56:38
2015-03-06T02:56:38
31,749,548
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
Attachment.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameTypes.h" #include "Attachment.generated.h" /** * */ UCLASS(Blueprintable) class UAttachment : public UStaticMeshComponent { GENERATED_UCLASS_BODY() // positive effects of this data UPROPERTY(EditDefaultsOnly, Category = Attachment) FBuffData Effect; // attach point on pawn UPROPERTY(EditDefaultsOnly, Category = Attachment) FName AttachPoint; };
afd0369236c620058169c03a7c554443e07d8e6f
239907bfd927f0b35848a9a133c0be64cc1e1ac0
/src/lib/plusula/ExtUUID.cpp
aff617182f8c89e81422e2b384429fa255bb57ea
[]
no_license
kulhanek/abs
6aa6e279d72af1b510e3d8ccc22d122e375b8ffb
aad1a45d9af418b97a8e21ee96774e2ea122de78
refs/heads/main
2023-08-31T23:53:22.708286
2023-08-26T13:33:32
2023-08-26T13:33:32
84,871,208
0
0
null
null
null
null
UTF-8
C++
false
false
4,177
cpp
ExtUUID.cpp
// ============================================================================= // NEMESIS - Molecular Modelling Package // ----------------------------------------------------------------------------- // Copyright (C) 2010 Petr Kulhanek, kulhanek@chemi.muni.cz // Copyright (C) 2008-2009 Petr Kulhanek, kulhanek@enzim.hu, // Jakub Stepan, xstepan3@chemi.muni.cz // Copyright (C) 1998-2004 Petr Kulhanek, kulhanek@chemi.muni.cz // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // ============================================================================= #include <ExtUUID.hpp> #include <PluginModule.hpp> //============================================================================== //------------------------------------------------------------------------------ //============================================================================== CExtUUID::CExtUUID(void) { } // ----------------------------------------------------------------------------- CExtUUID::CExtUUID(const CSmallString& extuuid) { LoadFromString(extuuid); } // ----------------------------------------------------------------------------- CExtUUID::CExtUUID(const CSmallString& extuuid,const CSmallString& name) { LoadFromString(extuuid); Name = name; } // ----------------------------------------------------------------------------- CExtUUID::CExtUUID(const CSmallString& extuuid,const CSmallString& name,const CSmallString& description) { LoadFromString(extuuid); Name = name; Description = description; } //============================================================================== //------------------------------------------------------------------------------ //============================================================================== // {class_name:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} bool CExtUUID::LoadFromString(const CSmallString& string) { int namelength=0; CSmallString tmp(string); for(unsigned int i=1; i<tmp.GetLength(); i++) { if( tmp.GetBuffer()[i] == ':' ) { namelength = i-1; break; } } if(namelength == 0)return(false); UUIDName = tmp.GetSubString(1,namelength); return(SetFromStringForm(tmp.GetSubString(namelength+2,tmp.GetLength()-3-namelength))); } // ----------------------------------------------------------------------------- const CSmallString CExtUUID::GetFullStringForm(void) const { CSmallString string; string = "{" + UUIDName + ":" + GetStringForm() + "}"; return(string); } //============================================================================== //------------------------------------------------------------------------------ //============================================================================== const CSmallString& CExtUUID::GetUUIDName(void) const { return(UUIDName); } // ----------------------------------------------------------------------------- const CSmallString& CExtUUID::GetName(void) const { return(Name); } // ----------------------------------------------------------------------------- const CSmallString& CExtUUID::GetDescription(void) const { return(Description); } //============================================================================== //------------------------------------------------------------------------------ //==============================================================================
78e11ad6f063c142213534d31e4b58aae9fb8f92
ce93985fae06976c8a127f58edaea8501baff07d
/lab_04/lab04/lab04.cpp
04a82974e1b757406ab474a0d3619bb14043d7ff
[]
no_license
anhud/poly_cpp
27276ec06c2e2e647345f9cdab563d99da5a1c87
5be575e77b59e08055e26bff819f06a5d7c0ce24
refs/heads/master
2023-01-31T01:33:56.252671
2020-12-15T14:40:02
2020-12-15T14:40:02
290,545,699
0
0
null
null
null
null
UTF-8
C++
false
false
2,161
cpp
lab04.cpp
// lab04.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include "pch.h" #include "drawfunc.h" #include "glutfunc.h" #include <iostream> void main(int argc, char **argv) { menu_system menus_; MenuInit("menu.txt"); MenuOpen(0); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(400, 400); glutCreateWindow("test"); glClearColor(0.8f, 0.8f, 0.8f, 1.0f); glutIgnoreKeyRepeat(1); glutKeyboardFunc(ProcessNormalKeys); glutSpecialFunc(ProcessSpecialKeys); glutSpecialUpFunc(ProcessKeysUp); glutDisplayFunc(RenderWindow); glutIdleFunc(RenderWindow); glutMainLoop(); } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
d8cecf5e2eaa73f24bfc4e333c4b2b51238eb164
049b53634c6f2b7f01edafcf98ddcb546fb57684
/test/ss_handle_test.cc
8c3934f923b85cab20064370e0be971ec8f800a5
[]
no_license
hhhizzz/libshadesocks
a533c721ce1e8cb95289346dc46ba8e9c8f49f36
e9f3fb4c5b8f3475f72df0f730690be6707306ec
refs/heads/master
2020-07-01T20:30:59.917738
2019-10-17T14:48:43
2019-10-17T14:48:43
201,291,974
3
0
null
null
null
null
UTF-8
C++
false
false
2,520
cc
ss_handle_test.cc
#include "ss_test.h" namespace shadesocks { TEST(ShadeHandleTest, ReadDataTest) { auto* stream = new uv_stream_t{}; stream->loop = uv_default_loop(); ShadeHandle shade_handle(stream); stream->data = &shade_handle; auto block = Util::StringToHex( "7396C95A33DFFA3042FF661FF0B85155268EF14E148EBFD1638AF66436717BC2ECF34B8044259EB5A5D5B2A0A47F9F5DFA6F242600C589034C2153C47C8E681BE67EA51796FFA7055D7636634222D7AD6417EF7250F1EAD171CFBEDBC2D474206DCA0A83A0446FFFBEB8262773073DF5D89C0A2A462C6F4A50EBB23FEC308AC64387CD7CE6066908512277E5E573C762171F631B375CAF0C59315F15E867"); uv_buf_t buf; buf.base = shade_handle.temp; buf.len = block.size(); for (int i = 0; i < block.size(); i++) { buf.base[i] = block.data()[i]; } shade_handle.proxy_state = ProxyState::ClientReading; ShadeHandle::ReadClientDone(stream, block.size(), &buf); delete stream; } TEST(ShadeHandleTest, GetRequestTest) { auto* stream = new uv_stream_t{}; stream->loop = uv_default_loop(); ShadeHandle shade_handle(stream); LOG(INFO) << "start to check domain"; auto block = Util::StringToHex( "031D636F6E6E6563746976697479636865636B2E677374617469632E636F6D0050"); shade_handle.data = block; shade_handle.offset = 0; char hostname[NI_MAXHOST]; shade_handle.GetRequest(); auto addr = std::move(shade_handle.addr_out); inet_ntop(addr->sin_family, &addr->sin_addr, hostname, NI_MAXHOST); auto port = ntohs(addr->sin_port); LOG(INFO) << "ip is: " << hostname; LOG(INFO) << "hostname is: " << shade_handle.hostname_out; LOG(INFO) << "port is: " << port; ASSERT_EQ(port, 80); ASSERT_STRCASEEQ(shade_handle.hostname_out.data(), "connectivitycheck.gstatic.com"); LOG(INFO) << "start to check IPv4"; block = Util::StringToHex( "01CBD02B580050"); shade_handle.data = block; shade_handle.offset = 0; shade_handle.GetRequest(); addr = std::move(shade_handle.addr_out); inet_ntop(addr->sin_family, &addr->sin_addr, hostname, NI_MAXHOST); port = ntohs(addr->sin_port); LOG(INFO) << "ip is: " << hostname; LOG(INFO) << "hostname is: " << shade_handle.hostname_out; LOG(INFO) << "port is: " << port; ASSERT_EQ(port, 80); ASSERT_STRCASEEQ(hostname, "203.208.43.88"); ASSERT_STRCASEEQ(shade_handle.hostname_out.data(), "203.208.43.88"); delete stream; } } int main(int argc, char** argv) { FLAGS_colorlogtostderr = 1; FLAGS_stderrthreshold = 0; testing::InitGoogleTest(&argc, argv); google::InitGoogleLogging(argv[0]); return RUN_ALL_TESTS(); }
f266fe146a4bef6e16ebd6c6303b1a2250882513
e2431caf49c0fb3d1e794f11ac50106d800c55f2
/RatWalkCore/Project.cpp
8e0526e6875828e8e0c8380b68e207e05e67e1b7
[]
no_license
CristianDavid/QtRatWalk
93ae50345c3dd2e82335a5fcb91f921747a9836e
a43b4951f9f52e966da71521fcee601a7e6d23e1
refs/heads/master
2021-01-19T12:39:33.078739
2017-04-28T21:10:22
2017-04-28T21:10:22
82,329,468
0
0
null
null
null
null
UTF-8
C++
false
false
16,311
cpp
Project.cpp
#include "RatWalkCore/Project.h" #include <unistd.h> #include <cstdio> #include <cstdlib> #include <algorithm> #include <iomanip> #include <iostream> #include <fstream> #include <vector> #include <string> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <QString> #include "RatWalkCore/Video.h" #include "RatWalkCore/Constantes.h" #include "RatWalkCore/Points.h" using namespace cv; using namespace std; constexpr int HALF_WINDOW_SIZE = 9; namespace RatWalkCore { Project::Project(const char *fileName) : ratFile(fileName), corrector(VideoToAnalyze) { CurrentVideoAnalyzed=0; //Open the video files for (int i = 0; i < ratFile.numberOfVideos(); i++) { VideoToAnalyze.push_back(Video()); stepRegisters.push_back(StepRegister()); const char *FileNameToRead = ratFile.getVideoFilename(i); if (!VideoToAnalyze[i].OpenVideoFile((char *)FileNameToRead)) { cout<<"Video File "<<FileNameToRead <<" Could not be opened"; return; // return 0; } } loadStepRegister(ratFile.getStepRegisterFilename()); if (!loadCalibrationParameters()) { performCalibration(400); saveCalibrationParameters(); } //Try to read the previously annotated things string lineToParse; ifstream PreviouslyAnnotatedFile(ratFile.getOutputFilenameWidthPath()); string delimiterRead = ","; if (PreviouslyAnnotatedFile.is_open()) { //Get rid of the line with the name of colums getline(PreviouslyAnnotatedFile, lineToParse); while ( getline(PreviouslyAnnotatedFile, lineToParse) ) { size_t pos = 0; std::string token; int VideoNumber = 0; int FrameNumber = 0; std::vector<std::string> tokens; do { pos = lineToParse.find(delimiterRead); token = lineToParse.substr(0, pos); tokens.push_back(token); lineToParse.erase(0, pos + delimiterRead.length()); } while (pos != std::string::npos); VideoNumber = stoi(tokens[0]); FrameNumber = stoi(tokens[1]); Frame &frame = VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber]; for (int i = 0; i < NUMBER_OF_POINTS_TO_TRACK && !tokens[i*2+2].empty(); i++) { frame.TrackedPointsInFrame[i].CoorX = stoi(tokens[i*2+2]); frame.TrackedPointsInFrame[i].CoorY = stoi(tokens[i*2+3]); frame.TrackedPointsInFrame[i].Theta = stod(tokens[i+12]); frame.NumberOfTRegisteredPoints++; } PointID = std::min(NUMBER_OF_POINTS_TO_TRACK-1, frame.NumberOfTRegisteredPoints); } //Create the corrected setGlobalCorrectionMatrices(); calculateCorrectedData(); //Save the previously Annotated Corrected saveCorrectedFile(); } else { cout<<"\n No previous annotated data"; } } void Project::nextFrame() { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; currentVideo.GetNextFrame(); PointID = currentVideo.FrameProperties[currentVideo.CurrentFrame].NumberOfTRegisteredPoints; PointID = std::min(PointID, 4); } void Project::prevFrame() { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; VideoToAnalyze[CurrentVideoAnalyzed].GetPreviousFrame(); PointID = currentVideo.FrameProperties[currentVideo.CurrentFrame].NumberOfTRegisteredPoints; PointID = std::min(PointID, 4); } void Project::save() { const char *HEADER = "VideoNumber,Frame,x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,T1,T2,T3,T4,T5\n"; std::ofstream ofs(ratFile.getOutputFilenameWidthPath(), std::ofstream::out); ofs << HEADER; for (int VideoNumber=0;VideoNumber<ratFile.numberOfVideos();VideoNumber++) { for (int i = 0 ;i < VideoToAnalyze[VideoNumber].NumberOfFrames; i++) { Frame &frame = VideoToAnalyze[VideoNumber].FrameProperties[i]; if (frame.NumberOfTRegisteredPoints > 0) { ofs << VideoNumber << "," << i; for(int j = 0; j < frame.NumberOfTRegisteredPoints; j++) { ofs << "," << frame.TrackedPointsInFrame[j].CoorX << "," << frame.TrackedPointsInFrame[j].CoorY; } for (int j = frame.NumberOfTRegisteredPoints; j < frame.NumberOfPointsToTrack; j++) { ofs << ",,"; } for(int j = 0; j < frame.NumberOfTRegisteredPoints; j++) { ofs << ',' << QString::number(frame.TrackedPointsInFrame[j].Theta, 'f', 10).toStdString(); } for (int j = frame.NumberOfTRegisteredPoints; j < frame.NumberOfPointsToTrack; j++) { ofs << ','; } ofs << "\n"; } } } ofs.close(); saveCorrectedFile(); saveStepRegister(ratFile.getStepRegisterFilename()); } void Project::bringPreviousSkeleton() { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; //!< \todo Project debería tener un método currentVideo() Frame &currentFrame = currentVideo.FrameProperties[currentVideo.CurrentFrame]; //!< \todo Video debería tener un método currentFrame() bool sinAsignar = true; for (int i = currentVideo.CurrentFrame-1; sinAsignar && i >= 0; i--) { Frame &prevFrame = currentVideo.FrameProperties[i]; if (prevFrame.NumberOfTRegisteredPoints > 0) { currentFrame.NumberOfTRegisteredPoints = 0; for (int i = 0; i < prevFrame.NumberOfTRegisteredPoints; i++) { ControlPoint p = prevFrame.TrackedPointsInFrame[i]; currentVideo.SelectPoint(p.CoorX, p.CoorY, HALF_WINDOW_SIZE, i, CurrentVideoAnalyzed); //currentFrame.SetTrackedPoints(i, p.x, p.y); } PointID = std::min(NUMBER_OF_POINTS_TO_TRACK-1, currentFrame.NumberOfTRegisteredPoints); sinAsignar = false; } } if (sinAsignar) { currentFrame.NumberOfTRegisteredPoints = 0; PointID = NUMBER_OF_POINTS_TO_TRACK-1; int step = currentVideo.Width / 6, x = step, y = currentVideo.Height / 2; for (int i = 0; i < 5; i++, x += step) { currentVideo.SelectPoint(x, y, HALF_WINDOW_SIZE, i, CurrentVideoAnalyzed); } } } Mat Project::getFrameWithRectangle() { return VideoToAnalyze[CurrentVideoAnalyzed].getFrameWithTrackingPoints(); } Mat Project::getFrameWithSkeleton() { return VideoToAnalyze[CurrentVideoAnalyzed].getFrameWithSkeleton(); } cv::Mat Project::getZoomedRegion(int x, int y, int frameWidth, int frameHeight) { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; cv::Mat mat = getFrameWithRectangle(); int x2 = mat.cols * x / frameWidth, y2 = mat.rows * y / frameHeight; return currentVideo.getZoomedRegion(x2, y2, HALF_WINDOW_SIZE); } const Video &Project::getCurrentVideoAnalyzed() { return VideoToAnalyze[CurrentVideoAnalyzed]; } const std::vector<string> &Project::getVideoFilenames() { return ratFile.getVideoFilenames(); } void Project::setCurrentVideo(int index) { CurrentVideoAnalyzed = index; Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; PointID = currentVideo.FrameProperties[currentVideo.CurrentFrame].NumberOfTRegisteredPoints; PointID = std::min(PointID, 4); } void Project::saveCorrectedFile() { std::ofstream ofsCorrected(ratFile.getOutputFilenameCorrected()); ofsCorrected << "VideoNumber,Frame,x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,T1,T2,T3,T4,T5\n"; for (int VideoNumber=0;VideoNumber<ratFile.numberOfVideos();VideoNumber++) { Video &video = VideoToAnalyze[VideoNumber]; for (int frameNumber = 0; frameNumber < video.NumberOfFrames; frameNumber++) { Frame &frame = video.FrameProperties[frameNumber]; ofsCorrected << VideoNumber << "," << frameNumber; for(int pointNumber = 0; pointNumber < frame.NumberOfPointsToTrack; pointNumber++) { if (pointNumber < frame.NumberOfTRegisteredPoints) { ControlPoint &point = frame.TrackedPointsInFrame[pointNumber]; ofsCorrected << "," << point.CoorXCorrected << "," << point.CoorYCorrected; } else { ofsCorrected << ",-1,-1"; } } for(int pointNumber = 0; pointNumber < frame.NumberOfPointsToTrack; pointNumber++) { if (pointNumber < frame.NumberOfTRegisteredPoints) { ControlPoint &point = frame.TrackedPointsInFrame[pointNumber]; ofsCorrected << ',' << QString::number(point.ThetaCorrected, 'f', 10).toStdString(); } else { ofsCorrected << ",-1"; } } ofsCorrected << '\n'; } } ofsCorrected.close(); } std::vector<Video> &Project::getVideos() { return VideoToAnalyze; } std::vector<StepRegister> &Project::getStepRegisters() { return stepRegisters; } StepRegister &Project::getCurrentStepRegister() { return stepRegisters[CurrentVideoAnalyzed]; } int Project::getCurrentVideoIndex() { return CurrentVideoAnalyzed; } void Project::loadStepRegister(const char *filename) { std::ifstream inFile(filename); if (inFile.is_open()) { int video, stepBegin, stepEnd; while (!(inFile >> video).eof()) { while (inFile.get() != ',') continue; inFile >> stepBegin; while (inFile.get() != ',') continue; inFile >> stepEnd; stepRegisters[video].addStep(stepBegin, stepEnd); } } } void Project::saveStepRegister(const char *filename) { std::ofstream outFile(filename); if (!outFile.is_open()) return; for (int i = 0; i < 3; i++) { for (auto step : stepRegisters[i].getSteps()) { outFile << i << ',' << step.first << ',' << step.second << std::endl; } } } const char *Project::getProjectName() { return ratFile.getProjectName(); } int Project::getSize() { return VideoToAnalyze.size(); } Mat Project::performCalibration(int minHessian) { return corrector.performCorrection(ratFile.getTargetFilename(), minHessian); } bool Project::saveCalibrationParameters() { return corrector.saveCalibrationParametersToFile( ratFile.getCalibrationParametersFilename()); } bool Project::loadCalibrationParameters() { return corrector.loadCalibrationParametersFromFile( ratFile.getCalibrationParametersFilename()); } void Project::calculateCorrectedData() { for (int VideoNumber=0;VideoNumber<ratFile.numberOfVideos();VideoNumber++){ for (int FrameNumber=0;FrameNumber<VideoToAnalyze[VideoNumber].NumberOfFrames;FrameNumber++){ for (int PointId=0;PointId<NUMBER_OF_POINTS_TO_TRACK;PointId++){ int x=VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId].CoorX; int y=VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId].CoorY; std::vector<Point2f> vec; std::vector<Point2f> vecCorrected; vec.push_back(Point2f(x,y)); if (VideoNumber==0) cv::perspectiveTransform(vec,vecCorrected, HLeft); if (VideoNumber==1) cv::perspectiveTransform(vec,vecCorrected, HMiddle); if (VideoNumber==2) cv::perspectiveTransform(vec,vecCorrected, HRight); VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId].CoorXCorrected=vecCorrected[0].x; VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId].CoorYCorrected=vecCorrected[0].y; if (PointId>0){ double xa=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId-1].CoorXCorrected; double ya=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId-1].CoorYCorrected; double xb=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId].CoorXCorrected; double yb=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId].CoorYCorrected; double Angle=180*atan2((yb-ya),(xb-xa))/3.1416; VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[PointId-1].ThetaCorrected=Angle; } if (PointId==4){ double xa=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[0].CoorXCorrected; double ya=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[0].CoorYCorrected; double xb=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[3].CoorXCorrected; double yb=(double) VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[3].CoorYCorrected; double Angle=180*atan2((yb-ya),(xb-xa))/3.1416; VideoToAnalyze[VideoNumber].FrameProperties[FrameNumber].TrackedPointsInFrame[4].ThetaCorrected=Angle; } } } } } void Project::setGlobalCorrectionMatrices() { HLeft = corrector.getHLeft(); HMiddle = corrector.getHMiddle(); HRight = corrector.getHRight(); } void Project::addPointOnCurrentFrame(int x, int y, int frameWidth, int frameHeight) { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; cv::Mat mat = getFrameWithRectangle(); int x2 = mat.cols * x / frameWidth, y2 = mat.rows * y / frameHeight; currentVideo.SelectPoint(x2, y2, HALF_WINDOW_SIZE, PointID, CurrentVideoAnalyzed); PointID = std::min(PointID+1, NUMBER_OF_POINTS_TO_TRACK-1); } void Project::setPointOnCurrentFrame(int pointId, int x, int y, int frameWidth, int frameHeight) { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; cv::Mat mat = getFrameWithRectangle(); int x2 = mat.cols * x / frameWidth, y2 = mat.rows * y / frameHeight; currentVideo.SelectPoint(x2, y2, HALF_WINDOW_SIZE, pointId, CurrentVideoAnalyzed); } void Project::deletePointOnCurrentFrame(int pointId) { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; Frame &currentFrame = currentVideo.FrameProperties[currentVideo.CurrentFrame]; auto iter = currentFrame.TrackedPointsInFrame.begin() + pointId; currentFrame.TrackedPointsInFrame.erase(iter); currentFrame.TrackedPointsInFrame.push_back(ControlPoint()); currentFrame.NumberOfTRegisteredPoints--; currentFrame.NumberOfTRegisteredPoints = PointID; } int Project::getClosestPointID(int x, int y, int frameWidth, int frameHeight, double maxDistance) { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; Frame &currentFrame = currentVideo.FrameProperties[currentVideo.CurrentFrame]; cv::Mat mat = getFrameWithRectangle(); int x2 = mat.cols * x / frameWidth, y2 = mat.rows * y / frameHeight; double minDistance = -1.0, currentDistance; int minId = -1; for (int i = 0; i < currentFrame.NumberOfTRegisteredPoints; i++) { ControlPoint p = currentFrame.TrackedPointsInFrame[i]; currentDistance = euclidianDistance(x2, y2, p.CoorX, p.CoorY); if (minDistance < 0 || currentDistance < minDistance) { minId = i; minDistance = currentDistance; } } if (minId != -1 && minDistance > maxDistance) { minId = -1; } return minId; } void Project::setFrame(int Position) { Video &currentVideo = VideoToAnalyze[CurrentVideoAnalyzed]; currentVideo.GetFrameNumber((double)Position); currentVideo.ShowSkeletonInCurrentFrame(); PointID = currentVideo.FrameProperties[currentVideo.CurrentFrame].NumberOfTRegisteredPoints; PointID = std::min(PointID, 4); } } // namespace RatWalkCore
77ffd366b460a7676e54066d8b541b746fb83b77
c7d88b6163c430293067a3915ca3456820c085cd
/FrmMain.h
8588a61413c6e6cd82c9ead0a15a1274647f4fae
[]
no_license
tmarkson/Cubesense
c068e6707b4bce5c2da26d1123c49e7a4e66c55c
49127e18a6886b9827d7ef9ff54ba6d379c0365d
refs/heads/master
2021-01-15T13:44:30.345653
2012-07-13T15:29:04
2012-07-13T15:29:04
5,010,362
2
1
null
null
null
null
UTF-8
C++
false
false
43,273
h
FrmMain.h
#pragma once #include "Ids.h" #include "FrmFrames.h" #include "FrmScriptSource.h" #include "FrmScriptOutput.h" #include "FrmNew.h" #include "Handler.h" #include "Threads.h" #include "WndProc.h" #include "Script.h" #include "Log.h" using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; namespace CubeSense { /// <summary> /// Summary for FrmMain /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class FrmMain : public System::Windows::Forms::Form { public: FrmMain(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~FrmMain() { if (components) { delete components; } } private: AxXtremeCommandBars::AxCommandBars^ axCommandBars1; protected: private: AxXtremeDockingPane::AxDockingPane^ axDockingPane1; private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::Panel^ panel1; private: AxXtremeSuiteControls::AxProgressBar^ axProgressBar1; private: System::Windows::Forms::OpenFileDialog^ openFileDialog1; private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(FrmMain::typeid)); this->axCommandBars1 = (gcnew AxXtremeCommandBars::AxCommandBars()); this->axDockingPane1 = (gcnew AxXtremeDockingPane::AxDockingPane()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->panel1 = (gcnew System::Windows::Forms::Panel()); this->axProgressBar1 = (gcnew AxXtremeSuiteControls::AxProgressBar()); this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog()); this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->axCommandBars1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->axDockingPane1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->BeginInit(); this->panel1->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->axProgressBar1))->BeginInit(); this->SuspendLayout(); // // axCommandBars1 // this->axCommandBars1->Enabled = true; this->axCommandBars1->Location = System::Drawing::Point(12, 12); this->axCommandBars1->Name = L"axCommandBars1"; this->axCommandBars1->OcxState = (cli::safe_cast<System::Windows::Forms::AxHost::State^ >(resources->GetObject(L"axCommandBars1.OcxState"))); this->axCommandBars1->Size = System::Drawing::Size(24, 24); this->axCommandBars1->TabIndex = 0; this->axCommandBars1->ControlNotify += gcnew AxXtremeCommandBars::_DCommandBarsEvents_ControlNotifyEventHandler(this, &FrmMain::axCommandBars1_ControlNotify); this->axCommandBars1->Execute += gcnew AxXtremeCommandBars::_DCommandBarsEvents_ExecuteEventHandler(this, &FrmMain::axCommandBars1_Execute); this->axCommandBars1->ResizeEvent += gcnew System::EventHandler(this, &FrmMain::axCommandBars1_ResizeEvent); // // axDockingPane1 // this->axDockingPane1->Enabled = true; this->axDockingPane1->Location = System::Drawing::Point(42, 12); this->axDockingPane1->Name = L"axDockingPane1"; this->axDockingPane1->OcxState = (cli::safe_cast<System::Windows::Forms::AxHost::State^ >(resources->GetObject(L"axDockingPane1.OcxState"))); this->axDockingPane1->Size = System::Drawing::Size(24, 24); this->axDockingPane1->TabIndex = 1; this->axDockingPane1->AttachPaneEvent += gcnew AxXtremeDockingPane::_DDockingPaneEvents_AttachPaneEventHandler(this, &FrmMain::axDockingPane1_AttachPaneEvent); this->axDockingPane1->Action += gcnew AxXtremeDockingPane::_DDockingPaneEvents_ActionEventHandler(this, &FrmMain::axDockingPane1_Action); // // pictureBox1 // this->pictureBox1->BackColor = System::Drawing::Color::Black; this->pictureBox1->Location = System::Drawing::Point(72, 12); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(24, 24); this->pictureBox1->TabIndex = 2; this->pictureBox1->TabStop = false; this->pictureBox1->MouseLeave += gcnew System::EventHandler(this, &FrmMain::pictureBox1_MouseLeave); this->pictureBox1->Click += gcnew System::EventHandler(this, &FrmMain::pictureBox1_Click); this->pictureBox1->Resize += gcnew System::EventHandler(this, &FrmMain::pictureBox1_Resize); this->pictureBox1->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &FrmMain::pictureBox1_MouseDown); // // panel1 // this->panel1->Controls->Add(this->axProgressBar1); this->panel1->Location = System::Drawing::Point(12, 42); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(84, 36); this->panel1->TabIndex = 3; this->panel1->Visible = false; // // axProgressBar1 // this->axProgressBar1->Location = System::Drawing::Point(12, 12); this->axProgressBar1->Name = L"axProgressBar1"; this->axProgressBar1->OcxState = (cli::safe_cast<System::Windows::Forms::AxHost::State^ >(resources->GetObject(L"axProgressBar1.OcxState"))); this->axProgressBar1->Size = System::Drawing::Size(58, 12); this->axProgressBar1->TabIndex = 1; // // openFileDialog1 // this->openFileDialog1->FileName = L"openFileDialog1"; this->openFileDialog1->Filter = L"Eightcubed animation files (*.eca)|*.eca|All files(*.*)|*.*"; this->openFileDialog1->FileOk += gcnew System::ComponentModel::CancelEventHandler(this, &FrmMain::openFileDialog1_FileOk); // // saveFileDialog1 // this->saveFileDialog1->Filter = L"Eightcubed animation files (*.eca)|*.eca|All files(*.*)|*.*"; this->saveFileDialog1->FileOk += gcnew System::ComponentModel::CancelEventHandler(this, &FrmMain::saveFileDialog1_FileOk_1); // // FrmMain // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(965, 532); this->Controls->Add(this->panel1); this->Controls->Add(this->pictureBox1); this->Controls->Add(this->axCommandBars1); this->Controls->Add(this->axDockingPane1); this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon"))); this->Name = L"FrmMain"; this->Text = L"CubeSense"; this->Load += gcnew System::EventHandler(this, &FrmMain::FrmMain_Load); this->FormClosing += gcnew System::Windows::Forms::FormClosingEventHandler(this, &FrmMain::FrmMain_FormClosing); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->axCommandBars1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->axDockingPane1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->EndInit(); this->panel1->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->axProgressBar1))->EndInit(); this->ResumeLayout(false); } #pragma endregion public: virtual void WndProc(System::Windows::Forms::Message% ThisMsg) override; private: FrmScriptSource ^frmScriptSource; FrmScriptOutput ^frmScriptOutput; FrmFrames ^frmFrames; FrmNew ^frmNew; XtremeCommandBars::CommandBarComboBox ^Combo ; XtremeCommandBars::CommandBarComboBox ^comboLedSize ; XtremeCommandBars::CommandBarComboBox ^comboLedSpacing; XtremeCommandBars::CommandBarComboBox ^comboBlackLeds; XtremeCommandBars::CommandBarComboBox ^comboQuality; XtremeCommandBars::RibbonBar ^ribbonBar; System::String^ animationFileName; int animationFileNameSet; void FrmMainCreateRibbonBar() { int i; axCommandBars1->EnableCustomization(true); XtremeCommandBars::StatusBar ^StatusBar0; StatusBar0 =axCommandBars1->StatusBar; StatusBar0->Visible=true; XtremeCommandBars::StatusBarPane ^Pane1; XtremeCommandBars::StatusBarPane ^Pane0; XtremeCommandBars::StatusBarPane ^Pane2; XtremeCommandBars::StatusBarPane ^Pane3; XtremeCommandBars::StatusBarPane ^Pane4; XtremeCommandBars::StatusBarPane ^Pane5; XtremeCommandBars::StatusBarPane ^Pane6; Pane0 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_DUMYY); Pane1 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_MAIN_STATUS); Pane2 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_FPS_OPENGL); Pane4 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_ACTIVE_FRAME); Pane5 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_LATTICE_SIZE); Pane6 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_USB_STATUS); Pane3 = StatusBar0->AddPane(IdsStatusBarItems::ITEM_PROGRESS); axCommandBars1->StatusBar->Visible = true; Pane0->Style= XtremeCommandBars::XTPStatusPaneStyle::SBPS_NOBORDERS; Pane0->Width=0; Pane0->Visible=0; Pane1->Style=XtremeCommandBars::XTPStatusPaneStyle::SBPS_STRETCH | XtremeCommandBars::XTPStatusPaneStyle::SBPS_NOBORDERS; Pane1->Text="Ready"; Pane1->Width=0; Pane2->Style= XtremeCommandBars::XTPStatusPaneStyle::SBPS_NOBORDERS; Pane2->Text="Fps:"; Pane2->Width=100; Pane3->Handle=axProgressBar1->Handle.ToInt32(); Pane3->Width=200; Pane4->Style= XtremeCommandBars::XTPStatusPaneStyle::SBPS_NOBORDERS; Pane4->Text="Frame:"; Pane4->Width=100; Pane5->Style= XtremeCommandBars::XTPStatusPaneStyle::SBPS_NOBORDERS; Pane5->Text="Lattice:"; Pane5->Width=100; Pane6->Style= XtremeCommandBars::XTPStatusPaneStyle::SBPS_NOBORDERS; Pane6->Text="USB: Ready"; Pane6->Width=100; // Pane3->BackgroundColor=Pane1->BackgroundColor; // Pane3->Style=Pane1->Style; // axCommandBars1->StatusBar->AddProgressPane(0); //axCommandBars1->StatusBar->AddProgressPane() ribbonBar = axCommandBars1->AddRibbonBar("The Ribbon"); ribbonBar->EnableDocking(XtremeCommandBars::XTPToolBarFlags::xtpFlagStretched); XtremeCommandBars::CommandBarPopup ^controlFile = ribbonBar->AddSystemButton(); controlFile->CommandBar->Controls->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SYSTEM_EXIT, "&Exit", false, false); XtremeCommandBars::RibbonTab ^ribbonTabHome = ribbonBar->InsertTab(0, "&Home"); ribbonTabHome->Id = 4; XtremeCommandBars::RibbonGroup ^groupFile = ribbonTabHome->Groups->AddGroup("File", 7); groupFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::HOME_FILE_NEW, "&New", false, false); groupFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::HOME_FILE_OPEN, "&Open", false, false); groupFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::HOME_FILE_SAVE, "&Save", false, false); groupFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::HOME_FILE_SAVEAS, "&Save as", false, false); // XtremeCommandBars::CommandBarControl^ tempControl; XtremeCommandBars::RibbonGroup ^groupParameters = ribbonTabHome->Groups->AddGroup("Parameters", 7); groupParameters->Add(XtremeCommandBars::XTPControlType::xtpControlEdit, IdsRibbonItems::HOME_PARAMETERS_TITLE, "&Title: ", false, false); /* tempControl->BeginGroup=true; tempControl=groupParameters->Add(XtremeCommandBars::XTPControlType::xtpControlLabel, IdsRibbonItems::HOME_PARAMETERS_TITLE, "&X: ", false, false); tempControl=groupParameters->Add(XtremeCommandBars::XTPControlType::xtpControlLabel, IdsRibbonItems::HOME_PARAMETERS_TITLE, "&Y: ", false, false); tempControl=groupParameters->Add(XtremeCommandBars::XTPControlType::xtpControlLabel, IdsRibbonItems::HOME_PARAMETERS_TITLE, "&Z: ", false, false); */ XtremeCommandBars::RibbonTab ^ribbonTabScripting = ribbonBar->InsertTab(1, "&Scripting"); ribbonTabScripting->Id = 5; XtremeCommandBars::RibbonGroup ^groupScriptingFile = ribbonTabScripting->Groups->AddGroup("File", 7); groupScriptingFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_FILE_NEW, "&New", false, false); groupScriptingFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_FILE_OPEN, "&Open", false, false); groupScriptingFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_FILE_SAVE, "&Save", false, false); groupScriptingFile->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_FILE_SAVEAS, "&Save as", false, false); XtremeCommandBars::RibbonGroup ^groupScriptingExecute = ribbonTabScripting->Groups->AddGroup("Prerendered", 7); groupScriptingExecute->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_EXECUTE_RUN, "&Run", false, false); groupScriptingExecute->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_EXECUTE_STOP, "&Stop", false, false); XtremeCommandBars::RibbonGroup ^groupScriptingRealTime = ribbonTabScripting->Groups->AddGroup("Real time", 7); groupScriptingRealTime->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_REAL_TIME_PREVIEW, "&Preview", false, false); groupScriptingRealTime->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_REAL_TIME_EXPORT, "&Export", false, false); groupScriptingRealTime->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_REAL_TIME_START, "&Start", false, false); groupScriptingRealTime->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::SCRIPTING_REAL_TIME_STOP, "&Stop", false, false); XtremeCommandBars::RibbonTab ^ribbonTabPreview = ribbonBar->InsertTab(1, "&Preview"); ribbonTabScripting->Id = 5; XtremeCommandBars::RibbonGroup ^groupPreviewPlayback = ribbonTabPreview->Groups->AddGroup("Playback", 7); groupPreviewPlayback->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::PREVIEW_PLAYBACK_PLAY, "Play", false, false); groupPreviewPlayback->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::PREVIEW_PLAYBACK_STOP, "Stop", false, false); groupPreviewPlayback->Add(XtremeCommandBars::XTPControlType::xtpControlLabel, IdsRibbonItems::DUMMY, "", false, false); groupPreviewPlayback->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::PREVIEW_PLAYBACK_REPEAT, "Repeat", false, false); groupPreviewPlayback->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::PREVIEW_PLAYBACK_SELECTION, "Selection only", false, false); XtremeCommandBars::RibbonGroup ^groupPreviewEightcubed = ribbonTabPreview->Groups->AddGroup("eightCubed", 7); groupPreviewEightcubed->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::PREVIEW_EIGHTCUBED_CONNECT, "Connect", false, false); groupPreviewEightcubed->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::PREVIEW_EIGHTCUBED_DISCONNECT, "Disconnect", false, false); groupPreviewEightcubed->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::PREVIEW_EIGHTCUBED_STREAM, "Stream video", false, false); // XtremeCommandBars::CommandBarGallery ^GallerySize; XtremeCommandBars::CommandBarGalleryItems ^ItemsSize; ItemsSize = axCommandBars1->CreateGalleryItems(IdsRibbonItems::SCRIPTING_EXECUTE_TYPE); ItemsSize->ItemWidth = 0; ItemsSize->ItemHeight = 17; ItemsSize->AddItem(1, "VB script"); ItemsSize->AddItem(2, "C# script"); Combo = (XtremeCommandBars::CommandBarComboBox^)groupScriptingExecute->Add(XtremeCommandBars::XTPControlType::xtpControlComboBox, IdsRibbonItems::SCRIPTING_EXECUTE_TYPE, "", false, false); Combo->DropDownListStyle = true; Combo->Width = 100; // Combo->Text = "C# script"; Combo->DropDownListStyle=0; XtremeCommandBars::CommandBar ^ComboPopup; ComboPopup = axCommandBars1->Add("Combo Popup", XtremeCommandBars::XTPBarPosition::xtpBarComboBoxGalleryPopup); GallerySize = (XtremeCommandBars::CommandBarGallery^)ComboPopup->Controls->Add(XtremeCommandBars::XTPControlType::xtpControlGallery, IdsRibbonItems::SCRIPTING_EXECUTE_TYPE, "", -1, false); GallerySize->Width = 90; GallerySize->Height = 2 * 17; GallerySize->Items = ItemsSize; Combo->CommandBar = ComboPopup; Combo->ListIndex=2; // XtremeCommandBars::RibbonTab ^ribbonTabView = ribbonBar->InsertTab(1, "&View"); ribbonTabView->Id = 5; XtremeCommandBars::RibbonGroup ^groupViewPresets = ribbonTabView->Groups->AddGroup("Presets", 7); groupViewPresets->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::VIEW_PRESETS_XZ, "XZ View", false, false); groupViewPresets->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::VIEW_PRESETS_XY, "XY View", false, false); groupViewPresets->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::VIEW_PRESETS_YZ, "YZ View", false, false); groupViewPresets->Add(XtremeCommandBars::XTPControlType::xtpControlButton, IdsRibbonItems::VIEW_PRESETS_DEFAULT, "Default view", false, false); XtremeCommandBars::RibbonGroup ^groupViewItems = ribbonTabView->Groups->AddGroup("Items", 7); groupViewItems->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::VIEW_ITEMS_LATTICE, "Lattice", false, false); // groupViewItems->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::VIEW_ITEMS_BASE, "Base", false, false); groupViewItems->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::VIEW_ITEMS_AXIS, "Axis", false, false); XtremeCommandBars::RibbonGroup ^groupViewLattice = ribbonTabView->Groups->AddGroup("Lattice", 7); XtremeCommandBars::RibbonGroup ^groupViewSettings = ribbonTabView->Groups->AddGroup("Settings", 7); XtremeCommandBars::CommandBarGallery ^galleryLedSize; XtremeCommandBars::CommandBarGalleryItems ^itemsLedSize; XtremeCommandBars::CommandBar ^popupLedSize; itemsLedSize = axCommandBars1->CreateGalleryItems(IdsRibbonItems::VIEW_LATTICE_SIZE); itemsLedSize->ItemWidth = 0; itemsLedSize->ItemHeight = 17; for(i=0;i<21;i++) itemsLedSize->AddItem(1, System::Convert::ToString(i)+" mm"); comboLedSize = (XtremeCommandBars::CommandBarComboBox^)groupViewLattice->Add(XtremeCommandBars::XTPControlType::xtpControlComboBox, IdsRibbonItems::VIEW_LATTICE_SIZE, "", false, false); comboLedSize->Width = 150; comboLedSize->DropDownListStyle=0; popupLedSize = axCommandBars1->Add("Combo Popup", XtremeCommandBars::XTPBarPosition::xtpBarComboBoxGalleryPopup); galleryLedSize = (XtremeCommandBars::CommandBarGallery^)popupLedSize->Controls->Add(XtremeCommandBars::XTPControlType::xtpControlGallery, IdsRibbonItems::VIEW_LATTICE_SIZE, "", -1, false); galleryLedSize->Width = 146; galleryLedSize->Height = 21 * 17; galleryLedSize->Items = itemsLedSize; comboLedSize->CommandBar = popupLedSize; comboLedSize->Caption="LED size:"; comboLedSize->ListIndex=1; XtremeCommandBars::CommandBarGallery ^galleryLedSpacing; XtremeCommandBars::CommandBarGalleryItems ^itemsLedSpacing; XtremeCommandBars::CommandBar ^popupLedSpacing; itemsLedSpacing = axCommandBars1->CreateGalleryItems(IdsRibbonItems::VIEW_LATTICE_SPACING); itemsLedSpacing->ItemWidth = 0; itemsLedSpacing->ItemHeight = 17; for(i=0;i<62;i+=2) itemsLedSpacing->AddItem(1, System::Convert::ToString(i)+" mm"); comboLedSpacing = (XtremeCommandBars::CommandBarComboBox^)groupViewLattice->Add(XtremeCommandBars::XTPControlType::xtpControlComboBox, IdsRibbonItems::VIEW_LATTICE_SPACING, "", false, false); comboLedSpacing->Width = 150; comboLedSpacing->DropDownListStyle=0; popupLedSpacing = axCommandBars1->Add("Combo Popup", XtremeCommandBars::XTPBarPosition::xtpBarComboBoxGalleryPopup); galleryLedSpacing = (XtremeCommandBars::CommandBarGallery^)popupLedSpacing->Controls->Add(XtremeCommandBars::XTPControlType::xtpControlGallery, IdsRibbonItems::VIEW_LATTICE_SPACING, "", -1, false); galleryLedSpacing->Width = 146; galleryLedSpacing->Height = 31 * 17; galleryLedSpacing->Items = itemsLedSpacing; comboLedSpacing->CommandBar = popupLedSpacing; comboLedSpacing->Caption="LED spacing:"; comboLedSpacing->ListIndex=1; XtremeCommandBars::CommandBarGallery ^galleryBlackLeds; XtremeCommandBars::CommandBarGalleryItems ^itemsBlackLeds; XtremeCommandBars::CommandBar ^popupBlackLeds; itemsBlackLeds = axCommandBars1->CreateGalleryItems(IdsRibbonItems::VIEW_LATTICE_BLACK_AS); itemsBlackLeds->ItemWidth = 0; itemsBlackLeds->ItemHeight = 17; itemsBlackLeds->AddItem(1, "Invisible"); itemsBlackLeds->AddItem(1, "Black"); itemsBlackLeds->AddItem(1, "Grey"); comboBlackLeds = (XtremeCommandBars::CommandBarComboBox^)groupViewLattice->Add(XtremeCommandBars::XTPControlType::xtpControlComboBox, IdsRibbonItems::VIEW_LATTICE_BLACK_AS, "", false, false); comboBlackLeds->Width = 150; comboBlackLeds->DropDownListStyle=0; popupBlackLeds = axCommandBars1->Add("Combo Popup", XtremeCommandBars::XTPBarPosition::xtpBarComboBoxGalleryPopup); galleryBlackLeds = (XtremeCommandBars::CommandBarGallery^)popupBlackLeds->Controls->Add(XtremeCommandBars::XTPControlType::xtpControlGallery, IdsRibbonItems::VIEW_LATTICE_BLACK_AS, "", -1, false); galleryBlackLeds->Width = 146; galleryBlackLeds->Height = 3 * 17; galleryBlackLeds->Items = itemsBlackLeds; comboBlackLeds->CommandBar = popupBlackLeds; comboBlackLeds->Caption="Black LEDs as:"; comboBlackLeds->ListIndex=1; XtremeCommandBars::CommandBarGallery ^galleryQuality; XtremeCommandBars::CommandBarGalleryItems ^itemsQuality; XtremeCommandBars::CommandBar ^popupQuality; itemsQuality = axCommandBars1->CreateGalleryItems(IdsRibbonItems::VIEW_SETTINGS_QUALITY); itemsQuality->ItemWidth = 0; itemsQuality->ItemHeight = 17; itemsQuality->AddItem(1, "High"); itemsQuality->AddItem(1, "Medium"); itemsQuality->AddItem(1, "Low"); itemsQuality->AddItem(1, "Very low"); comboQuality = (XtremeCommandBars::CommandBarComboBox^)groupViewSettings->Add(XtremeCommandBars::XTPControlType::xtpControlComboBox, IdsRibbonItems::VIEW_SETTINGS_QUALITY, "", false, false); comboQuality->Width = 150; comboQuality->DropDownListStyle=0; popupQuality = axCommandBars1->Add("Combo Popup", XtremeCommandBars::XTPBarPosition::xtpBarComboBoxGalleryPopup); galleryQuality = (XtremeCommandBars::CommandBarGallery^)popupQuality->Controls->Add(XtremeCommandBars::XTPControlType::xtpControlGallery, IdsRibbonItems::VIEW_SETTINGS_QUALITY, "", -1, false); galleryQuality->Width = 146; galleryQuality->Height = 4 * 17; galleryQuality->Items = itemsQuality; comboQuality->CommandBar = popupQuality; comboQuality->Caption="Quality"; comboQuality->ListIndex=1; XtremeCommandBars::RibbonTab ^ribbonTabSettings = ribbonBar->InsertTab(1, "&Settings"); ribbonTabView->Id = 5; XtremeCommandBars::RibbonGroup ^groupSettingsPanes = ribbonTabSettings->Groups->AddGroup("Panes", 7); groupSettingsPanes->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::SETTINGS_PANES_FRAMES, "Frames", false, false); groupSettingsPanes->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::SETTINGS_PANES_SCRIPT_SOURCE, "Script source", false, false); groupSettingsPanes->Add(XtremeCommandBars::XTPControlType::xtpControlCheckBox, IdsRibbonItems::SETTINGS_PANES_SCRIPT_OUTPUT, "Script output", false, false); /* CResource oRes ; oRes.Init "C:\The path to MyResourceDLL.dll" ImageManager1.Icons.LoadBitmapFromResource oRes.hModule, 1000, IDS(), xtpImageNormal Set oRes = Nothing axCommandBars1->Icons->LoadBitmapFromResource("F:\\Lumisense\\eigthCubed\\Software\\CubeSense\\iconMain3.png", 777, XtremeCommandBars::XTPImageState::xtpImageNormal); controlFile->IconId = 777; */ } void FrmMainInitDockingPanes() { XtremeDockingPane::Pane ^paneA=axDockingPane1->CreatePane(IdsDockingPanel::PANEL_SCRIPT_SOURCE,500,280,XtremeDockingPane::DockingDirection::DockRightOf); paneA->Title="Script source"; paneA->MinTrackSize->Width=500; paneA->MinTrackSize->Height=280; XtremeDockingPane::Pane ^paneB=axDockingPane1->CreatePane(IdsDockingPanel::PANEL_FRAMES,120,280,XtremeDockingPane::DockingDirection::DockLeftOf); paneB->Title="Frame list"; paneB->MinTrackSize->Width=80; paneB->MinTrackSize->Height=280; axDockingPane1->VisualTheme=XtremeDockingPane::VisualTheme::ThemeOffice2007; XtremeDockingPane::Pane ^paneC=axDockingPane1->CreatePane(IdsDockingPanel::PANEL_SCRIPT_OUTPUT,120,100,XtremeDockingPane::DockingDirection::DockBottomOf); paneC->Title="Script output"; paneC->MinTrackSize->Width=120; paneC->MinTrackSize->Height=100; axDockingPane1->VisualTheme=XtremeDockingPane::VisualTheme::ThemeOffice2007; axDockingPane1->Options->AlphaDockingContext = true; axDockingPane1->Options->ShowDockingContextStickers = true; } private: System::Void FrmMain_Load(System::Object^ sender, System::EventArgs^ e) { logEvent(LOG_THREAD_DEFAULT, "Main form load event handler entered"); FrmMainCreateRibbonBar(); logEvent(LOG_THREAD_DEFAULT, "Ribbon bar created"); FrmMainInitDockingPanes(); logEvent(LOG_THREAD_DEFAULT, "Docking panes created"); ((XtremeCommandBars::RibbonBar^)axCommandBars1->ActiveMenuBar)->EnableFrameTheme(); axDockingPane1->SetCommandBars (axCommandBars1->GetDispatch()); axDockingPane1->Options->ThemedFloatingFrames = true; axDockingPane1->VisualTheme = XtremeDockingPane::VisualTheme::ThemeOffice2003; frmNew=gcnew FrmNew(); frmNew->Visible=false; frmNew->Initialize(); logEvent(LOG_THREAD_DEFAULT, "Form for new animations created"); handlerFrmMainLoad(this->Handle.ToInt32(), this->pictureBox1->Handle.ToInt32(),frmFrames->Handle.ToInt32(),frmScriptSource->Handle.ToInt32()); comboQuality->ListIndex=handlerRenderQuality; comboLedSize->ListIndex=handlerLedSize+1; comboLedSpacing->ListIndex=(handlerLedSpacing/2)+1; comboBlackLeds->ListIndex=handlerBlackLeds; ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::VIEW_ITEMS_AXIS,0,0)->Checked=handlerShowAxis; // ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::VIEW_ITEMS_BASE,0,0)->Checked=handlerShowBase; ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::VIEW_ITEMS_LATTICE,0,0)->Checked=handlerShowLattice; ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::SETTINGS_PANES_FRAMES,0,0)->Checked=1; ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::SETTINGS_PANES_SCRIPT_OUTPUT,0,0)->Checked=1; ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::SETTINGS_PANES_SCRIPT_SOURCE,0,0)->Checked=1; ((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->TextLimit=20; ((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->EditHint="Enter title here"; (ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Width=180; logEvent(LOG_THREAD_DEFAULT, "Default values for main form components set"); animationFileName="animation.eca"; // Control.EditHint = "Enter You Text Here" /*handlerShowBase=0; handlerShowAxis=1; handlerShowLattice=1;*/ } private: System::Void axDockingPane1_AttachPaneEvent(System::Object^ sender, AxXtremeDockingPane::_DDockingPaneEvents_AttachPaneEvent^ e) { if (e->item->Id==IdsDockingPanel::PANEL_FRAMES) { frmFrames=gcnew FrmFrames; e->item->Handle=frmFrames->Handle.ToInt32(); return; } if (e->item->Id==IdsDockingPanel::PANEL_SCRIPT_SOURCE) { frmScriptSource=gcnew FrmScriptSource; e->item->Handle=frmScriptSource->Handle.ToInt32(); frmScriptSource->FrmScriptSourceInit(); return; } if (e->item->Id==IdsDockingPanel::PANEL_SCRIPT_OUTPUT) { frmScriptOutput=gcnew FrmScriptOutput; e->item->Handle=frmScriptOutput->Handle.ToInt32(); wndprocFrmScriptOutputHandle=frmScriptOutput->Handle.ToInt32(); return; } } private: System::Void axCommandBars1_ResizeEvent(System::Object^ sender, System::EventArgs^ e) { int left = 0; int top = 0; int right = 0; int bottom = 0; axCommandBars1->GetClientRect(left, top, right, bottom); pictureBox1->SetBounds(left + 2, top + 2, right - left - 2, bottom - top - 2); } private: System::Void FrmMain_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e) { handlerFrmMainFormClosing(); } private: System::Void axCommandBars1_Execute(System::Object^ sender, AxXtremeCommandBars::_DCommandBarsEvents_ExecuteEvent^ e) { int r; switch (e->control->Id) { case IdsRibbonItems::SYSTEM_EXIT: this->Close(); break; case IdsRibbonItems::HOME_FILE_NEW: r=handlerAskAboutSavingAnimation(); if (r==6) { handlerCreatingAnimation=1; if (animationFileNameSet==0) this->saveFileDialog1->ShowDialog(); else { handlerSaveAnimationFile=1; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerSaveAnimationFileName); handlerSaveAnimationFileName = (char*)(void*)Marshal::StringToHGlobalAnsi(animationFileName); handlerSaveAnimationFileNameLength=animationFileName->Length; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerAnimationTitle); handlerAnimationTitle = (char*)(void*)Marshal::StringToHGlobalAnsi(((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text); handlerAnimationTitleLength=((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text->Length; threadCopyContentDefaultCoreIn(); handlerDisableMainForm(); frmNew->Visible=true; } } if (r==7) { handlerDisableMainForm(); frmNew->Visible=true; } break; case IdsRibbonItems::SCRIPTING_EXECUTE_RUN: frmScriptSource->copyScriptSource(); threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SCRIPTING_EXECUTE_STOP: handlerStopScript=1; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SCRIPTING_REAL_TIME_PREVIEW: frmScriptSource->copyRealTimeScriptSource(); threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SCRIPTING_REAL_TIME_EXPORT: //handlerRealTimePlaying=!handlerRealTimePlaying; //threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SCRIPTING_REAL_TIME_START: handlerRealTimeCommand=1; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SCRIPTING_REAL_TIME_STOP: handlerRealTimeCommand=2; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SCRIPTING_FILE_NEW: frmScriptSource->createNewScript(); break; case IdsRibbonItems::SCRIPTING_FILE_SAVE: frmScriptSource->saveScript(); break; case IdsRibbonItems::SCRIPTING_FILE_SAVEAS: frmScriptSource->saveScriptAs(); break; case IdsRibbonItems::SCRIPTING_FILE_OPEN: frmScriptSource->openScript(); break; case IdsRibbonItems::SCRIPTING_EXECUTE_TYPE: if (!System::String::Compare(Combo->Text,"VB script")) frmScriptSource->changeScriptType(SCRIPT_TYPE_VB); if (!System::String::Compare(Combo->Text,"C# script")) frmScriptSource->changeScriptType(SCRIPT_TYPE_CS); /* if (!System::String::Compare(Combo->Text,"C (real-time)")) frmScriptSource->changeScriptType(SCRIPT_TYPE_CRT); */ case IdsRibbonItems::VIEW_LATTICE_SIZE: handlerLedSize=comboLedSize->ListIndex-1; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_LATTICE_SPACING: handlerLedSpacing=(comboLedSpacing->ListIndex-1)*2; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_LATTICE_BLACK_AS: handlerBlackLeds=comboBlackLeds->ListIndex; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_SETTINGS_QUALITY: handlerRenderQuality=comboQuality->ListIndex; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_ITEMS_AXIS: e->control->Checked = !e->control->Checked; handlerShowAxis=e->control->Checked; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_ITEMS_BASE: e->control->Checked = !e->control->Checked; handlerShowBase=e->control->Checked; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_ITEMS_LATTICE: e->control->Checked = !e->control->Checked; handlerShowLattice=e->control->Checked; threadCopyContentDefaultOpenglIn(); break; case IdsRibbonItems::VIEW_PRESETS_XY: handlerPresetView=4; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::VIEW_PRESETS_XZ: handlerPresetView=2; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::VIEW_PRESETS_YZ: handlerPresetView=3; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::VIEW_PRESETS_DEFAULT: handlerPresetView=1; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::SETTINGS_PANES_FRAMES: e->control->Checked = !e->control->Checked; if (e->control->Checked) axDockingPane1->ShowPane(IdsDockingPanel::PANEL_FRAMES); else axDockingPane1->FindPane(IdsDockingPanel::PANEL_FRAMES)->Close(); break; case IdsRibbonItems::SETTINGS_PANES_SCRIPT_OUTPUT: e->control->Checked = !e->control->Checked; if (e->control->Checked) axDockingPane1->ShowPane(IdsDockingPanel::PANEL_SCRIPT_OUTPUT); else axDockingPane1->FindPane(IdsDockingPanel::PANEL_SCRIPT_OUTPUT)->Close(); break; case IdsRibbonItems::SETTINGS_PANES_SCRIPT_SOURCE: e->control->Checked = !e->control->Checked; if (e->control->Checked) axDockingPane1->ShowPane(IdsDockingPanel::PANEL_SCRIPT_SOURCE); else axDockingPane1->FindPane(IdsDockingPanel::PANEL_SCRIPT_SOURCE)->Close(); break; case IdsRibbonItems::PREVIEW_PLAYBACK_PLAY: handlerPlaybackCommand=1; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::PREVIEW_PLAYBACK_STOP: handlerPlaybackCommand=2; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::PREVIEW_PLAYBACK_REPEAT: e->control->Checked = !e->control->Checked; if (e->control->Checked) handlerPlaybackCommand=3; else handlerPlaybackCommand=4; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::PREVIEW_PLAYBACK_SELECTION: e->control->Checked = !e->control->Checked; if (e->control->Checked) handlerPlaybackCommand=5; else handlerPlaybackCommand=6; threadCopyContentDefaultCoreIn(); break; case IdsRibbonItems::PREVIEW_EIGHTCUBED_CONNECT: handlerUsbControl=1; threadCopyContentDefaultUsbIn(); break; case IdsRibbonItems::PREVIEW_EIGHTCUBED_DISCONNECT: handlerUsbControl=2; threadCopyContentDefaultUsbIn(); break; case IdsRibbonItems::PREVIEW_EIGHTCUBED_STREAM: e->control->Checked = !e->control->Checked; handlerUsbControl=3+e->control->Checked; threadCopyContentDefaultUsbIn(); break; case IdsRibbonItems::HOME_FILE_OPEN: r=handlerAskAboutSavingAnimation(); if (r==6) { handlerOpeningAnimation=1; if (animationFileNameSet==0) this->saveFileDialog1->ShowDialog(); else { handlerSaveAnimationFile=1; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerSaveAnimationFileName); handlerSaveAnimationFileName = (char*)(void*)Marshal::StringToHGlobalAnsi(animationFileName); handlerSaveAnimationFileNameLength=animationFileName->Length; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerAnimationTitle); handlerAnimationTitle = (char*)(void*)Marshal::StringToHGlobalAnsi(((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text); handlerAnimationTitleLength=((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text->Length; threadCopyContentDefaultCoreIn(); this->openFileDialog1->ShowDialog(); } } if (r==7) this->openFileDialog1->ShowDialog(); break; case IdsRibbonItems::HOME_FILE_SAVEAS: saveFileDialog1->ShowDialog(); break; case IdsRibbonItems::HOME_FILE_SAVE: if (animationFileNameSet==0) this->saveFileDialog1->ShowDialog(); else { handlerSaveAnimationFile=1; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerSaveAnimationFileName); handlerSaveAnimationFileName = (char*)(void*)Marshal::StringToHGlobalAnsi(animationFileName); handlerSaveAnimationFileNameLength=animationFileName->Length; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerAnimationTitle); handlerAnimationTitle = (char*)(void*)Marshal::StringToHGlobalAnsi(((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text); handlerAnimationTitleLength=((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text->Length; threadCopyContentDefaultCoreIn(); } break; } } private: System::Void pictureBox1_Resize(System::Object^ sender, System::EventArgs^ e) { handlerPictureBox1Resize(pictureBox1->Height, pictureBox1->Width); } private: System::Void axDockingPane1_Action(System::Object^ sender, AxXtremeDockingPane::_DDockingPaneEvents_ActionEvent^ e) { int id; id=e->pane->Id; if (e->action==XtremeDockingPane::DockingPaneAction::PaneActionClosed) { if (id==IdsDockingPanel::PANEL_FRAMES) ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::SETTINGS_PANES_FRAMES,0,0)->Checked=0; if (id==IdsDockingPanel::PANEL_SCRIPT_OUTPUT) ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::SETTINGS_PANES_SCRIPT_OUTPUT,0,0)->Checked=0; if (id==IdsDockingPanel::PANEL_SCRIPT_SOURCE) ribbonBar->FindControl(XTPControlType::xtpControlCheckBox,IdsRibbonItems::SETTINGS_PANES_SCRIPT_SOURCE,0,0)->Checked=0; } } private: System::Void pictureBox1_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { if ((e->Button==System::Windows::Forms::MouseButtons::Right)| (e->Button==System::Windows::Forms::MouseButtons::Left)) { handlerCanvasActive=1; threadCopyContentDefaultCoreIn(); pictureBox1->Focus(); } } private: System::Void pictureBox1_MouseLeave(System::Object^ sender, System::EventArgs^ e) { handlerCanvasActive=0; threadCopyContentDefaultCoreIn(); } private: System::Void pictureBox1_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void axCommandBars1_ControlNotify(System::Object^ sender, AxXtremeCommandBars::_DCommandBarsEvents_ControlNotifyEvent^ e) { } private: System::Void openFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) { handlerOpenAnimationFile=1; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerOpenAnimationFileName); handlerOpenAnimationFileName = (char*)(void*)Marshal::StringToHGlobalAnsi(openFileDialog1->FileName); handlerOpenAnimationFileNameLength=openFileDialog1->FileName->Length; animationFileName=openFileDialog1->FileName; animationFileNameSet=1; handlerOpeningAnimation=0; threadCopyContentDefaultCoreIn(); } private: System::Void saveFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) { } private: System::Void saveFileDialog1_FileOk_1(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) { handlerSaveAnimationFile=1; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerSaveAnimationFileName); handlerSaveAnimationFileName = (char*)(void*)Marshal::StringToHGlobalAnsi(saveFileDialog1->FileName); handlerSaveAnimationFileNameLength=saveFileDialog1->FileName->Length; animationFileName=saveFileDialog1->FileName; animationFileNameSet=1; Marshal::FreeHGlobal((System::IntPtr)(void*)handlerAnimationTitle); handlerAnimationTitle = (char*)(void*)Marshal::StringToHGlobalAnsi(((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text); handlerAnimationTitleLength=((CommandBarEdit^)ribbonBar->FindControl(XTPControlType::xtpControlEdit,IdsRibbonItems::HOME_PARAMETERS_TITLE,0,0))->Text->Length; threadCopyContentDefaultCoreIn(); if (handlerCreatingAnimation) { handlerDisableMainForm(); frmNew->Visible=true; } if (handlerOpeningAnimation) openFileDialog1->ShowDialog(); } }; }
397f7082148fe19eeeadcbf8dada3ab9adfb4108
ad66f2291c1ac449d6451305d97474dc13847601
/Cpp_2DSTG_3/Cpp_2DSTG/UI.h
f6ee7b9434c7fd3285bba8dca52c867cf05f6401
[]
no_license
reima22/test_reima
bd3fd338dc3044d0a88b300b2113979f79de06ac
ff10e3ca889f332a2800abade97fd21fa8e4d905
refs/heads/master
2023-07-17T23:50:48.522442
2021-09-08T04:25:34
2021-09-08T04:25:34
404,206,740
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
880
h
UI.h
//============================================================================= // // UI描画処理 [UI.h] // Author : Mare Horiai // //============================================================================= #ifndef _UI_H_ #define _UI_H_ #include "main.h" #include "scene.h" // 前方宣言 class CPolygon; //============================================================================== // UIクラス //============================================================================== class CUI : public CScene { public: CUI(int nPriority = PRIORITY_UI); ~CUI(); HRESULT Init(D3DXVECTOR3 pos); void Uninit(void); void Update(void); void Draw(void); static CUI *Create(D3DXVECTOR3 pos); D3DXVECTOR3 GetPosition(void); D3DXVECTOR3 GetSize(void); private: CPolygon *m_pPolygon; // ポリゴンクラスポインタ }; #endif
62ee82b5dd02caae77e3a8b367af09234a1c50eb
1004816de8f435d930167ec03e7196f3d033db1f
/Rpkg/src/rutils.h
9f72da8ea6146175ec3e02df325bbca6b6304e95
[ "Apache-2.0" ]
permissive
zheng-da/FlashX
04e0eedb894f8504a51f0d88a398d766909b2ad5
3ddbd8e517d2141d6c2a4a5f712f6d8660bc25c6
refs/heads/release
2021-01-21T09:38:24.454071
2016-12-28T08:51:44
2016-12-28T08:51:44
19,077,386
22
11
null
null
null
null
UTF-8
C++
false
false
1,444
h
rutils.h
#ifndef __R_UTILS_H__ #define __R_UTILS_H__ /* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashR. * * 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 <memory> #include<Rcpp.h> bool R_is_real(SEXP v); bool R_is_integer(SEXP v); template<class T> bool R_get_number(SEXP v, T &ret) { if (R_is_real(v)) { ret = REAL(v)[0]; return true; } else if (R_is_integer(v)) { ret = INTEGER(v)[0]; return true; } else return false; } /* * Test if this is a sparse matrix. */ static inline bool is_sparse(const Rcpp::S4 &matrix) { std::string type = matrix.slot("type"); return type == "sparse"; } static inline bool is_vector(const Rcpp::S4 &vec) { return vec.is("fmV"); } static inline bool is_factor_vector(const Rcpp::S4 &vec) { return vec.is("fmFactorV"); } void R_gc(); SEXP R_create_s4fm(SEXP fm); #endif
9d837ccd5ed1ebf0f10b1e484e4311bdc2a6fb88
974d04d2ea27b1bba1c01015a98112d2afb78fe5
/paddle/fluid/platform/resource_pool.h
737001a50abbf1d710310e87b5e118f3ba59f93a
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle
b3d2583119082c8e4b74331dacc4d39ed4d7cff0
22a11a60e0e3d10a3cf610077a3d9942a6f964cb
refs/heads/develop
2023-08-17T21:27:30.568889
2023-08-17T12:38:22
2023-08-17T12:38:22
65,711,522
20,414
5,891
Apache-2.0
2023-09-14T19:20:51
2016-08-15T06:59:08
C++
UTF-8
C++
false
false
2,925
h
resource_pool.h
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <functional> #include <memory> #include <mutex> #include <string> #include <utility> #include <vector> #include "paddle/fluid/platform/enforce.h" #include "paddle/fluid/platform/macros.h" namespace paddle { namespace platform { template <typename T> class ResourcePool : public std::enable_shared_from_this<ResourcePool<T>> { private: struct ResourceDeleter { public: explicit ResourceDeleter(ResourcePool<T> *pool) : instance_(pool->shared_from_this()) {} void operator()(T *ptr) const { instance_->Restore(ptr); } private: std::shared_ptr<ResourcePool<T>> instance_; }; public: static std::shared_ptr<ResourcePool<T>> Create( const std::function<T *()> &creator, const std::function<void(T *)> &deleter) { return std::shared_ptr<ResourcePool<T>>( new ResourcePool<T>(creator, deleter)); } ~ResourcePool() { for (auto *ptr : instances_) { deleter_(ptr); } } std::shared_ptr<T> New() { std::lock_guard<std::mutex> guard(mtx_); T *obj = nullptr; if (instances_.empty()) { obj = creator_(); PADDLE_ENFORCE_NOT_NULL(obj, platform::errors::PermissionDenied( "The creator should not return nullptr.")); VLOG(10) << "Create new instance " << TypePtrName(); } else { obj = instances_.back(); instances_.pop_back(); VLOG(10) << "Pop new instance " << TypePtrName() << " from pool, size=" << instances_.size(); } return std::shared_ptr<T>(obj, ResourceDeleter(this)); } private: static std::string TypePtrName() { return platform::demangle(typeid(T *).name()); // NOLINT } private: ResourcePool(const std::function<T *()> &creator, const std::function<void(T *)> &deleter) : creator_(creator), deleter_(deleter) {} void Restore(T *ptr) { std::lock_guard<std::mutex> guard(mtx_); instances_.emplace_back(ptr); VLOG(10) << "Restore " << TypePtrName() << " into pool, size=" << instances_.size(); } private: std::vector<T *> instances_; const std::function<T *()> creator_; const std::function<void(T *)> deleter_; std::mutex mtx_; }; } // namespace platform } // namespace paddle
9e3a5c3cd3c10cffcbfa73e8cd831f78918b94dc
6eb9adc73c4bc64b891ea0309edbff29b8088ac3
/TrekStar/Genres.cpp
ac4de95911c7a5f88639765381351f65130f6446
[]
no_license
jpmono416/TrekStar-Pictures
1cc0c1202bfd2c044b5c2b2407fb87a351a8fe4b
fb88c8b5816cb164e6a38e699b24a38483d01882
refs/heads/master
2020-05-16T07:11:24.033730
2019-04-28T22:37:14
2019-04-28T22:37:14
182,872,725
0
0
null
null
null
null
UTF-8
C++
false
false
394
cpp
Genres.cpp
#include "pch.h" #include "Genres.h" Genres::Genres() { } Genres::~Genres() { } void Genres::setID(int id) { this->id = id; } std::string Genres::getGenre() { return this->genreList.at(id); } std::basic_ostream<char, std::char_traits<char>>& operator<<(std::basic_ostream<char, std::char_traits<char>>& os, Genres genre) { os << genre.getID(); return os; }
b0a4231b55ff2927ad8390b3338fbed4c59d6654
ae2fd79e8b46fb1f4c9fc1f5575df594c2033917
/WiiRemoteSensor.cpp
6aa089719be23f957f1803a1bb86acce757d79ac
[]
no_license
bertelkirk/wiiDemoRollPitch
98ea9480c5f61eb06a7080fe7b98502ce04b203e
76fcc06083084ca0fb7c4af25754a4673d8c76db
refs/heads/master
2020-04-01T11:46:24.983017
2018-10-15T20:51:05
2018-10-15T20:51:05
153,176,965
1
1
null
null
null
null
UTF-8
C++
false
false
7,168
cpp
WiiRemoteSensor.cpp
#include "WiiRemoteSensor.h" #include "SensorThread.h" #include <cstdio> #include <QDebug> WiiRemoteSensor::WiiRemoteSensor(QObject *parent) : QObject(parent) { SensorThread *thread = new SensorThread(); thread->mpParent= this; thread->start(); } void WiiRemoteSensor::runThread(){ bool running=true; bool wiiConnected=false; bdaddr = *BDADDR_ANY; /* Connect to the wiimote */ qDebug() << "Press button 1+2 to sync/connect wiimote"; while(wiiConnected==false) { if (!(wiimoteC = cwiid_open(&bdaddr, 0))) { fprintf(stderr, "Unable to connect to wiimote\n"); }else{ wiiConnected=true; } if (cwiid_set_mesg_callback(wiimoteC, this->cwiid_callback ) ) { fprintf(stderr, "Unable to set message callback\n"); wiiConnected=false; } } qDebug() << "Wii-remote connected"; cwiid_set_err(this->err); rpt_mode= CWIID_RPT_ACC | CWIID_RPT_BTN; set_rpt_mode(wiimoteC, rpt_mode); set_led_state(wiimoteC,4); while(running){ QThread::msleep(60); if (cwiid_get_state(wiimoteC, &(state) ) ) { fprintf(stderr, "Error getting state\n"); }else{ buttons = state.buttons; int x= acceleration[0]=state.acc[0]-123; int y= acceleration[1]=state.acc[1]-123; int z= acceleration[2]=state.acc[2]-123; point3d_t acc, accF; acc.x = x; acc.y = y; acc.z = z; addDataToFilter(acc, accFiltered, 5); accF = getFilteredData(accFiltered); qDebug() << "input x:" << acc.x << " y" << acc.y << " z" << acc.z << " filtered :x" << accF.x << " y" << accF.y << " z" << accF.z ; x=accF.x; y=accF.y; z=accF.z; roll = (atan2(y, z)*180.0)/M_PI; pitch = (atan2(x, sqrt(y*y + z*z))*180.0)/M_PI; //qDebug() << "State: BTNs: " << buttons << " x" << x << " y" << y << " z" << z << " roll:"<<roll<<" pitch:"<< pitch; signalWiiStatusUpdate(buttons, roll, pitch, x,y,z); } } } void WiiRemoteSensor::err(cwiid_wiimote_t *wiimote, const char *s, va_list ap) { if (wiimote) printf("%d:", cwiid_get_id(wiimote)); else printf("-1:"); vprintf(s, ap); printf("\n"); } void WiiRemoteSensor::set_led_state(cwiid_wiimote_t *wiimote, unsigned char led_state) { if (cwiid_set_led(wiimote, led_state)) { fprintf(stderr, "Error setting LEDs \n"); } } void WiiRemoteSensor::set_rpt_mode(cwiid_wiimote_t *wiimote, unsigned char rpt_mode) { if (cwiid_set_rpt_mode(wiimote, rpt_mode)) { fprintf(stderr, "Error setting report mode\n"); } } void WiiRemoteSensor::cwiid_callback(cwiid_wiimote_t *wiimote, int mesg_count, union cwiid_mesg mesg[], struct timespec *timestamp) { int i, j; int valid_source; (void) timestamp; for (i=0; i < mesg_count; i++) { switch (mesg[i].type) { case CWIID_MESG_STATUS: printf("Status Report: battery=%d extension=", mesg[i].status_mesg.battery); switch (mesg[i].status_mesg.ext_type) { case CWIID_EXT_NONE: printf("none"); break; case CWIID_EXT_NUNCHUK: printf("Nunchuk"); break; case CWIID_EXT_CLASSIC: printf("Classic Controller"); break; case CWIID_EXT_BALANCE: printf("Balance Board"); break; case CWIID_EXT_MOTIONPLUS: printf("MotionPlus"); break; default: printf("Unknown Extension"); break; } printf("\n"); break; case CWIID_MESG_BTN: printf("Button Report: %.4X\n", mesg[i].btn_mesg.buttons); break; case CWIID_MESG_ACC: printf("Acc Report: x=%d, y=%d, z=%d\n", mesg[i].acc_mesg.acc[CWIID_X], mesg[i].acc_mesg.acc[CWIID_Y], mesg[i].acc_mesg.acc[CWIID_Z]); break; case CWIID_MESG_IR: printf("IR Report: "); valid_source = 0; for (j = 0; j < CWIID_IR_SRC_COUNT; j++) { if (mesg[i].ir_mesg.src[j].valid) { valid_source = 1; printf("(%d,%d) ", mesg[i].ir_mesg.src[j].pos[CWIID_X], mesg[i].ir_mesg.src[j].pos[CWIID_Y]); } } if (!valid_source) { printf("no sources detected"); } printf("\n"); break; case CWIID_MESG_NUNCHUK: printf("Nunchuk Report: btns=%.2X stick=(%d,%d) acc.x=%d acc.y=%d " "acc.z=%d\n", mesg[i].nunchuk_mesg.buttons, mesg[i].nunchuk_mesg.stick[CWIID_X], mesg[i].nunchuk_mesg.stick[CWIID_Y], mesg[i].nunchuk_mesg.acc[CWIID_X], mesg[i].nunchuk_mesg.acc[CWIID_Y], mesg[i].nunchuk_mesg.acc[CWIID_Z]); break; case CWIID_MESG_CLASSIC: printf("Classic Report: btns=%.4X l_stick=(%d,%d) r_stick=(%d,%d) " "l=%d r=%d\n", mesg[i].classic_mesg.buttons, mesg[i].classic_mesg.l_stick[CWIID_X], mesg[i].classic_mesg.l_stick[CWIID_Y], mesg[i].classic_mesg.r_stick[CWIID_X], mesg[i].classic_mesg.r_stick[CWIID_Y], mesg[i].classic_mesg.l, mesg[i].classic_mesg.r); break; case CWIID_MESG_BALANCE: printf("Balance Report: right_top=%d right_bottom=%d " "left_top=%d left_bottom=%d\n", mesg[i].balance_mesg.right_top, mesg[i].balance_mesg.right_bottom, mesg[i].balance_mesg.left_top, mesg[i].balance_mesg.left_bottom); break; case CWIID_MESG_MOTIONPLUS: printf("MotionPlus Report: angle_rate=(%d,%d,%d) low_speed=(%d,%d,%d)\n", mesg[i].motionplus_mesg.angle_rate[0], mesg[i].motionplus_mesg.angle_rate[1], mesg[i].motionplus_mesg.angle_rate[2], mesg[i].motionplus_mesg.low_speed[0], mesg[i].motionplus_mesg.low_speed[1], mesg[i].motionplus_mesg.low_speed[2]); break; case CWIID_MESG_ERROR: if (cwiid_close(wiimote)) { fprintf(stderr, "Error on wiimote disconnect\n"); return; //exit(-1); } return; // exit(0); break; default: printf("Unknown Report"); break; } } }
e84b58f000d2bc1faa7425392e0885b1c23fbf93
bd288d119b361df94228f1951b62f6a3e4418301
/tests/test_validation.cc
5b5ad48bde685e8a1b4c60a8284a9c4d4ab7cfdb
[ "Apache-2.0" ]
permissive
Labs64/NetLicensingClient-cpp
bd66145bf19bd841a18bc33ce79c13c295542722
438114e353dca6eaee1ac522b8f9f6c3e31b8e9d
refs/heads/master
2022-12-06T19:59:02.884222
2022-11-22T11:47:46
2022-11-22T11:47:46
49,488,287
12
4
Apache-2.0
2022-11-22T11:47:48
2016-01-12T09:11:13
C++
UTF-8
C++
false
false
1,434
cc
test_validation.cc
#ifndef WIN32 #define BOOST_TEST_DYN_LINK #endif #include <cassert> #include <boost/test/unit_test.hpp> #include "common.h" #include "netlicensing/mapper.h" #include "netlicensing/validation_result.h" #include "netlicensing/traversal.h" BOOST_AUTO_TEST_SUITE(test_licensee_validation) BOOST_AUTO_TEST_CASE(test_plain_validation_result) { using namespace netlicensing; std::string answer = read_whole_file("licensee_validation_result_plain.json"); BOOST_REQUIRE(!answer.empty()); ValidationResult vr; ValidationResultMapper mvr(vr); traverse(mvr, answer); BOOST_REQUIRE_EQUAL(2u, vr.getValidations().size()); //BOOST_CHECK_EQUAL(2u, vr.getProperties().size()); BOOST_CHECK_EQUAL("MM3M9XN63", *vr.getValidations().begin()->second.get("productModuleNumber")); } BOOST_AUTO_TEST_CASE(test_recursive_validation_result) { using namespace netlicensing; std::string answer = read_whole_file("licensee_validation_result_recursive.json"); BOOST_REQUIRE(!answer.empty()); ValidationResult vr; ValidationResultMapper mvr(vr); traverse(mvr, answer); BOOST_REQUIRE_EQUAL(1u, vr.getValidations().size()); //BOOST_CHECK_EQUAL(2u, vr.getValidations().back().getProperties().size()); //BOOST_CHECK_EQUAL(2u, vr.getValidations().back().getProperties().front()->nested_lists_.size()); BOOST_CHECK_EQUAL("M5-DEMO", *vr.getValidations().begin()->second.get("productModuleNumber")); } BOOST_AUTO_TEST_SUITE_END()
d4fdbccb60448c0fcd61b8b097ba722b2b5bce8e
90222aeecc3eb746bf202ea397a8ed9fe0b19ff0
/Projects/engine/graphics/renderers/gfw_renderer.cpp
3a37b170d1c3c50c825f172bbbd53b114c443975
[ "MIT" ]
permissive
Octdoc/SevenDeities
5385264ec87e1775b6784cf41c711e970544c50e
648324b6b9fb907df93fdf2dfab7379369bdfe9e
refs/heads/master
2020-03-28T06:09:20.015284
2018-09-12T13:19:52
2018-09-12T13:19:52
147,817,141
0
0
MIT
2018-09-11T18:06:01
2018-09-07T11:55:27
C++
UTF-8
C++
false
false
554
cpp
gfw_renderer.cpp
#include "gfw_renderer.h" namespace gfw { void Renderer::SetSky(SkyDome::P sky) { m_sky = sky; } void Renderer::AddEntity(Entity::P entity) { m_entities.push_back(entity); } void Renderer::RemoveEntity(Entity::P entity) { for (auto e = m_entities.begin(); e != m_entities.end(); e++) { if (*e == entity) { m_entities.erase(e); return; } } } void Renderer::ClearEntities() { m_entities.clear(); } void Renderer::RemoveSky() { m_sky.reset(); } void Renderer::Clear() { ClearEntities(); RemoveSky(); } }
72078a18dd0ffb6ac6e25a1cf4a32b2de11ae704
a25273242e95a87885b08e6716b58d1c1d34416b
/LABFILES/Lab4/testpolygcd.cc
6697472283014d9d38d86e47e2ca8be5f5ac7da9
[]
no_license
liecn/eccbook
827c84136c51244e5c892cd48dc28a847aa14a56
9ac744e181c5d111027f165f759c9fb0f2f5255d
refs/heads/master
2023-05-26T04:32:07.340345
2020-08-19T02:17:33
2020-08-19T02:17:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,766
cc
testpolygcd.cc
// // Program: testpolygcd.cc #include <math.h> #include "ModArnew.h" #include "polynomialT.cc" #include "gcdpoly.cc" // create instantiations of the polynomial class of type ModAr template class polynomialT<ModAr<5> >; template class polytemp<ModAr<5> >; // create instantiations of the polynomial class of type double template class polynomialT<double>; template class polytemp<double>; typedef ModAr<5> Z5; // Create an instantiation of the gcd function, for polynomials of type ModAr template <class Z5 > void gcd(const polynomialT<Z5> &a, const polynomialT<Z5> &b, polynomialT<Z5> &g, polynomialT<Z5> &s, polynomialT<Z5> &t, int sdeg); // Create an instantiation of the gcd function, for polynomials of type double // template <double> void // gcd(const polynomialT<double> &a, const polynomialT<double> &b, // polynomialT<double> &g, // polynomialT<double> &s, polynomialT<double> &t, int sdeg); int main() { POLYC(Z5,a,{1,0,0,1,3,0,4,3}); // 1+x^3 + 3x^4 + 4x^6 + 3x^7 POLYC(Z5,b,{0,1,0,1,4}); // x+x^3+x^4 polynomialT<Z5> s, t, g; a.setprintdir(1); cout << "a=" << a << endl; cout << "b=" << b << endl; gcd(a,b,g,s,t); cout << "g=" << g << endl; cout << "s=" << s << endl; cout << "t=" << t << endl; cout << "\n\n\n"; double d1d[4] = {2,8,10,4}; double d2d[4] = {1,7,14,8}; POLYC(double,ad,{2,8,10,4}); // 2 + 8x + 10x^2 + 4x^3 POLYC(double,bd,{1,7,14,8}); // 1 + 7x + 14x^2 + 8x^3 polynomialT<double> sd,td,gd; cout << "a=" << ad << endl; cout << "b=" << bd << endl; gcd(ad,bd,gd,sd,td,0); cout << "g=" << gd << endl; cout << "s=" << sd << endl; cout << "t=" << td << endl; } /* Local Variables: compile-command:"g++ -o testpolygcd -g testpolygcd.cc" End: */
8aafafff5be7b3be65bd0a3eb52fe21e59aa6747
47210b905e964f5a2346b40129fcf88b30086d7b
/第二套/5/main.cpp
c2227f42a02d0da4ae12f66dd06ed4564365f451
[]
no_license
a5834099147/c_plus_plus_interview
d1030060632754edd6fe3df57db829e605bb4da9
827b459e1f96d3503bfde48dc1041d63599adbeb
refs/heads/master
2021-01-10T21:37:33.535609
2014-09-15T01:16:19
2014-09-15T01:16:19
null
0
0
null
null
null
null
GB18030
C++
false
false
736
cpp
main.cpp
#include <iostream> using namespace std; int fun(int) { return 0; } int main() { int a; ///< 一个整形数 int *b = &a; ///< 一个指向整形数的指针 int **c = &b; ///< 一个指向指针的指针, 它所指向的指针是一个整形数 int d[10]; ///< 一个有10个整形数的数组 int* e[10]; ///< 一个有10个指针的数组 int(*f)[10] = &d; ///< 一个指向有10个整形数数组的指针 int(*g)(int) = fun; ///< 一个指向函数的指针, 该函数有一个整形参数, 有一个整形参数的返回值 int(*h[10])(int); ///< 一个有10个指针的数组, 该指针指向一个如g的指针 cout << "Hello world!" << endl; return 0; }
87d465cefafed327d31c7cbcca1fe8258853e7b2
5abefd5ecfc74d925ed2e0051ba435e90303ca6a
/LogSys.h
04a6742553af293bd9b29dbbd8c50aacc862c04b
[]
no_license
dionysusxie/LOG-Module
cc88986db3b47ba3d7ff1e848cabc378397cb75d
cd3b44159c091487e3c66277c56699e3ca48422b
refs/heads/master
2020-06-04T02:53:42.137943
2013-06-05T12:26:23
2013-06-05T12:26:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
521
h
LogSys.h
/* * LogSys.h * * Created on: Aug 15, 2012 * Author: xieliang */ #ifndef LOGSYS_H_ #define LOGSYS_H_ #include "log_config.h" #include "Logger.h" class LogSys { public: // static methods: static LogSys& getInstance(); virtual ~LogSys(); bool initialize(const std::string& config_file); void log(const std::string& msg, ENUM_LOG_LEVEL level); void setLevel(ENUM_LOG_LEVEL level); private: LogSys(); private: boost::shared_ptr<Logger> logger_; }; #endif /* LOGSYS_H_ */
302ad16b6af2e813d60e75445d60f94259192b7a
9d46cc993666968d3a90250ea45c57eebd68ceb6
/GameSource/ja2_v1.13/Build/Tactical/Dialogue Control.h
7c987d899e5cd9cc38543caca31901e7e493a038
[]
no_license
janisozaur/ja2_1.13
950b014c5636b111af15bf91405445706e730e66
9cfeeac7d12a48cb936849964f9578f87d8ba9bc
refs/heads/master
2021-01-17T16:47:30.573267
2016-08-17T06:23:45
2016-08-17T06:23:45
65,851,027
1
1
null
null
null
null
UTF-8
C++
false
false
15,726
h
Dialogue Control.h
#ifndef _DIALOG_CONTROL_H #define _DIALOG_CONTROL_H #include "Faces.h" #include "GameScreen.h" #include "Soldier Profile Type.h" #include <vector> typedef struct { UINT16 uiIndex; // add BOOLEAN EnabledSound; } SOUND_PROFILE_VALUES; extern SOUND_PROFILE_VALUES gSoundProfileValue[NUM_PROFILES]; // An enumeration for dialog quotes enum DialogQuoteIDs { // 0 QUOTE_SEE_ENEMY = 0, QUOTE_SEE_ENEMY_VARIATION, QUOTE_IN_TROUBLE_SLASH_IN_BATTLE, QUOTE_SEE_CREATURE, QUOTE_FIRSTTIME_GAME_SEE_CREATURE, QUOTE_TRACES_OF_CREATURE_ATTACK, QUOTE_HEARD_SOMETHING, QUOTE_SMELLED_CREATURE, QUOTE_WEARY_SLASH_SUSPUCIOUS, QUOTE_WORRIED_ABOUT_CREATURE_PRESENCE, //10 QUOTE_ATTACKED_BY_MULTIPLE_CREATURES, QUOTE_SPOTTED_SOMETHING_ONE, QUOTE_SPOTTED_SOMETHING_TWO, QUOTE_OUT_OF_AMMO, QUOTE_SERIOUSLY_WOUNDED, QUOTE_BUDDY_ONE_KILLED, QUOTE_BUDDY_TWO_KILLED, QUOTE_LEARNED_TO_LIKE_MERC_KILLED, QUOTE_FORGETFULL_SLASH_CONFUSED, QUOTE_JAMMED_GUN, //20 QUOTE_UNDER_HEAVY_FIRE, QUOTE_TAKEN_A_BREATING, QUOTE_CLOSE_CALL, QUOTE_NO_LINE_OF_FIRE, QUOTE_STARTING_TO_BLEED, QUOTE_NEED_SLEEP, QUOTE_OUT_OF_BREATH, QUOTE_KILLED_AN_ENEMY, QUOTE_KILLED_A_CREATURE, QUOTE_HATED_MERC_ONE, //30 QUOTE_HATED_MERC_TWO, QUOTE_LEARNED_TO_HATE_MERC, QUOTE_AIM_KILLED_MIKE, QUOTE_MERC_QUIT_LEARN_TO_HATE = QUOTE_AIM_KILLED_MIKE, QUOTE_HEADSHOT, QUOTE_PERSONALITY_TRAIT, QUOTE_ASSIGNMENT_COMPLETE, QUOTE_REFUSING_ORDER, QUOTE_KILLING_DEIDRANNA, QUOTE_KILLING_QUEEN, QUOTE_ANNOYING_PC, //40 QUOTE_STARTING_TO_WHINE, QUOTE_NEGATIVE_COMPANY, QUOTE_AIR_RAID, QUOTE_WHINE_EQUIPMENT, QUOTE_SOCIAL_TRAIT, QUOTE_PASSING_DISLIKE, QUOTE_EXPERIENCE_GAIN, QUOTE_PRE_NOT_SMART, QUOTE_POST_NOT_SMART, QUOTE_HATED_1_ARRIVES, QUOTE_MERC_QUIT_HATED1 = QUOTE_HATED_1_ARRIVES, //50 QUOTE_HATED_2_ARRIVES, QUOTE_MERC_QUIT_HATED2 = QUOTE_HATED_2_ARRIVES, QUOTE_BUDDY_1_GOOD, QUOTE_BUDDY_2_GOOD, QUOTE_LEARNED_TO_LIKE_WITNESSED, QUOTE_DELAY_CONTRACT_RENEWAL, QUOTE_NOT_GETTING_PAID = QUOTE_DELAY_CONTRACT_RENEWAL, QUOTE_AIM_SEEN_MIKE, QUOTE_PC_DROPPED_OMERTA = QUOTE_AIM_SEEN_MIKE, QUOTE_BLINDED, QUOTE_DEFINITE_CANT_DO, QUOTE_LISTEN_LIKABLE_PERSON, QUOTE_ENEMY_PRESENCE, //60 QUOTE_WARNING_OUTSTANDING_ENEMY_AFTER_RT, QUOTE_FOUND_SOMETHING_SPECIAL, QUOTE_SATISFACTION_WITH_GUN_AFTER_KILL, QUOTE_SPOTTED_JOEY, QUOTE_RESPONSE_TO_MIGUEL_SLASH_QUOTE_MERC_OR_RPC_LETGO, QUOTE_SECTOR_SAFE, QUOTE_STUFF_MISSING_DRASSEN, QUOTE_KILLED_FACTORY_MANAGER, QUOTE_SPOTTED_BLOODCAT, QUOTE_END_GAME_COMMENT, //70 QUOTE_ENEMY_RETREATED, QUOTE_GOING_TO_AUTO_SLEEP, QUOTE_WORK_UP_AND_RETURNING_TO_ASSIGNMENT, // woke up from auto sleep, going back to wo QUOTE_ME_TOO, // me too quote, in agreement with whatever the merc previous said QUOTE_USELESS_ITEM, QUOTE_BOOBYTRAP_ITEM, QUOTE_SUSPICIOUS_GROUND, QUOTE_DROWNING, QUOTE_MERC_REACHED_DESTINATION, QUOTE_SPARE2, //80 QUOTE_REPUTATION_REFUSAL, //80 QUOTE_NON_AIM_BUDDY_THREE_KILLED = QUOTE_REPUTATION_REFUSAL, QUOTE_DEATH_RATE_REFUSAL, //= 81, QUOTE_NON_AIM_BUDDY_FOUR_KILLED = QUOTE_DEATH_RATE_REFUSAL, QUOTE_LAME_REFUSAL, //= 82, QUOTE_NON_AIM_BUDDY_FIVE_KILLED = QUOTE_LAME_REFUSAL, QUOTE_WONT_RENEW_CONTRACT_LAME_REFUSAL, //=83, QUOTE_NON_AIM_HATED_MERC_THREE = QUOTE_WONT_RENEW_CONTRACT_LAME_REFUSAL, QUOTE_ANSWERING_MACHINE_MSG, //= 84, QUOTE_NON_AIM_HATED_MERC_FOUR = QUOTE_ANSWERING_MACHINE_MSG, QUOTE_DEPARTING_COMMENT_CONTRACT_NOT_RENEWED_OR_48_OR_MORE, //=85, QUOTE_NON_AIM_HATED_MERC_FIVE = QUOTE_DEPARTING_COMMENT_CONTRACT_NOT_RENEWED_OR_48_OR_MORE, QUOTE_HATE_MERC_1_ON_TEAM,// = 86, QUOTE_NON_AIM_BUDDY_3_GOOD = QUOTE_HATE_MERC_1_ON_TEAM, QUOTE_HATE_MERC_2_ON_TEAM,// = 87, QUOTE_NON_AIM_BUDDY_4_GOOD = QUOTE_HATE_MERC_2_ON_TEAM, QUOTE_LEARNED_TO_HATE_MERC_ON_TEAM,// = 88, QUOTE_NON_AIM_BUDDY_5_GOOD = QUOTE_LEARNED_TO_HATE_MERC_ON_TEAM, QUOTE_CONTRACTS_OVER,// = 89, QUOTE_MERC_QUIT_HATED3 = QUOTE_CONTRACTS_OVER, //90 QUOTE_ACCEPT_CONTRACT_RENEWAL, // =90, QUOTE_MERC_QUIT_HATED4 = QUOTE_ACCEPT_CONTRACT_RENEWAL, QUOTE_CONTRACT_ACCEPTANCE,// =91, QUOTE_MERC_QUIT_HATED5 = QUOTE_CONTRACT_ACCEPTANCE, QUOTE_JOINING_CAUSE_BUDDY_1_ON_TEAM,// = 92, QUOTE_JOINING_CAUSE_BUDDY_2_ON_TEAM,// = 93, QUOTE_JOINING_CAUSE_LEARNED_TO_LIKE_BUDDY_ON_TEAM,// = 94, QUOTE_REFUSAL_RENEW_DUE_TO_MORALE,// = 95, QUOTE_PRECEDENT_TO_REPEATING_ONESELF,// = 96, QUOTE_REFUSAL_TO_JOIN_LACK_OF_FUNDS,// = 97, QUOTE_DEPART_COMMET_CONTRACT_NOT_RENEWED_OR_TERMINATED_UNDER_48,// = 98, QUOTE_DEATH_RATE_RENEWAL, //100 QUOTE_HATE_MERC_1_ON_TEAM_WONT_RENEW, QUOTE_HATE_MERC_2_ON_TEAM_WONT_RENEW, QUOTE_LEARNED_TO_HATE_MERC_1_ON_TEAM_WONT_RENEW, QUOTE_RENEWING_CAUSE_BUDDY_1_ON_TEAM, QUOTE_RENEWING_CAUSE_BUDDY_2_ON_TEAM, QUOTE_RENEWING_CAUSE_LEARNED_TO_LIKE_BUDDY_ON_TEAM, QUOTE_PRECEDENT_TO_REPEATING_ONESELF_RENEW, QUOTE_RENEW_REFUSAL_DUE_TO_LACK_OF_FUNDS, QUOTE_GREETING, QUOTE_SMALL_TALK, //110 QUOTE_IMPATIENT_QUOTE, QUOTE_LENGTH_OF_CONTRACT, QUOTE_COMMENT_BEFORE_HANG_UP, QUOTE_PERSONALITY_BIAS_WITH_MERC_1, QUOTE_PERSONALITY_BIAS_WITH_MERC_2, QUOTE_MERC_LEAVING_ALSUCO_SOON, QUOTE_MERC_GONE_UP_IN_PRICE, #ifdef JA2UB QUOTE_ENTER_SECTOR_WITH_FAN_1, QUOTE_ENTER_SECTOR_WITH_FAN_2, #endif QUOTE_AIM_BUDDY_THREE_KILLED = 119, //120 QUOTE_AIM_BUDDY_FOUR_KILLED, QUOTE_AIM_BUDDY_FIVE_KILLED, QUOTE_AIM_HATED_MERC_THREE, QUOTE_AIM_HATED_MERC_FOUR, QUOTE_AIM_HATED_MERC_FIVE, QUOTE_HATED_3_ARRIVES, QUOTE_HATED_4_ARRIVES, QUOTE_HATED_5_ARRIVES, QUOTE_AIM_BUDDY_3_GOOD, QUOTE_AIM_BUDDY_4_GOOD, //130 QUOTE_AIM_BUDDY_5_GOOD, QUOTE_HATE_MERC_3_ON_TEAM, QUOTE_HATE_MERC_4_ON_TEAM, QUOTE_HATE_MERC_5_ON_TEAM, QUOTE_JOINING_CAUSE_BUDDY_3_ON_TEAM, QUOTE_JOINING_CAUSE_BUDDY_4_ON_TEAM, QUOTE_JOINING_CAUSE_BUDDY_5_ON_TEAM, QUOTE_HATE_MERC_3_ON_TEAM_WONT_RENEW, QUOTE_HATE_MERC_4_ON_TEAM_WONT_RENEW, QUOTE_HATE_MERC_5_ON_TEAM_WONT_RENEW, //140 QUOTE_RENEWING_CAUSE_BUDDY_3_ON_TEAM, QUOTE_RENEWING_CAUSE_BUDDY_4_ON_TEAM, QUOTE_RENEWING_CAUSE_BUDDY_5_ON_TEAM, QUOTE_PERSONALITY_BIAS_WITH_MERC_3, QUOTE_PERSONALITY_BIAS_WITH_MERC_4, QUOTE_PERSONALITY_BIAS_WITH_MERC_5, } ; #define DEFAULT_EXTERN_PANEL_X_POS 320 #define DEFAULT_EXTERN_PANEL_Y_POS 40 #define DIALOGUE_TACTICAL_UI 1 #define DIALOGUE_CONTACTPAGE_UI 2 #define DIALOGUE_NPC_UI 3 #define DIALOGUE_SPECK_CONTACT_PAGE_UI 4 #define DIALOGUE_EXTERNAL_NPC_UI 5 #define DIALOGUE_SHOPKEEPER_UI 6 #define DIALOGUE_SNITCH_UI 7 // anv: special handle for snitch dialogue #define DIALOGUE_SPECIAL_EVENT_GIVE_ITEM 0x00000001 #define DIALOGUE_SPECIAL_EVENT_TRIGGER_NPC 0x00000002 #define DIALOGUE_SPECIAL_EVENT_GOTO_GRIDNO 0x00000004 #define DIALOGUE_SPECIAL_EVENT_DO_ACTION 0x00000008 #define DIALOGUE_SPECIAL_EVENT_CLOSE_PANEL 0x00000010 #define DIALOGUE_SPECIAL_EVENT_PCTRIGGERNPC 0x00000020 #define DIALOGUE_SPECIAL_EVENT_BEGINPREBATTLEINTERFACE 0x00000040 #define DIALOGUE_SPECIAL_EVENT_SKYRIDERMAPSCREENEVENT 0x00000080 #define DIALOGUE_SPECIAL_EVENT_SHOW_CONTRACT_MENU 0x00000100 #define DIALOGUE_SPECIAL_EVENT_MINESECTOREVENT 0x00000200 #define DIALOGUE_SPECIAL_EVENT_SHOW_UPDATE_MENU 0x00000400 #define DIALOGUE_SPECIAL_EVENT_ENABLE_AI 0x00000800 #define DIALOGUE_SPECIAL_EVENT_USE_ALTERNATE_FILES 0x00001000 #ifdef JA2UB #define DIALOGUE_SPECIAL_EVENT_JERRY_MILO 0x00002000 #else #define DIALOGUE_SPECIAL_EVENT_CONTINUE_TRAINING_MILITIA 0x00002000 #endif #define DIALOGUE_SPECIAL_EVENT_CONTRACT_ENDING 0x00004000 #define DIALOGUE_SPECIAL_EVENT_MULTIPURPOSE 0x00008000 #define DIALOGUE_SPECIAL_EVENT_SLEEP 0x00010000 #define DIALOGUE_SPECIAL_EVENT_DO_BATTLE_SND 0x00020000 #define DIALOGUE_SPECIAL_EVENT_SIGNAL_ITEM_LOCATOR_START 0x00040000 #define DIALOGUE_SPECIAL_EVENT_SHOPKEEPER 0x00080000 #define DIALOGUE_SPECIAL_EVENT_SKIP_A_FRAME 0x00100000 #define DIALOGUE_SPECIAL_EVENT_EXIT_MAP_SCREEN 0x00200000 #define DIALOGUE_SPECIAL_EVENT_DISPLAY_STAT_CHANGE 0x00400000 #define DIALOGUE_SPECIAL_EVENT_UNSET_ARRIVES_FLAG 0x00800000 #define DIALOGUE_SPECIAL_EVENT_TRIGGERPREBATTLEINTERFACE 0x01000000 #define DIALOGUE_ADD_EVENT_FOR_SOLDIER_UPDATE_BOX 0x02000000 #define DIALOGUE_SPECIAL_EVENT_ENTER_MAPSCREEN 0x04000000 #define DIALOGUE_SPECIAL_EVENT_LOCK_INTERFACE 0x08000000 #define DIALOGUE_SPECIAL_EVENT_REMOVE_EPC 0x10000000 #define DIALOGUE_SPECIAL_EVENT_CONTRACT_WANTS_TO_RENEW 0x20000000 #define DIALOGUE_SPECIAL_EVENT_CONTRACT_NOGO_TO_RENEW 0x40000000 #define DIALOGUE_SPECIAL_EVENT_CONTRACT_ENDING_NO_ASK_EQUIP 0x80000000 #ifdef JA2UB #define MULTIPURPOSE_SPECIAL_EVENT_TEAM_MEMBERS_DONE_TALKING 0x20000000 #define MULTIPURPOSE_SPECIAL_EVENT_DONE_KILLING_DEIDRANNA 0x10000000 #else #define MULTIPURPOSE_SPECIAL_EVENT_DONE_KILLING_DEIDRANNA 0x00000001 #define MULTIPURPOSE_SPECIAL_EVENT_TEAM_MEMBERS_DONE_TALKING 0x00000002 #endif #define MULTIPURPOSE_SPECIAL_EVENT_SNITCH_DIALOGUE 0x00000004 #ifdef JA2UB enum{ JERRY_MELO_FACE = 6, NUMBER_OF_EXTERNAL_NPC_FACES, }; #endif enum{ SKYRIDER_EXTERNAL_FACE =0, WALDO_EXTERNAL_FACE, //MINER_FRED_EXTERNAL_FACE, //MINER_MATT_EXTERNAL_FACE, //MINER_OSWALD_EXTERNAL_FACE, //MINER_CALVIN_EXTERNAL_FACE, //MINER_CARL_EXTERNAL_FACE, //NUMBER_OF_EXTERNAL_NPC_FACES, }; // soldier up-date box reasons enum{ UPDATE_BOX_REASON_ADDSOLDIER =0, UPDATE_BOX_REASON_SET_REASON, UPDATE_BOX_REASON_SHOW_BOX, }; #ifdef JA2UB extern UINT32 uiExternalStaticNPCFacesUB[ ]; extern UINT32 uiExternalFaceProfileIdsUB[ ]; #endif //extern UINT32 uiExternalStaticNPCFaces[ ]; extern std::vector<UINT32> uiExternalStaticNPCFaces; //extern UINT32 uiExternalFaceProfileIds[ ]; // Functions for handling dialogue Q BOOLEAN InitalizeDialogueControl(); void ShutdownDialogueControl(); void EmptyDialogueQueue( ); void HandleDialogue( ); void HandleImportantMercQuote( SOLDIERTYPE * pSoldier, UINT16 usQuoteNumber ); // Send in a profile number to see if text dialog exists for this guy.... BOOLEAN DialogueDataFileExistsForProfile( UINT8 ubCharacterNum, UINT16 usQuoteNum, BOOLEAN fWavFile, STR8 *ppStr ); // Do special event as well as dialogue! BOOLEAN CharacterDialogueWithSpecialEvent( UINT8 ubCharacterNum, UINT16 usQuoteNum, INT32 iFaceIndex, UINT8 bUIHandlerID, BOOLEAN fFromSoldier, BOOLEAN fDelayed, UINT32 uiFlag, UINT32 uiData1, UINT32 uiData2 ); // Do special event as well as dialogue! BOOLEAN CharacterDialogueWithSpecialEventEx( UINT8 ubCharacterNum, UINT16 usQuoteNum, INT32 iFaceIndex, UINT8 bUIHandlerID, BOOLEAN fFromSoldier, BOOLEAN fDelayed, UINT32 uiFlag, UINT32 uiData1, UINT32 uiData2, UINT32 uiData3 ); // A higher level function used for tactical quotes BOOLEAN TacticalCharacterDialogueWithSpecialEvent( SOLDIERTYPE *pSoldier, UINT16 usQuoteNum, UINT32 uiFlag, UINT32 uiData1, UINT32 uiData2 ); // A higher level function used for tactical quotes BOOLEAN TacticalCharacterDialogueWithSpecialEventEx( SOLDIERTYPE *pSoldier, UINT16 usQuoteNum, UINT32 uiFlag, UINT32 uiData1, UINT32 uiData2, UINT32 uiData3 ); // A higher level function used for tactical quotes BOOLEAN TacticalCharacterDialogue( SOLDIERTYPE *pSoldier, UINT16 usQuoteNum ); BOOLEAN SnitchTacticalCharacterDialogue( SOLDIERTYPE *pSoldier, UINT16 usQuoteNum, UINT8 ubEventType, UINT8 ubTargetProfile, UINT8 ubSecondaryTargetProfile ); // Flugente: replace text with other text BOOLEAN ReplaceTextWithOtherText( CHAR16 *pFinishedString, CHAR16 compare[32], CHAR16 replace[32] ); // A higher level function used for tactical quotes BOOLEAN DelayedTacticalCharacterDialogue( SOLDIERTYPE *pSoldier, UINT16 usQuoteNum ); // A more general purpose function for processing quotes BOOLEAN CharacterDialogue( UINT8 ubCharacterNum, UINT16 usQuoteNum, INT32 iFaceIndex, UINT8 bUIHandlerID, BOOLEAN fFromSoldier, BOOLEAN fDelayed ); BOOLEAN SnitchCharacterDialogue( UINT8 ubCharacterNum, UINT16 usQuoteNum, INT32 iFaceIndex, UINT32 uiSpecialEventFlag, UINT32 uiSpecialEventData1, UINT32 uiSpecialEventData2, UINT32 uiSpecialEventData3, UINT32 uiSpecialEventData4, UINT8 bUIHandlerID, BOOLEAN fFromSoldier, BOOLEAN fDelayed ); // A special event can be setup which can be queued with other speech BOOLEAN SpecialCharacterDialogueEvent( UINT32 uiSpecialEventFlag, UINT32 uiSpecialEventData1, UINT32 uiSpecialEventData2, UINT32 uiSpecialEventData3, INT32 iFaceIndex, UINT8 bUIHandlerID ); // Same as above, for triggers, with extra param to hold approach value BOOLEAN SpecialCharacterDialogueEventWithExtraParam( UINT32 uiSpecialEventFlag, UINT32 uiSpecialEventData1, UINT32 uiSpecialEventData2, UINT32 uiSpecialEventData3, UINT32 uiSpecialEventData4, INT32 iFaceIndex, UINT8 bUIHandlerID ); // execute specific character dialogue BOOLEAN ExecuteCharacterDialogue( UINT8 ubCharacterNum, UINT16 usQuoteNum, INT32 iFaceIndex, UINT8 bUIHandlerID, BOOLEAN fSoldier ); BOOLEAN ExecuteSnitchCharacterDialogue( UINT8 ubCharacterNum, UINT16 usQuoteNum, INT32 iFaceIndex, UINT8 bUIHandlerID, UINT8 ubSnitchEventType, UINT8 ubSnitchTargetID, UINT8 ubSecondarySnitchTargetID ); // Called when a face stops talking... void HandleDialogueEnd( FACETYPE *pFace ); // shut down last quotetext box void ShutDownLastQuoteTacticalTextBox( void ); // Called to advance speech // Used for option when no speech sound file void DialogueAdvanceSpeech( ); BOOLEAN DialogueQueueIsEmpty( ); BOOLEAN DialogueQueueIsEmptyOrSomebodyTalkingNow( ); // Adjust the face, etc when switching from panel to extern panel... void HandleDialogueUIAdjustments( ); // pause game time during void PauseTimeDuringNextQuote( ); void UnPauseGameDuringNextQuote( void ); // set up and shutdown static external NPC faces void InitalizeStaticExternalNPCFaces( void ); void ShutdownStaticExternalNPCFaces( void ); void SayQuoteFromAnyBodyInSector( UINT16 usQuoteNum ); void SayQuoteFromAnyBodyInThisSector( INT16 sSectorX, INT16 sSectorY, INT8 bSectorZ, UINT16 usQuoteNum ); void SayQuoteFromNearbyMercInSector( INT32 sGridNo, INT8 bDistance, UINT16 usQuoteNum ); void SayQuote58FromNearbyMercInSector( INT32 sGridNo, INT8 bDistance, UINT16 usQuoteNum, INT8 bSex ); void ExecuteTacticalTextBox( INT16 sLeftPosition, STR16 pString ); void ExecuteTacticalTextBoxForLastQuote( INT16 sLeftPosition, STR16 pString ); UINT32 FindDelayForString( STR16 sString ); void BeginLoggingForBleedMeToos( BOOLEAN fStart ); void UnSetEngagedInConvFromPCAction( SOLDIERTYPE *pSoldier ); void SetEngagedInConvFromPCAction( SOLDIERTYPE *pSoldier ); extern UINT32 guiDialogueLastQuoteTime; extern UINT32 guiDialogueLastQuoteDelay; void SetStopTimeQuoteCallback( MODAL_HOOK pCallBack ); BOOLEAN DialogueActive( ); extern INT32 giNPCReferenceCount; extern INT32 giNPCSpecialReferenceCount; #define NUMBER_VALID_MERC_PRECEDENT_QUOTES 13 extern UINT8 gubMercValidPrecedentQuoteID[ NUMBER_VALID_MERC_PRECEDENT_QUOTES ]; BOOLEAN ShouldMercSayPrecedentToRepeatOneSelf( UINT8 ubMercID, UINT32 uiQuoteID ); BOOLEAN GetMercPrecedentQuoteBitStatus( UINT8 ubMercID, UINT8 ubQuoteBit ); BOOLEAN SetMercPrecedentQuoteBitStatus( UINT8 ubMercID, UINT8 ubBitToSet ); BOOLEAN IsQuoteInPrecedentArray( UINT32 uiQuoteID ); UINT8 GetQuoteBitNumberFromQuoteID( UINT32 uiQuoteID ); void HandleShutDownOfMapScreenWhileExternfaceIsTalking( void ); void StopAnyCurrentlyTalkingSpeech( ); // handle pausing of the dialogue queue void PauseDialogueQueue( void ); // unpause the dialogue queue void UnPauseDialogueQueue( void ); void SetExternMapscreenSpeechPanelXY( INT16 sXPos, INT16 sYPos ); #ifdef JA2UB void RemoveJerryMiloBrokenLaptopOverlay(); #endif #endif
96fd2932af13cbc19aff79f422568f20bf6ed05c
16991ece2dace37f5742ce1ffb6107ffedd96eee
/countSort.cpp
d0ca0cedb3a202ea8bd589299c5fb8e6cb3cf477
[]
no_license
thakurutkarsh22/Hacktober-Open
0e34b9c67404d5c8a4dd853150f6d2418e7ea7ce
4405cd6cefabac71fbc164baeb66ab00c031d038
refs/heads/main
2023-08-13T14:36:59.304283
2021-10-19T08:53:37
2021-10-19T08:53:37
418,843,763
4
0
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
countSort.cpp
#include <bits/stdc++.h> using namespace std; int findMax(int arr[], int n) //to find max element of an array { int m = arr[0]; for(int i=1;i<n;i++) { if(arr[i] > m) m = arr[i]; } return m; } void countSort(int arr[],int n) { int max; max = findMax(arr,n); int Count[max + 1]; //Count-array of size max element of an array for (int i = 0; i < max+1; i++) //initializing Count with 0's Count[i] = 0; for (int i = 0; i < n; i++) Count[arr[i]]++; int i =0, j = 0; while (i < max+1) { if(Count[i] > 0){ arr[j++] = i; Count[i]--; } else i++; } } int main(){ int n; cout<<"Enter size: \n"; cin>>n; int arr[n]; cout<<"Enter an array: \n"; for (int i = 0; i < n; i++) { cin>>arr[i]; } countSort(arr,n); cout<<"Sorted array is :\n"; for (int i = 0; i < n; i++) { cout<<arr[i]<<" "; } }
cb37ecc5d9a60caf64a64f6354c2f1b7c475f81d
29a8845b958d4c45d700afebc233a46b7532379b
/Hackerrank/cut-the-sticks.cpp
76be7bc8679d0eee49f6674a09b07734efa01576
[]
no_license
aakashc31/Competitive-Programming
af08efe4297a58ba7de0822fbc79583b92b3f588
43b7516d83aebdd84cf6cad0506380885e1e9aec
refs/heads/master
2020-12-24T18:51:26.581034
2016-05-22T13:41:28
2016-05-22T13:41:28
59,413,653
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
cpp
cut-the-sticks.cpp
#include <bits/stdc++.h> using namespace std; #define g(n) scanf("%d",&n) // #define g(n) inp(n) #define gl(n) scanf("%lld", &n) #define f(i,n) for(int i=0; i<n; i++) #define pb push_back #define mp make_pair #define fab(i,a,b) for(int i=a; i<=b; i++) #define test(t) while(t--) #define getcx getchar//_unlocked typedef long long int ll; typedef long long int lli; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector< vi > vvi; int main() { int ar[1000]; int n; cin >> n; for(int i=0; i<n;i++) cin >> ar[i]; sort(ar,ar+n); int start = 0; int end = n - 1; cout << n << endl; while(start <= end) { int count = 0, top = ar[start]; fab(i,start,end) { if(ar[i] == top) count++; else break; } int pr = end-start+1 - count; if(pr == 0) break; else cout << end-start+1 - count << endl; start += count; } return 0; }
c98365ae668263f311020f51efc4882823b98a71
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir29315/dir29712/dir30926/dir32551/dir32552/dir32553/file32745.cpp
f810005e365745beb4169b63630640b2f1e9c582
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file32745.cpp
#ifndef file32745 #error "macro file32745 must be defined" #endif static const char* file32745String = "file32745";
acf09f357e906ba634299a20d2922c574e8b3652
144a61df621aac711cbbe6da92fd3e76b2ac64c2
/igisproject.cpp
9e6b8724541dc2e356c44474f4ea036087454328
[]
no_license
jacobflanagan/sylphDataManagement
32ba35083c2119c03a1c69b1efecf0adc2ae9cfc
0a2eb2b63e2d8b5fea49f928f34b931e3735396f
refs/heads/master
2020-06-05T05:13:25.507871
2019-06-19T05:50:27
2019-06-19T05:50:27
192,324,736
1
0
null
null
null
null
UTF-8
C++
false
false
2,184
cpp
igisproject.cpp
#include "igisproject.h" #include "p4dproject.h" IGISProject::IGISProject(QDir directory) { //create the IGISProject QString dirString = QDir::toNativeSeparators(directory.absolutePath()); //Check if not a IGIS project, otherwise detele this (make sure to test for null) if (this->isProject(directory)) { this->exists = true; this->missions = new QMap<QString, Mission*>; this->directory = directory; this->projectDetails = P4dProject::getProjectDetails(directory); //Get this list of could-be missions (sub-directories) QStringList missionList = directory.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for(QString mission : missionList){ qInfo("Looking at mission"); Mission *m = new Mission(QDir(directory.absoluteFilePath(mission))); if (m->state == Mission::STATE::FLOWN) (*this->missions)[mission] = m; } qInfo("Number of projects: %d",missionList.length()); } else //Not a project { this->exists = false; } } QDateTime *IGISProject::DateTime() { QJsonObject json = this->projectDetails->object(); auto epochTime = json["creationTime"].toDouble(); QDateTime *dt = new QDateTime(QDateTime::fromMSecsSinceEpoch(epochTime)); return dt; } bool IGISProject::writeProjectDetails(QDir directory) { QFile pd_file(directory.absoluteFilePath(project_details_filename)); if (!pd_file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; pd_file.write(projectDetails->toJson()); return true; } bool IGISProject::isProject(QDir directory) { if(QFile::exists(directory.absoluteFilePath("project_details.json"))){ //check if a true P4dProject by looking for the selectedTab entry - if this exists, its assumed this was created using pix4d capture QJsonDocument *pd = P4dProject::getProjectDetails(directory); if (pd->object().contains("creationType")) if (pd->object()["creationType"].toString() == "Manual"){ qInfo("IGIS Project Confirmed."); return true; } } return false; }
a335afb61fec7d1a97f5d9f5694e98410f1b52c3
0335a5fb8a553f243e29e5aee704238612c6dd11
/src/Collisions/CollisionalNuclearReaction.h
c4b826b39d92e5900c948e97a7b6b76a58df4c44
[]
no_license
ALaDyn/Smilei
a91b093da10ae4953e5a8d3397846952029a9979
81d858dd97ecbceb71dac804ee009763d50eb836
refs/heads/master
2023-07-20T16:56:01.085438
2023-07-05T10:13:57
2023-07-05T10:13:57
62,309,652
5
0
null
2016-06-30T12:41:29
2016-06-30T12:41:28
null
UTF-8
C++
false
false
1,862
h
CollisionalNuclearReaction.h
#ifndef COLLISIONALNUCLEARREACTION_H #define COLLISIONALNUCLEARREACTION_H #include <vector> #include "Tools.h" #include "Species.h" #include "Params.h" #include "Random.h" #include "BinaryProcess.h" #include "NuclearReactionProducts.h" class Patch; class CollisionalNuclearReaction : public BinaryProcess { public: //! Constructor CollisionalNuclearReaction( Params &, std::vector<Species *>&, double ); //! Cloning Constructor CollisionalNuclearReaction( CollisionalNuclearReaction * ); //! Destructor virtual ~CollisionalNuclearReaction(); //! Prepare the nuclear reaction void prepare() { tot_probability_ = 0.; npairs_tot_ = 0; }; void apply( Random *random, BinaryProcessData &D ); void finish( Params &, Patch *, std::vector<Diagnostic *> &, bool intra, std::vector<unsigned int> sg1, std::vector<unsigned int> sg2, int itime ); virtual std::string name() = 0; //! Calculates the cross-section vs energy virtual double crossSection( double log_ekin ) = 0; //! Prepare the products of the reaction virtual void makeProducts( Random* random, double ekin, double log_ekin, double tot_charge, NuclearReactionProducts &products ) = 0; //! Temporary species for reaction products std::vector<Particles *> product_particles_; //! Coefficient to adapt the rate of create of new particles double rate_multiplier_; //! True if rate multiplier isn't automatically adjusted double auto_multiplier_; //! sum of probabilities in this patch double tot_probability_; unsigned int npairs_tot_; private: //! Species where products are sent std::vector<unsigned int> product_ispecies_; //! Mass of reaction products std::vector<double> product_mass_; double coeff2_; }; #endif
6a1bf5908388d09f295dab8fe574d11e42cec1b9
682807efe7c3e20cc71c8929a720b2452d8443d6
/tinystl/construct.h
962417364af6b3464d13258e9d95c2ff2f37ac66
[]
no_license
clxsh/tinystl
f61438c4fb5c0f133dcfb8c45c20194442e234f0
1dbe6f810dc4cede1030790fd44a2a67dbd37906
refs/heads/master
2023-06-06T05:15:52.550938
2021-06-30T07:56:52
2021-06-30T07:56:52
368,804,486
0
0
null
null
null
null
UTF-8
C++
false
false
2,017
h
construct.h
#pragma once #include <new> #include "typetraits.h" #include "iterator.h" #include "util.h" /* ref: https://blog.csdn.net/lx627776548/article/details/51888789 */ #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) // unused variable #endif namespace mystl { // 使用 placement new, 构造对象 template <class Ty> void construct(Ty *ptr) { ::new (ptr) Ty(); } template <class Ty1, class Ty2> void construct(Ty1 *ptr, const Ty2 &value) { ::new (ptr) Ty1(value); } template <class Ty, class... Args> void construct(Ty *ptr, Args&&... args) { ::new (ptr) Ty(mystl::forward<Args>(args)...); // to be continued } // destroy, 析构对象 template <class Ty> void destroy_one(Ty *, std::true_type) { } template <class Ty> void destroy_one(Ty * pointer, std::false_type) { if (pointer != nullptr) { pointer->~Ty(); } } template <class ForwardIter> void destroy_aux(ForwardIter , ForwardIter , std::true_type) { } template <class ForwardIter> void destroy_aux(ForwardIter first, ForwardIter last, std::false_type) { for (; first != last; ++first) { destroy(&*first); } } template <class Ty> void destroy(Ty *pointer) { destroy_one(pointer, std::is_trivially_destructible<Ty>{}); } template <class ForwardIter> void destroy(ForwardIter first, ForwardIter last) { destroy_aux(first, last, std::is_trivially_destructible< typename iterator_traits<ForwardIter>::value_type>{}); } inline void destroy(char*, char*) {} inline void destroy(int*, int*) {} inline void destroy(long*, long*) {} inline void destroy(float*, float*) {} inline void destroy(double*, double*) {} #ifdef __STL_HAS_WCHAR_T inline void _Destroy(wchar_t*, wchar_t*) {} #endif /* __STL_HAS_WCHAR_T */ }; #ifdef _MSC_VER #pragma warning(pop) #endif
3bd3d323341f528731f4b4cfdc32278941ccae9f
be6dae26822ba5cbbf921d6926f06d27bd4a298f
/mainwindow.cpp
14f5c0bf30aa84c95069f65f010a4f24ee2072eb
[]
no_license
mfkiwl/RT-Sim
c5c613e21a06dd3a3ac9894ab0fe5d28f569ef6f
9ebec0d5b4a46d573919b84006c6a077d1929e94
refs/heads/master
2023-03-17T08:49:00.278768
2019-06-13T04:50:59
2019-06-13T04:50:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,399
cpp
mainwindow.cpp
#include "mainwindow.h" #include <iostream> #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // initial draw initial_draw(); connect(&cur_scene, SIGNAL(newImage(QImage)), this, SLOT(draw_image(QImage))); connect(this, SIGNAL(next_step()), &cur_scene, SLOT(nextStep())); connect(this, SIGNAL(prev_step()), &cur_scene, SLOT(prevStep())); connect(this, SIGNAL(cal_step()), &cur_scene, SLOT(calStep())); connect(this, SIGNAL(cal_whole_tra()), &cur_scene, SLOT(calWholeTrajectory())); connect(this, SIGNAL(stop_cal()), &cur_scene, SLOT(stopContinueCal())); connect(this, SIGNAL(cal_whole_scene()), &cur_scene, SLOT(calWholeScene())); // Load information saved in elements. on_btn_refresh_scene_clicked(); on_btn_refresh_beacon_clicked(); on_btn_refresh_trajectory_clicked(); } MainWindow::~MainWindow() { delete ui; } /** * @brief MainWindow::draw_image * draw image of current scene. * @param img */ void MainWindow::draw_image(QImage img) { int width = img_label->width(); int height = img_label->height(); QPixmap q_pix = QPixmap::fromImage(img).scaled( width, height, Qt::AspectRatioMode::KeepAspectRatio, Qt::TransformationMode::SmoothTransformation); img_label->setPixmap(q_pix); } bool MainWindow::initial_draw() { QWidget *w = ui->img_widget; w->setAcceptDrops(true); QGridLayout *layer = new QGridLayout(w); layer->setSpacing(10); layer->setMargin(8); layer->setSizeConstraint(QLayout::SetNoConstraint); // layout->setMargin(0); img_label = new QLabel(w); img_label->updatesEnabled(); img_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // img_label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); // img_label->setFixedSize(QSize(600, 600)); // img_label-> layer->addWidget(img_label, 0, 0); layer->setRowStretch(0, 1); layer->setColumnStretch(0, 1); return true; } void MainWindow::on_actionRefresh_Scene_triggered() { cur_scene.drawScene(); } void MainWindow::on_btn_refresh_beacon_clicked() { QString beacon_str; beacon_str = ui->txt_beacon->toPlainText(); cur_scene.loadBeacon(beacon_str); } void MainWindow::on_btn_refresh_scene_clicked() { QString scene_str = ui->txtScene->toPlainText(); cur_scene.loadScene(scene_str); } void MainWindow::on_btn_refresh_trajectory_clicked() { QString tra_str = ui->txtTrajectory->toPlainText(); cur_scene.loadTrajectory(tra_str); } void MainWindow::on_btn_pre_step_clicked() { emit prev_step(); emit cal_step(); } void MainWindow::on_btn_newx_step_clicked() { emit next_step(); emit cal_step(); } void MainWindow::on_btn_calculate_step_clicked() { emit cal_step(); } void MainWindow::on_actionLoad_Trajectory_From_File_triggered() {} void MainWindow::on_actionSave_Trajectory_To_File_triggered() {} void MainWindow::on_btn_global_search_clicked() { // searching all result in this scene needn't any trajectory. QString dir = QFileDialog::getExistingDirectory( this, tr("Open Directory"), "~/", QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly); cur_scene.saving_dir = dir.toStdString(); emit cal_whole_scene(); } void MainWindow::on_btn_cal_whole_tra_clicked() { emit cal_whole_tra(); } void MainWindow::on_btn_stop_sim_clicked() { emit stop_cal(); }
4a0094f5b0008e18ecd0fe0529c2e133bd494328
107b319c611cfd853cd41b84357c865452e194fd
/C++ Project/02. Destructor/mydestructor.cpp
7284fc37d5e7f1cf30cc24d2807c6b065e1b7954
[]
no_license
gelabi-alam/C-Plus-Plus-Programming-practice-Coding
0521b3fd0e7b7ee1c55969a214d6c2e2a30171bf
4d55c2e796756d513487541c5a901d55ff801902
refs/heads/main
2023-01-23T20:22:13.970605
2020-11-27T06:23:06
2020-11-27T06:23:06
316,417,367
2
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
mydestructor.cpp
#include "mydestructor.h" #include <iostream> using namespace std; myDestructor::myDestructor() { cout << "Constructor is Called."<<endl; } myDestructor:: ~myDestructor() { cout << "Destructor is Called."<<endl; }
f654b06ff36a4c0c669d2e22ad3609ad0554c3d3
bb057b858707a47c421db12d7cc3bb65311cacc2
/kotlin-native/runtime/src/custom_alloc/cpp/ExtraObjectPage.cpp
4f04ebad69075d418c25d9919ce787330d629e02
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
JetBrains/kotlin
b6c8922b22b54f4e269fddbbb37b7def4c97d788
0dd36ad456b8d67cf5f47ec9fe7428a4ee727b20
refs/heads/master
2023-08-28T11:15:27.222417
2023-08-25T11:01:10
2023-08-28T10:22:04
3,432,266
51,608
7,338
null
2023-09-14T09:30:01
2012-02-13T17:29:58
Kotlin
UTF-8
C++
false
false
2,771
cpp
ExtraObjectPage.cpp
/* * Copyright 2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ #include "ExtraObjectPage.hpp" #include <atomic> #include <cstdint> #include <cstring> #include <random> #include "AtomicStack.hpp" #include "CustomAllocConstants.hpp" #include "CustomLogging.hpp" #include "ExtraObjectData.hpp" #include "GCApi.hpp" namespace kotlin::alloc { ExtraObjectPage* ExtraObjectPage::Create(uint32_t ignored) noexcept { CustomAllocInfo("ExtraObjectPage::Create()"); return new (SafeAlloc(EXTRA_OBJECT_PAGE_SIZE)) ExtraObjectPage(); } ExtraObjectPage::ExtraObjectPage() noexcept { CustomAllocInfo("ExtraObjectPage(%p)::ExtraObjectPage()", this); nextFree_.store(cells_, std::memory_order_relaxed); ExtraObjectCell* end = cells_ + EXTRA_OBJECT_COUNT; for (ExtraObjectCell* cell = cells_; cell < end; cell = cell->next_.load(std::memory_order_relaxed)) { cell->next_.store(cell + 1, std::memory_order_relaxed); } } void ExtraObjectPage::Destroy() noexcept { Free(this, EXTRA_OBJECT_PAGE_SIZE); } mm::ExtraObjectData* ExtraObjectPage::TryAllocate() noexcept { auto* next = nextFree_.load(std::memory_order_relaxed); if (next >= cells_ + EXTRA_OBJECT_COUNT) { return nullptr; } ExtraObjectCell* freeBlock = next; nextFree_.store(freeBlock->next_.load(std::memory_order_relaxed), std::memory_order_relaxed); CustomAllocDebug("ExtraObjectPage(%p)::TryAllocate() = %p", this, freeBlock->Data()); return freeBlock->Data(); } bool ExtraObjectPage::Sweep(GCSweepScope& sweepHandle, FinalizerQueue& finalizerQueue) noexcept { CustomAllocInfo("ExtraObjectPage(%p)::Sweep()", this); // `end` is after the last legal allocation of a block, but does not // necessarily match an actual block starting point. ExtraObjectCell* end = cells_ + EXTRA_OBJECT_COUNT; bool alive = false; std::atomic<ExtraObjectCell*>* nextFree = &nextFree_; for (ExtraObjectCell* cell = cells_; cell < end; ++cell) { // If the current cell is free, move on. if (cell == nextFree->load(std::memory_order_relaxed)) { nextFree = &cell->next_; continue; } if (SweepExtraObject(cell->Data(), sweepHandle)) { // If the current cell was marked, it's alive, and the whole page is alive. alive = true; } else { // Free the current block and insert it into the free list. cell->next_.store(nextFree->load(std::memory_order_relaxed), std::memory_order_relaxed); nextFree->store(cell, std::memory_order_relaxed); nextFree = &cell->next_; } } return alive; } } // namespace kotlin::alloc
6ffd1f0116f88cc234b745fe6752737e060519d9
0532e6996508a5da50194ef0abf6637576238d62
/BOJ/9000/BOJ_9012.cpp
eeaacaff7e40308efd1cd5f608c8c93b168a1485
[]
no_license
FYLSunghwan/PS_Practice
72ca2a22a86d55bef276a6c66cc498d7d49ec664
082c63cd5db20a6c2e5a1bcb8d02d2461d115231
refs/heads/master
2021-07-23T06:42:23.292683
2020-05-30T11:26:21
2020-05-30T11:26:21
173,923,646
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
BOJ_9012.cpp
//BOJ 9012 #include <cstdio> #include <cstring> int c; int main() { for(scanf("%d",&c);c;c--) { char s[100]; scanf("%s",s); int cnt=0,ans=1; for(int i=0;i<strlen(s);i++) { if(s[i]=='(') ++cnt; if(s[i]==')') --cnt; if(cnt<0) { ans=0; break; } } if(cnt>0) ans=0; printf("%s\n",ans?"YES":"NO"); } return 0; }
59f6cdaea4436ac5d41f8aee8955276e271b65d5
52b6f625a804f07340b451d0273ab9d4263f96fe
/src/third-party/flann/algorithms/center_chooser.h
77a841722c8c66481faed9eaa359880bea0a781e
[ "BSD-3-Clause", "MIT" ]
permissive
ppwwyyxx/OpenPano
62a4cbc79d80a4f10e8cca720a47475f608c2872
ca1b86f6133c0f1ead82280f1a8355ff2711c5dc
refs/heads/master
2022-09-27T13:26:20.646101
2022-09-20T00:58:48
2022-09-20T00:58:48
9,639,042
1,548
477
MIT
2022-09-20T00:58:49
2013-04-24T03:56:02
C++
UTF-8
C++
false
false
6,771
h
center_chooser.h
/* * center_chooser.h * * Created on: 2012-11-04 * Author: marius */ #ifndef CENTER_CHOOSER_H_ #define CENTER_CHOOSER_H_ #include <flann/util/matrix.h> namespace flann { template <typename Distance> class CenterChooser { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; CenterChooser(const Distance& distance) : distance_(distance) {}; void setDataset(const flann::Matrix<ElementType>& dataset) { dataset_ = dataset; } virtual ~CenterChooser() {}; /** * Chooses cluster centers * * @param k number of centers to choose * @param indices indices of points to choose the centers from * @param indices_length length of indices * @param centers indices of chosen centers * @param centers_length length of centers array */ virtual void operator()(int k, int* indices, int indices_length, int* centers, int& centers_length) = 0; protected: flann::Matrix<ElementType> dataset_; Distance distance_; }; template <typename Distance> class RandomCenterChooser : public CenterChooser<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; using CenterChooser<Distance>::dataset_; using CenterChooser<Distance>::distance_; RandomCenterChooser(const Distance& distance) : CenterChooser<Distance>(distance) {} void operator()(int k, int* indices, int indices_length, int* centers, int& centers_length) { UniqueRandom r(indices_length); int index; for (index=0; index<k; ++index) { bool duplicate = true; int rnd; while (duplicate) { duplicate = false; rnd = r.next(); if (rnd<0) { centers_length = index; return; } centers[index] = indices[rnd]; for (int j=0; j<index; ++j) { DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols); if (sq<1e-16) { duplicate = true; } } } } centers_length = index; } }; /** * Chooses the initial centers using the Gonzales algorithm. */ template <typename Distance> class GonzalesCenterChooser : public CenterChooser<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; using CenterChooser<Distance>::dataset_; using CenterChooser<Distance>::distance_; GonzalesCenterChooser(const Distance& distance) : CenterChooser<Distance>( distance) {} void operator()(int k, int* indices, int indices_length, int* centers, int& centers_length) { int n = indices_length; int rnd = rand_int(n); assert(rnd >=0 && rnd < n); centers[0] = indices[rnd]; int index; for (index=1; index<k; ++index) { int best_index = -1; DistanceType best_val = 0; for (int j=0; j<n; ++j) { DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols); for (int i=1; i<index; ++i) { DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols); if (tmp_dist<dist) { dist = tmp_dist; } } if (dist>best_val) { best_val = dist; best_index = j; } } if (best_index!=-1) { centers[index] = indices[best_index]; } else { break; } } centers_length = index; } }; /** * Chooses the initial centers using the algorithm proposed in the KMeans++ paper: * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding */ template <typename Distance> class KMeansppCenterChooser : public CenterChooser<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; using CenterChooser<Distance>::dataset_; using CenterChooser<Distance>::distance_; KMeansppCenterChooser(const Distance& distance) : CenterChooser<Distance>(distance) {} void operator()(int k, int* indices, int indices_length, int* centers, int& centers_length) { int n = indices_length; double currentPot = 0; DistanceType* closestDistSq = new DistanceType[n]; // Choose one random center and set the closestDistSq values int index = rand_int(n); assert(index >=0 && index < n); centers[0] = indices[index]; for (int i = 0; i < n; i++) { closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); currentPot += closestDistSq[i]; } const int numLocalTries = 1; // Choose each center int centerCount; for (centerCount = 1; centerCount < k; centerCount++) { // Repeat several trials double bestNewPot = -1; int bestNewIndex = 0; for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { // Choose our center - have to be slightly careful to return a valid answer even accounting // for possible rounding errors double randVal = rand_double(currentPot); for (index = 0; index < n-1; index++) { if (randVal <= closestDistSq[index]) break; else randVal -= closestDistSq[index]; } // Compute the new potential double newPot = 0; for (int i = 0; i < n; i++) newPot += std::min( distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols), closestDistSq[i] ); // Store the best result if ((bestNewPot < 0)||(newPot < bestNewPot)) { bestNewPot = newPot; bestNewIndex = index; } } // Add the appropriate center centers[centerCount] = indices[bestNewIndex]; currentPot = bestNewPot; for (int i = 0; i < n; i++) closestDistSq[i] = std::min( distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols), closestDistSq[i] ); } centers_length = centerCount; delete[] closestDistSq; } }; } #endif /* CENTER_CHOOSER_H_ */
cba0cd51c541e4a7cd827a6b735af7aa2b4b5e65
b48480256cf2efd6b995dba5296ab0647d98b8ca
/Skaiciuotuvas/skaiciuotuvas.h
8980b2da8c3b68b28f17f469af1e1dff34d634d5
[]
no_license
dovileservaite/skaicius
c55fe1036cd293b0d4709a3677007d5bfed70918
f91859d6639a116fbe05088769715ae1c7ae6990
refs/heads/master
2020-12-30T14:00:38.322510
2017-05-14T22:38:55
2017-05-14T22:38:55
91,275,727
0
0
null
null
null
null
UTF-8
C++
false
false
28,610
h
skaiciuotuvas.h
#pragma once namespace Skaiciuotuvas { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for skaiciuotuvas /// </summary> public ref class skaiciuotuvas : public System::Windows::Forms::Form { public: skaiciuotuvas(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~skaiciuotuvas() { if (components) { delete components; } } protected: protected: private: System::Windows::Forms::Label^ zenklas; private: System::Windows::Forms::TextBox^ display; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ failasToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ uždarytiToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ redaguotiToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ keistiToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ fonąToolStripMenuItem; private: System::Windows::Forms::Button^ btt1; private: System::Windows::Forms::Button^ btt2; private: System::Windows::Forms::Button^ btt3; private: System::Windows::Forms::Button^ btt4; private: System::Windows::Forms::Button^ btt5; private: System::Windows::Forms::Button^ btt6; private: System::Windows::Forms::Button^ btt7; private: System::Windows::Forms::Button^ btt8; private: System::Windows::Forms::Button^ btt9; private: System::Windows::Forms::Button^ btt0; private: System::Windows::Forms::Button^ bttC; private: System::Windows::Forms::Button^ button12; private: System::Windows::Forms::Button^ button13; private: System::Windows::Forms::Button^ button14; private: System::Windows::Forms::Button^ button15; private: System::Windows::Forms::Button^ button16; private: System::Windows::Forms::Button^ button17; private: System::Windows::Forms::Button^ bttCE; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button3; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->btt1 = (gcnew System::Windows::Forms::Button()); this->btt2 = (gcnew System::Windows::Forms::Button()); this->btt3 = (gcnew System::Windows::Forms::Button()); this->btt4 = (gcnew System::Windows::Forms::Button()); this->btt5 = (gcnew System::Windows::Forms::Button()); this->btt6 = (gcnew System::Windows::Forms::Button()); this->btt7 = (gcnew System::Windows::Forms::Button()); this->btt8 = (gcnew System::Windows::Forms::Button()); this->btt9 = (gcnew System::Windows::Forms::Button()); this->btt0 = (gcnew System::Windows::Forms::Button()); this->bttC = (gcnew System::Windows::Forms::Button()); this->button12 = (gcnew System::Windows::Forms::Button()); this->button13 = (gcnew System::Windows::Forms::Button()); this->button14 = (gcnew System::Windows::Forms::Button()); this->button15 = (gcnew System::Windows::Forms::Button()); this->button16 = (gcnew System::Windows::Forms::Button()); this->button17 = (gcnew System::Windows::Forms::Button()); this->zenklas = (gcnew System::Windows::Forms::Label()); this->display = (gcnew System::Windows::Forms::TextBox()); this->bttCE = (gcnew System::Windows::Forms::Button()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->label1 = (gcnew System::Windows::Forms::Label()); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->failasToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->uždarytiToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->redaguotiToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->keistiToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->fonąToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->menuStrip1->SuspendLayout(); this->SuspendLayout(); // // btt1 // this->btt1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt1->Location = System::Drawing::Point(22, 340); this->btt1->Name = L"btt1"; this->btt1->Size = System::Drawing::Size(60, 50); this->btt1->TabIndex = 1; this->btt1->Text = L"1"; this->btt1->UseVisualStyleBackColor = true; this->btt1->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt2 // this->btt2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt2->Location = System::Drawing::Point(105, 340); this->btt2->Name = L"btt2"; this->btt2->Size = System::Drawing::Size(60, 50); this->btt2->TabIndex = 2; this->btt2->Text = L"2"; this->btt2->UseVisualStyleBackColor = true; this->btt2->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt3 // this->btt3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt3->Location = System::Drawing::Point(190, 340); this->btt3->Name = L"btt3"; this->btt3->Size = System::Drawing::Size(60, 50); this->btt3->TabIndex = 3; this->btt3->Text = L"3"; this->btt3->UseVisualStyleBackColor = true; this->btt3->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt4 // this->btt4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt4->Location = System::Drawing::Point(22, 273); this->btt4->Name = L"btt4"; this->btt4->Size = System::Drawing::Size(60, 50); this->btt4->TabIndex = 4; this->btt4->Text = L"4"; this->btt4->UseVisualStyleBackColor = true; this->btt4->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt5 // this->btt5->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt5->Location = System::Drawing::Point(105, 271); this->btt5->Name = L"btt5"; this->btt5->Size = System::Drawing::Size(60, 50); this->btt5->TabIndex = 5; this->btt5->Text = L"5"; this->btt5->UseVisualStyleBackColor = true; this->btt5->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt6 // this->btt6->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt6->Location = System::Drawing::Point(190, 271); this->btt6->Name = L"btt6"; this->btt6->Size = System::Drawing::Size(60, 50); this->btt6->TabIndex = 6; this->btt6->Text = L"6"; this->btt6->UseVisualStyleBackColor = true; this->btt6->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt7 // this->btt7->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt7->Location = System::Drawing::Point(22, 204); this->btt7->Name = L"btt7"; this->btt7->Size = System::Drawing::Size(60, 50); this->btt7->TabIndex = 7; this->btt7->Text = L"7"; this->btt7->UseVisualStyleBackColor = true; this->btt7->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt8 // this->btt8->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt8->Location = System::Drawing::Point(105, 204); this->btt8->Name = L"btt8"; this->btt8->Size = System::Drawing::Size(60, 50); this->btt8->TabIndex = 8; this->btt8->Text = L"8"; this->btt8->UseVisualStyleBackColor = true; this->btt8->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt9 // this->btt9->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt9->Location = System::Drawing::Point(190, 204); this->btt9->Name = L"btt9"; this->btt9->Size = System::Drawing::Size(60, 50); this->btt9->TabIndex = 9; this->btt9->Text = L"9"; this->btt9->UseVisualStyleBackColor = true; this->btt9->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // btt0 // this->btt0->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->btt0->Location = System::Drawing::Point(22, 411); this->btt0->Name = L"btt0"; this->btt0->Size = System::Drawing::Size(60, 50); this->btt0->TabIndex = 10; this->btt0->Text = L"0"; this->btt0->UseVisualStyleBackColor = true; this->btt0->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button_Click); // // bttC // this->bttC->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->bttC->Location = System::Drawing::Point(190, 139); this->bttC->Name = L"bttC"; this->bttC->Size = System::Drawing::Size(60, 50); this->bttC->TabIndex = 11; this->bttC->Text = L"C"; this->bttC->UseVisualStyleBackColor = true; this->bttC->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button11_Click); // // button12 // this->button12->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button12->Location = System::Drawing::Point(274, 340); this->button12->Name = L"button12"; this->button12->Size = System::Drawing::Size(60, 50); this->button12->TabIndex = 12; this->button12->Text = L"/"; this->button12->UseVisualStyleBackColor = true; this->button12->Click += gcnew System::EventHandler(this, &skaiciuotuvas::veiksmai); // // button13 // this->button13->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button13->Location = System::Drawing::Point(274, 273); this->button13->Name = L"button13"; this->button13->Size = System::Drawing::Size(60, 50); this->button13->TabIndex = 13; this->button13->Text = L"-"; this->button13->UseVisualStyleBackColor = true; this->button13->Click += gcnew System::EventHandler(this, &skaiciuotuvas::veiksmai); // // button14 // this->button14->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button14->Location = System::Drawing::Point(274, 411); this->button14->Name = L"button14"; this->button14->Size = System::Drawing::Size(60, 50); this->button14->TabIndex = 14; this->button14->Text = L"X"; this->button14->UseVisualStyleBackColor = true; this->button14->Click += gcnew System::EventHandler(this, &skaiciuotuvas::veiksmai); // // button15 // this->button15->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button15->Location = System::Drawing::Point(274, 204); this->button15->Name = L"button15"; this->button15->Size = System::Drawing::Size(60, 50); this->button15->TabIndex = 15; this->button15->Text = L"+"; this->button15->UseVisualStyleBackColor = true; this->button15->Click += gcnew System::EventHandler(this, &skaiciuotuvas::veiksmai); // // button16 // this->button16->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button16->Location = System::Drawing::Point(190, 411); this->button16->Name = L"button16"; this->button16->Size = System::Drawing::Size(60, 50); this->button16->TabIndex = 16; this->button16->Text = L"="; this->button16->UseVisualStyleBackColor = true; this->button16->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button16_Click); // // button17 // this->button17->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button17->Location = System::Drawing::Point(105, 411); this->button17->Name = L"button17"; this->button17->Size = System::Drawing::Size(60, 50); this->button17->TabIndex = 17; this->button17->Text = L"."; this->button17->UseVisualStyleBackColor = true; this->button17->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button17_Click); // // zenklas // this->zenklas->AutoSize = true; this->zenklas->BackColor = System::Drawing::Color::White; this->zenklas->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->zenklas->Location = System::Drawing::Point(116, 39); this->zenklas->Name = L"zenklas"; this->zenklas->Size = System::Drawing::Size(0, 20); this->zenklas->TabIndex = 18; // // display // this->display->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 20.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->display->Location = System::Drawing::Point(21, 76); this->display->Name = L"display"; this->display->Size = System::Drawing::Size(313, 38); this->display->TabIndex = 19; this->display->Text = L"0"; this->display->TextAlign = System::Windows::Forms::HorizontalAlignment::Right; this->display->TextChanged += gcnew System::EventHandler(this, &skaiciuotuvas::textBox1_TextChanged); // // bttCE // this->bttCE->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->bttCE->Location = System::Drawing::Point(105, 139); this->bttCE->Name = L"bttCE"; this->bttCE->Size = System::Drawing::Size(60, 50); this->bttCE->TabIndex = 20; this->bttCE->Text = L"CE"; this->bttCE->UseVisualStyleBackColor = true; this->bttCE->Click += gcnew System::EventHandler(this, &skaiciuotuvas::bttCE_Click); // // button2 // this->button2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button2->Location = System::Drawing::Point(274, 139); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(60, 50); this->button2->TabIndex = 21; this->button2->Text = L"+/-"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button2_Click_1); // // button3 // this->button3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->button3->Location = System::Drawing::Point(21, 139); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(60, 50); this->button3->TabIndex = 22; this->button3->Text = L"←"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &skaiciuotuvas::button3_Click_1); // // label1 // this->label1->AutoSize = true; this->label1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(186))); this->label1->Location = System::Drawing::Point(18, 40); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(76, 19); this->label1->TabIndex = 23; this->label1->Text = L"Veiksmai:"; // // menuStrip1 // this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) { this->failasToolStripMenuItem, this->redaguotiToolStripMenuItem }); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(353, 24); this->menuStrip1->TabIndex = 24; this->menuStrip1->Text = L"menuStrip1"; // // failasToolStripMenuItem // this->failasToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->uždarytiToolStripMenuItem }); this->failasToolStripMenuItem->Name = L"failasToolStripMenuItem"; this->failasToolStripMenuItem->Size = System::Drawing::Size(48, 20); this->failasToolStripMenuItem->Text = L"&Failas"; // // uždarytiToolStripMenuItem // this->uždarytiToolStripMenuItem->Name = L"uždarytiToolStripMenuItem"; this->uždarytiToolStripMenuItem->Size = System::Drawing::Size(172, 22); this->uždarytiToolStripMenuItem->Text = L"U&ždaryti programą"; this->uždarytiToolStripMenuItem->Click += gcnew System::EventHandler(this, &skaiciuotuvas::uždarytiToolStripMenuItem_Click); // // redaguotiToolStripMenuItem // this->redaguotiToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->keistiToolStripMenuItem }); this->redaguotiToolStripMenuItem->Name = L"redaguotiToolStripMenuItem"; this->redaguotiToolStripMenuItem->Size = System::Drawing::Size(73, 20); this->redaguotiToolStripMenuItem->Text = L"&Redaguoti"; // // keistiToolStripMenuItem // this->keistiToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->fonąToolStripMenuItem }); this->keistiToolStripMenuItem->Name = L"keistiToolStripMenuItem"; this->keistiToolStripMenuItem->Size = System::Drawing::Size(102, 22); this->keistiToolStripMenuItem->Text = L"K&eisti"; // // fonąToolStripMenuItem // this->fonąToolStripMenuItem->Name = L"fonąToolStripMenuItem"; this->fonąToolStripMenuItem->Size = System::Drawing::Size(137, 22); this->fonąToolStripMenuItem->Text = L"Fono spalvą"; this->fonąToolStripMenuItem->Click += gcnew System::EventHandler(this, &skaiciuotuvas::fonąToolStripMenuItem_Click); // // skaiciuotuvas // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(353, 477); this->Controls->Add(this->label1); this->Controls->Add(this->button3); this->Controls->Add(this->button2); this->Controls->Add(this->bttCE); this->Controls->Add(this->display); this->Controls->Add(this->zenklas); this->Controls->Add(this->button17); this->Controls->Add(this->button16); this->Controls->Add(this->button15); this->Controls->Add(this->button14); this->Controls->Add(this->button13); this->Controls->Add(this->button12); this->Controls->Add(this->bttC); this->Controls->Add(this->btt0); this->Controls->Add(this->btt9); this->Controls->Add(this->btt8); this->Controls->Add(this->btt7); this->Controls->Add(this->btt6); this->Controls->Add(this->btt5); this->Controls->Add(this->btt4); this->Controls->Add(this->btt3); this->Controls->Add(this->btt2); this->Controls->Add(this->btt1); this->Controls->Add(this->menuStrip1); this->MainMenuStrip = this->menuStrip1; this->Name = L"skaiciuotuvas"; this->Text = L"Skaičiuotuvas"; this->Load += gcnew System::EventHandler(this, &skaiciuotuvas::skaiciuotuvas_Load); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } double pirmassk; double antrassk; double rezultatas; String^ operacija; #pragma endregion private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas -> Text == "0") { apskaiciavimas->Text = "1"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "1"; }*/ } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "2"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "2"; }*/ } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "3"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "3"; }*/ } private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "4"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "4"; }*/ } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "5"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "5"; }*/ } private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "6"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "6"; }*/ } private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "7"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "7"; }*/ } private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "8"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "8"; }*/ } private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "9"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "9"; }*/ } private: System::Void button10_Click(System::Object^ sender, System::EventArgs^ e) { /*if (apskaiciavimas->Text == "0") { apskaiciavimas->Text = "0"; } else { apskaiciavimas->Text = Convert::ToInt32(apskaiciavimas->Text) + "0"; }*/ } private: System::Void button11_Click(System::Object^ sender, System::EventArgs^ e) { //apskaiciavimas->Text = ""; //apskaiciavimas->Text = "0"; //mygtukas "c" display->Text = "0"; zenklas->Text = ""; } private: System::Void button12_Click(System::Object^ sender, System::EventArgs^ e) { /*pirmassk = Convert::ToInt32(apskaiciavimas->Text); apskaiciavimas ->Text = "0"; operacija = '/'; */ } private: System::Void button13_Click(System::Object^ sender, System::EventArgs^ e) { /*pirmassk = Convert::ToInt32(apskaiciavimas->Text); apskaiciavimas->Text = "0"; operacija = '-';*/ } private: System::Void button14_Click(System::Object^ sender, System::EventArgs^ e) { /*pirmassk = Convert::ToInt32(apskaiciavimas->Text); apskaiciavimas->Text = "0"; operacija = '*';*/ } private: System::Void button15_Click(System::Object^ sender, System::EventArgs^ e) { /*pirmassk = Convert::ToInt32(apskaiciavimas->Text); apskaiciavimas->Text = "0"; operacija = '+';*/ } private: System::Void button16_Click(System::Object^ sender, System::EventArgs^ e) { //operaciju realizavimas zenklas->Text = ""; antrassk = Double::Parse(display->Text); if (operacija == "+") { rezultatas = pirmassk + antrassk; display->Text = System::Convert::ToString(rezultatas); } else if (operacija == "-") { rezultatas = pirmassk - antrassk; display->Text = System::Convert::ToString(rezultatas); } else if (operacija == "*") { rezultatas = pirmassk * antrassk; display->Text = System::Convert::ToString(rezultatas); } else if (operacija == "/") { rezultatas = pirmassk / antrassk; display->Text = System::Convert::ToString(rezultatas); } /*antrassk = Convert::ToInt32(apskaiciavimas->Text); switch (operacija) { case '+': rezultatas = pirmassk + antrassk; apskaiciavimas->Text = System::Convert::ToString(rezultatas); break; case '-': rezultatas = pirmassk - antrassk; apskaiciavimas->Text = System::Convert::ToString(rezultatas); break; case '/': rezultatas = pirmassk / antrassk; apskaiciavimas->Text = System::Convert::ToString(rezultatas); break; case '*': rezultatas = pirmassk * antrassk; apskaiciavimas->Text = System::Convert::ToString(rezultatas); break; }*/ } private: System::Void skaiciuotuvas_Load(System::Object^ sender, System::EventArgs^ e) { } private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) { //kad būtų nulis, kai įveda antrą skaičių if (display->Text == "") { display->Text = "0"; } } private: System::Void button2_Click_1(System::Object^ sender, System::EventArgs^ e) { //pliuso ir minuso pakeitimo mygtukas if (display->Text->Contains("-")) { display->Text = display->Text->Remove(0.1); } else { display->Text = "-" + display->Text; } } private: System::Void button3_Click_1(System::Object^ sender, System::EventArgs^ e) { //trynimas po vieną simbolį if (display->Text->Length > 0) { display->Text = display->Text->Remove(display->Text->Length - 1, 1); } } private: System::Void bttCE_Click(System::Object^ sender, System::EventArgs^ e) { //trinimas visų veiksmų display->Text = "0"; } private: System::Void button_Click(System::Object^ sender, System::EventArgs^ e) { //skaiciu įvedimo mygtukai Button ^ Numbers = safe_cast<Button^>(sender); if (display->Text == "0") { display->Text = Numbers->Text; } else { display->Text = display->Text + Numbers->Text; } } private: System::Void veiksmai(System::Object^ sender, System::EventArgs^ e) { //veiksmai aprašomi Button ^ op = safe_cast<Button^>(sender); pirmassk = Double::Parse(display->Text); display->Text = ""; operacija = op->Text; zenklas->Text = System::Convert::ToString(pirmassk) + " " + operacija; } private: System::Void button17_Click(System::Object^ sender, System::EventArgs^ e) { //aprašomas kablelis, kad galėtume realiuosius skaičius naudoti if (!display->Text->Contains(".")) { display->Text = display->Text + ("."); } } private: System::Void uždarytiToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { Application::Exit(); } private: System::Void fonąToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { } }; }
0a9e1b579a0fd353fe4532d73c89941aa77d6159
0b60ced553cb6ccd6c53cdd7eb34c13a499a5053
/Calculadora/Calculadora/Origem.cpp
04087c5b0787e970421bfc632baf2e485514f265
[]
no_license
Ale-Hoffmann/Calculadora-
763de141098e291c4a7784762f49d8d88cbd061c
5df457e20b6522ffbcc8374892dc466835297354
refs/heads/main
2023-03-28T00:10:45.232437
2021-03-11T22:02:07
2021-03-11T22:02:07
346,172,771
0
0
null
null
null
null
UTF-8
C++
false
false
520
cpp
Origem.cpp
#include<iostream> #include"Calculadora.h" using namespace std; int main() { Calculadora* calc = new Calculadora; cout << "A soma dos valores 10 + 5 eh igual a " << calc->soma(10.0f, 5.0f) << endl; cout << "A subtracao dos valores 10 - 5 eh igual a " << calc->subtracao(10.0f, 5.0f) << endl; cout << "A Multiplicacao dos valores 10 * 5 eh igual a " << calc->multiplicacao(10.0f, 5.0f) << endl; cout << "A Divisao dos valores 10 / 5 eh igual a " << calc->divisao(10.0f, 5.0f) << endl; system("pause"); return 1; }
d6b2e324ffa28f6c92afa9d3639734f5b20ac71c
6889dcc1bd55c309d240142ccba5c979efe37399
/tests/100_basic_work.cpp
eccbc7e540269b705860931fff0a792196b0925e
[ "MIT" ]
permissive
agnat/ncd
c6e8b3afa8de3228676d114be80b104f87b1e296
23c928d101dda3146f7a1701deab9ab00c9937b9
refs/heads/master
2021-05-07T09:32:11.528371
2017-11-22T00:38:47
2017-11-22T00:38:47
109,622,900
1
0
null
null
null
null
UTF-8
C++
false
false
1,611
cpp
100_basic_work.cpp
#include <nan.h> #include <ncd.hpp> #include <unistd.h> namespace { void testWorkQueue(Nan::FunctionCallbackInfo<v8::Value> const& args) { Nan::HandleScope scope; unsigned items = args[0]->Uint32Value(); unsigned delay = args[1]->Uint32Value(); for (unsigned i = 0; i < items; ++i) { dispatch(ncd::defaultWorkQueue(), [=](){ if (delay != 0) { usleep(delay * 1000); } }, args[2].As<v8::Function>()); } } void testStringResult(Nan::FunctionCallbackInfo<v8::Value> const& args) { dispatch(ncd::defaultWorkQueue(), [=](){ return "This is fine."; }, args[0].As<v8::Function>()); } void testDoubleResult(Nan::FunctionCallbackInfo<v8::Value> const& args) { dispatch(ncd::defaultWorkQueue(), [=](){ return 0.5; }, args[0].As<v8::Function>()); } void testStringOrError(Nan::FunctionCallbackInfo<v8::Value> const& args) { bool succeed = args[0]->ToBoolean()->Value(); dispatch(ncd::defaultWorkQueue(), [=](ncd::AsyncError ** error) { if (succeed) { return "This is fine."; } else { *error = new ncd::AsyncError("Kaputt."); return (char const*)nullptr; } }, args[1].As<v8::Function>()); } void init(v8::Local<v8::Object> exports) { exports->Set(ncd::v8str("testWorkQueue"), ncd::function(testWorkQueue)); exports->Set(ncd::v8str("testStringResult"), ncd::function(testStringResult)); exports->Set(ncd::v8str("testDoubleResult"), ncd::function(testDoubleResult)); exports->Set(ncd::v8str("testStringOrError"), ncd::function(testStringOrError)); } } // end of anonymous namespace NCD_NODE_ADDON(init)
292eecbf939e0026c5c9d10e51e3ad57d3755e02
500ff736294001e7fa66000e7c7268c739d901cd
/ex1/loja.h
532b8eb9c142c8052e27bdcd144fc3591d3e849b
[]
no_license
OnikenX/POO-TP
015090cc4111b71f1ddcf968596569b23df30f71
ccab3f1d1e34ce605aa73425fad6270c2f6e0277
refs/heads/master
2022-04-02T05:27:31.574921
2020-01-10T13:16:02
2020-01-10T13:16:02
218,657,199
1
0
null
null
null
null
UTF-8
C++
false
false
191
h
loja.h
#ifndef LOJA_H #define LOJA_H #include "imovel.h" class Loja : public Imovel { public: Loja(int area); }; std::ostream& operator<<(std::ostream &out, const Imovel &a); #endif //LOJA_H
8bf3106d4aabba60ea08a5bbc028eb23d59dfe17
58f070c58fcc3da40cf57101c5e9e80eface0afb
/Graph/DFS/Hard/332.ReconstructItinerary.cpp
1aefade612d81aaad3500a576751451b40da9472
[]
no_license
Imran4424/LeetCode-Solutions
ab32c829c8c916f0422f4899bc347accdfc50e0d
1f0f7a86e2ed74741a001e3ba2a6ea6c68c9b484
refs/heads/master
2023-04-08T13:01:46.322323
2023-03-25T19:17:14
2023-03-25T19:17:14
231,453,902
1
0
null
null
null
null
UTF-8
C++
false
false
1,700
cpp
332.ReconstructItinerary.cpp
/* You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. */ class Solution { unordered_map<string, map<string, bool> > travelList; vector <string> result; unordered_set<string> cityList; typedef map<string, bool>:: iterator innerIt; void dfs(string current, innerIt ptr) { if (!travelList.count(current)) { return; } result.push_back(current); cityList.erase(current); ptr->second = true; for (innerIt it = travelList[current].begin(); it != travelList[current].end(); it++) { if (!it->second) { dfs(it->first, it); } } } public: vector<string> findItinerary(vector<vector<string>>& tickets) { for (int i = 0; i < tickets.size(); i++) { travelList[tickets[i][0]][tickets[i][1]] = false; cityList.insert(tickets[i][0]); cityList.insert(tickets[i][1]); } result.clear(); map<string, bool> tempMap; tempMap["JFK"] = false; dfs("JFK", tempMap.begin()); if (!cityList.empty()) { result.push_back(*(cityList.begin())); } return result; } }; /* This solution will end up in wrong answer */
488a1515035c413f87ebb0c2c82a5d66c2904a3e
0e7ac176a65f6b690a13f6b72d0b92ec8dad790d
/tuio/libkerat/kerat/listener.hpp
3b54dddab465b22965caed5b1fc1fbb245b156e1
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Sitola/MUSE
4fef9a586dbcd746d9d549ce7e34cd7187549590
e3b6b6060d853beddfe8cda5e540434536b9e41f
refs/heads/master
2021-01-12T02:32:49.862578
2017-01-12T20:00:09
2017-01-12T20:00:09
78,058,615
1
0
null
null
null
null
UTF-8
C++
false
false
1,733
hpp
listener.hpp
/** * \file listener.hpp * \brief Provides the abstract class that provides automatic update calls when new TUIO messages are received. * \author Lukas Rucka <359687@mail.muni.cz>, Masaryk University, Brno, Czech Republic * \date 2011-09-22 12:29 UTC+2 * \copyright BSD */ #ifndef KERAT_LISTENER_HPP #define KERAT_LISTENER_HPP #include <kerat/typedefs.hpp> #include <kerat/session_manager.hpp> #include <set> namespace libkerat { class client; //! \brief TUIO Listener interface, notified when data arrives to the client class listener { public: virtual ~listener(); /** * \brief Callback called when any of the connected clients receive data * \param notifier - client to be contacted for the data request */ virtual void notify(const client * notifier) = 0; /** * \brief Callback called when client binds with the listener * \param notifier - client that is binding in */ virtual void notify_client_bind(client * notifier); /** * \brief Callback called when client disconnects from the listener * \param notifier - client that is disconnecting */ virtual void notify_client_release(client * notifier); /** * \brief Checks whether is this listener connected to any client * \return true if this listener is connected */ virtual bool is_connected() const; protected: //! set of clients this listener is binded with typedef std::set<client *> client_set; client_set m_connected_clients; }; // cls listener } // ns libkerat #endif // KERAT_LISTENER_HPP
c324952ff28d74754ff92763f31d25b5eb203729
c537cc790e2d579a6680e6732bd1fd45fd0f3730
/CWndSource.cpp
ce810fa59663383a0a789fe9fd4dfc94b6265fa1
[]
no_license
Fengerking/KPCP
2c32135de1dae40e63cfa87a4fb0c40dbb280992
b65387f02f33737e8025eb9056dcdc85177c9499
refs/heads/master
2020-09-15T05:51:22.316464
2020-06-16T13:17:19
2020-06-16T13:17:19
223,359,613
0
0
null
null
null
null
UTF-8
C++
false
false
2,496
cpp
CWndSource.cpp
/******************************************************************************* File: CWndSource.cpp Contains: Window slide pos implement code Written by: Bangfei Jin Change History (most recent first): 2016-12-29 Bangfei Create file *******************************************************************************/ #include "windows.h" #include "tchar.h" #include "CWndSource.h" #include <opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; CWndSource::CWndSource(HINSTANCE hInst) : CWndBase (hInst) { m_pImgAnalyse = NULL; } CWndSource::~CWndSource(void) { if (m_pImgAnalyse != NULL) delete m_pImgAnalyse; } bool CWndSource::CreateWnd (HWND hParent, RECT rcView, COLORREF clrBG) { if (!CWndBase::CreateWnd (hParent, rcView, clrBG)) return false; return true; } LRESULT CWndSource::OnReceiveMessage (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { RECT rcView; if (hwnd != NULL) GetClientRect (hwnd, &rcView); switch (uMsg) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); //BitBlt(hdc, 0, 0, ps.rcPaint.right, ps.rcPaint.bottom, m_hBmpDC, 0, 0, SRCCOPY); if (m_hBitmap != NULL) { BITMAP bmpInfo; GetObject(m_hBitmap, sizeof (BITMAP), &bmpInfo); SetStretchBltMode(hdc, HALFTONE); StretchBlt(hdc, 0, 0, rcView.right, rcView.bottom, m_hBmpDC, 0, 0, bmpInfo.bmWidth, bmpInfo.bmHeight, SRCCOPY); } EndPaint(hwnd, &ps); return S_OK;// DefWindowProc(hwnd, uMsg, wParam, lParam); } default: break; } return CWndBase::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } int CWndSource::OpenFile(char * pFileName) { Mat matImg = imread(pFileName, IMREAD_COLOR); if (matImg.empty()) return -1; int nW = matImg.cols; int nH = matImg.rows; int nSize = nW * nH * 4; unsigned char * pImgBuff = new unsigned char[nSize]; memset(pImgBuff, 0, nSize); uchar * pDst = pImgBuff; uchar * pSrc = matImg.data; for (int i = 0; i < nH; i++) { for (int j = 0; j < nW; j++) { *pDst++ = *pSrc++; *pDst++ = *pSrc++; *pDst++ = *pSrc++; *pDst++; } } if (m_hBitmap != NULL) { SelectObject(m_hBmpDC, m_hBmpOld); DeleteObject(m_hBitmap); } m_hBitmap = CreateBitmap(nW, nH, 1, 32, pImgBuff); m_hBmpOld = (HBITMAP)SelectObject(m_hBmpDC, m_hBitmap); matImg.release(); if (m_pImgAnalyse == NULL) { m_pImgAnalyse = new CImgAnalyse(m_hParent); m_pImgAnalyse->SetMusicPage(m_pMusicPage); } m_pImgAnalyse->OpenFile(pFileName); InvalidateRect(m_hWnd, NULL, FALSE); return 0; }
95fc14a20be5009d569416e78cd555523a654032
ce7fcd3d91a1c841de035971947d1c66cca70f3e
/external/opa_plll/plll-1.0/plll/src/lattices/enumimpl-parallelserial.cpp
e85c9000c5a1affdbf7abde3c3afb9775cec1632
[ "MIT" ]
permissive
unjambonakap/opa
ce4d6e83229f369097d07c253487def8ac9ea4f2
b0b529a855bab9f18c544d55bda1cbe968bbfabc
refs/heads/master
2023-04-14T15:30:33.374447
2023-04-08T21:09:54
2023-04-08T21:09:54
145,020,635
0
0
null
null
null
null
UTF-8
C++
false
false
32,453
cpp
enumimpl-parallelserial.cpp
/* Copyright (c) 2011-2014 University of Zurich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef PLLL_INCLUDE_GUARD__ENUMIMPL_PARALLELSERIAL_CPP #define PLLL_INCLUDE_GUARD__ENUMIMPL_PARALLELSERIAL_CPP #include "enumimpl-parallelserial-enum.cpp" #include "taskmanager.hpp" namespace plll { template<class RealTypeContext, class IntTypeContext> class ParallelEnumerator { public: typedef boost::function<void(const linalg::math_matrix<typename IntTypeContext::Integer> & basis, int p, const linalg::math_rowvector<typename IntTypeContext::Integer> & vec)> CallbackFunction; private: TaskManager d_tm; unsigned d_dim; // d_dim is the real dimension unsigned d_begin, d_end; Updater<RealTypeContext, IntTypeContext> d_update; Lattice<RealTypeContext, IntTypeContext> * d_lattice; class JobManager; class TMJob : public TaskManager::Job { private: ParallelEnumerator & d_pe; typename JobManager::JobDataT * d_job; public: TMJob(ParallelEnumerator & pe, typename JobManager::JobDataT * job) : d_pe(pe), d_job(job) { } virtual ~TMJob() { } virtual void run(unsigned thread_no, TaskManager * tm); }; class JobManager { public: typedef ThreadData<RealTypeContext, IntTypeContext, JobManager> ThreadDataT; typedef JobData<RealTypeContext, IntTypeContext, JobManager> JobDataT; private: std::list<JobDataT> d_jobs; ParallelEnumerator & d_pe; boost::mutex d_jobs_mutex; std::list<JobDataT*> d_jobs_to_run; class JobsMutexLock { private: JobManager & d_jm; public: inline JobsMutexLock(JobManager & jm) : d_jm(jm) { if (d_jm.d_parallel_mode) d_jm.d_jobs_mutex.lock(); } inline ~JobsMutexLock() { if (d_jm.d_parallel_mode) d_jm.d_jobs_mutex.unlock(); } }; linalg::math_rowvector<typename IntTypeContext::Integer> d_result; // is zero vector (of no length) until a solution was found volatile bool d_has_bound; typename RealTypeContext::Real d_bound; volatile bool d_bound_updated; CallbackFunction d_ecf; bool d_parallel_mode; long double computeHeuristic(const typename JobManager::JobDataT & job, const typename RealTypeContext::Real & bound) // Computes the Gauss volume heuristic for the given job { if (job.dimension() == 0) return 0.0; unsigned stage = d_pe.d_dim - job.dimension(); long double v = std::pow(arithmetic::convert<long double>(bound - job.ell()), 0.5 * stage); v *= d_pe.d_gaussianfactors.HPF(stage); long double d = arithmetic::convert<double>(d_pe.d_lattice->getNormSq(d_pe.d_begin)); for (unsigned i = 1; i <= stage; ++i) d *= arithmetic::convert<double>(d_pe.d_lattice->getNormSq(d_pe.d_begin + i)); return v * std::pow(d, -0.5l / (long double)stage); } void updateBound(const linalg::math_rowvector<typename IntTypeContext::Integer> & result, const typename RealTypeContext::Real bound) { bool did_update_here = false; bool hasSolutionYet = !d_has_bound; if (d_pe.d_update(*d_pe.d_lattice, d_pe.d_begin, d_pe.d_end, d_result, d_bound, result, bound, hasSolutionYet)) { d_bound_updated = true; did_update_here = true; // Call EnumCallbackFunction! if (!d_ecf.empty()) { std::pair<linalg::math_matrix<typename IntTypeContext::Integer> *, unsigned> l = d_pe.d_lattice->getMatrixIndex(d_pe.d_begin); if (l.first) d_ecf(*l.first, l.second, result); } } d_has_bound = !hasSolutionYet; if (did_update_here) d_pe.updateBound(d_bound); } void addResult(JobDataT * data) { // Mark as done data->markDone(); // Check out result if (data->d_result.size()) updateBound(data->d_result, data->d_bound); // All jobs done? if (!d_pe.d_tm.areJobsEnqueued()) d_pe.split(); } JobDataT * getJobImpl() { JobDataT * res = NULL; while (res == NULL) { if (d_jobs_to_run.empty()) break; res = d_jobs_to_run.front(); d_jobs_to_run.pop_front(); if (d_has_bound) if (!res->update(d_bound)) res = NULL; // job not needed anymore } return res; } public: PruningHelper<RealTypeContext, IntTypeContext> d_pruninghelper; JobManager(ParallelEnumerator & pe) : d_pe(pe), d_has_bound(false), d_bound_updated(false), d_ecf(NULL), d_parallel_mode(false), d_pruninghelper() { } void setCallback(CallbackFunction ecf) { d_ecf = ecf; } void restart(const typename RealTypeContext::Real & bound) { d_jobs.clear(); d_jobs_to_run.clear(); d_has_bound = false; d_bound = bound; d_result.resize(0); d_bound_updated = false; } class HSorter { public: bool operator() (const std::pair<JobDataT*, long double> & p1, const std::pair<JobDataT*, long double> & p2) const { // > seems to minimize total CPU time, but to "maximize" total wallclock time // < seems to "maximize" total CPU time, but to minimize total wallclock time return p1.second > p2.second; } }; void optimize() { JobsMutexLock jml(*this); // Store queue into std::vector including the heuristic's values std::vector<std::pair<JobDataT*, long double> > tmp; tmp.reserve(d_jobs_to_run.size()); for (typename std::list<JobDataT*>::iterator i = d_jobs_to_run.begin(); i != d_jobs_to_run.end(); ++i) tmp.push_back(std::make_pair(*i, computeHeuristic(**i, d_bound))); d_jobs_to_run.clear(); // Sort HSorter sorter; std::sort(tmp.begin(), tmp.end(), sorter); // Add jobs back to queue for (unsigned i = 0; i < tmp.size(); ++i) d_jobs_to_run.push_back(tmp[i].first); } // For scheduler void addJob(unsigned dim, const linalg::math_rowvector<typename IntTypeContext::Integer> & x_end, const typename RealTypeContext::Real & ell, const typename RealTypeContext::Real & bound, bool iszero) { JobsMutexLock jml(*this); d_jobs.push_back(JobDataT(dim, x_end, ell, d_has_bound ? (bound < d_bound ? bound : d_bound) : bound, iszero)); if (d_parallel_mode) d_pe.d_tm.enqueueJob(new TMJob(d_pe, &d_jobs.back())); else d_jobs_to_run.push_back(&d_jobs.back()); } template<class It> void addJobs(It begin, It end) { if (begin == end) return; JobsMutexLock jml(*this); while (begin != end) { bool skip = false; if (d_has_bound) if (!begin->update(d_bound)) skip = true; if (!skip) { d_jobs.push_back(*begin); if (d_parallel_mode) d_pe.d_tm.enqueueJob(new TMJob(d_pe, &d_jobs.back())); else d_jobs_to_run.push_back(&d_jobs.back()); } ++begin; } } void launchJobsInParallel() { boost::unique_lock<boost::mutex> lock(d_jobs_mutex); d_parallel_mode = true; for (typename std::list<JobDataT*>::iterator i = d_jobs_to_run.begin(); i != d_jobs_to_run.end(); ++i) d_pe.d_tm.enqueueJob(new TMJob(d_pe, *i)); d_jobs_to_run.clear(); } void stopLaunchingJobsInParallel() { boost::unique_lock<boost::mutex> lock(d_jobs_mutex); d_parallel_mode = false; } void tryToUpdateBound(const linalg::math_rowvector<typename IntTypeContext::Integer> & result, const typename RealTypeContext::Real bound) { JobsMutexLock jml(*this); updateBound(result, bound); } bool isBoundUpdated() const { return d_bound_updated; } typename RealTypeContext::Real getUpdatedBound() { JobsMutexLock jml(*this); typename RealTypeContext::Real bound(d_bound); d_bound_updated = false; return bound; } const linalg::math_rowvector<typename IntTypeContext::Integer> & getResult() const { return d_result; } const typename RealTypeContext::Real & getBound() const { return d_bound; } // For JobRunner: bool getJob(JobDataT * job) // Returns false if no job is left { if (d_has_bound) { boost::unique_lock<boost::mutex> lock(d_jobs_mutex); if (!job->update(d_bound)) return false; } return true; } JobDataT * getJob() // Returns NULL if no job is left { if (d_parallel_mode) { boost::unique_lock<boost::mutex> lock(d_jobs_mutex); return getJobImpl(); } else return getJobImpl(); } void sendResult(JobDataT * data) // Sends back result { if (d_parallel_mode) { boost::unique_lock<boost::mutex> lock(d_jobs_mutex); addResult(data); } else addResult(data); } // Stats unsigned getNoToDo() { boost::unique_lock<boost::mutex> lock(d_jobs_mutex); return d_jobs_to_run.size(); } void printStats() { std::pair<unsigned, unsigned> j = d_pe.d_tm.getJobsInfo(); unsigned jsize = d_jobs.size(); arithmetic::RealContext rc; arithmetic::Real bound = arithmetic::convert(d_bound, rc); d_pe.d_verbose(LatticeReduction::VL_Information) << jsize << " jobs, " << j.second << " to do, " << j.first << " running right now (" << d_pe.d_end - d_pe.d_begin + 1 << "-dimensional enumerate, indices " << d_pe.d_begin << "--" << d_pe.d_end << "); bound is " << bound; } // Accessors for JobDataT static const linalg::math_rowvector<typename IntTypeContext::Integer> & jobGetResult(const JobDataT & td) { return td.d_result; } static const typename RealTypeContext::Real & jobGetBound(const JobDataT & td) { return td.d_bound; } }; JobManager d_jm; std::vector<typename JobManager::ThreadDataT *> d_thread_data; void setup(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end) { for (typename std::vector<typename JobManager::ThreadDataT *>::iterator i = d_thread_data.begin(); i != d_thread_data.end(); ++i) (*i)->flagToSetup(lattice, begin, end); } void split() { for (typename std::vector<typename JobManager::ThreadDataT *>::iterator i = d_thread_data.begin(); i != d_thread_data.end(); ++i) (*i)->flagToSplit(); } void stop() { d_tm.clearAllJobs(); for (typename std::vector<typename JobManager::ThreadDataT *>::iterator i = d_thread_data.begin(); i != d_thread_data.end(); ++i) (*i)->flagToStop(); } void updateBound(const typename RealTypeContext::Real & bound) { for (typename std::vector<typename JobManager::ThreadDataT *>::iterator i = d_thread_data.begin(); i != d_thread_data.end(); ++i) (*i)->setUpdatedBound(bound); } volatile bool d_status_active, d_status_quit; boost::thread d_status_thread; static void statusThread(ParallelEnumerator * pe) { initTLAlloc(); // This might not seem necessary, but as soon as a temporary Real and/or // Integer object is created while outputting something, it is necessary. // boost::posix_time::milliseconds sleepTime(500); boost::posix_time::milliseconds sleepTime(5000); while (!pe->d_status_quit) { if (pe->d_status_active) pe->d_jm.printStats(); boost::this_thread::sleep(sleepTime); } } typename JobManager::ThreadDataT d_main_threaddata; StandardEnumSettings::PruningMethod d_pruning; double d_pruning_parameter; // needed for PM_Step, PM_Piecewise and PM_SchnorrHoerner2 Verbose & d_verbose; GaussianFactorComputer & d_gaussianfactors; enum StopType { ST_Normal, ST_StopEnum, ST_StopReduction, ST_BadAlloc, ST_Unknown }; StopType d_threads_stop; public: ParallelEnumerator(Verbose & v, GaussianFactorComputer & gf, unsigned enumdimension, unsigned nothreads) : d_tm(nothreads), d_dim(0), d_begin(0), d_end(0), d_update(), d_lattice(NULL), d_jm(*this), d_status_active(false), d_status_quit(false), d_status_thread(statusThread, this), d_main_threaddata(d_jm, d_update), d_pruning(StandardEnumSettings::PM_None), d_pruning_parameter(0), d_verbose(v), d_gaussianfactors(gf), d_threads_stop(ST_Normal) { d_thread_data.reserve(d_tm.getNumberOfThreads()); for (unsigned i = 0; i < d_tm.getNumberOfThreads(); ++i) d_thread_data.push_back(new typename JobManager::ThreadDataT(d_jm, d_update)); } ~ParallelEnumerator() { d_status_quit = true; d_status_thread.interrupt(); d_status_thread.join(); for (unsigned i = 0; i < d_thread_data.size(); ++i) delete d_thread_data[i]; } bool enumerate(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end, linalg::math_rowvector<typename IntTypeContext::Integer> & result, typename RealTypeContext::Real & bound, const StandardEnumSettings & s) // Finds a shortest vector in the lattice generated by the orthogonal projections of the vectors // A.row(begin) to A.row(end) into the orthogonal complement of the vectors A.row(0) to // A.row(begin-1). Uses the Kannan-Schnorr-Euchner enumeration method. { d_pruning = s.d_pruning; d_pruning_parameter = s.d_pruning_parameter; // Initialize updater d_lattice = &lattice; d_update.initialize(d_verbose, lattice, begin, end, bound); d_jm.d_pruninghelper.setup(begin, end - begin + 1, lattice, d_pruning, d_pruning_parameter); d_dim = end - begin + 1; d_begin = begin; d_end = end; bool verbose = false; // Restart job manager d_jm.restart(bound); d_threads_stop = ST_Normal; // Insert beginning stub linalg::math_rowvector<typename IntTypeContext::Integer> x; typename RealTypeContext::Real ell(lattice.rc()); setZero(ell); d_jm.addJob(0, x, ell, bound, true); // Refine queue d_main_threaddata.setup(lattice, d_begin, d_end); typename JobManager::JobDataT * job = d_jm.getJob(); unsigned last_loD = d_dim; while (job) { // Run the job unsigned loD = job->leftoverDims(d_main_threaddata); if (loD < last_loD) { // Sort d_jm.optimize(); // Stats if (verbose) d_jm.printStats(); last_loD = loD; } if (loD < 15) job->run(d_main_threaddata); else job->refine(d_main_threaddata, 1); // Return job d_jm.sendResult(job); // Is there enough? if (d_jm.getNoToDo() >= d_tm.getNumberOfThreads() * 75) break; // Get next (if available) job = d_jm.getJob(); } if (d_jm.getNoToDo() > 0) // only if there's something to do! { verbose = true; if (verbose) { d_verbose(LatticeReduction::VL_Information) << "(after refining)"; d_jm.printStats(); } if (verbose) d_verbose(LatticeReduction::VL_Information) << "(optimizing queue)"; d_jm.optimize(); setup(lattice, d_begin, d_end); if (verbose) d_verbose(LatticeReduction::VL_Information) << "(continuing threads)"; d_jm.launchJobsInParallel(); d_status_active = true; d_tm.waitForDone(); d_jm.stopLaunchingJobsInParallel(); d_status_active = false; if (verbose) d_verbose(LatticeReduction::VL_Information) << "(all threads done)"; if (d_threads_stop != ST_Normal) switch (d_threads_stop) { case ST_StopEnum: break; case ST_StopReduction: throw LatticeReduction::stop_reduction(); case ST_BadAlloc: throw std::bad_alloc(); default: case ST_Unknown: throw std::runtime_error("Unknown exception caught in enumeration thread"); } } // Fetch solutions if (d_jm.getResult().size() > 0) { for (unsigned i = 0; i < result.size(); ++i) result[i] = d_jm.getResult()[i]; bound = d_jm.getBound(); if (verbose) d_verbose(LatticeReduction::VL_Information) << "[done]"; return true; } else { if (verbose) { d_verbose(LatticeReduction::VL_Information) << "(no solution found!)"; d_verbose(LatticeReduction::VL_Information) << "[done]"; } return false; } } void setCallback(CallbackFunction cf) { d_jm.setCallback(cf); } }; template<class RealTypeContext, class IntTypeContext> class SerialEnumerator { public: typedef boost::function<void(const linalg::math_matrix<typename IntTypeContext::Integer> & basis, int p, const linalg::math_rowvector<typename IntTypeContext::Integer> & vec)> CallbackFunction; private: Lattice<RealTypeContext, IntTypeContext> * d_lattice; Updater<RealTypeContext, IntTypeContext> d_update; unsigned d_begin; class JobManager; typedef ThreadData<RealTypeContext, IntTypeContext, JobManager> ThreadDataT; typedef JobData<RealTypeContext, IntTypeContext, JobManager> JobDataT; class JobManager { private: SerialEnumerator & d_se; CallbackFunction d_ecf; public: PruningHelper<RealTypeContext, IntTypeContext> d_pruninghelper; JobManager(SerialEnumerator & se) : d_se(se), d_ecf(NULL), d_pruninghelper() { } static const linalg::math_rowvector<typename IntTypeContext::Integer> & jobGetResult(const JobDataT & td) { return td.d_result; } static const typename RealTypeContext::Real & jobGetBound(const JobDataT & td) { return td.d_bound; } template<class It> static inline void addJobs(It, It) // Dummy function which just ignores the given data { } void tryToUpdateBound(const linalg::math_rowvector<typename IntTypeContext::Integer> & result, const typename RealTypeContext::Real bound) { if (!d_ecf.empty()) { std::pair<linalg::math_matrix<typename IntTypeContext::Integer> *, unsigned> l = d_se.d_lattice->getMatrixIndex(d_se.d_begin); if (l.first) d_ecf(*l.first, l.second, result); } } inline bool hasCallback() const { return !d_ecf.empty(); } inline void setCallback(CallbackFunction ecf) { d_ecf = ecf; } }; JobManager d_jm; ThreadDataT d_threaddata; StandardEnumSettings::PruningMethod d_pruning; double d_pruning_parameter; // needed for PM_Step, PM_Piecewise and PM_SchnorrHoerner2 Verbose & d_verbose; GaussianFactorComputer & d_gaussianfactors; public: SerialEnumerator(Verbose & v, GaussianFactorComputer & gf, unsigned enumdimension) : d_lattice(NULL), d_update(), d_begin(0), d_jm(*this), d_threaddata(d_jm, d_update), d_pruning(StandardEnumSettings::PM_None), d_pruning_parameter(0), d_verbose(v), d_gaussianfactors(gf) { } bool enumerate(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end, linalg::math_rowvector<typename IntTypeContext::Integer> & result, typename RealTypeContext::Real & bound, const StandardEnumSettings & s) // Finds a shortest vector in the lattice generated by the orthogonal projections of the vectors // A.row(begin) to A.row(end) into the orthogonal complement of the vectors A.row(0) to // A.row(begin-1). Uses the Kannan-Schnorr-Euchner enumeration method. { d_pruning = s.d_pruning; d_pruning_parameter = s.d_pruning_parameter; d_begin = begin; // Initialize updater d_lattice = &lattice; d_update.initialize(d_verbose, lattice, begin, end, bound); d_jm.d_pruninghelper.setup(begin, end - begin + 1, lattice, d_pruning, d_pruning_parameter); // Beginning stub linalg::math_rowvector<typename IntTypeContext::Integer> x; typename RealTypeContext::Real ell(lattice.rc()); setZero(ell); JobDataT job(0, x, ell, bound, true); // Process d_threaddata.setup(lattice, begin, end); if (d_jm.hasCallback()) { try { // Use two-stage enum job.run2(d_threaddata); } catch (LatticeReduction::stop_enumeration &) { d_verbose(LatticeReduction::VL_Chatter) << "Stopping enumeration"; } } else // Do just one stage which covers everything job.run(d_threaddata); // Fetch solution if (d_jm.jobGetResult(job).size() > 0) { for (unsigned i = 0; i < d_jm.jobGetResult(job).size(); ++i) result[i] = d_jm.jobGetResult(job)[i]; bound = d_jm.jobGetBound(job); return true; } else return false; } void setCallback(CallbackFunction cf) { d_jm.setCallback(cf); } }; template<class RealTypeContext, class IntTypeContext> class ParallelSerialEnumerator { private: bool d_parallel; STD_AUTO_PTR<ParallelEnumerator<RealTypeContext, IntTypeContext> > d_enum_parallel; STD_AUTO_PTR<SerialEnumerator<RealTypeContext, IntTypeContext> > d_enum_serial; // Disable copying and copy-constructing ParallelSerialEnumerator(const ParallelSerialEnumerator &); ParallelSerialEnumerator & operator = (const ParallelSerialEnumerator &); typedef boost::function<void(const linalg::math_matrix<typename IntTypeContext::Integer> & basis, int p, const linalg::math_rowvector<typename IntTypeContext::Integer> & vec)> CallbackFunction; public: ParallelSerialEnumerator(Verbose & v, GaussianFactorComputer & gf, unsigned enumdimension, unsigned max_threads, LatticeReduction::Statistics & stats) : d_enum_parallel(), d_enum_serial() { unsigned nothreads = boost::thread::hardware_concurrency(); if (max_threads) { if (nothreads > max_threads) nothreads = max_threads; } if (nothreads == 1) { d_parallel = false; d_enum_serial.reset(new SerialEnumerator<RealTypeContext, IntTypeContext>(v, gf, enumdimension)); } else { d_parallel = true; d_enum_parallel.reset(new ParallelEnumerator<RealTypeContext, IntTypeContext>(v, gf, enumdimension, nothreads)); } } bool enumerate(unsigned begin, unsigned end, linalg::math_rowvector<typename IntTypeContext::Integer> & result, typename RealTypeContext::Real & bound, const StandardEnumSettings & s) // Finds a shortest vector in the lattice generated by the orthogonal projections of the vectors // A.row(begin) to A.row(end) into the orthogonal complement of the vectors A.row(0) to // A.row(begin-1). Uses the Kannan-Schnorr-Euchner enumeration method. { return d_parallel ? d_enum_parallel->enumerate(begin, end, result, bound, s) : d_enum_serial->enumerate(begin, end, result, bound, s); } void setCallback(CallbackFunction cf) { if (d_parallel) d_enum_parallel->setCallback(cf); else d_enum_serial->setCallback(cf); } }; template<class RealTypeContext, class IntTypeContext> void ParallelEnumerator<RealTypeContext, IntTypeContext>::TMJob::run(unsigned thread_no, TaskManager * tm) { try { if (d_pe.d_jm.getJob(d_job)) { // Run the job d_job->run2(*d_pe.d_thread_data[thread_no]); // Return d_pe.d_jm.sendResult(d_job); } } catch (LatticeReduction::stop_enumeration &) { d_pe.stop(); d_pe.d_threads_stop = ST_StopEnum; d_pe.d_verbose(LatticeReduction::VL_Chatter) << "Stopping enumeration"; } catch (LatticeReduction::stop_reduction &) { d_pe.stop(); d_pe.d_threads_stop = ST_StopReduction; d_pe.d_verbose(LatticeReduction::VL_Chatter) << "Stopping enumeration (stop reduction)"; } catch (std::bad_alloc &) { d_pe.stop(); d_pe.d_threads_stop = ST_BadAlloc; d_pe.d_verbose(LatticeReduction::VL_Chatter) << "Stopping enumeration (bad alloc)"; } catch(std::exception & e) { d_pe.stop(); d_pe.d_threads_stop = ST_Unknown; d_pe.d_verbose(LatticeReduction::VL_Chatter) << "Stopping enumeration (unknown exception: " << e.what() << ")"; } catch(...) { d_pe.stop(); d_pe.d_threads_stop = ST_Unknown; d_pe.d_verbose(LatticeReduction::VL_Chatter) << "Stopping enumeration (unknown exception)"; } } } #endif
a68adc360dadbfdb042638b31967f7f1de4807e8
7adea0299022caaf58fda29a273a4690989e3ff5
/tut-2-examples-and-vertex-attributes/examples/virtual-methods/Main.cpp
fc3fab69746a24787917250ece457f517c6e94fc
[]
no_license
emdeha/blackflame-opengl-tutorials
57ea4d3d8dd7d3abae6c5f8f8ea53559f8a63e27
addc729fe9cc9cd4615255f86b7d7307ff0bfafb
refs/heads/master
2020-04-12T19:25:45.151749
2012-07-01T16:16:13
2012-07-01T16:16:13
3,754,570
0
1
null
null
null
null
UTF-8
C++
false
false
449
cpp
Main.cpp
#include <iostream> using namespace std; class Object { protected: float position; public: Object(); Object(float newPosition) : position(newPosition) { } virtual void Move(float delta) = 0; }; class Human : public Object { public: void Move(float delta) { position += delta; } }; class Raptor : public Object { public: void Move(float delta) { position += 2 * delta; } }; int main() { Raptor phylosoraptor(3.4f); return 0; }
4ed1d81fddaff71fc2d78ca103ec4ee0495bfa60
0105094dc5ed9ca5bf344e887ae94b9bf25d353f
/emulator/src/cube_cpu_disasm.cpp
d0eb1d1d34e72b09c7d30f0215342bd87c81150b
[]
no_license
Green92/thundercracker
eed1f59a4c3bfcea9c3cd9e49b23b38720e4dd27
75e85aa1bddb1fa07851a12718fa8150ab8428b1
refs/heads/master
2021-01-12T10:59:25.892200
2016-11-03T21:24:13
2016-11-03T21:24:13
72,781,762
0
1
null
2016-11-03T19:58:37
2016-11-03T19:58:37
null
UTF-8
C++
false
false
32,829
cpp
cube_cpu_disasm.cpp
/* -*- mode: C; c-basic-offset: 4; intent-tabs-mode: nil -*- */ /* 8051 emulator core * * Copyright 2006 Jari Komppa * Copyright <c> 2011 Sifteo, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * disasm.c * Disassembler functions * * These functions decode 8051 operations into text strings, useful in * interactive debugger. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "cube_cpu.h" namespace Cube { namespace CPU { static const char *sfr_names[128] = { "P0", "SP", "DPL", "DPH", "DPL1", "DPH1", "DEBUG", "SFR_87", "TCON", "TMOD", "TL0", "TL1", "TH0", "TH1", "SFR_8E", "P3CON", "P1", "SFR_91", "DPS", "P0DIR", "P1DIR", "P2DIR", "P3DIR", "P2CON", "S0CON", "S0BUF", "SFR_9A", "SFR_9B", "SFR_9C", "SFR_9D", "P0CON", "P1CON", "P2", "PWMDC0", "PWMDC1", "CLKCTRL", "PWRDWN", "WUCON", "INTEXP", "MEMCON", "IEN0", "IP0", "S0RELL", "RTC2CPT01", "RTC2CPT10", "CLKLFCTRL", "OPMCON", "WDSV", "P3", "RSTREAS", "PWMCON", "RTC2CON", "RTC2CMP0", "RTC2CMP1", "RTC2CPT00", "SFR_B7", "IEN1", "IP1", "S0RELH", "SFR_BB", "SPISCON0", "SFR_BD", "SPISSTAT", "SPISDAT", "IRCON", "CCEN", "CCL1", "CCH1", "CCL2", "CCH2", "CCL3", "CCH3", "T2CON", "MPAGE", "CRCL", "CRCH", "TL2", "TH2", "WUOPC1", "WUOPC0", "PSW", "ADCCON3", "ADCCON2", "ADCCON1", "ADCDATH", "ADCDATL", "RNGCTL", "RNGDAT", "ADCON", "W2SADR", "W2DAT", "COMPCON", "POFCON", "CCPDATIA", "CCPDATIB", "CCPDATO", "ACC", "W2CON1", "W2CON0", "SFR_E3", "SPIRCON0", "SPIRCON1", "SPIRSTAT", "SPIRDAT", "RFCON", "MD0", "MD1", "MD2", "MD3", "MD4", "MD5", "ARCON", "B", "SFR_F1", "SFR_F2", "SFR_F3", "SFR_F4", "SFR_F5", "SFR_F6", "SFR_F7", "FSR", "FPCR", "FCR", "SFR_FB", "SPIMCON0", "SPIMCON1", "SPIMSTAT", "SPIMDAT", }; static void mem_mnemonic(int aValue, char *aBuffer) { if (aValue > 0x7f) strcpy(aBuffer, sfr_names[aValue - 0x80]); else sprintf(aBuffer, "%02Xh", aValue); } static void bitaddr_mnemonic(int aValue, char *aBuffer) { char regname[32]; if (aValue > 0x7f) mem_mnemonic(aValue & 0xf8, regname); else sprintf(regname, "%02Xh", aValue >> 3); sprintf(aBuffer, "%s.%d", regname, aValue & 7); } static int disasm_ajmp_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"AJMP #%04Xh", ((aPosition + 2) & 0xf800) | aCPU->mCodeMem[(aPosition + 1)&PC_MASK] | ((aCPU->mCodeMem[(aPosition)&PC_MASK] & 0xe0) << 3)); return 2; } static int disasm_ljmp_address(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"LJMP #%04Xh", (aCPU->mCodeMem[(aPosition + 1)&PC_MASK] << 8) | aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_rr_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"RR A"); return 1; } static int disasm_inc_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"INC A"); return 1; } static int disasm_inc_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"INC %s", mem); return 2; } static int disasm_inc_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"INC @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK] & 1); return 1; } static int disasm_jbc_bitaddr_offset(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"JBC %s, #%+d", baddr, (signed char)aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_acall_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ACALL %04Xh", ((aPosition + 2) & 0xf800) | aCPU->mCodeMem[(aPosition + 1)&PC_MASK] | ((aCPU->mCodeMem[(aPosition)&PC_MASK] & 0xe0) << 3)); return 2; } static int disasm_lcall_address(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"LCALL #%04Xh", (aCPU->mCodeMem[(aPosition + 1)&PC_MASK] << 8) | aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_rrc_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"RRC A"); return 1; } static int disasm_dec_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"DEC A"); return 1; } static int disasm_dec_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"DEC %s", mem); return 2; } static int disasm_dec_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"DEC @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK] & 1); return 1; } static int disasm_jb_bitaddr_offset(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"JB %s, #%+d", baddr, (signed char)aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_ret(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"RET"); return 1; } static int disasm_rl_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"RL A"); return 1; } static int disasm_add_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ADD A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_add_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ADD A, %s", mem); return 2; } static int disasm_add_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ADD A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_jnb_bitaddr_offset(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"JNB %s, #%+d", baddr, (signed char)aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_reti(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"RETI"); return 1; } static int disasm_rlc_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"RLC A"); return 1; } static int disasm_addc_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ADDC A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_addc_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ADDC A, %s", mem); return 2; } static int disasm_addc_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ADDC A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_jc_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"JC #%+d", (signed char)aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_orl_mem_a(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ORL %s, A", mem); return 2; } static int disasm_orl_mem_imm(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ORL %s, #%02Xh", mem, aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_orl_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ORL A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_orl_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ORL A, %s", mem); return 2; } static int disasm_orl_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ORL A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_jnc_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"JNC #%+d", (signed char)aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_anl_mem_a(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ANL %s, A", mem); return 2; } static int disasm_anl_mem_imm(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ANL %s, #%02Xh", mem, aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_anl_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ANL A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_anl_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"ANL A, %s", mem); return 2; } static int disasm_anl_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ANL A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_jz_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"JZ #%+d", (signed char)aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_xrl_mem_a(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"XRL %s, A", mem); return 2; } static int disasm_xrl_mem_imm(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"XRL %s, #%02Xh", mem, aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_xrl_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"XRL A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_xrl_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"XRL A, %s", mem); return 2; } static int disasm_xrl_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"XRL A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_jnz_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"JNZ #%+d", (signed char)aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_orl_c_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"ORL C, %s", baddr); return 2; } static int disasm_jmp_indir_a_dptr(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"JMP @A+DPTR"); return 1; } static int disasm_mov_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_mov_mem_imm(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV %s, #%02Xh", mem, aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_mov_indir_rx_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV @R%d, #%02Xh", aCPU->mCodeMem[(aPosition)&PC_MASK]&1, aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_sjmp_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"SJMP #%+d", (signed char)(aCPU->mCodeMem[(aPosition + 1)&PC_MASK])); return 2; } static int disasm_anl_c_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"ANL C, %s", baddr); return 2; } static int disasm_movc_a_indir_a_pc(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOVC A, @A+PC"); return 1; } static int disasm_div_ab(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"DIV AB"); return 1; } static int disasm_mov_mem_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem1[32]; char mem2[32]; mem_mnemonic(aCPU->mCodeMem[(aPosition + 2)&PC_MASK], mem1); mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem2); sprintf(aBuffer,"MOV %s, %s", mem1, mem2); return 3; } static int disasm_mov_mem_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV %s, @R%d", mem, aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 2; } static int disasm_mov_dptr_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV DPTR, #0%02X%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK], aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_mov_bitaddr_c(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"MOV %s, C", baddr); return 2; } static int disasm_movc_a_indir_a_dptr(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOVC A, @A+DPTR"); return 1; } static int disasm_subb_a_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"SUBB A, #%02Xh", aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_subb_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"SUBB A, %s", mem); return 2; } static int disasm_subb_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"SUBB A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_orl_c_compl_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"ORL C, /%s", baddr); return 2; } static int disasm_mov_c_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"MOV C, %s", baddr); return 2; } static int disasm_inc_dptr(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"INC DPTR"); return 1; } static int disasm_mul_ab(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MUL AB"); return 1; } static int disasm_mov_indir_rx_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV @R%d, %s", aCPU->mCodeMem[(aPosition)&PC_MASK]&1, mem); return 2; } static int disasm_anl_c_compl_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"ANL C, /%s", baddr); return 2; } static int disasm_cpl_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"CPL %s", baddr); return 2; } static int disasm_cpl_c(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CPL C"); return 1; } static int disasm_cjne_a_imm_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CJNE A, #%02Xh, #%+d", aCPU->mCodeMem[(aPosition + 1)&PC_MASK], (signed char)(aCPU->mCodeMem[(aPosition + 2)&PC_MASK])); return 3; } static int disasm_cjne_a_mem_offset(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"CJNE A, %s, #%+d", mem, (signed char)(aCPU->mCodeMem[(aPosition + 2)&PC_MASK])); return 3; } static int disasm_cjne_indir_rx_imm_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CJNE @R%d, #%02Xh, #%+d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1, aCPU->mCodeMem[(aPosition + 1)&PC_MASK], (signed char)(aCPU->mCodeMem[(aPosition + 2)&PC_MASK])); return 3; } static int disasm_push_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"PUSH %s", mem); return 2; } static int disasm_clr_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"CLR %s", baddr); return 2; } static int disasm_clr_c(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CLR C"); return 1; } static int disasm_swap_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"SWAP A"); return 1; } static int disasm_xch_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"XCH A, %s", mem); return 2; } static int disasm_xch_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"XCH A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_pop_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"POP %s", mem); return 2; } static int disasm_setb_bitaddr(em8051 *aCPU, int aPosition, char *aBuffer) { char baddr[32]; bitaddr_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], baddr); sprintf(aBuffer,"SETB %s", baddr); return 2; } static int disasm_setb_c(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"SETB C"); return 1; } static int disasm_da_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"DA A"); return 1; } static int disasm_djnz_mem_offset(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"DJNZ %s, #%+d", mem, (signed char)(aCPU->mCodeMem[(aPosition + 2)&PC_MASK])); return 3; } static int disasm_xchd_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"XCHD A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_movx_a_indir_dptr(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOVX A, @DPTR"); return 1; } static int disasm_movx_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOVX A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_clr_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CLR A"); return 1; } static int disasm_mov_a_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV A, %s", mem); return 2; } static int disasm_mov_a_indir_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV A, @R%d", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_movx_indir_dptr_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOVX @DPTR, A"); return 1; } static int disasm_movx_indir_rx_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOVX @R%d, A", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_cpl_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CPL A"); return 1; } static int disasm_mov_mem_a(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV %s, A", mem); return 2; } static int disasm_mov_indir_rx_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV @R%d, A", aCPU->mCodeMem[(aPosition)&PC_MASK]&1); return 1; } static int disasm_nop(em8051 *aCPU, int aPosition, char *aBuffer) { if (aCPU->mCodeMem[aPosition&PC_MASK]) sprintf(aBuffer,"??UNKNOWN"); else sprintf(aBuffer,"NOP"); return 1; } static int disasm_inc_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"INC R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_dec_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"DEC R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_add_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ADD A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_addc_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ADDC A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_orl_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ORL A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_anl_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"ANL A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_xrl_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"XRL A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_mov_rx_imm(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV R%d, #%02Xh", aCPU->mCodeMem[aPosition&PC_MASK]&7, aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_mov_mem_rx(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV %s, R%d", mem, aCPU->mCodeMem[aPosition&PC_MASK]&7); return 2; } static int disasm_subb_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"SUBB A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_mov_rx_mem(em8051 *aCPU, int aPosition, char *aBuffer) { char mem[32];mem_mnemonic(aCPU->mCodeMem[(aPosition + 1)&PC_MASK], mem); sprintf(aBuffer,"MOV R%d, %s", aCPU->mCodeMem[aPosition&PC_MASK]&7, mem); return 2; } static int disasm_cjne_rx_imm_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"CJNE R%d, #%02Xh, #%+d", aCPU->mCodeMem[aPosition&PC_MASK]&7, aCPU->mCodeMem[(aPosition + 1)&PC_MASK], (signed char)aCPU->mCodeMem[(aPosition + 2)&PC_MASK]); return 3; } static int disasm_xch_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"XCH A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_djnz_rx_offset(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"DJNZ R%d, #%+d", aCPU->mCodeMem[aPosition&PC_MASK]&7, (signed char)aCPU->mCodeMem[(aPosition + 1)&PC_MASK]); return 2; } static int disasm_mov_a_rx(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV A, R%d",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } static int disasm_mov_rx_a(em8051 *aCPU, int aPosition, char *aBuffer) { sprintf(aBuffer,"MOV R%d, A",aCPU->mCodeMem[aPosition&PC_MASK]&7); return 1; } void disasm_setptrs(em8051 *aCPU) { int i; for (i = 0; i < 8; i++) { aCPU->dec[0x08 + i] = &disasm_inc_rx; aCPU->dec[0x18 + i] = &disasm_dec_rx; aCPU->dec[0x28 + i] = &disasm_add_a_rx; aCPU->dec[0x38 + i] = &disasm_addc_a_rx; aCPU->dec[0x48 + i] = &disasm_orl_a_rx; aCPU->dec[0x58 + i] = &disasm_anl_a_rx; aCPU->dec[0x68 + i] = &disasm_xrl_a_rx; aCPU->dec[0x78 + i] = &disasm_mov_rx_imm; aCPU->dec[0x88 + i] = &disasm_mov_mem_rx; aCPU->dec[0x98 + i] = &disasm_subb_a_rx; aCPU->dec[0xa8 + i] = &disasm_mov_rx_mem; aCPU->dec[0xb8 + i] = &disasm_cjne_rx_imm_offset; aCPU->dec[0xc8 + i] = &disasm_xch_a_rx; aCPU->dec[0xd8 + i] = &disasm_djnz_rx_offset; aCPU->dec[0xe8 + i] = &disasm_mov_a_rx; aCPU->dec[0xf8 + i] = &disasm_mov_rx_a; } aCPU->dec[0x00] = &disasm_nop; aCPU->dec[0x01] = &disasm_ajmp_offset; aCPU->dec[0x02] = &disasm_ljmp_address; aCPU->dec[0x03] = &disasm_rr_a; aCPU->dec[0x04] = &disasm_inc_a; aCPU->dec[0x05] = &disasm_inc_mem; aCPU->dec[0x06] = &disasm_inc_indir_rx; aCPU->dec[0x07] = &disasm_inc_indir_rx; aCPU->dec[0x10] = &disasm_jbc_bitaddr_offset; aCPU->dec[0x11] = &disasm_acall_offset; aCPU->dec[0x12] = &disasm_lcall_address; aCPU->dec[0x13] = &disasm_rrc_a; aCPU->dec[0x14] = &disasm_dec_a; aCPU->dec[0x15] = &disasm_dec_mem; aCPU->dec[0x16] = &disasm_dec_indir_rx; aCPU->dec[0x17] = &disasm_dec_indir_rx; aCPU->dec[0x20] = &disasm_jb_bitaddr_offset; aCPU->dec[0x21] = &disasm_ajmp_offset; aCPU->dec[0x22] = &disasm_ret; aCPU->dec[0x23] = &disasm_rl_a; aCPU->dec[0x24] = &disasm_add_a_imm; aCPU->dec[0x25] = &disasm_add_a_mem; aCPU->dec[0x26] = &disasm_add_a_indir_rx; aCPU->dec[0x27] = &disasm_add_a_indir_rx; aCPU->dec[0x30] = &disasm_jnb_bitaddr_offset; aCPU->dec[0x31] = &disasm_acall_offset; aCPU->dec[0x32] = &disasm_reti; aCPU->dec[0x33] = &disasm_rlc_a; aCPU->dec[0x34] = &disasm_addc_a_imm; aCPU->dec[0x35] = &disasm_addc_a_mem; aCPU->dec[0x36] = &disasm_addc_a_indir_rx; aCPU->dec[0x37] = &disasm_addc_a_indir_rx; aCPU->dec[0x40] = &disasm_jc_offset; aCPU->dec[0x41] = &disasm_ajmp_offset; aCPU->dec[0x42] = &disasm_orl_mem_a; aCPU->dec[0x43] = &disasm_orl_mem_imm; aCPU->dec[0x44] = &disasm_orl_a_imm; aCPU->dec[0x45] = &disasm_orl_a_mem; aCPU->dec[0x46] = &disasm_orl_a_indir_rx; aCPU->dec[0x47] = &disasm_orl_a_indir_rx; aCPU->dec[0x50] = &disasm_jnc_offset; aCPU->dec[0x51] = &disasm_acall_offset; aCPU->dec[0x52] = &disasm_anl_mem_a; aCPU->dec[0x53] = &disasm_anl_mem_imm; aCPU->dec[0x54] = &disasm_anl_a_imm; aCPU->dec[0x55] = &disasm_anl_a_mem; aCPU->dec[0x56] = &disasm_anl_a_indir_rx; aCPU->dec[0x57] = &disasm_anl_a_indir_rx; aCPU->dec[0x60] = &disasm_jz_offset; aCPU->dec[0x61] = &disasm_ajmp_offset; aCPU->dec[0x62] = &disasm_xrl_mem_a; aCPU->dec[0x63] = &disasm_xrl_mem_imm; aCPU->dec[0x64] = &disasm_xrl_a_imm; aCPU->dec[0x65] = &disasm_xrl_a_mem; aCPU->dec[0x66] = &disasm_xrl_a_indir_rx; aCPU->dec[0x67] = &disasm_xrl_a_indir_rx; aCPU->dec[0x70] = &disasm_jnz_offset; aCPU->dec[0x71] = &disasm_acall_offset; aCPU->dec[0x72] = &disasm_orl_c_bitaddr; aCPU->dec[0x73] = &disasm_jmp_indir_a_dptr; aCPU->dec[0x74] = &disasm_mov_a_imm; aCPU->dec[0x75] = &disasm_mov_mem_imm; aCPU->dec[0x76] = &disasm_mov_indir_rx_imm; aCPU->dec[0x77] = &disasm_mov_indir_rx_imm; aCPU->dec[0x80] = &disasm_sjmp_offset; aCPU->dec[0x81] = &disasm_ajmp_offset; aCPU->dec[0x82] = &disasm_anl_c_bitaddr; aCPU->dec[0x83] = &disasm_movc_a_indir_a_pc; aCPU->dec[0x84] = &disasm_div_ab; aCPU->dec[0x85] = &disasm_mov_mem_mem; aCPU->dec[0x86] = &disasm_mov_mem_indir_rx; aCPU->dec[0x87] = &disasm_mov_mem_indir_rx; aCPU->dec[0x90] = &disasm_mov_dptr_imm; aCPU->dec[0x91] = &disasm_acall_offset; aCPU->dec[0x92] = &disasm_mov_bitaddr_c; aCPU->dec[0x93] = &disasm_movc_a_indir_a_dptr; aCPU->dec[0x94] = &disasm_subb_a_imm; aCPU->dec[0x95] = &disasm_subb_a_mem; aCPU->dec[0x96] = &disasm_subb_a_indir_rx; aCPU->dec[0x97] = &disasm_subb_a_indir_rx; aCPU->dec[0xa0] = &disasm_orl_c_compl_bitaddr; aCPU->dec[0xa1] = &disasm_ajmp_offset; aCPU->dec[0xa2] = &disasm_mov_c_bitaddr; aCPU->dec[0xa3] = &disasm_inc_dptr; aCPU->dec[0xa4] = &disasm_mul_ab; aCPU->dec[0xa5] = &disasm_nop; // unused aCPU->dec[0xa6] = &disasm_mov_indir_rx_mem; aCPU->dec[0xa7] = &disasm_mov_indir_rx_mem; aCPU->dec[0xb0] = &disasm_anl_c_compl_bitaddr; aCPU->dec[0xb1] = &disasm_acall_offset; aCPU->dec[0xb2] = &disasm_cpl_bitaddr; aCPU->dec[0xb3] = &disasm_cpl_c; aCPU->dec[0xb4] = &disasm_cjne_a_imm_offset; aCPU->dec[0xb5] = &disasm_cjne_a_mem_offset; aCPU->dec[0xb6] = &disasm_cjne_indir_rx_imm_offset; aCPU->dec[0xb7] = &disasm_cjne_indir_rx_imm_offset; aCPU->dec[0xc0] = &disasm_push_mem; aCPU->dec[0xc1] = &disasm_ajmp_offset; aCPU->dec[0xc2] = &disasm_clr_bitaddr; aCPU->dec[0xc3] = &disasm_clr_c; aCPU->dec[0xc4] = &disasm_swap_a; aCPU->dec[0xc5] = &disasm_xch_a_mem; aCPU->dec[0xc6] = &disasm_xch_a_indir_rx; aCPU->dec[0xc7] = &disasm_xch_a_indir_rx; aCPU->dec[0xd0] = &disasm_pop_mem; aCPU->dec[0xd1] = &disasm_acall_offset; aCPU->dec[0xd2] = &disasm_setb_bitaddr; aCPU->dec[0xd3] = &disasm_setb_c; aCPU->dec[0xd4] = &disasm_da_a; aCPU->dec[0xd5] = &disasm_djnz_mem_offset; aCPU->dec[0xd6] = &disasm_xchd_a_indir_rx; aCPU->dec[0xd7] = &disasm_xchd_a_indir_rx; aCPU->dec[0xe0] = &disasm_movx_a_indir_dptr; aCPU->dec[0xe1] = &disasm_ajmp_offset; aCPU->dec[0xe2] = &disasm_movx_a_indir_rx; aCPU->dec[0xe3] = &disasm_movx_a_indir_rx; aCPU->dec[0xe4] = &disasm_clr_a; aCPU->dec[0xe5] = &disasm_mov_a_mem; aCPU->dec[0xe6] = &disasm_mov_a_indir_rx; aCPU->dec[0xe7] = &disasm_mov_a_indir_rx; aCPU->dec[0xf0] = &disasm_movx_indir_dptr_a; aCPU->dec[0xf1] = &disasm_acall_offset; aCPU->dec[0xf2] = &disasm_movx_indir_rx_a; aCPU->dec[0xf3] = &disasm_movx_indir_rx_a; aCPU->dec[0xf4] = &disasm_cpl_a; aCPU->dec[0xf5] = &disasm_mov_mem_a; aCPU->dec[0xf6] = &disasm_mov_indir_rx_a; aCPU->dec[0xf7] = &disasm_mov_indir_rx_a; } }; // namespace CPU }; // namespace Cube
439af0775664e9aa63459fdcb3f83cf4bb82ed35
f84dda6aa2724aa2419f796d14c70d2281df6c61
/src/event.cpp
d2b88ef240a4348cdeb1e8f88bf1c9b9dd6a7da7
[]
no_license
jovana193206/Simple-OS-kernel
0af6f32bf5b6ad9f759fac4783a8c98446703d80
59cf7a8af1c1761203ecfbfc24f3b2e852c441cb
refs/heads/master
2022-11-20T03:32:23.269335
2020-07-19T00:37:05
2020-07-19T00:37:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
event.cpp
#include "event.h"; #include "global.h"; #include "kernelEv.h"; Event::Event(IVTNo ivtNo) { #ifndef BCC_BLOCK_IGNORE lockCout #endif if(IVTEntry::allEntries[ivtNo] != 0) myImpl = new KernelEv(ivtNo); //u necijem projektu pisalo == ali nema logike ?? else myImpl = 0; #ifndef BCC_BLOCK_IGNORE unlockCout #endif } Event::~Event() { #ifndef BCC_BLOCK_IGNORE lockCout #endif delete myImpl; #ifndef BCC_BLOCK_IGNORE unlockCout #endif } void Event::wait() { #ifndef BCC_BLOCK_IGNORE lockCout #endif myImpl->wait(); #ifndef BCC_BLOCK_IGNORE unlockCout #endif } void Event::signal() { myImpl->signal(); }
0ba601b6ed15ad09951113e611a7e01311afdd3a
0b9f841e1c1110aded8323c68240dafd8d155c6d
/ch20/fig_20_10.cpp
1c83a9e31d0418306e422f59a1b075636f801f9c
[ "MIT" ]
permissive
markccchiang/pro-TBB
03ccaa99991b7f8c440cc021a43dc0180132f7ae
bddbc599d0710283eb9fbd7634b0ae8deee20907
refs/heads/master
2020-08-17T23:04:05.215295
2020-02-06T02:46:03
2020-02-06T02:46:03
215,721,549
0
0
null
2019-10-17T06:42:37
2019-10-17T06:42:35
null
UTF-8
C++
false
false
6,539
cpp
fig_20_10.cpp
/* Copyright (C) 2019 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. SPDX-License-Identifier: MIT */ #define TBB_PREVIEW_LOCAL_OBSERVER 1 #include <hwloc.h> #include <cstdio> #include <iostream> #include <cstring> #include <vector> #include <thread> #include <assert.h> #include <tbb/tbb.h> std::vector<double> times; class PinningObserver : public tbb::task_scheduler_observer { hwloc_topology_t topo; hwloc_obj_t numa_node; int numa_id; int num_nodes; tbb::atomic<int> thds_per_node; tbb::atomic<int> masters_that_entered; tbb::atomic<int> workers_that_entered; tbb::atomic<int> threads_pinned; public: PinningObserver(tbb::task_arena& arena, hwloc_topology_t& _topo, int _numa_id, int _thds_per_node) : task_scheduler_observer{arena}, topo{_topo}, numa_id{_numa_id}, thds_per_node{_thds_per_node} { num_nodes = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_NUMANODE); numa_node = hwloc_get_obj_by_type(topo, HWLOC_OBJ_NUMANODE,numa_id); masters_that_entered = 0; workers_that_entered = 0; threads_pinned = 0; observe(true); } virtual ~PinningObserver() { int nid =numa_id; int nmt = masters_that_entered, nwt = workers_that_entered; int np = threads_pinned; std::printf("Node %d, numMasters %d, numWorkers %d, numPinned %d \n", nid,nmt,nwt,np); } void on_scheduler_entry(bool is_worker) { if (is_worker) ++workers_that_entered; else ++masters_that_entered; //std::printf("Thread %d enters arena %d\n", std::this_thread::get_id(),numa_id); if(--thds_per_node > 0){ int err=hwloc_set_cpubind(topo, numa_node->cpuset, HWLOC_CPUBIND_THREAD); std::cout << "Error setting CPU bind on this platform\n"; //std::printf("Pinned thread %d to NUMA node %d\n", std::this_thread::get_id(), numa_id); threads_pinned++; } } }; void alloc_mem_per_node(hwloc_topology_t topo, double **data, long size){ int num_nodes = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_NUMANODE); for(int i=0 ; i< num_nodes ; i++){ //for each NUMA node hwloc_obj_t numa_node = hwloc_get_obj_by_type(topo, HWLOC_OBJ_NUMANODE, i); if (numa_node) { data[i] = (double *) hwloc_alloc_membind(topo, size*sizeof(double), numa_node->nodeset, HWLOC_MEMBIND_BIND, HWLOC_MEMBIND_BYNODESET); } } } void alloc_thr_per_node(hwloc_topology_t topo, double** data, size_t lsize, int thds_per_node){ float alpha = 0.5; int num_nodes = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_NUMANODE); //int nPUs = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_PU); std::vector<std::thread> vth; for(int i = 0; i < num_nodes; i++){ vth.push_back(std::thread{ [=,&topo](){ hwloc_obj_t numa_node = hwloc_get_obj_by_type(topo, HWLOC_OBJ_NUMANODE,i); int err = hwloc_set_cpubind(topo, numa_node->cpuset, HWLOC_CPUBIND_THREAD); std::cout << "Error setting CPU bind on this platform\n"; double *A = data[i]; double *B = data[i] + lsize; double *C = data[i] + 2*lsize; for(size_t j = 0; j < lsize; j++){ A[j] = j; B[j] = j; } //task_arena numa_arena(thds_per_node*num_nodes); tbb::task_arena numa_arena{thds_per_node}; PinningObserver p{numa_arena, topo, i, thds_per_node}; auto t = tbb::tick_count::now(); numa_arena.execute([&](){ tbb::parallel_for(tbb::blocked_range<size_t>{0, lsize}, [&](const tbb::blocked_range<size_t>& r){ for (size_t i = r.begin(); i < r.end(); ++i) C[i] = A[i] + alpha * B[i]; }); }); double ts = (tbb::tick_count::now() - t).seconds(); times[i] = ts; } }); } for (auto& th: vth) th.join(); } int main(int argc, char** argv) { int thds_per_node = 8; size_t vsize = 100000000; hwloc_topology_t topo; hwloc_topology_init(&topo); hwloc_topology_load(topo); //* Print the number of NUMA nodes. int num_nodes = hwloc_get_nbobjs_by_type(topo, HWLOC_OBJ_NUMANODE); std::cout << "There are " << num_nodes << " NUMA node(s)\n"; double **data = new double*[num_nodes]; times = std::vector<double>(num_nodes); //* Allocate some memory on each NUMA node long doubles_per_node = vsize*3/num_nodes; alloc_mem_per_node(topo, data, doubles_per_node); //* One master thread per NUMA node tbb::task_scheduler_init init{(thds_per_node-1)*num_nodes}; auto t = tbb::tick_count::now(); alloc_thr_per_node(topo, data, vsize/num_nodes, thds_per_node); double ts = (tbb::tick_count::now() - t).seconds(); std::cout << "Total time (incl. init A and B): " << ts << " seconds -> " //vsize * 5 (2 stores --init A & B-- + 1str + 2ld triad ) << vsize*5*8/ts/1000000.0 << " MB/s \n"; double time = times[0]; for(int i = 1; i < num_nodes; i++){ if(time < times[i]) time = times[i]; } std::cout << "Slower thread time: " << time << " seconds -> " << vsize*3*8/time/1000000.0 << " MB/s \n"; //* Free the allocated data and topology for(int i = 0; i < num_nodes; i++){ hwloc_free(topo, data[i], doubles_per_node); } hwloc_topology_destroy(topo); delete [] data; return 0; }
3e28a3fffec85ab5623355f84dff491c9850b071
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/Wrapping/ClientServer/vtkImageDataStreamerClientServer.cxx
252a3a2b0febfed83ac0a268d6007f52f0c5a040
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
5,700
cxx
vtkImageDataStreamerClientServer.cxx
// ClientServer wrapper for vtkImageDataStreamer object // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkImageDataStreamer.h" #include "vtkSystemIncludes.h" #include "vtkClientServerInterpreter.h" #include "vtkClientServerStream.h" vtkObjectBase *vtkImageDataStreamerClientServerNewCommand(void* /*ctx*/) { return vtkImageDataStreamer::New(); } int VTK_EXPORT vtkImageDataStreamerCommand(vtkClientServerInterpreter *arlu, vtkObjectBase *ob, const char *method, const vtkClientServerStream& msg, vtkClientServerStream& resultStream, void* /*ctx*/) { vtkImageDataStreamer *op = vtkImageDataStreamer::SafeDownCast(ob); if(!op) { vtkOStrStreamWrapper vtkmsg; vtkmsg << "Cannot cast " << ob->GetClassName() << " object to vtkImageDataStreamer. " << "This probably means the class specifies the incorrect superclass in vtkTypeMacro."; resultStream.Reset(); resultStream << vtkClientServerStream::Error << vtkmsg.str() << 0 << vtkClientServerStream::End; return 0; } (void)arlu; if (!strcmp("New",method) && msg.GetNumberOfArguments(0) == 2) { vtkImageDataStreamer *temp20; { temp20 = (op)->New(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("GetClassName",method) && msg.GetNumberOfArguments(0) == 2) { const char *temp20; { temp20 = (op)->GetClassName(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("IsA",method) && msg.GetNumberOfArguments(0) == 3) { char *temp0; int temp20; if(msg.GetArgument(0, 2, &temp0)) { temp20 = (op)->IsA(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("NewInstance",method) && msg.GetNumberOfArguments(0) == 2) { vtkImageDataStreamer *temp20; { temp20 = (op)->NewInstance(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("SafeDownCast",method) && msg.GetNumberOfArguments(0) == 3) { vtkObject *temp0; vtkImageDataStreamer *temp20; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkObject")) { temp20 = (op)->SafeDownCast(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("SetNumberOfStreamDivisions",method) && msg.GetNumberOfArguments(0) == 3) { int temp0; if(msg.GetArgument(0, 2, &temp0)) { op->SetNumberOfStreamDivisions(temp0); return 1; } } if (!strcmp("GetNumberOfStreamDivisions",method) && msg.GetNumberOfArguments(0) == 2) { int temp20; { temp20 = (op)->GetNumberOfStreamDivisions(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("Update",method) && msg.GetNumberOfArguments(0) == 2) { { op->Update(); return 1; } } if (!strcmp("Update",method) && msg.GetNumberOfArguments(0) == 3) { int temp0; if(msg.GetArgument(0, 2, &temp0)) { op->Update(temp0); return 1; } } if (!strcmp("UpdateWholeExtent",method) && msg.GetNumberOfArguments(0) == 2) { { op->UpdateWholeExtent(); return 1; } } if (!strcmp("SetExtentTranslator",method) && msg.GetNumberOfArguments(0) == 3) { vtkExtentTranslator *temp0; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkExtentTranslator")) { op->SetExtentTranslator(temp0); return 1; } } if (!strcmp("GetExtentTranslator",method) && msg.GetNumberOfArguments(0) == 2) { vtkExtentTranslator *temp20; { temp20 = (op)->GetExtentTranslator(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } { const char* commandName = "vtkImageAlgorithm"; if (arlu->HasCommandFunction(commandName) && arlu->CallCommandFunction(commandName, op, method, msg, resultStream)) { return 1; } } if(resultStream.GetNumberOfMessages() > 0 && resultStream.GetCommand(0) == vtkClientServerStream::Error && resultStream.GetNumberOfArguments(0) > 1) { /* A superclass wrapper prepared a special message. */ return 0; } vtkOStrStreamWrapper vtkmsg; vtkmsg << "Object type: vtkImageDataStreamer, could not find requested method: \"" << method << "\"\nor the method was called with incorrect arguments.\n"; resultStream.Reset(); resultStream << vtkClientServerStream::Error << vtkmsg.str() << vtkClientServerStream::End; vtkmsg.rdbuf()->freeze(0); return 0; } //-------------------------------------------------------------------------auto void VTK_EXPORT vtkImageDataStreamer_Init(vtkClientServerInterpreter* csi) { static vtkClientServerInterpreter* last = NULL; if(last != csi) { last = csi; csi->AddNewInstanceFunction("vtkImageDataStreamer", vtkImageDataStreamerClientServerNewCommand); csi->AddCommandFunction("vtkImageDataStreamer", vtkImageDataStreamerCommand); } }
bb961b970b4a6a10bd638de9814c0c01acd4c418
1447489eb365f12fe96a425e3ae7b27f0d2c0a2d
/client/jsc_lv/bbqmfcex/cyclient.cxx
6a9f0232d07a75da67ac0c87bdedc6dcfbc4f925
[]
no_license
chonamdoo/-live-video-chat-room
54f367f4d498e08e97bcf865de59165b2d12a1e6
f2eb23af1d14fde1f1ce6205ac61fdd6ffdc2573
refs/heads/master
2021-09-06T19:47:10.219658
2017-12-19T07:00:31
2017-12-19T07:00:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,203
cxx
cyclient.cxx
#include "bbqbase.h" #include "cyclient.h" #include "bbqclient.h" #include "stdafx.h" // #include <ptlib\debstrm.h> #define UDP_BUFFER_SIZE 32768 static void SetMinBufferSize(PUDPSocket & sock, int buftype) { int sz = 0; if (sock.GetOption(buftype, sz)) { if (sz >= UDP_BUFFER_SIZE) return; } else { PTRACE(1, "RTP_UDP\tGetOption(" << buftype << ") failed: " << sock.GetErrorText()); } if (!sock.SetOption(buftype, UDP_BUFFER_SIZE)) { PTRACE(1, "RTP_UDP\tSetOption(" << buftype << ") failed: " << sock.GetErrorText()); } PTRACE_IF(1, !sock.GetOption(buftype, sz) && sz < UDP_BUFFER_SIZE, "RTP_UDP\tSetOption(" << buftype << ") failed, even though it said it succeeded!"); } BBQClient* m_client; class NullProcess : public PProcess { PCLASSINFO(NullProcess,PProcess) public: NullProcess():PProcess("","LPNGroup"){} void Main(){} }; NullProcess * GetProcess() { static NullProcess* _process=NULL; if (!_process) _process = new NullProcess(); return _process; } #define Status(x) PString(x) extern CClient* g_clientExtern; CClient::CClient( ) { GetProcess(); #ifdef _DEBUG PTrace::Initialise(5,"DEBUGSTREAM", PTrace::Timestamp|PTrace::Thread/*|PTrace::FileAndLine*/); PTRACE(1,"ptrace enabled."); #else #endif m_client =NULL; m_client = new BBQClient(1024 ); if (m_client) { m_client->SetNetworkBaseDelay(0); //m_client->SetTcpLogin(true); } } CClient::~CClient() { delete m_client; m_client =NULL; delete GetProcess(); } bool CClient::Register(CClient *p) { g_clientExtern = p; return true; } bool CClient::czHello() { if (!m_client->IsLogin()) return false; return m_client->SendHeartbeat(); } bool CClient::IsLogin() { return m_client->IsLogin(); } bool CClient::czLeftRoom(const char* name ) { m_client->leftRoom(PString(name).AsUnsigned() ); return true; } bool CClient::czHB() { if (!m_client->IsLogin()) return false; return m_client->SendHeartbeat(); } bool CClient::czCreateRoom(const char* name, const char* members) { if (!m_client->IsLogin()) return false; PString ID = name; return m_client->requestRoom(ID.AsUnsigned() ); } bool CClient::DeAttachRequestChannel(unsigned int pChannel) { if (pChannel!=0) { BBQ_CHANNEL* p1 = (BBQ_CHANNEL*)pChannel; if (p1->sock) m_client->DetachUdpListener(p1->sock); } return true; } bool CClient::CloseRequestChannel( unsigned int& p) { if (p!=0) { BBQ_CHANNEL* p1 = (BBQ_CHANNEL*)p; if (p1->sock) m_client->DetachUdpListener(p1->sock); m_client->ReleaseChannel(p1); //delete p1; } p=0; return true; } unsigned int CClient::UdpRecvFrom(void * buf, PINDEX len,unsigned int& addr, unsigned int&port, const unsigned int pChannel) { if (pChannel) { BBQ_CHANNEL* p = (BBQ_CHANNEL*)pChannel; if(p->sock) { PIPSocket::Address addr1; WORD port1; SIM_REQUEST rxMsg; if(p->sock->ReadFrom(&rxMsg.msg, sizeof(rxMsg.msg), /*buf, len,*/ addr1, port1)) { int nRtpPacketLen = p->sock->GetLastReadCount() -sizeof(SFIDMSGHEADER); if (rxMsg.msg.simHeader.magic == SIM_MAGIC&& nRtpPacketLen== rxMsg.msg.simHeader.size) { if (nRtpPacketLen>0) { port = port1; addr = DWORD(addr1); //memset(&rxMsg,0,sizeof(rxMsg)); SIMD_CS_PINGPROXY * pQ = (SIMD_CS_PINGPROXY *) & rxMsg.msg.simData[0]; memcpy(buf, pQ->strdata, nRtpPacketLen ); } return nRtpPacketLen/*p->sock->GetLastReadCount()*/; }else return 0; } else return 0; } } else return 0; } unsigned int CClient::UdpWriteTo(const void * buf, PINDEX len, const unsigned int pChannel) { if (pChannel) { BBQ_CHANNEL* p = (BBQ_CHANNEL*)pChannel; if(p->sock) { SIM_REQUEST req; SIM_REQINIT(req, 0, 0, p->info.thisLAN.port, p->info.peerWAN.ip, p->info.peerWAN.port, SIM_CS_PINGPROXY, len/*sizeof(SIMD_CS_PINGPROXY)*/ ); SIMD_CS_PINGPROXY * pQ = (SIMD_CS_PINGPROXY *) & req.msg.simData[0]; //memset( pQ, 0, sizeof(*pQ) ); memcpy(pQ->strdata, buf, len); if(p->sock->WriteTo(&req.msg, /*req.msg.simHeader.size*/len + sizeof(SFIDMSGHEADER), p->info.peerWAN.ip, p->info.peerWAN.port )) { return p->sock->GetLastWriteCount(); } else return 0; } } else return 0; } int CClient::socketSelect(const unsigned int pChanneldata, const unsigned int pChannelControl, unsigned int timeout) { if (pChanneldata/*&& pChannelControl*/) { BBQ_CHANNEL* p = (BBQ_CHANNEL*)pChanneldata; //BBQ_CHANNEL* p2 = (BBQ_CHANNEL*)pChannelControl; if(p->sock/*&& p2->sock*/) { //PSocket::SelectList lst; //lst.Append(p->sock); return PIPSocket::Select(*(p->sock), *(p->sock), timeout); } } return 0; } int CClient::gGetErrorNumber( const unsigned int pChannel,int errorcode) { if (pChannel) { BBQ_CHANNEL* p = (BBQ_CHANNEL*)pChannel; if(p->sock) { { return p->sock->GetErrorNumber((PChannel::ErrorGroup)errorcode); } } } else return 0; } CZ_CHANNEL * CClient::RequestChannel( uint32 uid, CZ_CHANNEL *result, int type, int modes /*UDP_P2P*/) { BBQ_CHANNEL* p=m_client->RequestChannel( uid, type, "hello, the world.", type, 15000, modes ); if (p) { //memcpy(result, &(p->info), sizeof(p->info) );; result->udpsock = p->sock; result->info.thisLAN.ip = p->info.thisLAN.ip; result->info.thisLAN.port = p->info.thisLAN.port; result->info.peerWAN.port = p->info.peerWAN.port; result->info.peerWAN.ip = p->info.peerWAN.ip; result->info.peerLAN.ip = p->info.peerLAN.ip; result->info.peerLAN.port = p->info.peerLAN.port; result->addrbbqchannel = (unsigned int)p; if (p->sock) { SetMinBufferSize(*(p->sock), SO_RCVBUF); SetMinBufferSize(*(p->sock), SO_SNDBUF); } if( p->sslChannel ) { // do nothing } else if( p->tcpSock ) { //m_pChannel->tcpSock->SetWriteTimeout( m_owner.m_loadparam->tcp_channel_block_timeout * 1000 ); // 30s //m_pConn = new BBQMsgConnection(false, m_pChannel->tcpSock, false); //if( m_pConn ) { // m_owner.AttachMsgConnection( m_pConn ); //} } else if ( p->sock ) { //m_client->AttachUdpListener( p->sock ); for(int i=0;i< 4;i++) { char buf[24] ={0}; sprintf(buf, "LPN%u,%u", i, i*10); p->sock->WriteTo(buf, strlen(buf), p->info.peerWAN.ip, p->info.peerWAN.port); } } p->sock = NULL; m_client->ReleaseChannel(p); return result; }else return NULL; } bool CClient::GetFirewallInfo(unsigned int& localip, unsigned int& wanip) { BBQClient::FirewallType type; PIPSocket::Address local, wan; if (m_client->GetFirewallInfo(local, wan, type)) { localip = (DWORD)local; wanip = (DWORD)wan; }else{ return false; } return true; } bool CClient::czConnect(const char * ip,const int port, const char* strID, const char* strPassword) { if (m_client->SetServerAddress(ip, port)) { MS_TIME msStart = BBQMsgTerminal::GetHostUpTimeInMs(); uint32 major, minor, build; char* p = (char*) (const char *) "2.0"; major = strtol( p, & p, 0 ); while(*p=='.') p++; minor = strtol( p, & p, 0 ); while(*p=='.') p++; build = strtol( p, & p, 0 ); BBQUserTechParamInfo techInfo; memset( & techInfo, 0, sizeof(techInfo) ); techInfo.version = ((major & 0xff) << 24) | ((minor & 0xff) << 16) | (build & 0xffff); m_client->SetTechInfo( & techInfo ); SIMD_CS_LOGIN_EX in; SIMD_SC_LOGIN_EX out; memset( & in, 0, sizeof(in) ); memset( & out, 0, sizeof(out) ); in.vfonId.userid = strtol(strID,NULL,0); in.techParam = techInfo; MD5Encryption( in.lpszPassword, strPassword ); PTRACE( 1, "MD5 password: " << in.lpszPassword ); memcpy( in.lpszHardwareId, (const char *) "GetHardwareToken()", USERDATA_NAME_SIZE ); in.lpszHardwareId[ USERDATA_NAME_SIZE-1 ] = '\0'; in.onlineStatus = CLIENT_NORMAL;//StatusStringToInt( strStatus ); if( m_client->LoginEx( & in, & out ) ) { PTime t1( out.tStartTime ), t2( out.tExpireTime ); //Status( PString( PString::Printf, "Okay, login to %s:%d.\r\n" // "My Id: %d\r\n" // "Free time: [%s, %s], %s.\r\n" // "Points: %d\r\n" // "Access flag: %04x\r\n", // (const char *)(PString)(PIPSocket::Address)(DWORD)m_dwIP, m_nPort, // out.sessionInfo.id, // (const char *)t1.AsString("yyyy/MM/dd hh:mm:ss"), (const char *)t2.AsString("yyyy/MM/dd hh:mm:ss"), // (out.tNowServerTime < out.tExpireTime) ? "valid" : "expired", // out.nPoints, // out.accessFlags.value // ) ); m_client->SendHeartbeat(); return true; } else { PString strReason = ""; switch( out.errCode ) { case ERR_NONE: strReason = "ERR_NONE"; break; case ERR_CLIENTAPP: strReason = "ERR_CLIENTAPP"; break; case ERR_VERSION: strReason = "ERR_VERSION"; break; case ERR_AUTHFAIL: strReason = "ERR_AUTHFAIL"; break; case ERR_TOOMANY: strReason = "ERR_TOOMANY"; break; case ERR_FORBIDDEN: strReason = "ERR_FORBIDDEN"; break; case ERR_ISGROUPID: strReason = "ERR_ISGROUPID"; break; } Status( PString( PString::Printf, "Login failed, error: %d, %s, %s.\r\n", m_client->GetLastErrorCode(), (const char *) m_client->GetLastErrorString(), (const char *) strReason ) ); } } return false; } bool CClient::GetSocketWanInfoByBBQChannel(const unsigned int pChannel, unsigned int& ip, unsigned int& port) { if (pChannel) { BBQ_CHANNEL* p = (BBQ_CHANNEL*)pChannel; if(p->sock) { ip = p->info.peerWAN.ip;port = p->info.peerWAN.port; return true; } } return false; }
70dc2062a106b3319984e8d87b83aef5b1187cb4
792adcf040a9c1542c2c0adda391d75270cdd8a1
/main.cpp
0a0b24b95d904d20c0ca1481d7d686ad39df489b
[]
no_license
IlonaAK/AdressBookObjectOriented
39272977b9c945544c88126513432892384ecc98
5576082bb4ee28de369f8df8826ac745d4822366
refs/heads/master
2023-01-14T06:04:24.896263
2020-11-17T12:41:35
2020-11-17T12:41:35
307,804,551
0
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
main.cpp
#include <iostream> #include "AddressBook.h" #include "AdresatMenedzer.h" using namespace std; int main () { KsiazkaAdresowa ksiazkaAdresowa ("Uzytkownicy.txt", "Adresaci.txt"); return 0; }
c0d58541c231eaccb54b1946fc85742bdd012835
5ea21725bd5958fbfbb9434d8aad3e4b70f47f10
/include/Hexagon/BuildSystem/BuildStageFactory.hpp
a9c3e850d1bb7ba41df3bb1de1605682394f7a37
[]
no_license
MarkOates/hexagon
38610a11bee4c57afb36690d3174da47d093d2bb
f103d717848c903dc24f1e6564fdad36d4fc1e23
refs/heads/master
2023-08-31T18:00:28.302024
2023-08-28T10:35:00
2023-08-28T10:35:00
147,267,150
0
0
null
2022-08-30T22:44:12
2018-09-04T00:36:30
C++
UTF-8
C++
false
false
453
hpp
BuildStageFactory.hpp
#pragma once #include <Hexagon/BuildSystem/BuildStages/ShellCommand.hpp> #include <string> namespace Hexagon { namespace BuildSystem { class BuildStageFactory { private: protected: public: BuildStageFactory(); ~BuildStageFactory(); Hexagon::BuildSystem::BuildStages::ShellCommand* create_shell_command_build_stage(std::string shell_command="echo \"Hi friend\""); }; } }
b1ee50455cd7614378b62200edfcd4ba139a1d42
70095bef25d836d85a34f0a7d278dd17d6e907c1
/src/registerManager/registermanager.cpp
753ce93e88c262e3d7d41c063d09dde711cc4d51
[]
no_license
JosafatV/FIleSystem
75e720570d6445ca2227ffdca8217e30ea8aa7c0
c5b160202b591beceb15a7606d5d31f16141f659
refs/heads/master
2021-01-20T05:32:08.466285
2014-10-31T18:48:36
2014-10-31T18:48:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,955
cpp
registermanager.cpp
#include "src/registerManager/registermanager.h" #include "src/HeaderManager/headermanager.h" #include "src/dataStructures/SimpleList.h" #include "src/Register/register.h" #include "src/stringProcessor/decript.h" #include "readfile.h" #include "writefile.h" #include <iostream> #include <stdlib.h> #include <fstream> #include <string> #include "simpletoarr.h" using namespace std; RegisterManager::RegisterManager (string tableName, SimpleList< char* >* tableColumns, SimpleList<int>* columnsize, int regSize) { //table creation Header = new HeaderManager(regSize); Reg = new Register(tableColumns, columnsize); filesystem = new FSQLServerFileSystem(); createHardTable(tableName, tableColumns, columnsize, regSize); } void RegisterManager::createHardTable(string tableName, SimpleList<char *>* tableColumns, SimpleList<int>* columnsize, int regSize) { simpleToArr<char*>* ARR1 = new simpleToArr<char*>(); simpleToArr<int>* ARR2 = new simpleToArr<int>(); array<char*> Names = ARR1->convertFromSL(tableColumns); array<int> Sizes = ARR2->convertFromSL(columnsize); if (filesystem->createNewFile(&regSize, &Sizes, &Names, &tableName)){ cout << "| -> Table: " << tableName << " created successfully"<<endl; } } void RegisterManager::select(string tableName, SimpleList<char *>* tableColumns){ cout << tableName << Header->totalRegister() << " " <<tableColumns->getLenght() << endl; Header->resetmovingPointer(); for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator Header->movingPointer +=i*(*Header->registerSize); // movingPointer points at the beg of register if (Reg->getContentValue(Header->movingPointer) != Reg->nullChar) { //it's not empty! cout << "| "; for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); cout << Reg->getData(Header->movingPointer+Col, Col) << " | "; } cout << endl; //end of reg } }//no break; -> check all file cout << "|-------------------------------------------------|" << endl; } void RegisterManager::select(string tableName, string columnName, SimpleList<char *>* Conditions, SimpleList<int>* Booperands){ array<char*> ARR = filesystem->readFromFile(tableName, columnName, 0); for (int i = 0 ; i < ARR.getLenght() ; i++){ ARR[i]; } // Header->resetmovingPointer(); // for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator // Header->movingPointer +=i*(*Header->registerSize); // movingPointer points at the beg of register // if (Reg->getContentValue(Header->movingPointer) != Reg->nullChar && Reg->check(Header->movingPointer, Conditions, Booperands)) { //it's not empty and fulfils the conditions! // cout << "| "; // for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data // int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); // cout << Reg->getData(Header->movingPointer+Col, Col) << " | "; // } // cout << endl; //end of reg // } // }//no break; -> check all file cout << "|-------------------------------------------------|" << endl; } void RegisterManager::insertInto(string tableName, SimpleList<char*>* tableColumns, SimpleList<char*>* values){ simpleToArr<char*>* ARR1 = new simpleToArr<char*>(); simpleToArr<char*>* ARR2 = new simpleToArr<char*>(); array<char*> newColumnsarr = ARR1->convertFromSL(tableColumns); array<char*> newValuesArr = ARR2->convertFromSL(values); if(filesystem->writeNewLineToFile(tableName , &newValuesArr , &newColumnsarr)){ cout << "| Insertion successful |" << endl; }else{ cout << "| Insertion NOT successful |" << endl; Header->resetmovingPointer(); cout << *Header->freeRegister; if (*Header->freeRegister > 0) { for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator, looks for a freeRegister Header->movingPointer+=i*(*Header->registerSize); // movingPointer moves to the beg of register if (Reg->getContentValue(Header->movingPointer)==Reg->nullChar) {//we found it! for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); Reg->setData(Header->movingPointer+Col, Col, *values->elementAt(j)->getElement()); } Header->addRegister(); break; } } } else { //there are no freeRegisters, we proceed to write at the endint for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); Reg->setData(Header->EndOF+Col, Col, *values->elementAt(j)->getElement()); } Header->addRegister(); } // Header->resetmovingPointer(); // cout << *Header->freeRegister; // if (*Header->freeRegister > 0) { // for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator, looks for a freeRegister // Header->movingPointer+=i*(*Header->registerSize); // movingPointer moves to the beg of register // if (Reg->getContentValue(Header->movingPointer)==Reg->nullChar) {//we found it! // for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data // int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); // Reg->setData(Header->movingPointer+Col, Col, *values->elementAt(j)->getElement()); // } // Header->addRegister(); // break; // } // } // } else { //there are no freeRegisters, we proceed to write at the endint // for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data // int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); // Reg->setData(Header->EndOF+Col, Col, *values->elementAt(j)->getElement()); // } // Header->addRegister(); // } // cout << "| Insertion successful |" << endl; } } void RegisterManager::update(string tableName, SimpleList<char *>* tableColumns, SimpleList<char *>* values) { // simpleToArr<char*>* ARR1 = new simpleToArr<char*>(); // simpleToArr<char*>* ARR2 = new simpleToArr<char*>(); // array<char*> newColumnsarr = ARR1->convertFromSL(tableColumns); // array<char*> newValuesArr = ARR2->convertFromSL(values); // for(int i = 0 ; i < newColumnsarr.getLenght() ;i++){ // filesystem->updateColumn() // } //' Header->resetmovingPointer(); // for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator // Header->movingPointer+=i*(*Header->registerSize); // movingPointer points at the beg of register // if (Reg->check(Header->movingPointer, conditions, booperands)) {//we found it! // for (int j; j<tableColumns->getLenght(); j++) { //general column iterator, writes all data // int Col = Reg->NametoiSize(*tableColumns->elementAt(j)->getElement()); // Reg->setData(Header->movingPointer+Col, Col, *values->elementAt(j)->getElement()); // } // } // }//no break; -> check all file // cout << "| Update successful |" << endl;' } void RegisterManager::deleteFrom(string tableName, SimpleList<char *> *conditions, SimpleList<int>* booperands){ Header->resetmovingPointer(); for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator Header->movingPointer+=i*(*Header->registerSize); // movingPointer points at the beg of register if (Reg->check(Header->movingPointer, conditions, booperands)) {//we found it! Reg->setEmpty(Header->movingPointer); Header->removeRegister(); } }//no break; -> check all file } void RegisterManager::deleteFrom(string tableName, string pColumnName, string pData){ if (filesystem->deleteData(tableName,pColumnName, pData)){ cout << "| -> Table: " << tableName << " created successfully"<<endl; } // Header->resetmovingPointer(); // for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator // Header->movingPointer+=i*(*Header->registerSize); // movingPointer points at the beg of register // if (Reg->check(Header->movingPointer, conditions, booperands)) {//we found it! // Reg->setEmpty(Header->movingPointer); // Header->removeRegister(); // } // }//no break; -> check all file cout << "| Deletion Completed |" << endl; } /*///////////////////////////////////////////////////*/ void RegisterManager::createIndexOn(string tableName, SimpleList<char *>* column, string type){ simpleToArr<char*>* ARR1 = new simpleToArr<char*>(); array<char*> newColumnsarr = ARR1->convertFromSL(column); filesystem->createIndexOn(tableName , newColumnsarr , type); // Header->resetmovingPointer(); // SimpleList<char *> Nodes = SimpleList<char*>(); // int Col = Reg->NametoiSize(column->elementAt(0)->getElement()); // for (int i = 0; i<Header->totalRegister(); i++){ //general register iterator // Header->movingPointer+=i*(*Header->registerSize); // movingPointer points at the beg of register // if (Reg->getContentValue(Header->movingPointer) != Reg->nullChar) { //it's not empty! // Nodes.append(Reg->getData(Header->movingPointer+Col, Col).c_str()); // } // }//no break; -> check all file // //BTree->Index/type, Nodes); } void RegisterManager::compressTable(string tableName) { //table selection cout << "| Compression Completed |" << endl; } /*////////////////////////////////////////////////*/ void RegisterManager::backupTable(string tableName){ //table selection //Header->saveHeader(); filesystem->backUpFile(tableName); cout << "| Backup Completed |" << endl; } void RegisterManager::restoreTable(string tableName) { //table selection //Header->loadHeader(); filesystem->restoreFile(tableName); cout << "| Table Restored Successfully |" << endl; }
a6254ada6912f2328d88f4736d6dfb6ee4d9ab64
93492518f6cf0a616eaafa637a82b8310a01c1a7
/LightTheremin_Test/LightTheremin_Test.ino
8ff9e8bc8997f6e08f28ca71033604c036e4725b
[]
no_license
MrWizard69/Wilson_Final_Project
cfecab0fe3512b29bd6ce3f51946321bc1512b53
4ef7d4d94703c7142909f99383107b28c0778e7c
refs/heads/master
2016-09-07T04:23:15.981451
2015-05-29T18:47:15
2015-05-29T18:47:15
33,157,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
ino
LightTheremin_Test.ino
/* Arduino Starter Kit example Modified Project 6 - Light Theremin Parts required: photoresistor 10 kilohm resistor piezo http://arduino.cc/starterKit This example code is part of the public domain */ // variable to hold sensor value int sensorValue; // variable to calibrate low value int sensorLow = 1023; // variable to calibrate high value int sensorHigh = 0; void setup() { Serial.begin(9600); // calibrate for the first five seconds after program runs while (millis() < 5000) { // record the maximum sensor value sensorValue = analogRead(A0); if (sensorValue > sensorHigh) { sensorHigh = sensorValue; } // record the minimum sensor value if (sensorValue < sensorLow) { sensorLow = sensorValue; } } Serial.println("Done Checking Lights..."); delay(2000); } void loop() { //read the input from A0 and store it in a variable sensorValue = analogRead(A0); // Shows the light value/intensity Serial.println(sensorValue); // wait for a moment delay(10); }
321f003f56cd161043da0ccdbb5467015a01be07
5f04086a1c242aee48655d9c7c0d2d3fbf646867
/front/source/symbol_table.cpp
bd93e984605b63cda3af62db01d4285d00a710fc
[ "MIT" ]
permissive
fanyi3315/Merdog
539fd094e4f22c2221380e76b052c45f2d06c113
60303b0cbcd0c03e493606b8c535a975f8d56185
refs/heads/master
2020-09-10T04:07:31.984558
2019-11-14T05:02:23
2019-11-14T05:02:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,437
cpp
symbol_table.cpp
#include "../include/symbol_table.hpp" #include "../include/type.hpp" namespace mer { // symbol table for user SymbolTable _symbol_table; std::string get_tmp_var_name(bool c) { static int index = 0; if (c) { index = 0; return ""; } return "%" + std::to_string(index++); } WordRecorder* find_recorder_by_id(const std::string& str) { auto result = _symbol_table.find(str); if (result == nullptr) throw Error(" id: " + str + " hasn't been defined yet!"); return result; } void SymbolTable::type_check(Token* id, WordRecorder::SymbolTag e) { auto result = find(Id::get_value(id)); if (result == nullptr) throw Error("id " + id->to_string() + " no found."); if (result->symbol_type != e) throw Error("id typ not matched"); } WordRecorder* SymbolTable::find_front(std::string id) { auto result = data.front().find(id); if (result == data.front().end()) return nullptr; return result->second; } WordRecorder* SymbolTable::find(std::string id) { for (int i = 0; i < data.size(); i++) { auto result = data[i].find(id); if (result != data[i].end()) { return result->second; } } return nullptr; } void SymbolTable::print() { for (const auto& a : data) { for (const auto& b : a) { std::cout << "ID:" << b.first << " TYPE:" << b.second->type->name() << std::endl;; } std::cout << "=================================\n"; } std::cout << "#########################################\n\n\n"; } }
d9777f10b63691d512d0d1efff24361b3259efb9
8164dd9ec33a14acdeda6c148c33de5ff30c91ae
/src/StructuralPattern/FlyweightPattern/FlyweightPattern/UnsharedConcreteFlyweight.h
41d87c909cc31a3196a54305c071df56898bcd8b
[]
no_license
kingdekong/Design-Patterns
a4ff6d5e91d5d401f8de5b2943a2de2d25d3f805
cf0dc873d92f45d3457405b5dc670f290974eac6
refs/heads/master
2020-03-29T08:37:34.061320
2018-09-21T08:56:23
2018-09-21T08:56:23
149,719,919
6
0
null
null
null
null
UTF-8
C++
false
false
307
h
UnsharedConcreteFlyweight.h
#ifndef _HEADER_UnsharedConcreteFlyweight_ #define _HEADER_UnsharedConcreteFlyweight_ class UnsharedConcreteFlyweight { public: UnsharedConcreteFlyweight(); virtual ~UnsharedConcreteFlyweight(); void operation(); private: int allState; }; #endif // !_HEADER_UnsharedConcreteFlyweight_
958496d3cc737ae11bda5ffad54a4b75e347b1b3
05df3699579aba2879d2dd6c4de421e7d4e75c61
/src/plugins/updaters/qchocolatey/qchocolateyupdaterbackend.h
17d831b0d3d5924abc16f2a37fde721e698d00fa
[ "BSD-3-Clause" ]
permissive
Skycoder42/QtAutoUpdater
2474f1df5b8cbbdb63319110941adec99082a4c3
762710464659176d1e41e0dc475e6f23c1b278ad
refs/heads/master
2023-03-17T01:10:59.086734
2023-03-04T10:55:51
2023-03-04T10:55:51
48,326,244
731
183
BSD-3-Clause
2022-03-28T05:56:51
2015-12-20T15:26:26
C++
UTF-8
C++
false
false
1,260
h
qchocolateyupdaterbackend.h
#ifndef QCHOCOLATEYUPDATERBACKEND_H #define QCHOCOLATEYUPDATERBACKEND_H #include <QtCore/QLoggingCategory> #include <QtAutoUpdaterCore/ProcessBackend> class QChocolateyUpdaterBackend : public QtAutoUpdater::ProcessBackend { Q_OBJECT public: explicit QChocolateyUpdaterBackend(QString &&key, QObject *parent = nullptr); Features features() const override; SecondaryInfo secondaryInfo() const override; void checkForUpdates() override; QtAutoUpdater::UpdateInstaller *createInstaller() override; protected: bool initialize() override; void onToolDone(int id, int exitCode, QIODevice *processDevice) override; std::optional<InstallProcessInfo> installerInfo(const QList<QtAutoUpdater::UpdateInfo> &infos, bool track) override; private: static const QString KeyPackages; static const QString KeyPath; static const QString KeyExtraCheckArgs; static const QString KeyGuiExePath; static const QString KeyExtraGuiArgs; static const QString KeyRunAsAdmin; static const QString DefaultGuiExePath; static constexpr bool DefaultRunAsAdmin {true}; QProcess *_chocoProc = nullptr; QStringList _packages; QString chocoPath() const; QString guiPath() const; }; Q_DECLARE_LOGGING_CATEGORY(logChocoBackend) #endif // QCHOCOLATEYUPDATERBACKEND_H
de1f1e38a06a482d80541bea543b267fb1fc4e32
e9ca469cc84f3431538c04e5e3f7fbeedefd07a0
/util.h
ee21f1af4240272c9424673e650b21b7381106e4
[ "MIT" ]
permissive
daodun/ls1-sys-prog-task6-sockets-YukioZzz
b6c35211cd545907ac1275aab8c1edbe4f2b1b86
2a70f5e62a5d686ebb84e2a44c97eec29fee1f58
refs/heads/main
2023-08-18T16:23:00.080276
2021-06-23T21:19:22
2021-06-23T21:19:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,208
h
util.h
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <signal.h> #include <cstring> #include <iostream> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <algorithm> #include <memory> /** * It takes as arguments one char[] array of 4 or bigger size and an integer. * It converts the integer into a byte array. */ void convertIntToByteArray(char* dst, int sz) { auto tmp = dst; tmp[0] = (sz >> 24) & 0xFF; tmp[1] = (sz >> 16) & 0xFF; tmp[2] = (sz >> 8) & 0xFF; tmp[3] = sz & 0xFF; } /** * It takes as an argument a ptr to an array of size 4 or bigger and * converts the char array into an integer. */ int convertByteArrayToInt(char* b) { return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF); } /** * It constructs the message to be sent. * It takes as arguments a destination char ptr, the payload (data to be sent) * and the payload size. * It returns the expected message format at dst ptr; * * |<---msg size (4 bytes)--->|<---payload (msg size bytes)--->| * * */ void construct_message(char* dst, char* payload, size_t payload_size) { // TODO: int psize=int(payload_size); convertIntToByteArray(dst,psize); //how to control the size of dst? for(int i=0;i<psize;i++){ dst[i+4] = payload[i]; } } /** * It returns the actual size of msg. * Not that msg might not contain all payload data. * The function expects at least that the msg contains the first 4 bytes that * indicate the actual size of the payload. */ int get_payload_size(char* msg, size_t bytes) { // TODO: return convertByteArrayToInt(msg); } /** * Sends to the connection defined by the fd, a message with a payload (data) of size len bytes. * The fd should be non-blocking socket. */ int secure_send(int fd, char* data, size_t len) { // TODO: int sentbyte; len = len+4; auto dst = std::make_unique<char[]>(len); construct_message(dst.get(),data,len-4); sentbyte = send(fd,dst.get(),len,0); int offset = sentbyte; while(len-offset){ sentbyte = send(fd, dst.get()+offset, len-offset,0); if(sentbyte==-1)return -1; offset += sentbyte; } return offset-4; } /** * Receives a message from the fd (non-blocking) and stores it in buf. */ int secure_recv(int fd, std::unique_ptr<char[]>& buf) { // TODO static int cnt; ssize_t recvedbyte; char header[4]; while(recv(fd, header, 4,0) == -1)continue; int len = convertByteArrayToInt(header); buf = std::make_unique<char[]>(len); char* ptr = buf.get(); int count = len; while(count>0){ recvedbyte = recv(fd, ptr, count, 0); if(recvedbyte==-1){continue;} ///> for nothing received but still under connection if(recvedbyte==0){return 0;} ///> for disconnection ptr += recvedbyte; count -= recvedbyte; } ++cnt; return len; }
d97c378c46d112b869da5447d3c8a2cef403ece9
2efc8493e4df2b5304f007cf0bd1e03a629120cb
/popen-example/myuclc.cpp
2db098c506354f1e1c47c99108ffcca045279166
[]
no_license
luyongkang/Linux-code
46ba399fe5baa2f1f928a5aea63027246ba9b323
7b82ea09968e08b69e8296414a91d7501be26c10
refs/heads/master
2023-04-03T23:46:53.533978
2021-04-13T06:48:15
2021-04-13T06:48:15
301,134,422
0
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
myuclc.cpp
#include<iostream> #include<ctype.h> using namespace std; int main() { int c; while((c=getchar())!=EOF) { if(isupper(c)) { c = tolower(c); } else if(islower(c)) { c = toupper(c); } if(putchar(c)==EOF) { cerr << "output error" << endl; } if(c=='\n') { fflush(stdout); } } return 0; }
154d588d399505722ad5019e069a2ebe0b649025
8a82e2252b2336772aa4825804154a48751c2b5f
/utilities/include/helper/SNoCopyable.hpp
ad3d611711077de683240352d5b0bfac8271ce2a
[ "MIT" ]
permissive
wrongswany/soui
a778a2b0f2e5b2eb3a929b94741144d66a5db709
00ed1f21af02877dd2be4881b1caccc168ed9a9b
refs/heads/master
2020-04-19T23:41:32.464597
2019-01-31T01:26:24
2019-01-31T01:26:24
168,502,695
2
0
NOASSERTION
2019-01-31T09:58:47
2019-01-31T09:58:47
null
UTF-8
C++
false
false
293
hpp
SNoCopyable.hpp
#pragma once namespace SOUI { /** * Inheriate this class to make your class cannot be copy and assign. * */ class SNoCopyable { public: SNoCopyable() {} ~SNoCopyable() {} private: SNoCopyable(const SNoCopyable &); const SNoCopyable &operator=(const SNoCopyable &); }; }
b3060e37d810a021aeff406f35e22139d453d482
4ccf7aa23ae97ce06ebbea5ecb311d9e5604d28a
/2018codes/2018-08-25 HDU-6446丨找规律丨排列组合丨细心.cpp
adc866a7837a757303a33e3011c97959d514c68c
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
TieWay59/HappyACEveryday
25682d30aafed3a51f645562fb7e5348e9515417
6474a05a9eafc83e9c185ba8e6d716f7d44eade0
refs/heads/master
2021-08-22T21:29:31.138853
2021-06-16T04:19:14
2021-06-16T04:19:14
190,430,779
3
1
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
2018-08-25 HDU-6446丨找规律丨排列组合丨细心.cpp
/*http://acm.hdu.edu.cn/showproblem.php?pid=6446 ??????е??????????????Щ????x */ #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int mod = 1e9 + 7; const int N = 1e5 + 5; typedef long long ll; ll sum[N], ans; int head[N], cnted, n; bool vis[N]; struct Edge { int nx, v; ll w; } ed[N + N]; void AddEd(int u, int v, int w) { ed[++cnted] = {head[u], v, (ll) w}; head[u] = cnted; } void dfs(int u) { vis[u] = true; sum[u] = 1ll; for (int v, i = head[u]; ~i; i = ed[i].nx) { v = ed[i].v; if (vis[v])continue; dfs(v); sum[u] = (sum[u] + sum[v]) % mod; ans += 1ll * sum[v] * (n - sum[v]) % mod * ed[i].w % mod; } } int main() { while (scanf("%d", &n) != EOF) { memset(head, -1, sizeof head); memset(vis, false, sizeof vis); ans = 0; cnted = 0; for (int i = 1, u, v, w; i < n; i++) { scanf("%d%d%d", &u, &v, &w); AddEd(u, v, w); AddEd(v, u, w); } dfs(1); for (ll i = 1; i < n; i++) ans = ans * i % mod; ans = ans * 2ll % mod; printf("%lld\n", ans); } return 0; } /* */