text
stringlengths
54
60.6k
<commit_before>83000e37-2d15-11e5-af21-0401358ea401<commit_msg>83000e38-2d15-11e5-af21-0401358ea401<commit_after>83000e38-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>097256d8-2f67-11e5-ab2e-6c40088e03e4<commit_msg>0978f2fe-2f67-11e5-8e3c-6c40088e03e4<commit_after>0978f2fe-2f67-11e5-8e3c-6c40088e03e4<|endoftext|>
<commit_before>d4027086-35ca-11e5-a563-6c40088e03e4<commit_msg>d4094c8a-35ca-11e5-9fc8-6c40088e03e4<commit_after>d4094c8a-35ca-11e5-9fc8-6c40088e03e4<|endoftext|>
<commit_before>94cda1e1-327f-11e5-8087-9cf387a8033e<commit_msg>94d3cfde-327f-11e5-8f4c-9cf387a8033e<commit_after>94d3cfde-327f-11e5-8f4c-9cf387a8033e<|endoftext|>
<commit_before>41e461a6-2e3a-11e5-a69d-c03896053bdd<commit_msg>41f26df8-2e3a-11e5-beef-c03896053bdd<commit_after>41f26df8-2e3a-11e5-beef-c03896053bdd<|endoftext|>
<commit_before>b3ae9921-327f-11e5-b7ec-9cf387a8033e<commit_msg>b3b4be40-327f-11e5-b7cf-9cf387a8033e<commit_after>b3b4be40-327f-11e5-b7cf-9cf387a8033e<|endoftext|>
<commit_before>bcb095c0-2e4f-11e5-9974-28cfe91dbc4b<commit_msg>bcb74ba3-2e4f-11e5-bb92-28cfe91dbc4b<commit_after>bcb74ba3-2e4f-11e5-bb92-28cfe91dbc4b<|endoftext|>
<commit_before>9198a82e-4b02-11e5-b230-28cfe9171a43<commit_msg>fix for the previous fix<commit_after>91a8d6a6-4b02-11e5-ac80-28cfe9171a43<|endoftext|>
<commit_before>133c9697-ad5b-11e7-babe-ac87a332f658<commit_msg>Test..<commit_after>13d9774a-ad5b-11e7-8549-ac87a332f658<|endoftext|>
<commit_before>3341f642-2e4f-11e5-9a97-28cfe91dbc4b<commit_msg>33480805-2e4f-11e5-9668-28cfe91dbc4b<commit_after>33480805-2e4f-11e5-9668-28cfe91dbc4b<|endoftext|>
<commit_before>6540c0c2-2fa5-11e5-8d7d-00012e3d3f12<commit_msg>65429586-2fa5-11e5-8d7d-00012e3d3f12<commit_after>65429586-2fa5-11e5-8d7d-00012e3d3f12<|endoftext|>
<commit_before>8d6dfcd3-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcd4-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcd4-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>83000e41-2d15-11e5-af21-0401358ea401<commit_msg>83000e42-2d15-11e5-af21-0401358ea401<commit_after>83000e42-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f43877e8-327f-11e5-9c38-9cf387a8033e<commit_msg>f43e4bab-327f-11e5-acf3-9cf387a8033e<commit_after>f43e4bab-327f-11e5-acf3-9cf387a8033e<|endoftext|>
<commit_before>f2ea43d8-585a-11e5-b723-6c40088e03e4<commit_msg>f2f0d728-585a-11e5-b857-6c40088e03e4<commit_after>f2f0d728-585a-11e5-b857-6c40088e03e4<|endoftext|>
<commit_before>a0314c45-2e4f-11e5-95fd-28cfe91dbc4b<commit_msg>a0381c61-2e4f-11e5-a5f8-28cfe91dbc4b<commit_after>a0381c61-2e4f-11e5-a5f8-28cfe91dbc4b<|endoftext|>
<commit_before>// gl-stuff #include <GL/glew.h> #include <GLFW/glfw3.h> // GLFW helper library #include <GL/glu.h> // std stuff #include <stdio.h> #include <iostream> #include <vector> #include <array> #define printOpenGLError() printOglError(__FILE__, __LINE__) int printOglError(const char* file, int line) { GLenum glErr; int retCode = 0; glErr = glGetError(); if (glErr != GL_NO_ERROR) { printf("glError in file %s @ line %d: %s\n", file, line, gluErrorString(glErr)); retCode = 1; } return retCode; } void GLAPIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { printf("0x%X: %s\n", id, message); } GLFWwindow* setupOpenGLContextWindow(unsigned int numSamples, bool useGLDebugOutput) { // start GL context and O/S window using the GLFW helper library if (!glfwInit()) { throw std::runtime_error("ERROR: could not start GLFW3\n"); } glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, numSamples); GLFWwindow* window = glfwCreateWindow(1, 1, "glSampleIDCheck", NULL, NULL); if (!window) { glfwTerminate(); throw std::runtime_error("ERROR: could not open window with GLFW3\n"); } glfwMakeContextCurrent(window); // start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); if (useGLDebugOutput) { glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(DebugCallback, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } if (useGLDebugOutput) { // get version info const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string const GLubyte* version = glGetString(GL_VERSION); // version as a string printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); } return window; } void checkShaderCompilation(GLuint shader) { GLint success = GL_TRUE; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { GLint maxLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); std::vector<GLchar> errorLog(maxLength); glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]); for (auto const& character : errorLog) { std::cout << character; } std::cout << std::endl; } } GLuint setupShaderProgram() { const char* vertex_shader = "#version 400\n" "in vec3 vp;" "void main () {" " vec2 texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );" " gl_Position = vec4( texcoord * vec2( 2.0f, -2.0f ) + vec2( -1.0f, " "1.0f), 0.0f, 1.0f );" "}"; const char* fragment_shader = "#version 440\n" "layout(binding = 0) uniform atomic_uint atomic_counter;" "void main () {" //ensure that only one fragment counts, should be redundant due to 1px size of the window " if( ivec2( gl_FragCoord.xy ) == ivec2( 0, 0 ) ){" " for(uint i = 0; i<gl_SampleID; ++i){" " atomicCounterIncrement(atomic_counter);" " }" " }" "}"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertex_shader, NULL); glCompileShader(vs); checkShaderCompilation(vs); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragment_shader, NULL); glCompileShader(fs); checkShaderCompilation(fs); GLuint shader_programm = glCreateProgram(); glAttachShader(shader_programm, fs); glAttachShader(shader_programm, vs); glLinkProgram(shader_programm); return shader_programm; } GLuint* setupBuffers(GLuint& vao, GLuint& atomicBuffer) { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glCreateBuffers(1, &atomicBuffer); printOpenGLError(); GLuint const data = 0; GLbitfield usageFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; glNamedBufferStorage(atomicBuffer, sizeof(data), &data, usageFlags); printOpenGLError(); auto mappedBuffer = static_cast<GLuint*>( glMapNamedBufferRange(atomicBuffer, 0, sizeof(data), usageFlags)); printOpenGLError(); return mappedBuffer; } void testSumOfGLSLSampleIDs(unsigned int numSamples, bool useGLDebugOutput) { GLFWwindow* window = setupOpenGLContextWindow(numSamples, useGLDebugOutput); printOpenGLError(); GLuint vaoID, atomicCounterID; auto atomicCounter = setupBuffers(vaoID, atomicCounterID); printOpenGLError(); GLuint shader_programm = setupShaderProgram(); printOpenGLError(); std::cout << "atomic Counter initial value: " << atomicCounter[0] << " | 0 is correct" << std::endl; // wipe the drawing surface clear glUseProgram(shader_programm); glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, atomicCounterID, 0, sizeof(GLuint)); glBindVertexArray(vaoID); // draw fullscreen triangle created in vertex shader based on the VertexID glDrawArrays(GL_TRIANGLES, 0, 3); // update other events like input handling glfwPollEvents(); // put the stuff we've been drawing onto the display glfwSwapBuffers(window); glFinish(); unsigned int correctSumOfSampleIDs = 0; for (unsigned int i = 0; i < numSamples; ++i) { correctSumOfSampleIDs += i; } std::cout << "sum of gl_SampleIDs: " << atomicCounter[0] << " | " << correctSumOfSampleIDs << " is correct" << std::endl; // close GL context and any other GLFW resources glfwTerminate(); } int main(int argc, char* argv[]) { std::array<unsigned int, 5> listOfSamples{2, 4, 8, 16, 32}; for (auto const& numSamples : listOfSamples) { std::cout << "numSamples: " << numSamples << std::endl; testSumOfGLSLSampleIDs(numSamples, false); std::cout << std::endl; } return 0; } <commit_msg>Querying sampling limits<commit_after>// gl-stuff #include <GL/glew.h> #include <GLFW/glfw3.h> // GLFW helper library #include <GL/glu.h> // std stuff #include <stdio.h> #include <iostream> #include <vector> #include <array> #define printOpenGLError() printOglError(__FILE__, __LINE__) int printOglError(const char* file, int line) { GLenum glErr; int retCode = 0; glErr = glGetError(); if (glErr != GL_NO_ERROR) { printf("glError in file %s @ line %d: %s\n", file, line, gluErrorString(glErr)); retCode = 1; } return retCode; } void GLAPIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { printf("0x%X: %s\n", id, message); } GLFWwindow* setupOpenGLContextWindow(unsigned int numSamples, bool useGLDebugOutput) { // start GL context and O/S window using the GLFW helper library if (!glfwInit()) { throw std::runtime_error("ERROR: could not start GLFW3\n"); } glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, numSamples); GLFWwindow* window = glfwCreateWindow(1, 1, "glSampleIDCheck", NULL, NULL); if (!window) { glfwTerminate(); throw std::runtime_error("ERROR: could not open window with GLFW3\n"); } glfwMakeContextCurrent(window); // start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); if (useGLDebugOutput) { glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(DebugCallback, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } if (useGLDebugOutput) { // get version info const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string const GLubyte* version = glGetString(GL_VERSION); // version as a string printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); } return window; } void checkShaderCompilation(GLuint shader) { GLint success = GL_TRUE; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { GLint maxLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); std::vector<GLchar> errorLog(maxLength); glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]); for (auto const& character : errorLog) { std::cout << character; } std::cout << std::endl; } } GLuint setupShaderProgram() { const char* vertex_shader = "#version 400\n" "in vec3 vp;" "void main () {" " vec2 texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );" " gl_Position = vec4( texcoord * vec2( 2.0f, -2.0f ) + vec2( -1.0f, " "1.0f), 0.0f, 1.0f );" "}"; const char* fragment_shader = "#version 440\n" "layout(binding = 0) uniform atomic_uint atomic_counter;" "void main () {" //ensure that only one fragment counts, should be redundant due to 1px size of the window " if( ivec2( gl_FragCoord.xy ) == ivec2( 0, 0 ) ){" " for(uint i = 0; i<gl_SampleID; ++i){" " atomicCounterIncrement(atomic_counter);" " }" " }" "}"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertex_shader, NULL); glCompileShader(vs); checkShaderCompilation(vs); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragment_shader, NULL); glCompileShader(fs); checkShaderCompilation(fs); GLuint shader_programm = glCreateProgram(); glAttachShader(shader_programm, fs); glAttachShader(shader_programm, vs); glLinkProgram(shader_programm); return shader_programm; } GLuint* setupBuffers(GLuint& vao, GLuint& atomicBuffer) { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glCreateBuffers(1, &atomicBuffer); printOpenGLError(); GLuint const data = 0; GLbitfield usageFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; glNamedBufferStorage(atomicBuffer, sizeof(data), &data, usageFlags); printOpenGLError(); auto mappedBuffer = static_cast<GLuint*>( glMapNamedBufferRange(atomicBuffer, 0, sizeof(data), usageFlags)); printOpenGLError(); return mappedBuffer; } GLint get(GLenum name) { GLint value = -1; glGetIntegerv(name, &value); return value; } void testSumOfGLSLSampleIDs(unsigned int numSamples, bool useGLDebugOutput) { GLFWwindow* window = setupOpenGLContextWindow(numSamples, useGLDebugOutput); printOpenGLError(); #define GLGET(NAME) std::cout << #NAME ": " << get(NAME) << "\n" GLGET(GL_MAX_COLOR_TEXTURE_SAMPLES); GLGET(GL_MAX_DEPTH_TEXTURE_SAMPLES); GLGET(GL_MAX_FRAMEBUFFER_SAMPLES); GLuint vaoID, atomicCounterID; auto atomicCounter = setupBuffers(vaoID, atomicCounterID); printOpenGLError(); GLuint shader_programm = setupShaderProgram(); printOpenGLError(); std::cout << "atomic Counter initial value: " << atomicCounter[0] << " | 0 is correct" << std::endl; // wipe the drawing surface clear glUseProgram(shader_programm); glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, atomicCounterID, 0, sizeof(GLuint)); glBindVertexArray(vaoID); // draw fullscreen triangle created in vertex shader based on the VertexID glDrawArrays(GL_TRIANGLES, 0, 3); // update other events like input handling glfwPollEvents(); // put the stuff we've been drawing onto the display glfwSwapBuffers(window); glFinish(); unsigned int correctSumOfSampleIDs = 0; for (unsigned int i = 0; i < numSamples; ++i) { correctSumOfSampleIDs += i; } std::cout << "sum of gl_SampleIDs: " << atomicCounter[0] << " | " << correctSumOfSampleIDs << " is correct" << std::endl; // close GL context and any other GLFW resources glfwTerminate(); } int main(int argc, char* argv[]) { std::array<unsigned int, 5> listOfSamples{2, 4, 8, 16, 32}; for (auto const& numSamples : listOfSamples) { std::cout << "numSamples: " << numSamples << std::endl; testSumOfGLSLSampleIDs(numSamples, false); std::cout << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <string> #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_primitives.h> #include <enet/enet.h> #include "inputcatcher.h" #include "engine.h" #include "renderer.h" #include "datastructures.h" #include "global_constants.h" #include "mainmenu.h" long int getmillisec(); int main(int argc, char **argv) { // Initialize Allegro if (!al_init()) { fprintf(stderr, "Fatal Error: Allegro initialization failed!\n"); return -1; } // Initialize the Allegro Image addon, used to load sprites and maps if (!al_init_image_addon()) { fprintf(stderr, "Fatal Error: Allegro Image Addon initialization failed!\n"); return -1; } // Initialize primitives for drawing if (!al_init_primitives_addon()) { fprintf(stderr, "Fatal Error: Could not initialize primitives module!"); throw -1; } // Initialize keyboard modules if (!al_install_keyboard()) { fprintf(stderr, "Fatal Error: Could not initialize keyboard module!"); throw -1; } // Initialize mouse if (!al_install_mouse()) { fprintf(stderr, "Fatal Error: Could not initialize mouse module!"); throw -1; } // Initialize networking system if (enet_initialize()) { fprintf(stderr, "Fatal Error: Could not initialize enet!"); throw -1; } // Create a display ALLEGRO_DISPLAY *display; al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE); al_set_new_display_flags(ALLEGRO_OPENGL); display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT); if(!display) { // FIXME: Make the error argument mean anything? fprintf(stderr, "Fatal Error: Could not create display\n"); throw -1; } //load font //gg2 font as placeholder for now i guess al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_FONT *font = al_load_font("gg2bold.ttf", 12, ALLEGRO_TTF_MONOCHROME); if (!font) { fprintf(stderr, "Could not load 'gg2bold.ttf'.\n"); throw -1; } // MainMenu *mainmenu = new MainMenu(display); bool isserver; if (argc >= 2) { // If there are any arguments isserver = false; } else { isserver = true; } double lasttimeupdated = al_get_time(); // bool run = true; // while (run) // { // if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP) // { // run = mainmenu->run(display, &gametype); // lasttimeupdated = al_get_time(); // } // } // delete mainmenu; InputCatcher *inputcatcher; Engine *engine; Renderer *renderer; Gamestate *renderingstate; try { // Initialize everything // The various allegro initializations can throw errors engine = new Engine(isserver); renderer = new Renderer(font); inputcatcher = new InputCatcher(display); renderingstate = new Gamestate(engine); } catch (int e) { if (e == -1) { fprintf(stderr, "\nAllegro initialization failed."); } else { fprintf(stderr, "\nUNKNOWN ERROR HAPPENED"); } return -1; } engine->loadmap("conflict"); EntityPtr myself = engine->newplayer(); // FIXME: Hack to make sure the oldstate is properly initialized engine->update(0); lasttimeupdated = al_get_time(); while (true) { try { while (al_get_time() - lasttimeupdated >= ENGINE_TIMESTEP) { inputcatcher->run(myself, engine, renderer); engine->update(ENGINE_TIMESTEP); lasttimeupdated += ENGINE_TIMESTEP; } renderingstate->interpolate(engine->oldstate.get(), engine->currentstate.get(), (al_get_time()-lasttimeupdated)/ENGINE_TIMESTEP); renderer->render(display, renderingstate, myself); } catch (int e) { if (e != 0) { fprintf(stderr, "\nError during regular loop."); fprintf(stderr, "\nExiting.."); } al_destroy_display(display); return 0; } } al_destroy_display(display); enet_deinitialize(); return 0; } <commit_msg>Replaced some not-freed pointers with unique_ptrs.<commit_after>#include <cstdio> #include <string> #include <memory> #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_primitives.h> #include <enet/enet.h> #include "inputcatcher.h" #include "engine.h" #include "renderer.h" #include "datastructures.h" #include "global_constants.h" #include "mainmenu.h" long int getmillisec(); int main(int argc, char **argv) { // Initialize Allegro if (!al_init()) { fprintf(stderr, "Fatal Error: Allegro initialization failed!\n"); return -1; } // Initialize the Allegro Image addon, used to load sprites and maps if (!al_init_image_addon()) { fprintf(stderr, "Fatal Error: Allegro Image Addon initialization failed!\n"); return -1; } // Initialize primitives for drawing if (!al_init_primitives_addon()) { fprintf(stderr, "Fatal Error: Could not initialize primitives module!"); throw -1; } // Initialize keyboard modules if (!al_install_keyboard()) { fprintf(stderr, "Fatal Error: Could not initialize keyboard module!"); throw -1; } // Initialize mouse if (!al_install_mouse()) { fprintf(stderr, "Fatal Error: Could not initialize mouse module!"); throw -1; } // Initialize networking system if (enet_initialize()) { fprintf(stderr, "Fatal Error: Could not initialize enet!"); throw -1; } // Create a display ALLEGRO_DISPLAY *display; al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE); al_set_new_display_flags(ALLEGRO_OPENGL); display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT); if(!display) { // FIXME: Make the error argument mean anything? fprintf(stderr, "Fatal Error: Could not create display\n"); throw -1; } //load font //gg2 font as placeholder for now i guess al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_FONT *font = al_load_font("gg2bold.ttf", 12, ALLEGRO_TTF_MONOCHROME); if (!font) { fprintf(stderr, "Could not load 'gg2bold.ttf'.\n"); throw -1; } // MainMenu *mainmenu = new MainMenu(display); bool isserver; if (argc >= 2) { // If there are any arguments isserver = false; } else { isserver = true; } double lasttimeupdated = al_get_time(); // bool run = true; // while (run) // { // if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP) // { // run = mainmenu->run(display, &gametype); // lasttimeupdated = al_get_time(); // } // } // delete mainmenu; std::unique_ptr<Engine> engine; std::unique_ptr<Renderer> renderer; std::unique_ptr<InputCatcher> inputcatcher; std::unique_ptr<Gamestate> renderingstate; try { // Initialize everything // The various allegro initializations can throw errors engine = std::unique_ptr<Engine>(new Engine(isserver)); renderer = std::unique_ptr<Renderer>(new Renderer(font)); inputcatcher = std::unique_ptr<InputCatcher>(new InputCatcher(display)); renderingstate = std::unique_ptr<Gamestate>(new Gamestate(engine.get())); } catch (int e) { if (e == -1) { fprintf(stderr, "\nAllegro initialization failed."); } else { fprintf(stderr, "\nUNKNOWN ERROR HAPPENED"); } return -1; } engine->loadmap("conflict"); EntityPtr myself = engine->newplayer(); // FIXME: Hack to make sure the oldstate is properly initialized engine->update(0); lasttimeupdated = al_get_time(); while (true) { try { while (al_get_time() - lasttimeupdated >= ENGINE_TIMESTEP) { inputcatcher->run(myself, engine.get(), renderer.get()); engine->update(ENGINE_TIMESTEP); lasttimeupdated += ENGINE_TIMESTEP; } renderingstate->interpolate(engine->oldstate.get(), engine->currentstate.get(), (al_get_time()-lasttimeupdated)/ENGINE_TIMESTEP); renderer->render(display, renderingstate.get(), myself); } catch (int e) { if (e != 0) { fprintf(stderr, "\nError during regular loop."); fprintf(stderr, "\nExiting.."); } al_destroy_display(display); return 0; } } al_destroy_display(display); enet_deinitialize(); return 0; } <|endoftext|>
<commit_before>dd24381c-2e4e-11e5-b700-28cfe91dbc4b<commit_msg>dd2cad9c-2e4e-11e5-885b-28cfe91dbc4b<commit_after>dd2cad9c-2e4e-11e5-885b-28cfe91dbc4b<|endoftext|>
<commit_before>7e791955-2d15-11e5-af21-0401358ea401<commit_msg>7e791956-2d15-11e5-af21-0401358ea401<commit_after>7e791956-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>a30ac187-2e4f-11e5-a7bb-28cfe91dbc4b<commit_msg>a3107dc5-2e4f-11e5-9a10-28cfe91dbc4b<commit_after>a3107dc5-2e4f-11e5-9a10-28cfe91dbc4b<|endoftext|>
<commit_before>767fe562-2d53-11e5-baeb-247703a38240<commit_msg>76806352-2d53-11e5-baeb-247703a38240<commit_after>76806352-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>0f9c26c2-2748-11e6-bc23-e0f84713e7b8<commit_msg>Tuesday, turns out it was tuesday<commit_after>0faf4568-2748-11e6-8ecc-e0f84713e7b8<|endoftext|>
<commit_before>0d303963-2748-11e6-908a-e0f84713e7b8<commit_msg>For roselyn to integrate at some point<commit_after>0d3c8c00-2748-11e6-badc-e0f84713e7b8<|endoftext|>
<commit_before>47c54254-2e4f-11e5-b9df-28cfe91dbc4b<commit_msg>47cf451c-2e4f-11e5-b3c2-28cfe91dbc4b<commit_after>47cf451c-2e4f-11e5-b3c2-28cfe91dbc4b<|endoftext|>
<commit_before>d66d631e-585a-11e5-803a-6c40088e03e4<commit_msg>d6747b66-585a-11e5-bf7e-6c40088e03e4<commit_after>d6747b66-585a-11e5-bf7e-6c40088e03e4<|endoftext|>
<commit_before>1813c187-2e4f-11e5-a9a9-28cfe91dbc4b<commit_msg>181b9351-2e4f-11e5-b4b9-28cfe91dbc4b<commit_after>181b9351-2e4f-11e5-b4b9-28cfe91dbc4b<|endoftext|>
<commit_before>78262257-2e4f-11e5-a40f-28cfe91dbc4b<commit_msg>782c8be6-2e4f-11e5-9e9b-28cfe91dbc4b<commit_after>782c8be6-2e4f-11e5-9e9b-28cfe91dbc4b<|endoftext|>
<commit_before>9101adb3-2d14-11e5-af21-0401358ea401<commit_msg>9101adb4-2d14-11e5-af21-0401358ea401<commit_after>9101adb4-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>cf82fefd-327f-11e5-b1d6-9cf387a8033e<commit_msg>cf892dfd-327f-11e5-8b6b-9cf387a8033e<commit_after>cf892dfd-327f-11e5-8b6b-9cf387a8033e<|endoftext|>
<commit_before>d6288294-585a-11e5-9404-6c40088e03e4<commit_msg>d62f937a-585a-11e5-a6a9-6c40088e03e4<commit_after>d62f937a-585a-11e5-a6a9-6c40088e03e4<|endoftext|>
<commit_before>206957eb-2e4f-11e5-a0d4-28cfe91dbc4b<commit_msg>20709ade-2e4f-11e5-8f08-28cfe91dbc4b<commit_after>20709ade-2e4f-11e5-8f08-28cfe91dbc4b<|endoftext|>
<commit_before>9363bf02-2d14-11e5-af21-0401358ea401<commit_msg>9363bf03-2d14-11e5-af21-0401358ea401<commit_after>9363bf03-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f10a501c-2e4e-11e5-bbc0-28cfe91dbc4b<commit_msg>f118d6e6-2e4e-11e5-828d-28cfe91dbc4b<commit_after>f118d6e6-2e4e-11e5-828d-28cfe91dbc4b<|endoftext|>
<commit_before>0b0503fd-2d3e-11e5-8a0d-c82a142b6f9b<commit_msg>0b7de5c5-2d3e-11e5-94b7-c82a142b6f9b<commit_after>0b7de5c5-2d3e-11e5-94b7-c82a142b6f9b<|endoftext|>
<commit_before>e069e287-313a-11e5-b692-3c15c2e10482<commit_msg>e06fdf59-313a-11e5-9e5d-3c15c2e10482<commit_after>e06fdf59-313a-11e5-9e5d-3c15c2e10482<|endoftext|>
<commit_before>28d2f53d-2e4f-11e5-bb5a-28cfe91dbc4b<commit_msg>28da2097-2e4f-11e5-a343-28cfe91dbc4b<commit_after>28da2097-2e4f-11e5-a343-28cfe91dbc4b<|endoftext|>
<commit_before>45bc5185-ad5d-11e7-a4f8-ac87a332f658<commit_msg>updated some files<commit_after>47099128-ad5d-11e7-b793-ac87a332f658<|endoftext|>
<commit_before>1319a570-585b-11e5-8996-6c40088e03e4<commit_msg>132081e2-585b-11e5-9e2c-6c40088e03e4<commit_after>132081e2-585b-11e5-9e2c-6c40088e03e4<|endoftext|>
<commit_before>a9d52542-2e4f-11e5-8a89-28cfe91dbc4b<commit_msg>a9dca19e-2e4f-11e5-ab5f-28cfe91dbc4b<commit_after>a9dca19e-2e4f-11e5-ab5f-28cfe91dbc4b<|endoftext|>
<commit_before>8fd048d8-2d14-11e5-af21-0401358ea401<commit_msg>8fd048d9-2d14-11e5-af21-0401358ea401<commit_after>8fd048d9-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>31fc843e-2f67-11e5-8219-6c40088e03e4<commit_msg>32034346-2f67-11e5-959f-6c40088e03e4<commit_after>32034346-2f67-11e5-959f-6c40088e03e4<|endoftext|>
<commit_before>666cbda4-2fa5-11e5-839f-00012e3d3f12<commit_msg>666ee082-2fa5-11e5-8ed7-00012e3d3f12<commit_after>666ee082-2fa5-11e5-8ed7-00012e3d3f12<|endoftext|>
<commit_before>3aaab92b-2e4f-11e5-99c4-28cfe91dbc4b<commit_msg>3ab12935-2e4f-11e5-99dc-28cfe91dbc4b<commit_after>3ab12935-2e4f-11e5-99dc-28cfe91dbc4b<|endoftext|>
<commit_before>763998e6-2d53-11e5-baeb-247703a38240<commit_msg>763a1802-2d53-11e5-baeb-247703a38240<commit_after>763a1802-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>b6120d2c-35ca-11e5-8178-6c40088e03e4<commit_msg>b618b4d8-35ca-11e5-807e-6c40088e03e4<commit_after>b618b4d8-35ca-11e5-807e-6c40088e03e4<|endoftext|>
<commit_before>10f50451-2d3f-11e5-92b1-c82a142b6f9b<commit_msg>114ce3dc-2d3f-11e5-aacc-c82a142b6f9b<commit_after>114ce3dc-2d3f-11e5-aacc-c82a142b6f9b<|endoftext|>
<commit_before>8e9fac84-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac85-2d14-11e5-af21-0401358ea401<commit_after>8e9fac85-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>d7897fd7-4b02-11e5-b7de-28cfe9171a43<commit_msg>compiles now<commit_after>d7991c5c-4b02-11e5-8127-28cfe9171a43<|endoftext|>
<commit_before>8de59acc-2e4f-11e5-a72f-28cfe91dbc4b<commit_msg>8dedcfc0-2e4f-11e5-8b2f-28cfe91dbc4b<commit_after>8dedcfc0-2e4f-11e5-8b2f-28cfe91dbc4b<|endoftext|>
<commit_before>#define FUSE_USE_VERSION 30 #include <fuse.h> // POSIX #include <sys/types.h> #include <sys/stat.h> // mode info #include <pwd.h> // user id #include <grp.h> // group id #include <unistd.h> #include <time.h> #include <limits.h> // PATH_MAX // STL #include <system_error> #include <map> #include <set> #include <string> #include <cstdint> #include <cassert> #include <cstring> #include <iostream> namespace posix { static const int success_response = 0; static const int error_response = -1; static int success(void) { errno = 0; return success_response; } static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; } } namespace circlefs { enum class Epath { root, directory, file, }; struct file_entry_t { bool operator < (const file_entry_t& other) const // for locating files by name { return name < other.name; } std::string name; pid_t pid; struct stat stat; }; std::map<uid_t, std::set<file_entry_t>> files; void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) { const char* dir_pos = std::strchr(path, '/') + 1; const char* file_pos = std::strchr(dir_pos, '/'); std::string dir; if(path[1] == '\0') { type = Epath::root; pw_ent = nullptr; filename.clear(); } else { if(file_pos == nullptr) { dir = dir_pos; filename.clear(); type = Epath::directory; } else { dir = std::string(dir_pos, file_pos - dir_pos); filename = file_pos + 1; type = Epath::file; } pw_ent = ::getpwnam(dir.c_str()); } } void clean_set(std::set<file_entry_t>& dir_set) { char path[PATH_MAX + 1]; struct stat info; auto pos = dir_set.begin(); while(pos != dir_set.end()) { // Linux only sprintf(path, "/proc/%d", pos->pid); if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) // if process pos = dir_set.erase(pos); else ++pos; } } int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) { (void)fileInfo; filler(buf, "." , nullptr, 0); filler(buf, "..", nullptr, 0); Epath type; passwd* pw_ent; std::string filename; deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory (fill with usernames in use) { auto pos = files.begin(); while(pos != files.end()) { clean_set(pos->second); if(pos->second.empty()) pos = files.erase(pos); else { filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset); ++pos; } } break; } case Epath::directory: // list files in directory (based on username) { auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username has no files { posix::error(std::errc::no_such_file_or_directory); return 0 - errno; } clean_set(pos->second); for(const file_entry_t& entry : pos->second) filler(buf, entry.name.c_str(), &entry.stat, offset); break; } case Epath::file: // there must have been a parsing error (impossible situation) assert(false); } return posix::success(); } int mknod(const char* path, mode_t mode, dev_t rdev) { (void)rdev; if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set return posix::error(std::errc::permission_denied); Epath type; passwd* pw_ent = nullptr; std::string filename; struct stat stat = {}; struct timespec time; clock_gettime(CLOCK_REALTIME, &time); deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory - cannot make root! case Epath::directory: // directory (based on username) - cannot make directory! return posix::error(std::errc::permission_denied); case Epath::file: // create a node file! fuse_context* ctx = fuse_get_context(); auto& dir = files[pw_ent->pw_uid]; auto entry = dir.find({ filename, 0, stat }); if(entry != dir.end()) dir.erase(entry); stat.st_uid = pw_ent->pw_uid; stat.st_gid = pw_ent->pw_gid; stat.st_mode = mode; stat.st_atim = stat.st_ctim = stat.st_mtim = time; dir.insert({ filename, ctx->pid, stat }); break; } return posix::success(); } int getattr(const char* path, struct stat* statbuf) { Epath type; passwd* pw_ent = nullptr; std::string filename; deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory (always exists) statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; posix::success(); break; case Epath::directory: // username (exists if username exists) statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; if(pw_ent == nullptr) posix::error(std::errc::no_such_file_or_directory); else posix::success(); break; case Epath::file: auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username not registered { posix::error(std::errc::no_such_file_or_directory); break; } clean_set(pos->second); for(const file_entry_t& entry : pos->second) // check every file { if(entry.name == filename) { *statbuf = entry.stat; posix::success(); return 0 - errno; } } posix::error(std::errc::no_such_file_or_directory); // no file matched break; } return 0 - errno; } } int main(int argc, char *argv[]) { static struct fuse_operations ops; ops.readdir = circlefs::readdir; ops.mknod = circlefs::mknod; ops.getattr = circlefs::getattr; return fuse_main(argc, argv, &ops, nullptr); } <commit_msg>cleanup<commit_after>#define FUSE_USE_VERSION 30 #include <fuse.h> // POSIX #include <sys/types.h> #include <sys/stat.h> // mode info #include <pwd.h> // user id #include <grp.h> // group id #include <unistd.h> #include <time.h> #include <limits.h> // PATH_MAX // STL #include <system_error> #include <map> #include <set> #include <string> #include <cstdint> #include <cassert> #include <cstring> #include <iostream> namespace posix { static const int success_response = 0; static const int error_response = -1; static int success(void) { errno = 0; return success_response; } static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; } } namespace circlefs { enum class Epath { root, directory, file, }; struct file_entry_t { bool operator < (const file_entry_t& other) const // for locating files by name { return name < other.name; } std::string name; pid_t pid; struct stat stat; }; std::map<uid_t, std::set<file_entry_t>> files; void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) { const char* dir_pos = std::strchr(path, '/') + 1; const char* file_pos = std::strchr(dir_pos, '/'); std::string dir; if(path[1] == '\0') { type = Epath::root; pw_ent = nullptr; filename.clear(); } else { if(file_pos == nullptr) { dir = dir_pos; filename.clear(); type = Epath::directory; } else { dir = std::string(dir_pos, file_pos - dir_pos); filename = file_pos + 1; type = Epath::file; } pw_ent = ::getpwnam(dir.c_str()); } } void clean_set(std::set<file_entry_t>& dir_set) { char path[PATH_MAX + 1]; struct stat info; auto pos = dir_set.begin(); while(pos != dir_set.end()) { // Linux only sprintf(path, "/proc/%d", pos->pid); if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) // if process pos = dir_set.erase(pos); else ++pos; } } struct timespec get_oldest(std::set<file_entry_t>& dir_set) { struct timespec oldest = dir_set.begin()->stat.st_atim; auto pos = dir_set.begin(); while(pos != dir_set.end()) { if(pos->stat.st_atim.tv_sec < oldest.tv_sec) oldest.tv_sec = pos->stat.st_atim.tv_sec; } return oldest; } int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) { (void)fileInfo; filler(buf, "." , nullptr, 0); filler(buf, "..", nullptr, 0); Epath type; passwd* pw_ent; std::string filename; deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory (fill with usernames in use) { auto pos = files.begin(); while(pos != files.end()) { clean_set(pos->second); if(pos->second.empty()) pos = files.erase(pos); else { filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset); ++pos; } } break; } case Epath::directory: // list files in directory (based on username) { auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username has no files { posix::error(std::errc::no_such_file_or_directory); return 0 - errno; } clean_set(pos->second); for(const file_entry_t& entry : pos->second) filler(buf, entry.name.c_str(), &entry.stat, offset); break; } case Epath::file: // there must have been a parsing error (impossible situation) assert(false); } return posix::success(); } int mknod(const char* path, mode_t mode, dev_t rdev) { (void)rdev; if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set return posix::error(std::errc::permission_denied); Epath type; passwd* pw_ent = nullptr; std::string filename; struct stat stat = {}; struct timespec time; clock_gettime(CLOCK_REALTIME, &time); deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory - cannot make root! case Epath::directory: // directory (based on username) - cannot make directory! return posix::error(std::errc::permission_denied); case Epath::file: // create a node file! fuse_context* ctx = fuse_get_context(); auto& dir = files[pw_ent->pw_uid]; auto entry = dir.find({ filename, 0, stat }); if(entry != dir.end()) dir.erase(entry); stat.st_uid = pw_ent->pw_uid; stat.st_gid = pw_ent->pw_gid; stat.st_mode = mode; stat.st_ctim = stat.st_mtim = stat.st_atim = time; dir.insert({ filename, ctx->pid, stat }); break; } return posix::success(); } int getattr(const char* path, struct stat* statbuf) { Epath type; passwd* pw_ent = nullptr; std::string filename; deconstruct_path(path, type, pw_ent, filename); switch(type) { case Epath::root: // root directory (always exists) statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; posix::success(); break; case Epath::directory: // username (exists if username exists) statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; if(pw_ent == nullptr) posix::error(std::errc::no_such_file_or_directory); else posix::success(); break; case Epath::file: auto pos = files.find(pw_ent->pw_uid); if(pos == files.end()) // username not registered { posix::error(std::errc::no_such_file_or_directory); break; } clean_set(pos->second); for(const file_entry_t& entry : pos->second) // check every file { if(entry.name == filename) { *statbuf = entry.stat; posix::success(); return 0 - errno; } } posix::error(std::errc::no_such_file_or_directory); // no file matched break; } return 0 - errno; } } int main(int argc, char *argv[]) { static struct fuse_operations ops; ops.readdir = circlefs::readdir; ops.mknod = circlefs::mknod; ops.getattr = circlefs::getattr; return fuse_main(argc, argv, &ops, nullptr); } <|endoftext|>
<commit_before>dedbe207-327f-11e5-82ba-9cf387a8033e<commit_msg>dee2ed07-327f-11e5-84e3-9cf387a8033e<commit_after>dee2ed07-327f-11e5-84e3-9cf387a8033e<|endoftext|>
<commit_before>75016048-5216-11e5-970f-6c40088e03e4<commit_msg>7507e026-5216-11e5-9ebb-6c40088e03e4<commit_after>7507e026-5216-11e5-9ebb-6c40088e03e4<|endoftext|>
<commit_before>ce6e8087-327f-11e5-a0ad-9cf387a8033e<commit_msg>ce748b85-327f-11e5-a008-9cf387a8033e<commit_after>ce748b85-327f-11e5-a008-9cf387a8033e<|endoftext|>
<commit_before>eab41c66-2e4e-11e5-a1b5-28cfe91dbc4b<commit_msg>eabafccc-2e4e-11e5-8e17-28cfe91dbc4b<commit_after>eabafccc-2e4e-11e5-8e17-28cfe91dbc4b<|endoftext|>
<commit_before>// // main.cpp // Calculator // // Created by Gavin Scheele on 4/6/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Solver.h" using namespace std; int main(int argc, char * argv[]) { // Rational *a = new Rational(2,1); // Rational *b = new Rational(1,-8); // Rational *c = new Rational(2,1); // Integer *d = new Integer(4); // Integer *e = new Integer(-1); // Integer *f = new Integer(0); // // cout << *a->add(c) << endl; // cout << *a->subtract(d) << endl; // cout << *a->multiply(e) << endl; // cout << *a->divide(b) << endl; Solver *s = new Solver("3 - 300"); cout << s->solve() << endl;; return 0; }<commit_msg>got started<commit_after>// // main.cpp // Calculator // // Created by Gavin Scheele on 4/6/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Solver.h" using namespace std; int main(int argc, char * argv[]) //a main method shouldn't have perameters - at least I don't think so. -Dan { string choice; choice = "z"; cout << "Menu" << "\n" << "a. Compute a New Expression" << "\n" << "b. Help" << "\n" << "c. Review Previous Expressions and Answers" << "\n"; cin >> choice; cout << "\n"; if (choice.compare("a") == 0) { string secondChoice = "n" while (secondChoice.compare("y") == 0) { string expression; cin >> expression; //that's the input - I don't know how you want to handle it cout <<"\n" << "Would you like to go back to the menu? (y/n)" << "\n"; cin >> secondChoice; cout << "\n"; } } // Rational *a = new Rational(2,1); // Rational *b = new Rational(1,-8); // Rational *c = new Rational(2,1); // Integer *d = new Integer(4); // Integer *e = new Integer(-1); // Integer *f = new Integer(0); // // cout << *a->add(c) << endl; // cout << *a->subtract(d) << endl; // cout << *a->multiply(e) << endl; // cout << *a->divide(b) << endl; Solver *s = new Solver("3 - 300"); cout << s->solve() << endl;; return 0; } <|endoftext|>
<commit_before>d215278a-327f-11e5-97d9-9cf387a8033e<commit_msg>d21d05de-327f-11e5-8b53-9cf387a8033e<commit_after>d21d05de-327f-11e5-8b53-9cf387a8033e<|endoftext|>
<commit_before>7977a0b3-4b02-11e5-911d-28cfe9171a43<commit_msg>Long commit messages are not required<commit_after>7983f754-4b02-11e5-8d5d-28cfe9171a43<|endoftext|>
<commit_before>b0d31d9a-35ca-11e5-9b4d-6c40088e03e4<commit_msg>b0db3866-35ca-11e5-91dc-6c40088e03e4<commit_after>b0db3866-35ca-11e5-91dc-6c40088e03e4<|endoftext|>
<commit_before>768ce9c4-2d53-11e5-baeb-247703a38240<commit_msg>768d7006-2d53-11e5-baeb-247703a38240<commit_after>768d7006-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>ddfaf6dc-585a-11e5-9c1b-6c40088e03e4<commit_msg>de025d98-585a-11e5-ae93-6c40088e03e4<commit_after>de025d98-585a-11e5-ae93-6c40088e03e4<|endoftext|>
<commit_before>e3b42666-585a-11e5-a42b-6c40088e03e4<commit_msg>e3ba953a-585a-11e5-8f06-6c40088e03e4<commit_after>e3ba953a-585a-11e5-8f06-6c40088e03e4<|endoftext|>
<commit_before>a15bcb94-327f-11e5-9716-9cf387a8033e<commit_msg>a16184a6-327f-11e5-a253-9cf387a8033e<commit_after>a16184a6-327f-11e5-a253-9cf387a8033e<|endoftext|>
<commit_before>9101adf6-2d14-11e5-af21-0401358ea401<commit_msg>9101adf7-2d14-11e5-af21-0401358ea401<commit_after>9101adf7-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>e0bf882b-4b02-11e5-9982-28cfe9171a43<commit_msg>My Life for Auir<commit_after>e0c8e7ee-4b02-11e5-b74c-28cfe9171a43<|endoftext|>
<commit_before>1a58f510-2f67-11e5-9b2c-6c40088e03e4<commit_msg>1a5f8490-2f67-11e5-9046-6c40088e03e4<commit_after>1a5f8490-2f67-11e5-9046-6c40088e03e4<|endoftext|>
<commit_before>470a3f2e-2e4f-11e5-8c0f-28cfe91dbc4b<commit_msg>47114ce1-2e4f-11e5-8fd3-28cfe91dbc4b<commit_after>47114ce1-2e4f-11e5-8fd3-28cfe91dbc4b<|endoftext|>
<commit_before>#include <algorithm> #include <map> #include <iostream> #include <fstream> #include <cstdio> #include "document.h" extern FILE * xmlin; extern int xmlparse(Document **); static std::string help_message = "Available commands are:\n\ ../xmltool -p file.xml : parse and display the xml file\n\ ../xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\n\ ../xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\n\ ../xmltool -h : displays this help\n"; static int handle_help(int, const char **); static int handle_validate(int, const char **); static int handle_parse(int, const char **); static int handle_transform(int, const char **); // Valid commands (no dash character) typedef int (*command_handler)(int, const char **) ; static std::map<std::string, command_handler> command_map = { { "h", handle_help}, { "v", handle_validate }, { "p", handle_parse }, { "t", handle_transform } }; int main(int argc, const char ** argv) { // Command must be given if (argc < 2) { std::cerr << "No argument given" << std::endl; return handle_help(argc, argv); } // Command must be handled std::string cmd(argv[1] + 1); std::map<std::string, command_handler>::const_iterator it; if ((it = command_map.find(cmd)) == command_map.end()) { std::cerr << "Bad argument given" << std::endl; return handle_help(argc, argv); } // Call command handler, making argc and argv correspond int nb_ignored = 2; argc -= nb_ignored; argv += nb_ignored; return it->second(argc, argv); } int handle_help(int, const char **) { std::cerr << help_message; return 1; } static Document * read_document(const char * fname) { // Change xmlparse input FILE * fp = fopen(fname, "r"); if (fp == nullptr) { return nullptr; } xmlin = fp; // Construct document Document * doc = nullptr; xmlparse(&doc); // who gives a f**k about the return code ? // TODO semantic analysis return doc; } int handle_parse(int argc, const char ** argv) { if (argc < 1) { std::cerr << "You must provide an argument to the command -p" << std::endl; return EXIT_FAILURE; } // XML Document * doc = read_document(argv[0]); if (doc == nullptr) { return EXIT_FAILURE; } std::cout << doc->str() << std::endl; delete doc; return EXIT_SUCCESS; } int handle_validate(int argc, const char ** argv) { if (argc < 1) { std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl; return EXIT_FAILURE; } else if (argc < 2) { std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl; return EXIT_FAILURE; } // XML/XSD Document * xml_doc = read_document(argv[0]); Document * xsd_doc = read_document(argv[1]); // TODO delete xml_doc; delete xsd_doc; return EXIT_SUCCESS; } int handle_transform(int argc, const char ** argv) { if (argc < 1) { std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl; return EXIT_FAILURE; } else if (argc < 2) { std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl; return EXIT_FAILURE; } // XML/XSL Document * xml_doc = read_document(argv[0]); Document * xsl_doc = read_document(argv[1]); // TODO delete xsl_doc; delete xml_doc; return EXIT_FAILURE; } // vim:ft=cpp et sw=2 sts=2: <commit_msg>More tests<commit_after>#include <algorithm> #include <map> #include <iostream> #include <fstream> #include <cstdio> #include "document.h" extern FILE * xmlin; extern int xmlparse(Document **); static std::string help_message = "Available commands are:\n\ ../xmltool -p file.xml : parse and display the xml file\n\ ../xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\n\ ../xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\n\ ../xmltool -h : displays this help\n"; static int handle_help(int, const char **); static int handle_validate(int, const char **); static int handle_parse(int, const char **); static int handle_transform(int, const char **); // Valid commands (no dash character) typedef int (*command_handler)(int, const char **) ; static std::map<std::string, command_handler> command_map = { { "h", handle_help}, { "v", handle_validate }, { "p", handle_parse }, { "t", handle_transform } }; int main(int argc, const char ** argv) { // Command must be given if (argc < 2) { std::cerr << "No argument given" << std::endl; return handle_help(argc, argv); } // Command must be handled std::string cmd(argv[1] + 1); std::map<std::string, command_handler>::const_iterator it; if ((it = command_map.find(cmd)) == command_map.end()) { std::cerr << "Bad argument given" << std::endl; return handle_help(argc, argv); } // Call command handler, making argc and argv correspond int nb_ignored = 2; argc -= nb_ignored; argv += nb_ignored; return it->second(argc, argv); } int handle_help(int, const char **) { std::cerr << help_message; return 1; } static Document * read_document(const char * fname) { // Change xmlparse input FILE * fp = fopen(fname, "r"); if (fp == nullptr) { std::cerr << "Unable to open does_not_exist.xml" << std::endl; return nullptr; } xmlin = fp; // Construct document Document * doc = nullptr; xmlparse(&doc); // who gives a f**k about the return code ? // TODO semantic analysis return doc; } int handle_parse(int argc, const char ** argv) { if (argc < 1) { std::cerr << "You must provide an argument to the command -p" << std::endl; return 1; } // XML Document * doc = read_document(argv[0]); if (doc == nullptr) { return 1; } std::cout << doc->str() << std::endl; delete doc; return 0; } int handle_validate(int argc, const char ** argv) { if (argc < 1) { std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl; return 1; } else if (argc < 2) { std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl; return 1; } // XML/XSD Document * xml_doc = read_document(argv[0]); Document * xsd_doc = read_document(argv[1]); // TODO delete xml_doc; delete xsd_doc; return 0; } int handle_transform(int argc, const char ** argv) { if (argc < 1) { std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl; return 1; } else if (argc < 2) { std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl; return 1; } // XML/XSL Document * xml_doc = read_document(argv[0]); Document * xsl_doc = read_document(argv[1]); // TODO delete xsl_doc; delete xml_doc; return 1; } // vim:ft=cpp et sw=2 sts=2: <|endoftext|>
<commit_before>69411354-2fa5-11e5-82f8-00012e3d3f12<commit_msg>6942e814-2fa5-11e5-9c27-00012e3d3f12<commit_after>6942e814-2fa5-11e5-9c27-00012e3d3f12<|endoftext|>
<commit_before>5bf6740a-2d16-11e5-af21-0401358ea401<commit_msg>5bf6740b-2d16-11e5-af21-0401358ea401<commit_after>5bf6740b-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0b360ddc-2e4f-11e5-a6ca-28cfe91dbc4b<commit_msg>0b3e0e11-2e4f-11e5-9015-28cfe91dbc4b<commit_after>0b3e0e11-2e4f-11e5-9015-28cfe91dbc4b<|endoftext|>
<commit_before>4944db8c-2e4f-11e5-91de-28cfe91dbc4b<commit_msg>494eef63-2e4f-11e5-baff-28cfe91dbc4b<commit_after>494eef63-2e4f-11e5-baff-28cfe91dbc4b<|endoftext|>
<commit_before>170fcd28-2f67-11e5-a20c-6c40088e03e4<commit_msg>17167708-2f67-11e5-a71a-6c40088e03e4<commit_after>17167708-2f67-11e5-a71a-6c40088e03e4<|endoftext|>
<commit_before>#ifndef Rice__Hash__hpp_ #define Rice__Hash__hpp_ #include "Builtin_Object_defn.hpp" #include "to_from_ruby_defn.hpp" #include "detail/ruby.hpp" #include "detail/st.hpp" #include "detail/remove_const.hpp" #include <iterator> namespace Rice { //! A wrapper for the ruby Hash class. //! This class provides a C++-style interface to ruby's Hash class and //! its associated rb_hash_* functions. //! Example: //! \code //! Hash h; //! h[42] = String("foo"); //! h[10] = String("bar"); //! std::cout << String(h[42]) << std::endl; //! \endcode class Hash : public Builtin_Object<RHash, T_HASH> { public: //! Construct a new hash. Hash(); //! Wrap an existing hash. /*! \param v the hash to wrap. */ Hash(Object v); //! Return the number of elements in the hash. size_t size() const; private: //! A helper class so hash[key]=value can work. class Proxy; public: //! Get the value for the given key. /*! \param key the key whose value should be retrieved from the hash. * \return the value associated with the given key. */ template<typename Key_T> Proxy const operator[](Key_T const & key) const; //! Get the value for the given key. /*! \param key the key whose value should be retrieved from the hash. * \return the value associated with the given key. */ template<typename Key_T> Proxy operator[](Key_T const & key); //! Get the value for the given key /*! The returned value is converted to the type given by Value_T. * \param key the key whose value should be retrieved from the hash. * \return the value associated with the given key, converted to C++ * type Value_T. */ template<typename Value_T, typename Key_T> Value_T get(Key_T const & key); //! A helper class for dereferencing iterators class Entry; //! A helper class for implementing iterators for a Hash. template<typename Hash_Ref_T, typename Value_T> class Iterator; public: //! An iterator. typedef Iterator<Hash &, Entry> iterator; //! A const iterator. typedef Iterator<Hash const &, Entry const> const_iterator; public: //! Return an iterator to the beginning of the hash. iterator begin(); //! Return a const iterator to the beginning of the hash. const_iterator begin() const; //! Return an iterator to the end of the hash. iterator end(); //! Return a const to the end of the hash. const_iterator end() const; }; //! A helper class so hash[key]=value can work. class Hash::Proxy { public: //! Construct a new Proxy. Proxy(Hash hash, Object key); //! Implicit conversion to Object. operator Object() const; //! Explicit conversion to VALUE. VALUE value() const; //! Assignment operator. template<typename T> Object operator=(T const & value); void swap(Proxy & proxy); private: Hash hash_; Object key_; }; //! A helper class for dereferencing iterators /*! This class is intended to look similar to an std::pair. */ class Hash::Entry { public: //! Construct a new Entry. Entry(Hash hash, Object key); //! Copy constructor. Entry(Entry const & entry); Object const key; //!< The key Object const & first; //!< An alias for the key Proxy value; //!< The value Proxy & second; //!< An alias for the value Entry & operator=(Entry const & rhs); void swap(Entry & entry); friend bool operator<(Entry const & lhs, Entry const & rhs); }; bool operator<(Hash::Entry const & lhs, Hash::Entry const & rhs); //! A helper class for implementing iterators for a Hash. template<typename Hash_Ref_T, typename Value_T> class Hash::Iterator : public std::iterator< std::input_iterator_tag, Value_T> { public: //! Construct a new Iterator. Iterator(Hash_Ref_T hash, st_data_t bin, st_table_entry * ptr); //! Copy construct an Iterator. Iterator(Iterator const & iterator); //! Construct an Iterator from another Iterator of a different const //! qualification. template<typename Iterator_T> Iterator(Iterator_T const & iterator); //! Assignment operator. Iterator & operator=(Iterator const & rhs); //! Preincrement operator. Iterator & operator++(); //! Postincrement operator. Iterator operator++(int); //! Dereference operator. Value_T operator*(); //! Dereference operator. Value_T * operator->(); //! Equality operator. bool operator==(Iterator const & rhs) const; //! Inequality operator. bool operator!=(Iterator const & rhs) const; template<typename Hash_Ref_T_, typename Value_T_> friend class Hash::Iterator; //! Swap with another iterator of the same type. void swap(Iterator & iterator); private: Hash hash_; st_table * tbl_; st_data_t bin_; st_table_entry * ptr_; mutable typename detail::remove_const<Value_T>::Type tmp_; }; } // namespace Rice #include "Hash.ipp" #endif // Rice__Hash__hpp_ <commit_msg>Use int for type of bin_ on ruby 1.8.x.<commit_after>#ifndef Rice__Hash__hpp_ #define Rice__Hash__hpp_ #include "Builtin_Object_defn.hpp" #include "to_from_ruby_defn.hpp" #include "detail/ruby.hpp" #include "detail/st.hpp" #include "detail/remove_const.hpp" #include <iterator> namespace Rice { //! A wrapper for the ruby Hash class. //! This class provides a C++-style interface to ruby's Hash class and //! its associated rb_hash_* functions. //! Example: //! \code //! Hash h; //! h[42] = String("foo"); //! h[10] = String("bar"); //! std::cout << String(h[42]) << std::endl; //! \endcode class Hash : public Builtin_Object<RHash, T_HASH> { public: //! Construct a new hash. Hash(); //! Wrap an existing hash. /*! \param v the hash to wrap. */ Hash(Object v); //! Return the number of elements in the hash. size_t size() const; private: //! A helper class so hash[key]=value can work. class Proxy; public: //! Get the value for the given key. /*! \param key the key whose value should be retrieved from the hash. * \return the value associated with the given key. */ template<typename Key_T> Proxy const operator[](Key_T const & key) const; //! Get the value for the given key. /*! \param key the key whose value should be retrieved from the hash. * \return the value associated with the given key. */ template<typename Key_T> Proxy operator[](Key_T const & key); //! Get the value for the given key /*! The returned value is converted to the type given by Value_T. * \param key the key whose value should be retrieved from the hash. * \return the value associated with the given key, converted to C++ * type Value_T. */ template<typename Value_T, typename Key_T> Value_T get(Key_T const & key); //! A helper class for dereferencing iterators class Entry; //! A helper class for implementing iterators for a Hash. template<typename Hash_Ref_T, typename Value_T> class Iterator; public: //! An iterator. typedef Iterator<Hash &, Entry> iterator; //! A const iterator. typedef Iterator<Hash const &, Entry const> const_iterator; public: //! Return an iterator to the beginning of the hash. iterator begin(); //! Return a const iterator to the beginning of the hash. const_iterator begin() const; //! Return an iterator to the end of the hash. iterator end(); //! Return a const to the end of the hash. const_iterator end() const; }; //! A helper class so hash[key]=value can work. class Hash::Proxy { public: //! Construct a new Proxy. Proxy(Hash hash, Object key); //! Implicit conversion to Object. operator Object() const; //! Explicit conversion to VALUE. VALUE value() const; //! Assignment operator. template<typename T> Object operator=(T const & value); void swap(Proxy & proxy); private: Hash hash_; Object key_; }; //! A helper class for dereferencing iterators /*! This class is intended to look similar to an std::pair. */ class Hash::Entry { public: //! Construct a new Entry. Entry(Hash hash, Object key); //! Copy constructor. Entry(Entry const & entry); Object const key; //!< The key Object const & first; //!< An alias for the key Proxy value; //!< The value Proxy & second; //!< An alias for the value Entry & operator=(Entry const & rhs); void swap(Entry & entry); friend bool operator<(Entry const & lhs, Entry const & rhs); }; bool operator<(Hash::Entry const & lhs, Hash::Entry const & rhs); //! A helper class for implementing iterators for a Hash. template<typename Hash_Ref_T, typename Value_T> class Hash::Iterator : public std::iterator< std::input_iterator_tag, Value_T> { public: //! Construct a new Iterator. Iterator(Hash_Ref_T hash, st_data_t bin, st_table_entry * ptr); //! Copy construct an Iterator. Iterator(Iterator const & iterator); //! Construct an Iterator from another Iterator of a different const //! qualification. template<typename Iterator_T> Iterator(Iterator_T const & iterator); //! Assignment operator. Iterator & operator=(Iterator const & rhs); //! Preincrement operator. Iterator & operator++(); //! Postincrement operator. Iterator operator++(int); //! Dereference operator. Value_T operator*(); //! Dereference operator. Value_T * operator->(); //! Equality operator. bool operator==(Iterator const & rhs) const; //! Inequality operator. bool operator!=(Iterator const & rhs) const; template<typename Hash_Ref_T_, typename Value_T_> friend class Hash::Iterator; //! Swap with another iterator of the same type. void swap(Iterator & iterator); private: Hash hash_; st_table * tbl_; #if RUBY_VERSION_CODE >= 190 st_index_t bin_; #else int bin_; #endif st_table_entry * ptr_; mutable typename detail::remove_const<Value_T>::Type tmp_; }; } // namespace Rice #include "Hash.ipp" #endif // Rice__Hash__hpp_ <|endoftext|>
<commit_before>#include <QApplication> #include <QTranslator> #include "qtbleditor.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("kambala"); app.setApplicationName("QTblEditor"); app.setApplicationVersion("1.2"); #ifdef Q_OS_MAC app.setAttribute(Qt::AA_DontShowIconsInMenus); #endif QString locale = QLocale::system().name(), translationsPath = #ifdef Q_OS_MAC qApp->applicationDirPath() + "/../Resources/" + #endif "Translations/" + locale; QTranslator qtTranslator; qtTranslator.load("qt_" + locale, translationsPath); app.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load("qtbleditor_" + locale, translationsPath); app.installTranslator(&myappTranslator); QTblEditor w; w.show(); return app.exec(); } <commit_msg>bump version<commit_after>#include <QApplication> #include <QTranslator> #include "qtbleditor.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("kambala"); app.setApplicationName("QTblEditor"); app.setApplicationVersion("1.3"); #ifdef Q_OS_MAC app.setAttribute(Qt::AA_DontShowIconsInMenus); #endif QString locale = QLocale::system().name(), translationsPath = #ifdef Q_OS_MAC qApp->applicationDirPath() + "/../Resources/" + #endif "Translations/" + locale; QTranslator qtTranslator; qtTranslator.load("qt_" + locale, translationsPath); app.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load("qtbleditor_" + locale, translationsPath); app.installTranslator(&myappTranslator); QTblEditor w; w.show(); return app.exec(); } <|endoftext|>
<commit_before>a58a668f-2747-11e6-b623-e0f84713e7b8<commit_msg>I finished programming, there is nothing left to program<commit_after>a59e1711-2747-11e6-8080-e0f84713e7b8<|endoftext|>
<commit_before>a11e2168-327f-11e5-8338-9cf387a8033e<commit_msg>a123e83a-327f-11e5-8db9-9cf387a8033e<commit_after>a123e83a-327f-11e5-8db9-9cf387a8033e<|endoftext|>
<commit_before>/* * Copyright © 2008, 2009 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 (including the next * paragraph) 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. */ #include <cstdlib> #include <cstdio> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "ast.h" #include "glsl_parser_extras.h" #include "glsl_parser.h" #include "ir_optimization.h" #include "ir_print_visitor.h" #include "program.h" static char * load_text_file(const char *file_name, size_t *size) { char *text = NULL; struct stat st; ssize_t total_read = 0; int fd = open(file_name, O_RDONLY); *size = 0; if (fd < 0) { return NULL; } if (fstat(fd, & st) == 0) { text = (char *) malloc(st.st_size + 1); if (text != NULL) { do { ssize_t bytes = read(fd, text + total_read, st.st_size - total_read); if (bytes < 0) { free(text); text = NULL; break; } if (bytes == 0) { break; } total_read += bytes; } while (total_read < st.st_size); text[total_read] = '\0'; *size = total_read; } } close(fd); return text; } void usage_fail(const char *name) { printf("%s <filename.frag|filename.vert>\n", name); exit(EXIT_FAILURE); } int dump_ast = 0; int dump_lir = 0; const struct option compiler_opts[] = { { "dump-ast", 0, &dump_ast, 1 }, { "dump-lir", 0, &dump_lir, 1 }, { NULL, 0, NULL, 0 } }; void compile_shader(struct glsl_shader *prog) { struct _mesa_glsl_parse_state state; memset(& state, 0, sizeof(state)); switch (prog->Type) { case GL_VERTEX_SHADER: state.target = vertex_shader; break; case GL_FRAGMENT_SHADER: state.target = fragment_shader; break; case GL_GEOMETRY_SHADER: state.target = geometry_shader; break; } state.scanner = NULL; state.translation_unit.make_empty(); state.symbols = new glsl_symbol_table; state.error = false; state.temp_index = 0; state.loop_or_switch_nesting = NULL; state.ARB_texture_rectangle_enable = true; _mesa_glsl_lexer_ctor(& state, prog->Source, prog->SourceLen); _mesa_glsl_parse(& state); _mesa_glsl_lexer_dtor(& state); if (dump_ast) { foreach_list_const(n, &state.translation_unit) { ast_node *ast = exec_node_data(ast_node, n, link); ast->print(); } printf("\n\n"); } prog->ir.make_empty(); if (!state.error && !state.translation_unit.is_empty()) _mesa_ast_to_hir(&prog->ir, &state); /* Optimization passes */ if (!state.error && !prog->ir.is_empty()) { bool progress; do { progress = false; progress = do_function_inlining(&prog->ir) || progress; progress = do_if_simplification(&prog->ir) || progress; progress = do_copy_propagation(&prog->ir) || progress; progress = do_dead_code_local(&prog->ir) || progress; progress = do_dead_code_unlinked(&prog->ir) || progress; progress = do_constant_variable_unlinked(&prog->ir) || progress; progress = do_constant_folding(&prog->ir) || progress; progress = do_vec_index_to_swizzle(&prog->ir) || progress; progress = do_swizzle_swizzle(&prog->ir) || progress; } while (progress); } /* Print out the resulting IR */ if (!state.error && dump_lir) { _mesa_print_ir(&prog->ir, &state); } prog->symbols = state.symbols; prog->CompileStatus = !state.error; return; } int main(int argc, char **argv) { int status = EXIT_SUCCESS; int c; int idx = 0; while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1) /* empty */ ; if (argc <= optind) usage_fail(argv[0]); struct glsl_shader **prog_list = NULL; unsigned prog_list_len = 0; for (/* empty */; argc > optind; optind++) { prog_list = (struct glsl_shader **) realloc(prog_list, sizeof(struct glsl_shader *) * (prog_list_len + 1)); assert(prog_list != NULL); struct glsl_shader *prog = new glsl_shader; memset(prog, 0, sizeof(*prog)); prog_list[prog_list_len] = prog; prog_list_len++; const unsigned len = strlen(argv[optind]); if (len < 6) usage_fail(argv[0]); const char *const ext = & argv[optind][len - 5]; if (strncmp(".vert", ext, 5) == 0) prog->Type = GL_VERTEX_SHADER; else if (strncmp(".geom", ext, 5) == 0) prog->Type = GL_GEOMETRY_SHADER; else if (strncmp(".frag", ext, 5) == 0) prog->Type = GL_FRAGMENT_SHADER; else usage_fail(argv[0]); prog->Source = load_text_file(argv[optind], &prog->SourceLen); compile_shader(prog); if (!prog->CompileStatus) { status = EXIT_FAILURE; break; } } return status; } <commit_msg>Use glsl_program instead of an open-coded vector of shaders<commit_after>/* * Copyright © 2008, 2009 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 (including the next * paragraph) 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. */ #include <cstdlib> #include <cstdio> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "ast.h" #include "glsl_parser_extras.h" #include "glsl_parser.h" #include "ir_optimization.h" #include "ir_print_visitor.h" #include "program.h" static char * load_text_file(const char *file_name, size_t *size) { char *text = NULL; struct stat st; ssize_t total_read = 0; int fd = open(file_name, O_RDONLY); *size = 0; if (fd < 0) { return NULL; } if (fstat(fd, & st) == 0) { text = (char *) malloc(st.st_size + 1); if (text != NULL) { do { ssize_t bytes = read(fd, text + total_read, st.st_size - total_read); if (bytes < 0) { free(text); text = NULL; break; } if (bytes == 0) { break; } total_read += bytes; } while (total_read < st.st_size); text[total_read] = '\0'; *size = total_read; } } close(fd); return text; } void usage_fail(const char *name) { printf("%s <filename.frag|filename.vert>\n", name); exit(EXIT_FAILURE); } int dump_ast = 0; int dump_lir = 0; const struct option compiler_opts[] = { { "dump-ast", 0, &dump_ast, 1 }, { "dump-lir", 0, &dump_lir, 1 }, { NULL, 0, NULL, 0 } }; void compile_shader(struct glsl_shader *prog) { struct _mesa_glsl_parse_state state; memset(& state, 0, sizeof(state)); switch (prog->Type) { case GL_VERTEX_SHADER: state.target = vertex_shader; break; case GL_FRAGMENT_SHADER: state.target = fragment_shader; break; case GL_GEOMETRY_SHADER: state.target = geometry_shader; break; } state.scanner = NULL; state.translation_unit.make_empty(); state.symbols = new glsl_symbol_table; state.error = false; state.temp_index = 0; state.loop_or_switch_nesting = NULL; state.ARB_texture_rectangle_enable = true; _mesa_glsl_lexer_ctor(& state, prog->Source, prog->SourceLen); _mesa_glsl_parse(& state); _mesa_glsl_lexer_dtor(& state); if (dump_ast) { foreach_list_const(n, &state.translation_unit) { ast_node *ast = exec_node_data(ast_node, n, link); ast->print(); } printf("\n\n"); } prog->ir.make_empty(); if (!state.error && !state.translation_unit.is_empty()) _mesa_ast_to_hir(&prog->ir, &state); /* Optimization passes */ if (!state.error && !prog->ir.is_empty()) { bool progress; do { progress = false; progress = do_function_inlining(&prog->ir) || progress; progress = do_if_simplification(&prog->ir) || progress; progress = do_copy_propagation(&prog->ir) || progress; progress = do_dead_code_local(&prog->ir) || progress; progress = do_dead_code_unlinked(&prog->ir) || progress; progress = do_constant_variable_unlinked(&prog->ir) || progress; progress = do_constant_folding(&prog->ir) || progress; progress = do_vec_index_to_swizzle(&prog->ir) || progress; progress = do_swizzle_swizzle(&prog->ir) || progress; } while (progress); } /* Print out the resulting IR */ if (!state.error && dump_lir) { _mesa_print_ir(&prog->ir, &state); } prog->symbols = state.symbols; prog->CompileStatus = !state.error; return; } int main(int argc, char **argv) { int status = EXIT_SUCCESS; int c; int idx = 0; while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1) /* empty */ ; if (argc <= optind) usage_fail(argv[0]); struct glsl_program whole_program; memset(&whole_program, 0, sizeof(whole_program)); for (/* empty */; argc > optind; optind++) { whole_program.Shaders = (struct glsl_shader **) realloc(whole_program.Shaders, sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1)); assert(whole_program.Shaders != NULL); struct glsl_shader *prog = new glsl_shader; memset(prog, 0, sizeof(*prog)); whole_program.Shaders[whole_program.NumShaders] = prog; whole_program.NumShaders++; const unsigned len = strlen(argv[optind]); if (len < 6) usage_fail(argv[0]); const char *const ext = & argv[optind][len - 5]; if (strncmp(".vert", ext, 5) == 0) prog->Type = GL_VERTEX_SHADER; else if (strncmp(".geom", ext, 5) == 0) prog->Type = GL_GEOMETRY_SHADER; else if (strncmp(".frag", ext, 5) == 0) prog->Type = GL_FRAGMENT_SHADER; else usage_fail(argv[0]); prog->Source = load_text_file(argv[optind], &prog->SourceLen); compile_shader(prog); if (!prog->CompileStatus) { status = EXIT_FAILURE; break; } } return status; } <|endoftext|>
<commit_before>86936f47-2d15-11e5-af21-0401358ea401<commit_msg>86936f48-2d15-11e5-af21-0401358ea401<commit_after>86936f48-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>2c6bbc7d-2e4f-11e5-b860-28cfe91dbc4b<commit_msg>2c7321f8-2e4f-11e5-b7bf-28cfe91dbc4b<commit_after>2c7321f8-2e4f-11e5-b7bf-28cfe91dbc4b<|endoftext|>
<commit_before>a7a0d182-4b02-11e5-a29a-28cfe9171a43<commit_msg>my cat is cute<commit_after>a7acc49e-4b02-11e5-bd26-28cfe9171a43<|endoftext|>
<commit_before>96ec01ee-2e4f-11e5-bcb6-28cfe91dbc4b<commit_msg>96f2b92e-2e4f-11e5-9ba4-28cfe91dbc4b<commit_after>96f2b92e-2e4f-11e5-9ba4-28cfe91dbc4b<|endoftext|>
<commit_before>#include <fstream> #include <cstring> #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; //~ string revComp(const string& seq){ //~ string revCompSeq = ""; //~ int pos = seq.size()-1; //~ char nt; //~ do{ //~ nt = seq[pos]; //~ switch (nt) { //~ case 'A': //~ revCompSeq += 'T'; //~ break; //~ case 'T': //~ revCompSeq += 'A'; //~ break; //~ case 'C': //~ revCompSeq += 'G'; //~ break; //~ case 'G': //~ revCompSeq += 'C'; //~ break; //~ } //~ --pos; //~ } while (pos>=0); //~ return revCompSeq; //~ } //~ string getCanonical(const string& seq){ //~ string revCompSeq = revComp(seq); //~ return min(seq, revCompSeq); //~ } //~ string getKmer(const string& sequence, int posi, int k){ //~ return getCanonical(sequence.substr(posi, k)); //~ } //~ void getKmersFromRead(const string& readSeq, int k, unordered_map<string, int>& kmersFromFile){ //~ for (uint posi(0); posi < readSeq.size()-k+1; ++posi){ //~ string kmer = getKmer(readSeq, posi, k); //~ if (not kmersFromFile.count(kmer)){ //~ kmersFromFile[kmer] = 1; //~ } else { //~ kmersFromFile[kmer] += 1; //~ } //~ } //~ } //~ void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){ //~ for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){ //~ if (iter->second >1){ //~ solidKmers[iter->first] = iter->second; //~ } //~ } //~ } //~ vector<int> removeDuplicates(const vector<int>& vect){ //~ vector<int> vectResult; //~ for (uint i(0); i< vect.size(); ++i){ //~ if (i == vect.size()-1 or vect[i]!=vect[i+1]){ //~ vectResult.push_back(vect[i]); //~ } //~ } //~ return vectResult; //~ } //~ void putKmersToWindowsTarget(const unordered_map <string, int>& solidKmers, unordered_map <string, vector<int>>& kmerToWindows, const string& target, int indexWindow, uint posiOnTarget, int w, int k){ //~ for (uint posInW(0); posInW < posiOnTarget+w; ++posInW){ //~ string kmer = getKmer(target, posInW, k); //~ if (solidKmers.count(kmer)){ //~ if (not kmerToWindows.count(kmer)){ //~ vector<int> vecIndexes; //~ vecIndexes.push_back(indexWindow); //~ kmerToWindows[kmer] = vecIndexes; //~ } else { //~ kmerToWindows[kmer].push_back(indexWindow); //~ sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end()); //~ vector <int> vect = removeDuplicates(kmerToWindows[kmer]); //~ kmerToWindows[kmer] = vect; //~ } //~ } else { //~ cout << kmer << endl; //~ } //~ } //~ } //~ void getSimilarityWindowQuery(int posiOnQuery, string readSeq, int k, int w, unordered_map <string, int> solidKmers, unordered_map <string, vector<int>> kmerToWindowsTarget, unordered_map<int,double>& similarity){ //~ int nbKmersinWindowQuery(0); //~ for (int posInW(0); posInW < posiOnQuery+w; ++posInW){ //~ string kmer = getKmer(readSeq, posInW, k); //~ if (solidKmers.count(kmer)){ //~ ++ nbKmersinWindowQuery; //~ if (kmerToWindowsTarget.count(kmer)){ // kmer is in target //~ for (uint i(0); i<kmerToWindowsTarget[kmer].size();++i){ //~ int winT(kmerToWindowsTarget[kmer][i]); //~ if (similarity.count(winT)==1){ //~ ++ similarity[winT]; //~ } else { //~ similarity[winT] = 1; //~ } //~ } //~ } //~ } //~ } //~ for (auto iter(similarity.begin()); iter != similarity.end(); ++iter ){ //~ if (iter->second != 0){ //~ iter->second /= nbKmersinWindowQuery; //~ } //~ } //~ } //~ int main(int argc, char ** argv){ //~ if (argc < 4){ //~ cout << "command line: ./rnaLR reads.fasta k w" << endl; //~ } else { //~ int k = stoi(argv[2]); //~ int w = stoi(argv[3]); //~ string target = "AATCGATTCTT"; //~ vector<string> query = {"AATCGATTCTTGTGGGCCCTGAGATCGATTCTT", revComp(target)}; //~ unordered_map <string, int> kmersFromFile; //~ unordered_map <string, int> solidKmers; //~ unordered_map <string, vector<int>> kmerToWindows; //~ getKmersFromRead(target, k, kmersFromFile); //~ for (uint s(0); s < query.size(); ++s){ //~ getKmersFromRead(query[s], k, kmersFromFile); //~ } //~ getSolidKmers(kmersFromFile, solidKmers); //~ uint posi(0); //~ int indexWindow(0); //~ do{ //~ putKmersToWindowsTarget(solidKmers, kmerToWindows, target, indexWindow, posi, w, k); //~ ++ indexWindow; //~ posi += w; //~ } while (posi < target.size()-w-k+2); //~ for (uint reads(0); reads < query.size(); ++reads){ //~ cout << "read n" << reads << endl; //~ uint posiOnQuery(0); //~ int indexWindowQuery(0); //~ do{ //~ unordered_map<int,double> similarity; //key: window on target/value: score //~ getSimilarityWindowQuery(posiOnQuery, query[reads], k, w, solidKmers, kmerToWindows, similarity); //~ for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){ //~ if (iter->second >= 0.5){ //~ cout << iter->first << " " << indexWindowQuery << " " << iter->second << endl; //~ } //~ } //~ ++ indexWindowQuery; //~ posiOnQuery += w; //~ } while (posiOnQuery < query[reads].size()-w-k+2); //~ } //~ return 0; //~ } //~ } struct window{ int index; int read; bool operator==(const window& a) const { return (index == a.index && read == a.read); } }; uint64_t transformWindowToHash(window win){ hash<int> winHash; return winHash(win.read + win.index); } namespace std { template <> struct hash<window> { typedef window argument_type; typedef uint64_t result_type; uint64_t operator()(window key) const { return transformWindowToHash(key); } }; } struct compareWindow{ bool operator()(const window& win1, const window& win2){ return win1.index <win2.index; } }; vector<window> removeDuplicates(const vector<window>& vect){ vector<window> vectResult; for (uint i(0); i< vect.size(); ++i){ if (i == vect.size()-1 or not (vect[i].index == vect[i+1].index and vect[i].read == vect[i+1].read)){ vectResult.push_back(vect[i]); } } return vectResult; } string revComp(const string& seq){ string revCompSeq = ""; int pos = seq.size()-1; char nt; do{ nt = seq[pos]; switch (nt) { case 'A': revCompSeq += 'T'; break; case 'T': revCompSeq += 'A'; break; case 'C': revCompSeq += 'G'; break; case 'G': revCompSeq += 'C'; break; } --pos; } while (pos>=0); return revCompSeq; } string getCanonical(const string& seq){ string revCompSeq = revComp(seq); return min(seq, revCompSeq); } string getKmer(const string& sequence, int posi, int k){ return getCanonical(sequence.substr(posi, k)); } void setKmersToWindows(int indexRead, int indexWindow, string kmer, const unordered_map<string, int>& solidKmers, unordered_map <string, vector <window>>& kmerToWindows){ if (solidKmers.count(kmer)){ window win({indexWindow, indexRead}); if (kmerToWindows.count(kmer)){ kmerToWindows[kmer].push_back(win); sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end(), compareWindow()); kmerToWindows[kmer] = removeDuplicates(kmerToWindows[kmer]); } else { vector <window> vectWin({win}); kmerToWindows[kmer] = vectWin; } } } void getKmersinWindowsFromReads(int k, int w, const vector <string>& readSet, const unordered_map<string, int>& solidKmers, unordered_map <string, vector<window>>& kmerToWindows){ for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){ string readSequence(readSet[indexRead]); if (not readSequence.empty()) { int position(0); int posiForKmer; string kmer; int indexWindow(0); while (position != -1){ if (position + w + k - 1 < (int)readSequence.size()){ posiForKmer = position; position += w; } else { posiForKmer = readSequence.size() - w - k + 1; position = -1; } for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){ kmer = getKmer(readSequence, iter, k); setKmersToWindows(indexRead, indexWindow, kmer, solidKmers, kmerToWindows); } ++indexWindow; } //~ for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){ //~ cout << iter->first << endl; //~ for (uint i(0); i <iter->second.size();++i){ //~ cout << "index:"<<iter->second[i].index << " read:" <<iter->second[i].read << endl; //~ } //~ } } } } void getKmersinFromReadsInMap(int k, const vector <string>& readSet, unordered_map <string, int>& kmersFromFile){ for (uint readIndex(0); readIndex < readSet.size(); ++ readIndex){ string readSequence(readSet[readIndex]); if (not readSequence.empty()){ int position(0); string kmer; while (position + k - 1 < (int)readSequence.size()){ kmer = getKmer(readSequence, position, k); if (kmersFromFile.count(kmer)){ ++kmersFromFile[kmer]; } else { kmersFromFile[kmer] = 1; } ++position; } } } } void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){ for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){ if (iter->second > 1){ solidKmers[iter->first] = iter->second; } } } void compareReadWindows(int k, int w, const vector<string>& readSet,const unordered_map<string, int> solidKmers, const unordered_map<string, vector<window>> kmerToWindows){ for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){ string readSequence(readSet[indexRead]); if (not readSequence.empty()){ int position(0), posiForKmer(0); uint indexWindow(0); while (position != -1){ uint nbKmers(0); unordered_map<window, double> similarity; if (position + w + k - 1 <(int) readSequence.size()){ posiForKmer = position; position += w; } else { posiForKmer = readSequence.size() - w - k + 1; position = -1; } for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){ string kmer = getKmer(readSequence, iter, k); if (solidKmers.count(kmer)){ ++ nbKmers; for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){ for (uint i(0); i<iter->second.size(); ++i){ if (iter->second[i].read != (int)indexRead){ if (kmer == iter->first){ if (similarity.count(iter->second[i])){ ++similarity[iter->second[i]]; } else { similarity[iter->second[i]] = 1; } } } } } } } for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){ iter->second /= nbKmers; if (iter->second >= 0.7){ cout << "reads:" << iter->first.read << " " << indexRead << " windows:" << iter->first.index << " " << indexWindow << " score:" << iter->second <<endl; } } ++indexWindow; } } break; } } int main(int argc, char ** argv){ if (argc < 4){ cout << "command line: ./rnaLR reads.fasta k w" << endl; } else { string fileName = argv[1]; uint k = stoi(argv[2]); uint w = stoi(argv[3]); ifstream readFile(fileName); //~ ofstream out("out.fa"); //~ vector <string> readSet ({"AATCGATTCTT", "AATCGATTCTT", "AATCGATTCTT"}); //~ vector <string> readSet ({"AATCGATTCTT", revComp("AATCGATTCTT")}); vector <string> readSet; string sequence; while (not readFile.eof()){ getline(readFile, sequence); getline(readFile, sequence); readSet.push_back(sequence); } unordered_map <string, int> kmersFromFile; // TODO: destroy unordered_map <string, int> solidKmers; unordered_map <string, vector<window>> kmerToWindows; getKmersinFromReadsInMap(k, readSet, kmersFromFile); getSolidKmers(kmersFromFile, solidKmers); getKmersinWindowsFromReads(k, w, readSet, solidKmers, kmerToWindows); compareReadWindows(k, w, readSet, solidKmers, kmerToWindows); } return 0; } <commit_msg>ordered output<commit_after>#include <fstream> #include <cstring> #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; struct window{ int index; int read; bool operator==(const window& a) const { return (index == a.index && read == a.read); } }; uint64_t transformWindowToHash(window win){ hash<int> winHash; return winHash(win.read + win.index); } namespace std { template <> struct hash<window> { typedef window argument_type; typedef uint64_t result_type; uint64_t operator()(window key) const { return transformWindowToHash(key); } }; } struct compareWindow{ bool operator()(const window& win1, const window& win2){ return win1.index <win2.index; } }; vector<window> removeDuplicates(const vector<window>& vect){ vector<window> vectResult; for (uint i(0); i< vect.size(); ++i){ if (i == vect.size()-1 or not (vect[i].index == vect[i+1].index and vect[i].read == vect[i+1].read)){ vectResult.push_back(vect[i]); } } return vectResult; } string revComp(const string& seq){ string revCompSeq = ""; int pos = seq.size()-1; char nt; do{ nt = seq[pos]; switch (nt) { case 'A': revCompSeq += 'T'; break; case 'T': revCompSeq += 'A'; break; case 'C': revCompSeq += 'G'; break; case 'G': revCompSeq += 'C'; break; } --pos; } while (pos>=0); return revCompSeq; } string getCanonical(const string& seq){ string revCompSeq = revComp(seq); return min(seq, revCompSeq); } string getKmer(const string& sequence, int posi, int k){ return getCanonical(sequence.substr(posi, k)); } void setKmersToWindows(int indexRead, int indexWindow, string kmer, const unordered_map<string, int>& solidKmers, unordered_map <string, vector <window>>& kmerToWindows){ if (solidKmers.count(kmer)){ window win({indexWindow, indexRead}); if (kmerToWindows.count(kmer)){ kmerToWindows[kmer].push_back(win); sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end(), compareWindow()); kmerToWindows[kmer] = removeDuplicates(kmerToWindows[kmer]); } else { vector <window> vectWin({win}); kmerToWindows[kmer] = vectWin; } } } void getKmersinWindowsFromReads(int k, int w, const vector <string>& readSet, const unordered_map<string, int>& solidKmers, unordered_map <string, vector<window>>& kmerToWindows){ for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){ string readSequence(readSet[indexRead]); if (not readSequence.empty()) { int position(0); int posiForKmer; string kmer; int indexWindow(0); while (position != -1){ if (position + w + k - 1 < (int)readSequence.size()){ posiForKmer = position; position += w; } else { posiForKmer = readSequence.size() - w - k + 1; position = -1; } for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){ kmer = getKmer(readSequence, iter, k); setKmersToWindows(indexRead, indexWindow, kmer, solidKmers, kmerToWindows); } ++indexWindow; } //~ for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){ //~ cout << iter->first << endl; //~ for (uint i(0); i <iter->second.size();++i){ //~ cout << "index:"<<iter->second[i].index << " read:" <<iter->second[i].read << endl; //~ } //~ } } } } void getKmersinFromReadsInMap(int k, const vector <string>& readSet, unordered_map <string, int>& kmersFromFile){ for (uint readIndex(0); readIndex < readSet.size(); ++ readIndex){ string readSequence(readSet[readIndex]); if (not readSequence.empty()){ int position(0); string kmer; while (position + k - 1 < (int)readSequence.size()){ kmer = getKmer(readSequence, position, k); if (kmersFromFile.count(kmer)){ ++kmersFromFile[kmer]; } else { kmersFromFile[kmer] = 1; } ++position; } } } } void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){ for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){ if (iter->second > 1){ solidKmers[iter->first] = iter->second; } } } void compareReadWindows(int k, int w, const vector<string>& readSet,const unordered_map<string, int> solidKmers, const unordered_map<string, vector<window>> kmerToWindows){ for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){ string readSequence(readSet[indexRead]); if (not readSequence.empty()){ int position(0), posiForKmer(0); uint indexWindow(0); while (position != -1){ uint nbKmers(0); unordered_map<window, double> similarity; if (position + w + k - 1 <(int) readSequence.size()){ posiForKmer = position; position += w; } else { posiForKmer = readSequence.size() - w - k + 1; position = -1; } for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){ string kmer = getKmer(readSequence, iter, k); if (solidKmers.count(kmer)){ ++ nbKmers; for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){ for (uint i(0); i<iter->second.size(); ++i){ if (iter->second[i].read != (int)indexRead){ if (kmer == iter->first){ if (similarity.count(iter->second[i])){ ++similarity[iter->second[i]]; } else { similarity[iter->second[i]] = 1; } } } } } } } for (uint rIndex(0); rIndex<readSet.size();++rIndex){ // to order the output in cout //~ cout << rIndex << endl; for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){ if (iter->first.read == rIndex){ // to order the output in cout iter->second /= nbKmers; if (iter->second >= 0.7){ cout << "reads:" << iter->first.read << " " << indexRead << " windows:" << iter->first.index << " " << indexWindow << " score:" << iter->second <<endl; } } } } ++indexWindow; } } break; // REMOVE IF all v all } } int main(int argc, char ** argv){ if (argc < 4){ cout << "command line: ./rnaLR reads.fasta k w" << endl; } else { string fileName = argv[1]; uint k = stoi(argv[2]); uint w = stoi(argv[3]); ifstream readFile(fileName); vector <string> readSet; string sequence; while (not readFile.eof()){ getline(readFile, sequence); getline(readFile, sequence); readSet.push_back(sequence); } unordered_map <string, int> kmersFromFile; // TODO: destroy unordered_map <string, int> solidKmers; unordered_map <string, vector<window>> kmerToWindows; getKmersinFromReadsInMap(k, readSet, kmersFromFile); getSolidKmers(kmersFromFile, solidKmers); getKmersinWindowsFromReads(k, w, readSet, solidKmers, kmerToWindows); compareReadWindows(k, w, readSet, solidKmers, kmerToWindows); } return 0; } <|endoftext|>
<commit_before>#include <GLXW/glxw.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <GLFW/glfw3.h> #include <iostream> #include <vector> #include <defer.h> #include <chrono> #include "utils/utils.h" static const GLfloat globVertexBufferData[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; void windowSizeCallback(GLFWwindow *, int width, int height) { glViewport(0, 0, width, height); } // TODO: box instead of triangle // TODO: mouse, keyboard (camera.cpp / hpp ? ) int main() { if(glfwInit() == GL_FALSE) { std::cerr << "Failed to initialize GLFW" << std::endl; return -1; } defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate()); glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); GLFWwindow* window = glfwCreateWindow(800, 600, "Triangle", nullptr, nullptr); if(window == nullptr) { std::cerr << "Failed to open GLFW window" << std::endl; return -1; } defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window)); glfwMakeContextCurrent(window); if(glxwInit()) { std::cerr << "Failed to init GLXW" << std::endl; return -1; } glfwSwapInterval(1); glfwSetWindowSizeCallback(window, windowSizeCallback); glfwShowWindow(window); glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); // TODO: describe GL_CULL_FACE! glDepthFunc(GL_LESS); glClearColor(0, 0, 0, 1); bool errorFlag = false; std::vector<GLuint> shaders; GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag); if(errorFlag) { std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl; return -1; } shaders.push_back(vertexShaderId); GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag); if(errorFlag) { std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl; return -1; } shaders.push_back(fragmentShaderId); GLuint programId = prepareProgram(shaders, &errorFlag); if(errorFlag) { std::cerr << "Failed to prepare program" << std::endl; return -1; } glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO glBindVertexArray(0); // unbind VAO float speed = 0.1f; // units per second glm::vec3 position(0, 0, 5); // Camera is at (0, 0, 5) float horizontalAngleRad = 3.14f; // horizontal angle : toward -Z float verticalAngleRad = 0.0f; // vertical angle : 0, look at the horizon float mouseSpeedRad = 0.0025f; glm::mat4 projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.3f, 100.0f); GLint matrixId = glGetUniformLocation(programId, "MVP"); auto startTime = std::chrono::high_resolution_clock::now(); // hide cursor glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); while(glfwWindowShouldClose(window) == GL_FALSE) { auto currentTime = std::chrono::high_resolution_clock::now(); auto duration = currentTime - startTime; float deltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); float deltaTimeSec = deltaTimeMs/1000.0f; float rotationTimeMs = 3000.0f; float currentRotation = deltaTimeMs / rotationTimeMs; float angle = 360.0f*(currentRotation - (long)currentRotation); int windowWidth, windowHeight; glfwGetWindowSize(window, &windowWidth, &windowHeight); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); horizontalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowWidth/2 - mouseX); verticalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowHeight/2 - mouseY); glfwSetCursorPos(window, windowWidth/2, windowHeight/2); // Direction : Spherical coordinates to Cartesian coordinates conversion glm::vec3 direction( cos(verticalAngleRad) * sin(horizontalAngleRad), sin(verticalAngleRad), cos(verticalAngleRad) * cos(horizontalAngleRad) ); // Right vector glm::vec3 right = glm::vec3( sin(horizontalAngleRad - 3.14f/2.0f), 0, cos(horizontalAngleRad - 3.14f/2.0f) ); glm::vec3 up = glm::cross( right, direction ); // Move forward if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){ position += direction * deltaTimeSec * speed; } // Move backward if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){ position -= direction * deltaTimeSec * speed; } // Strafe left if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){ position -= right * deltaTimeSec * speed; } // Strafe right if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){ position += right * deltaTimeSec * speed; } // Camera matrix glm::mat4 view = glm::lookAt(position, position + direction, up); glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f); glm::mat4 mvp = projection * view * model; // Remember, matrix multiplication is the other way around glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programId); glBindVertexArray(vao); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteProgram(programId); return 0; } <commit_msg>Minor changes<commit_after>#include <GLXW/glxw.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <GLFW/glfw3.h> #include <iostream> #include <vector> #include <defer.h> #include <chrono> #include "utils/utils.h" static const GLfloat globVertexBufferData[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; void windowSizeCallback(GLFWwindow *, int width, int height) { glViewport(0, 0, width, height); } // TODO: box instead of triangle // TODO: mouse, keyboard (camera.cpp / hpp ? ) int main() { if(glfwInit() == GL_FALSE) { std::cerr << "Failed to initialize GLFW" << std::endl; return -1; } defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate()); glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); GLFWwindow* window = glfwCreateWindow(800, 600, "Triangle", nullptr, nullptr); if(window == nullptr) { std::cerr << "Failed to open GLFW window" << std::endl; return -1; } defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window)); glfwMakeContextCurrent(window); if(glxwInit()) { std::cerr << "Failed to init GLXW" << std::endl; return -1; } glfwSwapInterval(1); glfwSetWindowSizeCallback(window, windowSizeCallback); glfwShowWindow(window); glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); // TODO: describe GL_CULL_FACE! glDepthFunc(GL_LESS); glClearColor(0, 0, 0, 1); bool errorFlag = false; std::vector<GLuint> shaders; GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag); if(errorFlag) { std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl; return -1; } shaders.push_back(vertexShaderId); GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag); if(errorFlag) { std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl; return -1; } shaders.push_back(fragmentShaderId); GLuint programId = prepareProgram(shaders, &errorFlag); if(errorFlag) { std::cerr << "Failed to prepare program" << std::endl; return -1; } glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO glBindVertexArray(0); // unbind VAO static const float speed = 0.1f; // units per second glm::vec3 position(0, 0, 5); // Camera is at (0, 0, 5) float horizontalAngleRad = 3.14f; // horizontal angle : toward -Z float verticalAngleRad = 0.0f; // vertical angle : 0, look at the horizon static const float mouseSpeedRad = 0.0025f; glm::mat4 projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.3f, 100.0f); GLint matrixId = glGetUniformLocation(programId, "MVP"); auto startTime = std::chrono::high_resolution_clock::now(); // TODO: getViewMatrix // in: float deltaTimeMs, context: { horizontalAngleRad, verticalAngleRad, position, ... } // out: view metrix // hide cursor glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); while(glfwWindowShouldClose(window) == GL_FALSE) { auto currentTime = std::chrono::high_resolution_clock::now(); auto duration = currentTime - startTime; float deltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); float deltaTimeSec = deltaTimeMs/1000.0f; float rotationTimeMs = 3000.0f; float currentRotation = deltaTimeMs / rotationTimeMs; float angle = 360.0f*(currentRotation - (long)currentRotation); int windowWidth, windowHeight; glfwGetWindowSize(window, &windowWidth, &windowHeight); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); horizontalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowWidth/2 - mouseX); verticalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowHeight/2 - mouseY); glfwSetCursorPos(window, windowWidth/2, windowHeight/2); // Direction : Spherical coordinates to Cartesian coordinates conversion glm::vec3 direction( cos(verticalAngleRad) * sin(horizontalAngleRad), sin(verticalAngleRad), cos(verticalAngleRad) * cos(horizontalAngleRad) ); // Right vector glm::vec3 right = glm::vec3( sin(horizontalAngleRad - 3.14f/2.0f), 0, cos(horizontalAngleRad - 3.14f/2.0f) ); glm::vec3 up = glm::cross( right, direction ); // Move forward if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){ position += direction * deltaTimeSec * speed; } // Move backward if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){ position -= direction * deltaTimeSec * speed; } // Strafe left if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){ position -= right * deltaTimeSec * speed; } // Strafe right if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){ position += right * deltaTimeSec * speed; } // Camera matrix glm::mat4 view = glm::lookAt(position, position + direction, up); glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f); glm::mat4 mvp = projection * view * model; // Remember, matrix multiplication is the other way around glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programId); glBindVertexArray(vao); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteProgram(programId); return 0; } <|endoftext|>
<commit_before>c55a4f30-2e4e-11e5-9dc2-28cfe91dbc4b<commit_msg>c5622240-2e4e-11e5-bdd7-28cfe91dbc4b<commit_after>c5622240-2e4e-11e5-bdd7-28cfe91dbc4b<|endoftext|>
<commit_before>07b13dfa-2e4f-11e5-84aa-28cfe91dbc4b<commit_msg>07b83e5c-2e4f-11e5-b0fe-28cfe91dbc4b<commit_after>07b83e5c-2e4f-11e5-b0fe-28cfe91dbc4b<|endoftext|>
<commit_before>de849d8c-2e4e-11e5-972f-28cfe91dbc4b<commit_msg>de8d4680-2e4e-11e5-8a56-28cfe91dbc4b<commit_after>de8d4680-2e4e-11e5-8a56-28cfe91dbc4b<|endoftext|>
<commit_before>0460282e-585b-11e5-b65b-6c40088e03e4<commit_msg>0467bddc-585b-11e5-ad1d-6c40088e03e4<commit_after>0467bddc-585b-11e5-ad1d-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <sstream> #include <vector> #include <iterator> #include <memory> #include <algorithm> #include <cstring> #include <unordered_map> using namespace std; vector<string> split(const string& str) { string buf; // Have a buffer string stringstream ss(str); // Insert the string into a stream vector<string> tokens; // Create vector to hold our words while (ss >> buf) tokens.push_back(buf); return tokens; } using RoomID = int; struct RoomObject { }; struct Map { static const int max_width = 100, max_height = 100; static const int player_start_x = 50, player_start_y = 50; enum Location { UNKNOWN, GRAVEYARD, GRAVEYARD_GATES, KHATHARRS_MOMS_HOUSE, }; Location map_location[max_width][max_height]; int x, y; Map() { memset(map_location, UNKNOWN, sizeof(map_location)); x = 50; y = 50; map_location[50][50] = GRAVEYARD; map_location[50][51] = GRAVEYARD_GATES; map_location[50][52] = KHATHARRS_MOMS_HOUSE; } }; struct Entity { Entity(string name, int maxHealth) : name(name), health(maxHealth) {} void heal(int points) { health = min(100, health + points); cout << name << " healed to " << health << " health" << endl; } void damage(int points) { health = max(0, health - points); cout << name << " damaged to " << health << "health" << endl; } int getHealth() const { return health; } // Return false if the entity didn't know the command virtual bool act(vector<string> commands) = 0; string name; Map map; private: int health; }; struct Shogun : public Entity { Shogun() : Entity("Shogibear", 100) {} }; struct Item { virtual void apply(Entity* entity) = 0; virtual string identify() const = 0; }; struct HealthItem : public Item { HealthItem(int healPower) : healPower(healPower) {} void apply(Entity* entity) override { entity->heal(healPower); } string identify() const override { stringstream ss; ss << "Health Potion (" << healPower << ")"; return ss.str(); } private: int healPower; }; struct BlessedSword : public Item { BlessedSword(int Weapon) : Weapon(Weapon){} void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";} private: int Weapon;};//will add this to entity on my next commit. <.< /* struct TheFastcall : public Entity { TheFastcall() : Entity("The Fastcall", 22) {} */ struct Player : public Entity { Player(string name, int health) : Entity(name, health) {} virtual bool act(vector<string> commands) override { auto& cmd = commands[0]; if(cmd == "n") { commands = vector<string>{"go","north"}; } if(cmd == "s") { commands = vector<string>{"go","south"}; } if(cmd == "e") { commands = vector<string>{"go","east"}; } if(cmd == "w") { commands = vector<string>{"go","west"}; } if (commands.size() >= 1 && commands[0] == "look") { look(); return true; } else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x")) { } else if (commands.size() >= 2 && commands[0] == "go") { if (travel(commands[1]) == true) { look(); } else { cout << "Can't travel " << commands[1] << endl; } return true; } else if (commands.size() >= 1 && commands[0] == "items") { showItems(); return true; } else if (commands.size() >= 2 && commands[0] == "use") { int index = stoi(commands[1]); useItem(index); return true; } return false; } bool travel(string direction) { if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east")) return false; if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north")) return false; if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--; return true;/* switch (map.map_location[map.x][map.y]) { case Map::GRAVEYARD: if (direction == "north") { map.y++; return true; } break; case Map::GRAVEYARD_GATES: if (direction == "south") { map.y--; return true; } if (direction == "north") { map.y++; return true; } break; } cout << "Can't travel " << direction << endl; return false;*/ } void look() { switch (map.map_location[map.x][map.y]) { case Map::GRAVEYARD: cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl; break; case Map::GRAVEYARD_GATES: cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl; break; case Map::KHATHARRS_MOMS_HOUSE: cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl; break; } } void giveItem(shared_ptr<Item> item) { inventory.push_back(item); } void showItems() { if (inventory.size() == 0) cout << "You have no items." << endl; int i = 1; for (auto item : inventory) { cout << " " << i++ << ". " << item->identify() << std::endl; } } void useItem(size_t index) { if (index > inventory.size()) { cout << "Invalid index" << endl; return; } inventory[index-1]->apply(this); inventory.erase(inventory.begin() + index - 1); } private: vector<shared_ptr<Item>> inventory; }; struct Room { string description; vector<Entity> entities; vector<RoomObject> objects; unordered_map<string, RoomID> exits; }; class Adventure { public: void begin() { string command; cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl; cout << "> "; getline(cin, command); Player player(command, 100); player.giveItem(make_shared<HealthItem>(20)); cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl; player.look(); while (player.getHealth() > 0) { cout << "> "; getline(cin, command); if (player.act(split(command)) == false) cout << "Unknown command" << endl; } cout << "You died. Game over." << endl; } }; int main() { Adventure adventure; adventure.begin(); return 0; } <commit_msg>Not as fast as your mom's plot in this text adventure<commit_after>#include <iostream> #include <string> #include <sstream> #include <vector> #include <iterator> #include <memory> #include <algorithm> #include <cstring> #include <unordered_map> using namespace std; vector<string> split(const string& str) { string buf; // Have a buffer string stringstream ss(str); // Insert the string into a stream vector<string> tokens; // Create vector to hold our words while (ss >> buf) tokens.push_back(buf); return tokens; } using RoomID = int; struct RoomObject { }; struct Map { static const int max_width = 100, max_height = 100; static const int player_start_x = 50, player_start_y = 50; enum Location { UNKNOWN, GRAVEYARD, GRAVEYARD_GATES, KHATHARRS_MOMS_HOUSE, }; Location map_location[max_width][max_height]; int x, y; Map() { memset(map_location, UNKNOWN, sizeof(map_location)); x = 50; y = 50; map_location[50][50] = GRAVEYARD; map_location[50][51] = GRAVEYARD_GATES; map_location[50][52] = KHATHARRS_MOMS_HOUSE; } }; struct Entity { Entity(string name, int maxHealth) : name(name), health(maxHealth) {} void heal(int points) { health = min(100, health + points); cout << name << " healed to " << health << " health" << endl; } void damage(int points) { health = max(0, health - points); cout << name << " damaged to " << health << "health" << endl; } int getHealth() const { return health; } // Return false if the entity didn't know the command virtual bool act(vector<string> commands) = 0; string name; Map map; private: int health; }; struct Shogun : public Entity { Shogun() : Entity("Shogibear", 100) {} }; struct Item { virtual void apply(Entity* entity) = 0; virtual string identify() const = 0; }; struct HealthItem : public Item { HealthItem(int healPower) : healPower(healPower) {} void apply(Entity* entity) override { entity->heal(healPower); } string identify() const override { stringstream ss; ss << "Health Potion (" << healPower << ")"; return ss.str(); } private: int healPower; }; struct BlessedSword : public Item { BlessedSword(int Weapon) : Weapon(Weapon){} void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";} private: int Weapon;};//will add this to entity on my next commit. <.< /* struct TheFastcall : public Entity { TheFastcall() : Entity("The Fastcall", 22) {} virtual bool act(vector<string> commands) override { } */ struct Player : public Entity { Player(string name, int health) : Entity(name, health) {} virtual bool act(vector<string> commands) override { auto& cmd = commands[0]; if(cmd == "n") { commands = vector<string>{"go","north"}; } if(cmd == "s") { commands = vector<string>{"go","south"}; } if(cmd == "e") { commands = vector<string>{"go","east"}; } if(cmd == "w") { commands = vector<string>{"go","west"}; } if (commands.size() >= 1 && commands[0] == "look") { look(); return true; } else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x")) { } else if (commands.size() >= 2 && commands[0] == "go") { if (travel(commands[1]) == true) { look(); } else { cout << "Can't travel " << commands[1] << endl; } return true; } else if (commands.size() >= 1 && commands[0] == "items") { showItems(); return true; } else if (commands.size() >= 2 && commands[0] == "use") { int index = stoi(commands[1]); useItem(index); return true; } return false; } bool travel(string direction) { if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east")) return false; if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north")) return false; if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--; return true;/* switch (map.map_location[map.x][map.y]) { case Map::GRAVEYARD: if (direction == "north") { map.y++; return true; } break; case Map::GRAVEYARD_GATES: if (direction == "south") { map.y--; return true; } if (direction == "north") { map.y++; return true; } break; } cout << "Can't travel " << direction << endl; return false;*/ } void look() { switch (map.map_location[map.x][map.y]) { case Map::GRAVEYARD: cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl; break; case Map::GRAVEYARD_GATES: cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl; break; case Map::KHATHARRS_MOMS_HOUSE: cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl; break; } } void giveItem(shared_ptr<Item> item) { inventory.push_back(item); } void showItems() { if (inventory.size() == 0) cout << "You have no items." << endl; int i = 1; for (auto item : inventory) { cout << " " << i++ << ". " << item->identify() << std::endl; } } void useItem(size_t index) { if (index > inventory.size()) { cout << "Invalid index" << endl; return; } inventory[index-1]->apply(this); inventory.erase(inventory.begin() + index - 1); } private: vector<shared_ptr<Item>> inventory; }; struct Room { string description; vector<Entity> entities; vector<RoomObject> objects; unordered_map<string, RoomID> exits; }; class Adventure { public: void begin() { string command; cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl; cout << "> "; getline(cin, command); Player player(command, 100); player.giveItem(make_shared<HealthItem>(20)); cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl; player.look(); while (player.getHealth() > 0) { cout << "> "; getline(cin, command); if (player.act(split(command)) == false) cout << "Unknown command" << endl; } cout << "You died. Game over." << endl; } }; int main() { Adventure adventure; adventure.begin(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <iterator> #include <algorithm> bool sortHighLow(int i, int j) { return j < i; }; int main(int argc, char** argv) { std::vector<int> tradingValues; std::vector<int> currentItems; int startingValue; int currentValue = startingValue; int numTrades = 0; bool turnTime = true; //temporary values startingValue = 120; tradingValues.push_back(15); tradingValues.push_back(8); tradingValues.push_back(5); tradingValues.push_back(62); tradingValues.push_back(1); std::sort(tradingValues.begin(), tradingValues.end(), sortHighLow); while(currentItems.empty()) { std::cout << "test1" << std::endl; currentValue = *currentItems.begin(); std::cout << "test2" << std::endl; currentItems.erase(currentItems.begin()); std::vector<int>::iterator itr = tradingValues.begin(); while(itr != tradingValues.end()) { if(*itr < currentValue){ std::cout << "test"; ++numTrades; currentValue -= *itr; if(*itr != 1) currentItems.push_back(*itr); } else ++itr; } } std::cout << numTrades; }<commit_msg>More updates<commit_after>#include <iostream> #include <vector> #include <iterator> #include <algorithm> #include <string> bool sortHighLow(int i, int j) { return j < i; }; int main(int argc, char** argv) { std::vector<int> tradingValues; std::vector<int> currentItems; int startingValue; int currentValue; int numTrades = 0; bool turnTime = true; //temporary values startingValue = 10; tradingValues.push_back(15); tradingValues.push_back(10); tradingValues.push_back(3); tradingValues.push_back(1); currentItems.push_back(startingValue); while(!currentItems.empty()) { currentValue = currentItems[0]; currentItems.erase(currentItems.begin()); for(std::vector<int>::iterator itr = tradingValues.begin(); itr != tradingValues.end();) { while(currentValue > *itr){ currentValue -= *itr; if(*itr != 1) currentItems.push_back(*itr); ++numTrades; std::cout << "currentValue = " << currentValue << " *itr = " << *itr << " numTrades = " << numTrades << std::endl; std::string dummy; std::getline(std::cin, dummy); } ++itr; std::cout << "The currentItems list is: "; for(std::vector<int>::iterator mtr = currentItems.begin(); mtr != currentItems.end(); ++mtr) { std::cout << *mtr << " "; } std::cout << std::endl; std::string dummy; std::getline(std::cin, dummy); } } // currentItems.push_back(startingValue); // std::sort(tradingValues.begin(), tradingValues.end(), sortHighLow); // while(!currentItems.empty()) { // currentValue = currentItems[0]; // currentItems.erase(currentItems.begin()); // for(std::vector<int>::iterator itr = tradingValues.begin(); itr != tradingValues.end();) { // std::cout << "The current value of the iterator is " << *itr << std::endl; // std::cout << "The current value of currentValue is " << currentValue << std::endl; // if(*itr < currentValue){ // ++numTrades; // currentValue -= *itr; // if(*itr != 1) // currentItems.push_back(*itr); // } // else // ++itr; // } // } std::cout << numTrades; }<|endoftext|>
<commit_before>#include "matrix.h" #include "parser.h" #include "finite.h" #include <iostream> #include <map> #include <sstream> #include <cstdlib> using namespace std; void die(const string &s) { cout << s << endl; exit(1); } string safeGetline() { string s; while (s.empty()) { getline(cin, s); while (s.size() && isspace(s.back())) s.pop_back(); } return s; } template<class NumMatrix> NumMatrix getMatrix(string prompt) { string s, sum; cout << prompt << endl; s = safeGetline(); unsigned width = 0, height = 0; while (s.length()) { istringstream is; is.str(s); unsigned cwidth = 0; Rational dummy; while (is >> dummy) ++cwidth; if (!cwidth) break; if (width && width != cwidth) die("Incorrect matrix"); width = cwidth; ++height; sum += s + ' '; getline(cin, s); } NumMatrix m(height, width); istringstream is; is.str(sum); is >> m; return m; } template<class NumMatrix> NumMatrix f_solve(const vector<NumMatrix*> &a) { unsigned sz = a[0]->height(); if (!sz || a[0]->width() != sz + 1) die("Invalid use of solve: N*N+1 matrix required"); NumMatrix sys = a[0]->submatrix(0, 0, sz - 1, sz - 1); NumMatrix right = a[0]->submatrix(0, sz, sz - 1, sz); sys.inverseExt(right); return right.transposed(); } template<class NumMatrix> void processOp(string op, vector<NumMatrix> &st, map<string, pair<int, NumMatrix (*)(const vector<NumMatrix*>&)> > &operations) { if (operations[op].first == 1) { st.back() = operations[op].second({&st.back()}); } else if (operations[op].first == 2) { NumMatrix a = st.back(); st.pop_back(); st.back() = operations[op].second({&st.back(), &a}); } else { NumMatrix a = st.back(); st.pop_back(); NumMatrix b = st.back(); st.pop_back(); st.back() = operations[op].second({&st.back(), &b, &a}); } } template<class Field> void f_expr() { typedef Matrix<Field> NumMatrix; map<string, pair<int, NumMatrix (*)(const vector<NumMatrix*>&)> > operations = { {"+", {2, [](const vector<NumMatrix*>& a) { return *a[0] + *a[1]; }}}, {"^", {2, [](const vector<NumMatrix*>& a) { if (a[1]->width() != 1 || a[1]->height() != 1 || (*a[1])[0][0] != int((*a[1])[0][0])) die("Invalid use of ^: integer required"); return a[0]->power(int((*a[1])[0][0])); }}}, {"*", {2, [](const vector<NumMatrix*>& a) { if (a[0]->height() == 1 && a[0]->width() == 1) return *a[1] * (*a[0])[0][0]; else if (a[1]->height() == 1 && a[1]->width() == 1) return *a[0] * (*a[1])[0][0]; else return *a[0] * *a[1]; }}}, {"/", {2, [](const vector<NumMatrix*>& a) { if (a[0]->height() == 1 && a[0]->width() == 1) return a[1]->inverted() * (*a[0])[0][0]; else if (a[1]->height() == 1 && a[1]->width() == 1) return *a[0] * a[1]->inverted()[0][0]; else return *a[0] * a[1]->inverted(); }}}, {"-", {2, [](const vector<NumMatrix*>& a) { return *a[0] - *a[1]; }}}, {"_", {1, [](const vector<NumMatrix*>& a) { return -*a[0]; }}}, {"det", {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->det()); }}}, {"rank", {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->rank()); }}}, {"trace", {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->trace()); }}}, {"t", {1, [](const vector<NumMatrix*>& a) { return a[0]->transposed(); }}}, {"inv", {1, [](const vector<NumMatrix*>& a) { return a[0]->inverted(); }}}, {"id", {1, [](const vector<NumMatrix*>& a) { if (a[0]->width() != 1 || a[0]->height() != 1) die("Invalid use of id"); return NumMatrix::identity(abs(int((*a[0])[0][0]))); }}}, {"=", {2, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(*a[0] == *a[1]); }}}, {"width", {1, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(a[0]->width()); }}}, {"height", {1, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(a[0]->height()); }}}, {"solve", {1, f_solve}}, {"at", {3, [](const vector<NumMatrix*> &a) { if (a[1]->width() != 1 || a[1]->height() != 1 || a[2]->width() != 1 || a[2]->height() != 1) die("Invalid use of at"); if (int((*a[1])[0][0]) != (*a[1])[0][0] || int((*a[2])[0][0]) != (*a[2])[0][0]) die("at: indices must be integers"); if (int((*a[1])[0][0]) < 0 || int((*a[1])[0][0]) >= int(a[0]->height()) || int((*a[2])[0][0]) < 0 || int((*a[2])[0][0]) >= int(a[0]->width())) die("at: out of range"); return NumMatrix::fromNumber((*a[0])[int((*a[1])[0][0])][int((*a[2])[0][0])]); }}} }; cout << "Expression: "; string s = safeGetline(); auto v = splitExpression(s); map<char, NumMatrix> mmap; vector<pair<token_type, string> > opst; vector<NumMatrix> st; int st_size = 0; for (pair<token_type, string> &i : v) { switch (i.first) { case TOKEN_NUMBER: case TOKEN_MATRIX: ++st_size; break; case TOKEN_OP: while (opst.size() && opst.back().first == TOKEN_OP && priority[int(i.second[0])] + rightassoc[int(i.second[0])] <= priority[int(opst.back().second[0])]) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (st_size <= 0) die("Invalid expression"); case TOKEN_FUNC: if (!operations.count(i.second)) die("Invalid function: " + i.second); case TOKEN_LEFTPAR: opst.push_back(i); break; case TOKEN_RIGHTPAR: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (opst.empty() || st_size <= 0) die("Invalid expression"); opst.pop_back(); if (opst.size() && opst.back().first == TOKEN_FUNC) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } break; case TOKEN_COMMA: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (opst.empty() || st_size <= 0) die("Invalid expression"); break; } } while (opst.size()) { if (opst.back().first == TOKEN_LEFTPAR || opst.back().first == TOKEN_RIGHTPAR) die("Invalid expression"); st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (st_size != 1) die("Invalid expression"); for (pair<token_type, string> &i : v) { NumMatrix tt(1, 1); istringstream is; switch (i.first) { case TOKEN_NUMBER: is.str(i.second); is >> tt[0][0]; st.push_back(tt); break; case TOKEN_MATRIX: if (!mmap.count(i.second[0])) mmap[i.second[0]] = getMatrix<NumMatrix>(string("Matrix ") + i.second + ':'); st.push_back(mmap[i.second[0]]); break; case TOKEN_OP: while (opst.size() && opst.back().first == TOKEN_OP && priority[int(i.second[0])] + rightassoc[int(i.second[0])] <= priority[int(opst.back().second[0])]) { processOp(opst.back().second, st, operations); opst.pop_back(); } case TOKEN_FUNC: case TOKEN_LEFTPAR: opst.push_back(i); break; case TOKEN_RIGHTPAR: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { processOp(opst.back().second, st, operations); opst.pop_back(); } opst.pop_back(); if (opst.size() && opst.back().first == TOKEN_FUNC) { processOp(opst.back().second, st, operations); opst.pop_back(); } break; case TOKEN_COMMA: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { processOp(opst.back().second, st, operations); opst.pop_back(); } break; } } while (opst.size()) { processOp(opst.back().second, st, operations); opst.pop_back(); } cout << "Result:\n" << st[0]; } int main(int argc, char **argv) { try { if (argc == 1) { f_expr<Rational>(); } else { _FINITE_ORDER = atoi(argv[1]); if(_FINITE_ORDER < 2) die("Order must be at least 2"); f_expr<Finite>(); } } catch (matrix_error e) { cout << "Matrix error: " << e.what() << endl; return 1; } return 0; } <commit_msg>Типизация<commit_after>#include "matrix.h" #include "parser.h" #include "finite.h" #include <iostream> #include <map> #include <sstream> #include <cstdlib> using namespace std; void die(const string &s) { cout << s << endl; exit(1); } string safeGetline() { string s; while (s.empty()) { getline(cin, s); while (s.size() && isspace(s.back())) s.pop_back(); } return s; } template<class FMatrix> FMatrix getMatrix(string prompt) { string s, sum; cout << prompt << endl; s = safeGetline(); unsigned width = 0, height = 0; while (s.length()) { istringstream is; is.str(s); unsigned cwidth = 0; Rational dummy; while (is >> dummy) ++cwidth; if (!cwidth) break; if (width && width != cwidth) die("Incorrect matrix"); width = cwidth; ++height; sum += s + ' '; getline(cin, s); } FMatrix m(height, width); istringstream is; is.str(sum); is >> m; return m; } template<class NumMatrix> void processOp(string op, vector<NumMatrix> &st, map<string, pair<int, NumMatrix (*)(const vector<NumMatrix *> &)> > &operations) { if (operations[op].first == 1) { st.back() = operations[op].second({&st.back()}); } else if (operations[op].first == 2) { NumMatrix a = st.back(); st.pop_back(); st.back() = operations[op].second({&st.back(), &a}); } else { NumMatrix a = st.back(); st.pop_back(); NumMatrix b = st.back(); st.pop_back(); st.back() = operations[op].second({&st.back(), &b, &a}); } } template<class Field> struct _NumMatrix { union { int im; Matrix<Field> fm; }; bool is_int; _NumMatrix(): im(0), is_int(true) {} _NumMatrix(const _NumMatrix &a): is_int(a.is_int) { if (is_int) im = a.im; else { new(&fm) Matrix<Field>(); fm = a.fm; } } _NumMatrix(int a): im(a), is_int(true) {} _NumMatrix(const Matrix<Field> &a): fm(a), is_int(false) {} _NumMatrix(const Field &a): fm(Matrix<Field>::fromNumber(a)), is_int(false) {} _NumMatrix &operator=(const _NumMatrix &a) { if(this == &a) return *this; if(!is_int && a.is_int) fm.~Matrix(); is_int = a.is_int; if(is_int) im = a.im; else fm = a.fm; return *this; } Matrix<Field> toMatrix() const { if (is_int) return Matrix<Field>::fromNumber(Field(im)); else return fm; } ~_NumMatrix() { if (!is_int) fm.~Matrix(); } _NumMatrix operator*(const _NumMatrix &m) const { if (is_int && m.is_int) return im * m.im; if (is_int) return m.fm * Field(im); if (m.is_int) return fm * Field(m.im); if (fm.width() == 1 && fm.height() == 1) return m.fm * fm[0][0]; if (m.fm.width() == 1 && m.fm.height() == 1) return fm * m.fm[0][0]; return fm * m.fm; } _NumMatrix operator/(const _NumMatrix &m) const { return operator*(m.toMatrix().inverted()); } _NumMatrix operator+(const _NumMatrix &m) const { if (is_int && m.is_int) return im + m.im; return toMatrix() + m.toMatrix(); } _NumMatrix operator-() const { if (is_int) return -im; else return -fm; } }; template<class Field> void f_expr() { typedef _NumMatrix<Field> NumMatrix; map<string, pair<int, NumMatrix (*)(const vector<NumMatrix *> &)> > operations = { {"+", {2, [](const vector<NumMatrix *> &a) { return *a[0] + *a[1]; }}}, {"^", {2, [](const vector<NumMatrix *> &a) { if (!a[1]->is_int) die("Invalid use of ^: integer required"); return NumMatrix(a[0]->toMatrix().power(a[1]->im)); }}}, {"*", {2, [](const vector<NumMatrix *> &a) { return *a[0] * *a[1]; }}}, {"/", {2, [](const vector<NumMatrix *> &a) { return *a[0] / *a[1]; }}}, {"-", {2, [](const vector<NumMatrix *> &a) { return *a[0] + -*a[1]; }}}, {"_", {1, [](const vector<NumMatrix *> &a) { return -*a[0]; }}}, {"det", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().det()); }}}, {"rank", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().rank()); }}}, {"trace", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().trace()); }}}, {"t", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().transposed()); }}}, {"inv", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().inverted()); }}}, {"id", {1, [](const vector<NumMatrix *> &a) { if (!a[1]->is_int) die("Invalid use of id"); return NumMatrix(Matrix<Field>::identity(abs(a[0]->im))); }}}, {"=", {2, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix() == a[1]->toMatrix()); }}}, {"width", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().width()); }}}, {"height", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().height()); }}}, {"solve", {1, [](const vector<NumMatrix *> &a) { unsigned sz = a[0]->toMatrix().height(); if (!sz || a[0]->toMatrix().width() != sz + 1) die("Invalid use of solve: N*N+1 matrix required"); Matrix<Field> sys = a[0]->toMatrix().submatrix(0, 0, sz - 1, sz - 1); Matrix<Field> right = a[0]->toMatrix().submatrix(0, sz, sz - 1, sz); sys.inverseExt(right); return NumMatrix(right.transposed()); }}}, {"at", {3, [](const vector<NumMatrix *> &a) { if (!a[1]->is_int || !a[2]->is_int) die("Invalid use of at"); if (a[1]->im < 0 || a[1]->im >= int(a[0]->toMatrix().height()) || a[2]->im < 0 || a[2]->im >= int(a[0]->toMatrix().width())) die("at: out of range"); return NumMatrix(a[0]->toMatrix()[a[1]->im][a[2]->im]); }}} }; cout << "Expression: "; string s = safeGetline(); auto v = splitExpression(s); map<char, NumMatrix> mmap; vector<pair<token_type, string> > opst; vector<NumMatrix> st; int st_size = 0; for (pair<token_type, string> &i : v) { switch (i.first) { case TOKEN_NUMBER: case TOKEN_MATRIX: ++st_size; break; case TOKEN_OP: while (opst.size() && opst.back().first == TOKEN_OP && priority[int(i.second[0])] + rightassoc[int(i.second[0])] <= priority[int(opst.back().second[0])]) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (st_size <= 0) die("Invalid expression"); case TOKEN_FUNC: if (!operations.count(i.second)) die("Invalid function: " + i.second); case TOKEN_LEFTPAR: opst.push_back(i); break; case TOKEN_RIGHTPAR: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (opst.empty() || st_size <= 0) die("Invalid expression"); opst.pop_back(); if (opst.size() && opst.back().first == TOKEN_FUNC) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } break; case TOKEN_COMMA: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (opst.empty() || st_size <= 0) die("Invalid expression"); break; } } while (opst.size()) { if (opst.back().first == TOKEN_LEFTPAR || opst.back().first == TOKEN_RIGHTPAR) die("Invalid expression"); st_size -= operations[opst.back().second].first - 1; opst.pop_back(); } if (st_size != 1) die("Invalid expression"); for (pair<token_type, string> &i : v) { Rational tt; istringstream is, iis; switch (i.first) { case TOKEN_NUMBER: is.str(i.second); is >> tt; if(tt == int(tt)) st.push_back(NumMatrix(int(tt))); else { Field tf; iis.str(i.second); iis >> tf; st.push_back(NumMatrix(tf)); } break; case TOKEN_MATRIX: if (!mmap.count(i.second[0])) mmap[i.second[0]] = getMatrix<Matrix<Field>>(string("Matrix ") + i.second + ':'); st.push_back(mmap[i.second[0]]); break; case TOKEN_OP: while (opst.size() && opst.back().first == TOKEN_OP && priority[int(i.second[0])] + rightassoc[int(i.second[0])] <= priority[int(opst.back().second[0])]) { processOp(opst.back().second, st, operations); opst.pop_back(); } case TOKEN_FUNC: case TOKEN_LEFTPAR: opst.push_back(i); break; case TOKEN_RIGHTPAR: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { processOp(opst.back().second, st, operations); opst.pop_back(); } opst.pop_back(); if (opst.size() && opst.back().first == TOKEN_FUNC) { processOp(opst.back().second, st, operations); opst.pop_back(); } break; case TOKEN_COMMA: while (opst.size() && opst.back().first != TOKEN_LEFTPAR) { processOp(opst.back().second, st, operations); opst.pop_back(); } break; } } while (opst.size()) { processOp(opst.back().second, st, operations); opst.pop_back(); } cout << "Result:\n" << st[0].toMatrix(); } int main(int argc, char **argv) { try { if (argc == 1) { f_expr<Rational>(); } else { _FINITE_ORDER = atoi(argv[1]); if (_FINITE_ORDER < 2) die("Order must be at least 2"); f_expr<Finite>(); } } catch (matrix_error e) { cout << "Matrix error: " << e.what() << endl; return 1; } return 0; } <|endoftext|>
<commit_before>8d6dfd8e-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd8f-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd8f-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>/**************************************************************************** ** ** The MIT License (MIT) ** ** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk) ** ** 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 ** ****************************************************************************/ #include <misc/CODeMMisc.h> #include <misc/examples/CODeMProblems.h> #include <core/CODeMGlobal.h> #include <random> #include <ctime> #include <iostream> #include <stdio.h> #include <string> using namespace std; using namespace CODeM; inline void defineSeed(int seed) {std::srand(seed);} inline void randomSeed() {std::srand((unsigned)std::time(0));} void dispVector(vector<double> vec, string sep=", ", string endVec="; ") { for(auto i = vec.begin(); i != (vec.end() -1); ++i) { cout << *i << sep; } cout << vec.back() << endVec; } void showUsage(progName) { printf("\n" "Usage: %s [OPTION(S)]\n\n", progName); printf( "This program evaluates a set of candidate solutions for an uncertain \n" " multiobjective optimization problem using the CODeM toolkit. The output of the\n" " program is a set of decision vectors and a set of objective vectors for each \n" " decision vector. The objective vectors for every solution represent different \n" " samples from the random variate. \n\n" "Options: \n" " -h, --help Print this summary and exit. \n" " -v, --version Print version number and exit. \n" " -f, --file = FILENAME An input file with all the configuration options. \n" " If FILENAME is not specified, the options are \n" " configured from the command. FILENAME may include a \n" " relative or absolute path. \n" " -o, --output = FILENAME A file to write the outputs. If FILENAME is not \n" " specified, the output is printed to the console. \n" " -p, --problem = NUMBER A chioce of benchmark problem from the CODeM suite. \n" " Use NUMBER = 0 for the problem in the GECCO'16 \n" " paper. Use NUMBER = 1,...,6 for CODeM1,...,CODeM6. \n" " -x, --solSet = SET A set of decision vectors to evaluate. SET needs to \n" " be provided within double qoutes, where each vector \n" " is separated with a semicolon, and the elements \n" " within a vector separated with a space. e.g., a set \n" " of three vectors with two variables each: \n" " SET = \"1.1 1.2; 2.1 2.2; 3.0 4.0\" \n" " If SET is not specified two defalut sets are \n" " generated: one with solutions that are optimal for \n" " the deterministic problem, and one with random \n" " vectors. Their sizes are specified with the -s and \n" " -n options. \n" " -m, --nObj = NUMBER The dimensionality of the objective space. If NUMBER\n" " is not specified, the default is 2 objectives. \n" " -d, --nVars = NUMBER The dimensionality of the decision space. If NUMBER \n" " is not specified, the default is nObj + 10. \n" " -s, --nSols = NUMBER The number of decision vectors to evaluate. Two \n" " sets of size NUMBER are generated: one with \n" " solutions that are optimal for the deterministic \n" " problem, and one with random vectors. If NUMBER is \n" " not specified, the default value is NUMBER = 10. \n" " -n, --nSamps = NUMBER The number of function evaluations for each decision\n" " vector. if NUMER is not specified, the default value\n" " is NUMBER = 5." "\n"); } //int main(int argc, char* argv[]) //{ // if (argc < 3) { // showUsage(argv[0]); // return 1; // } // std::vector <std::string> sources; // std::string destination; // for (int i = 1; i < argc; ++i) { // std::string arg = argv[i]; // if ((arg == "-h") || (arg == "--help")) { // show_usage(argv[0]); // return 0; // } else if ((arg == "-d") || (arg == "--destination")) { // if (i + 1 < argc) { // Make sure we aren't at the end of argv! // destination = argv[i++]; // Increment 'i' so we don't get the argument as the next argv[i]. // } else { // Uh-oh, there was no argument to the destination option. // std::cerr << "--destination option requires one argument." << std::endl; // return 1; // } // } else { // sources.push_back(argv[i]); // } // } // return move(sources, destination); //} int main(int argc, char** argv) { for(int i = 0; i < argc; ++i) { cout << "Argument " << i << ": " << argv[i] << endl; } return 0; } //int main() //{ // defineSeed(0); // int nObj = 2; // int nVar = 6; // int nPareto = 5; // int nRand = 10; // int nSamp = 50; // vector<vector<double> > paretoDeterministic; // vector<vector<double> > randDeterministic; // vector<vector<vector<double> > > paretoObj; // vector<vector<vector<double> > > randObj; // vector<vector<double> > paretoDirVars = simplexLattice(nPareto-1, 2); // // Pareto optimal vectors // for(int i=0; i<paretoDirVars.size(); i++) { // vector<double> iVec(nVar, 0.5); // iVec[0] = paretoDirVars[i][0]; // vector<double> determObjVec = deterministicOVec(7, iVec, nObj); // paretoDeterministic.push_back(determObjVec); // vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp); // paretoObj.push_back(oVecSamps); // } // // Random vectors // for(int i=0; i<nRand; i++) { // vector<double> iVec; // for(int j=0; j<nVar; j++) { // iVec.push_back(randUni()); // } // vector<double> determObjVec = deterministicOVec(7, iVec, nObj); // randDeterministic.push_back(determObjVec); // vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp); // randObj.push_back(oVecSamps); // } // // Display the results // cout << "\n% Optimal vectors:" << endl; // for(int v=0; v<paretoObj.size(); v++) { // cout << "paretoObj{" << v+1 << "} = ["; // for(int i=0; i<paretoObj[v].size(); i++) { // dispVector(paretoObj[v][i]); // } // cout << "];" << endl; // } // cout << "\n% Random vectors:" << endl; // for(int v=0; v<randObj.size(); v++) { // cout << "randObj{" << v+1 << "} = ["; // for(int i=0; i<randObj[v].size(); i++) { // dispVector(randObj[v][i]); // } // cout << "];" << endl; // } // cout << "\n% Optimal deterministic vectors:" << endl; // cout << "determOptimal = ["; // for(int i=0; i<paretoDeterministic.size(); i++) { // dispVector(paretoDeterministic[i]); // } // cout << "];" << endl; // cout << "\n% Random deterministic vectors:" << endl; // cout << "determRand = ["; // for(int i=0; i<randDeterministic.size(); i++) { // dispVector(randDeterministic[i]); // } // cout << "];\n" << endl; // return 0; //} <commit_msg>enabled command line argument input<commit_after>/**************************************************************************** ** ** The MIT License (MIT) ** ** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk) ** ** 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 ** ****************************************************************************/ #include <misc/CODeMMisc.h> #include <misc/examples/CODeMProblems.h> #include <core/CODeMGlobal.h> #include <random> #include <ctime> #include <iostream> #include <stdio.h> #include <string> using namespace std; using namespace CODeM; inline void defineSeed(int seed) {std::srand(seed);} inline void randomSeed() {std::srand((unsigned)std::time(0));} void printVector(vector<double> vec, string sep=", ", string endVec="; ") { for(auto i = vec.begin(); i != (vec.end() -1); ++i) { cout << *i << sep; } cout << vec.back() << endVec; } void showUsage(char* progName) { cout << "\nUsage: " << progName << " [OPTION(S)]\n\n"; cout << "This program evaluates a set of candidate solutions for an uncertain \n" " multiobjective optimization problem using the CODeM toolkit. The output of the\n" " program is a set of decision vectors and a set of objective vectors for each \n" " decision vector. The objective vectors for every solution represent different \n" " samples from the random variate. \n\n" "Options: \n" "-------- \n" " -h, --help Print this summary and exit. \n\n" //" -i, --inFile = FILENAME An input file with all the configuration options. \n" //" If FILENAME is not specified, the options are \n" //" configured from the command. FILENAME may include a \n" //" relative or absolute path. \n\n" " -f, --file = FILENAME A file to write the outputs. If FILENAME is not \n" " specified, the output is printed to the console. \n\n" " -p, --problem = NUMBER A chioce of benchmark problem from the CODeM suite. \n" " Use NUMBER = 0 for the problem in the GECCO'16 \n" " paper. Use NUMBER = 1,...,6 for CODeM1,...,CODeM6. \n" " Default is NUMBER = 0. \n\n" //" -x, --solSet = SET A set of decision vectors to evaluate. SET needs to \n" //" be provided within double qoutes, where each vector \n" //" is separated with a semicolon, and the elements \n" //" within a vector separated with a space. e.g., a set \n" //" of three vectors with two variables each: \n" //" SET = \"1.1 1.2; 2.1 2.2; 3.0 4.0\" \n" //" If SET is not specified two defalut sets are \n" //" generated: one with solutions that are optimal for \n" //" the deterministic problem, and one with random \n" //" vectors. Their sizes are specified with the -s and \n" //" -n options. \n\n" " -m, --nObj = NUMBER The dimensionality of the objective space. If NUMBER\n" " is not specified, the default is 2 objectives. \n\n" " -d, --nVars = NUMBER The dimensionality of the decision space. If NUMBER \n" " is not specified, the default is 10, or nobj + 1 \n" " when nObj >= 9. \n\n" " -s, --nSols = NUMBER The number of decision vectors to evaluate. Two \n" " sets of size NUMBER are generated: one with \n" " solutions that are optimal for the deterministic \n" " problem, and one with random vectors. If NUMBER is \n" " not specified, the default value is NUMBER = 10. \n\n" " -n, --nSamps = NUMBER The number of function evaluations for each decision\n" " vector. if NUMER is not specified, the default value\n" " is NUMBER = 5. \n\n" " -r, --rndSeed = NUMBER The seed for the pseudo-random number generator. If \n" " NUMBER is not specified, the default seed is 0. For \n" " a random seed, based on the CPU time, provide a \n" " negative value for NUMBER. \n" "\n"; } int main(int argc, char** argv) { if (argc < 2) { showUsage(argv[0]); return EXIT_FAILURE; } // set defaults int seed = 0; int nObj = 2; int nVars = 10; int nSols = 10; int nSamps = 5; int prob = 0; int argInd = 1; while(argInd < argc) { string arg = argv[argInd++]; if ((arg == "-h") || (arg == "--help")) { showUsage(argv[0]); return EXIT_SUCCESS; } else if ((arg == "-f") || (arg == "--file")) { if (argInd < argc) { freopen(argv[argInd++], "w", stdout); } else { cerr << "--file option requires one argument." << endl; return EXIT_FAILURE; } } else if ((arg == "-p") || (arg == "--problem")) { if (argInd < argc) { int argI = atoi(argv[argInd++]); if((argI >= 0) && (argI <= 6)) { prob = argI; } else { cerr << "Invalid argument for --problem option: Requires a " "number between 0-6." << endl; return EXIT_FAILURE; } } else { cerr << "--problem option requires one argument." << endl; return EXIT_FAILURE; } // TODO: accept a set to evaluate // } else if ((arg == "-x") || (arg == "--solSet")) { // if (argInd < argc) { // } else { // cerr << "--solSet option requires one argument." << endl; // return EXIT_FAILURE; // } } else if ((arg == "-m") || (arg == "--nObj")) { if (argInd < argc) { int argI = atoi(argv[argInd++]); if(argI >= 2) { nObj = argI; } else { cerr << "Invalid argument for --nObj option: Number of " "objectives must be larger than 1." << endl; return EXIT_FAILURE; } } else { cerr << "--nObj option requires one argument." << endl; return EXIT_FAILURE; } } else if ((arg == "-d") || (arg == "--nVars")) { if (argInd < argc) { int argI = atoi(argv[argInd++]); if(argI >= 3) { nVars = argI; } else { cerr << "Invalid argument for --nVars option: Number of " "variables must be larger than 2." << endl; return EXIT_FAILURE; } } else { cerr << "--nVars option requires one argument." << endl; return EXIT_FAILURE; } } else if ((arg == "-s") || (arg == "--nSols")) { if (argInd < argc) { int argI = atoi(argv[argInd++]); if(argI >= 0) { nSols = argI; } else { cerr << "Invalid argument for --nSols option: Number of " "solutions must be larger than 0." << endl; return EXIT_FAILURE; } } else { cerr << "--nSols option requires one argument." << endl; return EXIT_FAILURE; } } else if ((arg == "-n") || (arg == "--nSamps")) { if (argInd < argc) { int argI = atoi(argv[argInd++]); if(argI >= 0) { nSamps = argI; } else { cerr << "Invalid argument for --nSamps option: Number of " "solutions must be larger than 0." << endl; return EXIT_FAILURE; } } else { cerr << "--nSamps option requires one argument." << endl; return EXIT_FAILURE; } } else if ((arg == "-r") || (arg == "--rndSeed")) { if (argInd < argc) { seed = atoi(argv[argInd++]); } else { cerr << "--rndSeed option requires one argument." << endl; return EXIT_FAILURE; } } else { cerr << "Unknown argument " << arg << endl; return EXIT_FAILURE; } } if(seed < 0) { randomSeed(); } else { defineSeed(seed); } cout << "seed = " << seed << endl; cout << "nObj = " << nObj << endl; cout << "nVars = " << nVars << endl; cout << "nSols = " << nSols << endl; cout << "nSamps = " << nSamps << endl; cout << "prob = " << prob << endl; } //int main() //{ // defineSeed(0); // int nObj = 2; // int nVar = 6; // int nPareto = 5; // int nRand = 10; // int nSamp = 50; // vector<vector<double> > paretoDeterministic; // vector<vector<double> > randDeterministic; // vector<vector<vector<double> > > paretoObj; // vector<vector<vector<double> > > randObj; // vector<vector<double> > paretoDirVars = simplexLattice(nPareto-1, 2); // // Pareto optimal vectors // for(int i=0; i<paretoDirVars.size(); i++) { // vector<double> iVec(nVar, 0.5); // iVec[0] = paretoDirVars[i][0]; // vector<double> determObjVec = deterministicOVec(7, iVec, nObj); // paretoDeterministic.push_back(determObjVec); // vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp); // paretoObj.push_back(oVecSamps); // } // // Random vectors // for(int i=0; i<nRand; i++) { // vector<double> iVec; // for(int j=0; j<nVar; j++) { // iVec.push_back(randUni()); // } // vector<double> determObjVec = deterministicOVec(7, iVec, nObj); // randDeterministic.push_back(determObjVec); // vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp); // randObj.push_back(oVecSamps); // } // // Display the results // cout << "\n% Optimal vectors:" << endl; // for(int v=0; v<paretoObj.size(); v++) { // cout << "paretoObj{" << v+1 << "} = ["; // for(int i=0; i<paretoObj[v].size(); i++) { // printVector(paretoObj[v][i]); // } // cout << "];" << endl; // } // cout << "\n% Random vectors:" << endl; // for(int v=0; v<randObj.size(); v++) { // cout << "randObj{" << v+1 << "} = ["; // for(int i=0; i<randObj[v].size(); i++) { // printVector(randObj[v][i]); // } // cout << "];" << endl; // } // cout << "\n% Optimal deterministic vectors:" << endl; // cout << "determOptimal = ["; // for(int i=0; i<paretoDeterministic.size(); i++) { // printVector(paretoDeterministic[i]); // } // cout << "];" << endl; // cout << "\n% Random deterministic vectors:" << endl; // cout << "determRand = ["; // for(int i=0; i<randDeterministic.size(); i++) { // printVector(randDeterministic[i]); // } // cout << "];\n" << endl; // return 0; //} //int main(int argc, char** argv) //{ // for(int i = 0; i < argc; ++i) { // cout << "Argument " << i << ": " << argv[i] << endl; // } // return 0; //} <|endoftext|>
<commit_before>7c060a5e-5216-11e5-be03-6c40088e03e4<commit_msg>7c0c6f70-5216-11e5-85fd-6c40088e03e4<commit_after>7c0c6f70-5216-11e5-85fd-6c40088e03e4<|endoftext|>
<commit_before>6d98fbc2-2fa5-11e5-802d-00012e3d3f12<commit_msg>6d9aa976-2fa5-11e5-972a-00012e3d3f12<commit_after>6d9aa976-2fa5-11e5-972a-00012e3d3f12<|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <string> #include <stdlib.h> #include <stdio.h> #include <direct.h> #include <fcntl.h> #include <math.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <io.h> using namespace std; int info_RF(const char * dirName); int info_D(const char * dirName); int info_CS(const char * dirName); int info_BS(const char * dirName); int info_S(const char * dirName); int info_SL(const char * dirName); int info_R(const char * dirName); int info_W(const char * dirName); int info_X(const char * dirName); int main() { char *word[50]; char buf[500] = "\0"; while(word[0] != "exit"){ int i, k=0; cin.getline(buf, 500); word[k] = strtok(buf, " "); while (word[k++] != NULL) { word[k] = strtok(NULL, " "); } char checking_first = *word[0]; /* pid_t pid; pid = fork(); if(pid == 0) { if(k<=3 && word[0] != "exit"){ string cmd("./src./single_command.sh "); cmd += word[0]; cmd += " "; cmd += word[1]; system(cmd.c_str()); perror("invalid input"); } //run for single_command.sh else if(checking_first == '#'){ string cmd("./src./comment_command.sh "); system(cmd.c_str()); //run for comment_command.sh perror("invalid input"); } else if(word[0] == "exit"){ string cmd("./src./exit.sh "); cmd += word[0]; system(cmd.c_str()); perror("invalid input"); } //run for exit.sh else { int initial = 0; int hold_number = 0; int hold_other_number = 0; int ret[20]; int v[20]; while(initial <= k){ string cmd("./src./multi_command.sh "); if(word[initial] == "|"|| word[initial] == "&" || word[initial][strlen(word[initial]-1)] == ';'){ if(hold_number < initial){ while(hold_number <initial){ cmd += word[hold_number]; hold_number++; } ret[hold_other_number] = system(cmd.c_str()); v[hold_other_number] = WEXITSTATUS(ret[hold_other_number]); } } initial++; } } int status = 0; waitpid(pid, status, WNOHANG); if(status != 1){ perror("fail to close child process"); } } else if(pid == -1){ cout<<"fork error!"<<endl; } else{ cout<<"Should not be in parents"<<endl; } */ //top of part is for homework 01 which does not working so i made it as comment if(checking_first == '[' || word[0] =="test"){ checking_first = *word[1]; if(checking_first == '-'){ //All functions need that file exist if(word[1] == "-a" || word[1] == "-e"){ //True if <file> exist cout<<"file exist"<<endl; } else if(word[1] == "-f"){//True if <file> exist and is regular file info_RF(*word[2]); } else if(word[1] == "-d"){//True if <file> exist and is a directory info_D(*word[2]); } else if(word[1] == "-c"){//True if <file> exist and is character special file info_CS(*word[2]); } else if(word[1] == "-b"){//True if <file> exist and is block special file info_BS(*word[2]); } else if(word[1] == "-p"){//True if <file> exist and is named pipe // need to } else if(word[1] == "-S"){//True if <file> exist and is socket file info_S(*word[2]); } else if(word[1] == "-L" || word[1] =="-h"){//True if <file> exist and is symbolic link info_SL(*word[2]); } else if(word[1] == "-g"){//True if <file> exist and is sgid bit set // need to } else if(word[1] == "-u"){//True if <file> exist and is suid bit set // need to } else if(word[1] == "-r"){//True if <file> exist and is readable info_R(*word[2]); } else if(word[1] == "-w"){//True if <file> exist and is writeable info_W(*word[2]); } else if(word[1] == "-x"){//True if <file> exist and is excutable info_X(*word[2]); } else if(word[1] == "-s"){//True if <file> exist and size of file is bigger than 0 (not empty) //need to } else if(word[1] == "-t"){//True if file descriptor <fd> is open and refers to a terminal //need to } } checking_first = *word[2]; if(checking_first == '-'){ // there is two files to compare if(word[2] == "-nt"){// True if <file1> is newer than <file2> } else if(word[2] == "-ot"){// True if <file1> is older than <file2> } else if(word[2] == "-ef"){// True if <file1> and <file2> refer to the same device and inode numbers. } } } } return 0; } int info_RF(const char * dirName){//regular file struct stat sb; if((sb.st_mode & S_IFREG)){ return 1; } return 0; } int info_D(const char * dirName){ struct stat sb; if((sb.st_mode & S_ISDIR)){ return 1; } return 0; } int info_CS(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFCHR)){ return 1; } return 0; } int info_BS(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFBLK)){ return 1; } return 0; } int info_S(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFSOCK)){ return 1; } return 0; } int info_SL(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFKNK)){ return 1; } return 0; } int info_R(const char * dirName){//read struct stat sb; if((sb.st_mode & S_IRUSR)){ return 1; } return 0; } int info_W(const char * dirName){ struct stat sb; if((sb.st_mode & S_IWUSR)){ return 1; } return 0; } int info_X(const char * dirName){ struct stat sb; if((sb.st_mode & S_IXUSR)){ return 1; } return 0; }<commit_msg>201611191753<commit_after>#include <iostream> #include <cstring> #include <string> #include <stdlib.h> #include <stdio.h> #include <direct.h> #include <fcntl.h> #include <math.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <io.h> using namespace std; int info_RF(char* dirName); int info_D(char* dirName); int info_CS(char* dirName); int info_BS(char* dirName); int info_S(char* dirName); int info_SL(char* dirName); int info_R(char* dirName); int info_W(char* dirName); int info_X(char* dirName); int main() { char *word[50]; char buf[500] = "\0"; while(word[0] != "exit"){ int i, k=0; cin.getline(buf, 500); word[k] = strtok(buf, " "); while (word[k++] != NULL) { word[k] = strtok(NULL, " "); } char checking_first = *word[0]; /* pid_t pid; pid = fork(); if(pid == 0) { if(k<=3 && word[0] != "exit"){ string cmd("./src./single_command.sh "); cmd += word[0]; cmd += " "; cmd += word[1]; system(cmd.c_str()); perror("invalid input"); } //run for single_command.sh else if(checking_first == '#'){ string cmd("./src./comment_command.sh "); system(cmd.c_str()); //run for comment_command.sh perror("invalid input"); } else if(word[0] == "exit"){ string cmd("./src./exit.sh "); cmd += word[0]; system(cmd.c_str()); perror("invalid input"); } //run for exit.sh else { int initial = 0; int hold_number = 0; int hold_other_number = 0; int ret[20]; int v[20]; while(initial <= k){ string cmd("./src./multi_command.sh "); if(word[initial] == "|"|| word[initial] == "&" || word[initial][strlen(word[initial]-1)] == ';'){ if(hold_number < initial){ while(hold_number <initial){ cmd += word[hold_number]; hold_number++; } ret[hold_other_number] = system(cmd.c_str()); v[hold_other_number] = WEXITSTATUS(ret[hold_other_number]); } } initial++; } } int status = 0; waitpid(pid, status, WNOHANG); if(status != 1){ perror("fail to close child process"); } } else if(pid == -1){ cout<<"fork error!"<<endl; } else{ cout<<"Should not be in parents"<<endl; } */ //top of part is for homework 01 which does not working so i made it as comment if(checking_first == '[' || word[0] =="test"){ checking_first = *word[1]; if(checking_first == '-'){ //All functions need that file exist if(word[1] == "-a" || word[1] == "-e"){ //True if <file> exist cout<<"file exist"<<endl; } else if(word[1] == "-f"){//True if <file> exist and is regular file info_RF(*word[2]); } else if(word[1] == "-d"){//True if <file> exist and is a directory info_D(*word[2]); } else if(word[1] == "-c"){//True if <file> exist and is character special file info_CS(*word[2]); } else if(word[1] == "-b"){//True if <file> exist and is block special file info_BS(*word[2]); } else if(word[1] == "-p"){//True if <file> exist and is named pipe // need to } else if(word[1] == "-S"){//True if <file> exist and is socket file info_S(*word[2]); } else if(word[1] == "-L" || word[1] =="-h"){//True if <file> exist and is symbolic link info_SL(*word[2]); } else if(word[1] == "-g"){//True if <file> exist and is sgid bit set // need to } else if(word[1] == "-u"){//True if <file> exist and is suid bit set // need to } else if(word[1] == "-r"){//True if <file> exist and is readable info_R(*word[2]); } else if(word[1] == "-w"){//True if <file> exist and is writeable info_W(*word[2]); } else if(word[1] == "-x"){//True if <file> exist and is excutable info_X(*word[2]); } else if(word[1] == "-s"){//True if <file> exist and size of file is bigger than 0 (not empty) //need to } else if(word[1] == "-t"){//True if file descriptor <fd> is open and refers to a terminal //need to } } checking_first = *word[2]; if(checking_first == '-'){ // there is two files to compare if(word[2] == "-nt"){// True if <file1> is newer than <file2> } else if(word[2] == "-ot"){// True if <file1> is older than <file2> } else if(word[2] == "-ef"){// True if <file1> and <file2> refer to the same device and inode numbers. } } } } return 0; } int info_RF(char* dirName){//regular file struct stat sb; if((sb.st_mode & S_IFREG)){ return 1; } return 0; } int info_D(char* dirName){ struct stat sb; if((sb.st_mode & S_ISDIR)){ return 1; } return 0; } int info_CS(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFCHR)){ return 1; } return 0; } int info_BS(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFBLK)){ return 1; } return 0; } int info_S(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFSOCK)){ return 1; } return 0; } int info_SL(const char * dirName){ struct stat sb; if((sb.st_mode & S_IFKNK)){ return 1; } return 0; } int info_R(const char * dirName){//read struct stat sb; if((sb.st_mode & S_IRUSR)){ return 1; } return 0; } int info_W(const char * dirName){ struct stat sb; if((sb.st_mode & S_IWUSR)){ return 1; } return 0; } int info_X(const char * dirName){ struct stat sb; if((sb.st_mode & S_IXUSR)){ return 1; } return 0; }<|endoftext|>
<commit_before>9c2de3c2-2747-11e6-bc07-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>9c3e3500-2747-11e6-ae0a-e0f84713e7b8<|endoftext|>
<commit_before>66af1aca-2e4f-11e5-9e5d-28cfe91dbc4b<commit_msg>66b777b0-2e4f-11e5-aed2-28cfe91dbc4b<commit_after>66b777b0-2e4f-11e5-aed2-28cfe91dbc4b<|endoftext|>
<commit_before>/* * Copyright 2017 Jussi Pakkanen * * 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<speedup.hpp> #include<cstdio> #include<vector> #include<random> #include<chrono> constexpr const int BUFSIZE=100*1024*1024; std::vector<uint8_t> create_random_array() { std::vector<uint8_t> buf; std::mt19937 gen(42); // For reproducibility. std::uniform_int_distribution<> dis(0, 255); buf.reserve(BUFSIZE); for(int i=0; i<BUFSIZE; i++) { buf.push_back(dis(gen)); } return buf; } int main(int, char**) { int failed = 0; const uint64_t correct_answer = 10038597640; auto buf = create_random_array(); auto mutbuf = buf; auto mutbuf2 = buf; auto t0 = std::chrono::high_resolution_clock::now(); auto simple_answer = simple_loop(buf.data(), buf.size()); auto t1 = std::chrono::high_resolution_clock::now(); auto cheaty_answer = cheaty_mccheatface(buf.data(), buf.size()); auto t2 = std::chrono::high_resolution_clock::now(); auto lut_answer = lookup_table(buf.data(), buf.size()); auto t3 = std::chrono::high_resolution_clock::now(); auto bit_answer = bit_fiddling(buf.data(), buf.size()); auto t4 = std::chrono::high_resolution_clock::now(); auto partition_answer = partition(mutbuf.data(), mutbuf.size()); auto t5 = std::chrono::high_resolution_clock::now(); auto zeroing_answer = zeroing(mutbuf2.data(), mutbuf.size()); auto t6 = std::chrono::high_resolution_clock::now(); auto bucket_answer = bucket(buf.data(), buf.size()); auto t7 = std::chrono::high_resolution_clock::now(); if(simple_answer != correct_answer) { printf("Simple loop produced wrong answer: %ld\n", simple_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count(); printf("Simple loop took %ld ms\n", count); } if(cheaty_answer != correct_answer) { printf("Cheaty produced wrong answer: %ld\n", cheaty_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count(); printf("Cheaty McCheatface took %ld ms\n", count); } if(lut_answer != correct_answer) { printf("Lookup table produced wrong answer: %ld\n", lut_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t3-t2).count(); printf("Lookup table took %ld ms\n", count); } if(bit_answer != correct_answer) { printf("Bit fiddling produced wrong answer: %ld\n", bit_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t4-t3).count(); printf("Bit fiddling took %ld ms\n", count); } if(partition_answer != correct_answer) { printf("Partitioning produced wrong answer: %ld\n", partition_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t5-t4).count(); printf("Partitioning took %ld ms\n", count); } if(zeroing_answer != correct_answer) { printf("Zeroing produced wrong answer: %ld\n", zeroing_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t6-t5).count(); printf("Zeroing took %ld ms\n", count); } if(bucket_answer != correct_answer) { printf("Bucket produced wrong answer: %ld\n", bucket_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t7-t6).count(); printf("Bucket took %ld ms\n", count); } return failed; } <commit_msg>Portability fix.<commit_after>/* * Copyright 2017 Jussi Pakkanen * * 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<speedup.hpp> #include<cstdio> #include<vector> #include<random> #include<chrono> constexpr const int BUFSIZE=100*1024*1024; std::vector<uint8_t> create_random_array() { std::vector<uint8_t> buf; std::mt19937 gen(42); // For reproducibility. std::uniform_int_distribution<> dis(0, 255); buf.reserve(BUFSIZE); for(int i=0; i<BUFSIZE; i++) { buf.push_back(dis(gen)); } return buf; } int main(int, char**) { int failed = 0; const uint64_t correct_answer = 10038597640; auto buf = create_random_array(); auto mutbuf = buf; auto mutbuf2 = buf; auto t0 = std::chrono::high_resolution_clock::now(); auto simple_answer = simple_loop(buf.data(), buf.size()); auto t1 = std::chrono::high_resolution_clock::now(); auto cheaty_answer = cheaty_mccheatface(buf.data(), buf.size()); auto t2 = std::chrono::high_resolution_clock::now(); auto lut_answer = lookup_table(buf.data(), buf.size()); auto t3 = std::chrono::high_resolution_clock::now(); auto bit_answer = bit_fiddling(buf.data(), buf.size()); auto t4 = std::chrono::high_resolution_clock::now(); auto partition_answer = partition(mutbuf.data(), mutbuf.size()); auto t5 = std::chrono::high_resolution_clock::now(); auto zeroing_answer = zeroing(mutbuf2.data(), mutbuf.size()); auto t6 = std::chrono::high_resolution_clock::now(); auto bucket_answer = bucket(buf.data(), buf.size()); auto t7 = std::chrono::high_resolution_clock::now(); if(simple_answer != correct_answer) { printf("Simple loop produced wrong answer: %ld\n", (long)simple_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count(); printf("Simple loop took %ld ms\n", (long)count); } if(cheaty_answer != correct_answer) { printf("Cheaty produced wrong answer: %ld\n", (long)cheaty_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count(); printf("Cheaty McCheatface took %ld ms\n", (long)count); } if(lut_answer != correct_answer) { printf("Lookup table produced wrong answer: %ld\n", (long)lut_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t3-t2).count(); printf("Lookup table took %ld ms\n", (long)count); } if(bit_answer != correct_answer) { printf("Bit fiddling produced wrong answer: %ld\n", (long)bit_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t4-t3).count(); printf("Bit fiddling took %ld ms\n", (long)count); } if(partition_answer != correct_answer) { printf("Partitioning produced wrong answer: %ld\n", (long)partition_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t5-t4).count(); printf("Partitioning took %ld ms\n", (long)count); } if(zeroing_answer != correct_answer) { printf("Zeroing produced wrong answer: %ld\n", (long)zeroing_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t6-t5).count(); printf("Zeroing took %ld ms\n", (long)count); } if(bucket_answer != correct_answer) { printf("Bucket produced wrong answer: %ld\n", (long)bucket_answer); failed++; } else { int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t7-t6).count(); printf("Bucket took %ld ms\n", (long)count); } return failed; } <|endoftext|>
<commit_before>e02826fd-2747-11e6-9bc2-e0f84713e7b8<commit_msg>Finished?<commit_after>e0338fb0-2747-11e6-8f5b-e0f84713e7b8<|endoftext|>