text
stringlengths
54
60.6k
<commit_before>/** * Project * # # # ###### ###### * # # # # # # # # * # # # # # # # # * ### # # ###### ###### * # # ####### # # # # * # # # # # # # # * # # # # # # # # * * Copyright (c) 2014, Project KARR * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <GL/glut.h> #include <vg/openvg.h> #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #include <bgfx.h> #include <bgfxplatform.h> #include <string> #include <sstream> #include "ArduinoDataPacket.h" #include "Display.h" #include "DisplayManager.h" #include "GLUtil.h" #include "CelicaDisplay.h" #include "Instrument.h" #include "SimpleTextDisplay.h" #include "SerialConnection.h" #include "TestInput.h" #include "Knight_Industries.C" using namespace KARR; using namespace std; static const int w = 1024; static const int h = 600; static SerialConnection sArduinoConnection; static std::vector<Instrument> sInstruments; void handleKeyboard(unsigned char key, int x, int y) { if (key == 27) exit(0); } void handleDisplay() { int now; static bool timeinit = false; static int fpsdraw = -1; static int fps = 0; static int lastfps = 0; static ArduinoDataPacket dataPacket; { /* Read data from Arduino */ if (sArduinoConnection.isOpened()) { memset(&dataPacket, '\0', sizeof(ArduinoDataPacket)); if (sArduinoConnection.read((void *)&dataPacket, sizeof(ArduinoDataPacket))) { // Update data } } } // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, w, h); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text."); for (Instrument &instrument : sInstruments) { instrument.draw(); } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } void cleanup() { // Shutdown bgfx. bgfx::shutdown(); } int initScreen() { SDL_InitSubSystem(SDL_INIT_VIDEO); auto sdlWindow = SDL_CreateWindow("karr" , SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED , w , h , SDL_WINDOW_SHOWN ); bgfx::sdlSetWindow(sdlWindow); #if 0 glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_STENCIL | GLUT_MULTISAMPLE); glutInitWindowPosition(0,0); glutInitWindowSize(w,h); glutCreateWindow("KARR"); glutDisplayFunc(handleDisplay); glutIdleFunc(glutPostRedisplay ); glutKeyboardFunc(handleKeyboard); #endif atexit(cleanup); bgfx::init(); bgfx::reset(w, h, BGFX_RESET_VSYNC); // Set view 0 clear state. bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x303030ff, 1.0f, 0); return 0; } void initCommunication() { sArduinoConnection.open("/dev/ttyAMA0"); } int main(int argc, char** argv) { SDL_Init(0); initScreen(); initCommunication(); TestInput::run(); do { SDL_Event event; if (SDL_PollEvent(&event)) { // Do something with event } handleDisplay(); } while (1); glutMainLoop(); return 0; } <commit_msg>Destroy the SDL window on exit.<commit_after>/** * Project * # # # ###### ###### * # # # # # # # # * # # # # # # # # * ### # # ###### ###### * # # ####### # # # # * # # # # # # # # * # # # # # # # # * * Copyright (c) 2014, Project KARR * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <GL/glut.h> #include <vg/openvg.h> #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #include <bgfx.h> #include <bgfxplatform.h> #include <string> #include <sstream> #include "ArduinoDataPacket.h" #include "Display.h" #include "DisplayManager.h" #include "GLUtil.h" #include "CelicaDisplay.h" #include "Instrument.h" #include "SimpleTextDisplay.h" #include "SerialConnection.h" #include "TestInput.h" #include "Knight_Industries.C" using namespace KARR; using namespace std; static const int w = 1024; static const int h = 600; static SDL_Window *sSdlWindow = nullptr; static SerialConnection sArduinoConnection; static std::vector<Instrument> sInstruments; void handleKeyboard(unsigned char key, int x, int y) { if (key == 27) exit(0); } void handleDisplay() { int now; static bool timeinit = false; static int fpsdraw = -1; static int fps = 0; static int lastfps = 0; static ArduinoDataPacket dataPacket; { /* Read data from Arduino */ if (sArduinoConnection.isOpened()) { memset(&dataPacket, '\0', sizeof(ArduinoDataPacket)); if (sArduinoConnection.read((void *)&dataPacket, sizeof(ArduinoDataPacket))) { // Update data } } } // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, w, h); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text."); for (Instrument &instrument : sInstruments) { instrument.draw(); } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } void cleanup() { // Shutdown bgfx. bgfx::shutdown(); SDL_DestroyWindow(sSdlWindow); SDL_Quit(); } int initScreen() { SDL_InitSubSystem(SDL_INIT_VIDEO); sSdlWindow = SDL_CreateWindow("karr", SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED, w , h , SDL_WINDOW_SHOWN); bgfx::sdlSetWindow(sSdlWindow); atexit(cleanup); bgfx::init(); bgfx::reset(w, h, BGFX_RESET_VSYNC); // Set view 0 clear state. bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x303030ff, 1.0f, 0); return 0; } void initCommunication() { sArduinoConnection.open("/dev/ttyAMA0"); } int main(int argc, char** argv) { SDL_Init(0); initScreen(); initCommunication(); TestInput::run(); do { SDL_Event event; if (SDL_PollEvent(&event)) { // Do something with event } handleDisplay(); } while (1); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2016, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_TYPES_REFERENCE_H_ #define LUWRA_TYPES_REFERENCE_H_ #include "../common.hpp" #include "../values.hpp" #include <memory> LUWRA_NS_BEGIN namespace internal { // Create reference to the value pointed to by `index`. Does not remove the referenced value. inline int referenceValue(State* state, int index) { lua_pushvalue(state, index); return luaL_ref(state, LUA_REGISTRYINDEX); } } /// Lifecyle of a reference struct RefLifecycle { /// State with the reference registry State* state; /// Reference identification int ref; /// Create a reference using the value on top of the stack. Consumes the value. inline RefLifecycle(State* state): state(state), ref(luaL_ref(state, LUA_REGISTRYINDEX)) {} /// Create a reference to a value on the stack. Does not consume the value. inline RefLifecycle(State* state, int index): state(state) { lua_pushvalue(state, index); ref = luaL_ref(state, LUA_REGISTRYINDEX); } /// Create a reference using an existing one. The lifecycles of these references are /// independent. inline RefLifecycle(const RefLifecycle& other): state(other.state) { lua_rawgeti(other.state, LUA_REGISTRYINDEX, other.ref); ref = luaL_ref(state, LUA_REGISTRYINDEX); } /// Take over an existing reference. The given reference's lifecycle is terminated. inline RefLifecycle(RefLifecycle&& other): state(other.state), ref(other.ref) { other.ref = LUA_NOREF; } inline ~RefLifecycle() { luaL_unref(state, LUA_REGISTRYINDEX, ref); } /// Push the value inside the reference cell onto the originating Lua stack. inline void load() const { lua_rawgeti(state, LUA_REGISTRYINDEX, ref); } /// Push the value inside the reference cell onto the given Lua stack. inline void load(State* target) const { lua_rawgeti(state, LUA_REGISTRYINDEX, ref); if (target != state) lua_xmove(state, target, 1); } }; /// Handle for a reference struct Reference { /// Smart pointer to the reference's lifecycle manager /// /// Why a smart pointer? Copying RefLifecycle creates new Lua references, which we want to /// avoid. Therefore we use shared_ptr which gives us cheap reference counting. std::shared_ptr<const RefLifecycle> life; /// Create a reference using the value on top of the stack. Consumes the value. inline Reference(State* state): life(std::make_shared<RefLifecycle>(state)) {} /// Create a reference to a value on the stack. Does not consume the value. inline Reference(State* state, int index): life(std::make_shared<RefLifecycle>(state, index)) {} }; /// Enables referencing/dereferencing values template <> struct Value<Reference> { static inline Reference read(State* state, int index) { return {state, index}; } static inline void push(State* state, const Reference& value) { if (!value.life) { lua_pushnil(state); return; } value.life->load(state); } }; LUWRA_NS_END #endif <commit_msg>Add 'Value' specialization for 'RefLifecycle'<commit_after>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2016, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_TYPES_REFERENCE_H_ #define LUWRA_TYPES_REFERENCE_H_ #include "../common.hpp" #include "../values.hpp" #include <memory> LUWRA_NS_BEGIN namespace internal { // Create reference to the value pointed to by `index`. Does not remove the referenced value. inline int referenceValue(State* state, int index) { lua_pushvalue(state, index); return luaL_ref(state, LUA_REGISTRYINDEX); } } /// Lifecyle of a reference struct RefLifecycle { /// State with the reference registry State* state; /// Reference identification int ref; /// Create a reference using the value on top of the stack. Consumes the value. inline RefLifecycle(State* state): state(state), ref(luaL_ref(state, LUA_REGISTRYINDEX)) {} /// Create a reference to a value on the stack. Does not consume the value. inline RefLifecycle(State* state, int index): state(state) { lua_pushvalue(state, index); ref = luaL_ref(state, LUA_REGISTRYINDEX); } /// Create a reference using an existing one. The lifecycles of these references are /// independent. inline RefLifecycle(const RefLifecycle& other): state(other.state) { lua_rawgeti(other.state, LUA_REGISTRYINDEX, other.ref); ref = luaL_ref(state, LUA_REGISTRYINDEX); } /// Take over an existing reference. The given reference's lifecycle is terminated. inline RefLifecycle(RefLifecycle&& other): state(other.state), ref(other.ref) { other.ref = LUA_NOREF; } inline ~RefLifecycle() { luaL_unref(state, LUA_REGISTRYINDEX, ref); } /// Push the value inside the reference cell onto the originating Lua stack. inline void load() const { lua_rawgeti(state, LUA_REGISTRYINDEX, ref); } /// Push the value inside the reference cell onto the given Lua stack. inline void load(State* target) const { lua_rawgeti(state, LUA_REGISTRYINDEX, ref); if (target != state) lua_xmove(state, target, 1); } }; /// template <> struct Value<RefLifecycle> { static inline RefLifecycle read(State* state, int index) { return {state, index}; } static inline void push(State* state, const RefLifecycle& life) { life.push(state); } }; /// Handle for a reference struct Reference { /// Smart pointer to the reference's lifecycle manager /// /// Why a smart pointer? Copying RefLifecycle creates new Lua references, which we want to /// avoid. Therefore we use shared_ptr which gives us cheap reference counting. std::shared_ptr<const RefLifecycle> life; /// Create a reference using the value on top of the stack. Consumes the value. inline Reference(State* state): life(std::make_shared<RefLifecycle>(state)) {} /// Create a reference to a value on the stack. Does not consume the value. inline Reference(State* state, int index): life(std::make_shared<RefLifecycle>(state, index)) {} }; /// Enables referencing/dereferencing values template <> struct Value<Reference> { static inline Reference read(State* state, int index) { return {state, index}; } static inline void push(State* state, const Reference& value) { if (!value.life) { lua_pushnil(state); return; } value.life->load(state); } }; LUWRA_NS_END #endif <|endoftext|>
<commit_before>/* * boostMPI template, boost+boostMPI, include boost include/lib MS-MPI include, and MS-MPI library, which is msmpi.lib * Author: Shirong Bai * Email: bunnysirah@hotmail.com or shirong.bai@colorado.edu * Date: 10/08/2015 */ #include <cstdlib> #include "../include/drivers/drivers.h" #include "../include/tools/my_debug/my_debug.h" int main(int argc, char **argv) { /*************************************************************************************************/ /* * 0. Parse parameters * Default, has to run */ /*************************************************************************************************/ po::variables_map vm; // current working directory std::string main_cwd; // boost property tree boost::property_tree::ptree pt; driver::parse_parameters(argc, argv, vm, main_cwd, pt); #if defined(__NO_USE_MPI_) if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(main_cwd, pt); #endif // __NO_USE_MPI_ #if defined(__USE_MPI_) boost::mpi::environment env(argc, argv); boost::mpi::communicator world; MyClock_us timer; if (world.rank() == 0) timer.begin(); /*************************************************************************************************/ /* * 1. Solve for concentration of Lokta-Voltera system or Dimerization or Michaelis Menten, using LSODE */ /*************************************************************************************************/ if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_LSODE")) driver::solve_ODEs_for_concentration_using_LSODE(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_SSA")) driver::solve_ODEs_for_concentration_using_SSA(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("write_concentration_at_time_to_file")) driver::write_concentration_at_time_to_file(world, main_cwd, pt); /*************************************************************************************************/ /* * 2. Generate pathway first, it might take some time, depends on what kinds of pathway you want */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); //2.1. else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); /*************************************************************************************************/ /* * 3. Evaluate pathway integral using Importance based Monte Carlo simulation */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(world, main_cwd, pt); /*************************************************************************************************/ /* * 4. For speciation, print out concentration at for different sets of rate constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("speciation_evaluate_concentrations_for_different_sets_rate_coefficients")) driver::speciation_evaluate_concentrations_for_different_sets_rate_coefficients(world, main_cwd, pt); /*************************************************************************************************/ /* * 5. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 2 * Monte Carlo simulation * not parallel code */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_single_core")) driver::ODE_solver_MC_trajectory_single_core(world, main_cwd, pt); /*************************************************************************************************/ /* * 6. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 4 * constant temperature, surface reactions, independent of pressure * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_s_ct_np_parallel")) driver::ODE_solver_MC_trajectory_s_ct_np_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 7. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 5 * varing temperature, varing pressure, constant volume, H2-O2 system, not working because the initiation * is actually a rare event, stochastic trajectory converge too slow * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_cv_parallel")) driver::ODE_solver_MC_trajectory_cv_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 8. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v2")) driver::ODE_solver_path_integral_parallel_s_ct_np_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v3")) driver::ODE_solver_path_integral_parallel_s_ct_np_v3(world, main_cwd, pt); /*************************************************************************************************/ /* * 9. Pathway based equation solver, solve differential equations derived from chemical mechanisms * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability * hold concentration of some species to be constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_cc1_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_cc1_v1(world, main_cwd, pt); /*************************************************************************************************/ /* * 10. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * constant volume, varying temperature, varying pressure * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v9")) driver::ODE_solver_path_integral_parallel_cv_v9(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v10")) driver::ODE_solver_path_integral_parallel_cv_v10(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v11")) driver::ODE_solver_path_integral_parallel_cv_v11(world, main_cwd, pt); /* * 11. constant volume, constant temperature */ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v1")) driver::ODE_solver_path_integral_parallel_cv_ct_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v2")) driver::ODE_solver_path_integral_parallel_cv_ct_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v3")) driver::ODE_solver_path_integral_parallel_cv_ct_v3(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v4")) driver::ODE_solver_path_integral_parallel_cv_ct_v4(world, main_cwd, pt); /*************************************************************************************************/ /* * 12. Dijkstra based algorithm, actually it is eppstein's k-shortest path algorightm */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("k_shortest_path_algorithms")) driver::k_shortest_path_algorithms(world, main_cwd); /*************************************************************************************************/ /* * 13. M-matrix test */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("M_matrix_R_matrix")) driver::M_matrix_R_matrix(world, main_cwd); /*************************************************************************************************/ /* * MISC */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("MISC")) driver::MISC(world, main_cwd); #endif // __USE_MPI_ return EXIT_SUCCESS; } <commit_msg>minor<commit_after>/* * boostMPI template, boost+boostMPI, include boost include/lib MS-MPI include, and MS-MPI library, which is msmpi.lib * Author: Shirong Bai * Email: bunnysirah@hotmail.com or shirong.bai@colorado.edu * Date: 10/08/2015 */ #include <cstdlib> #include "../include/drivers/drivers.h" #include "../include/tools/my_debug/my_debug.h" int main(int argc, char **argv) { /*************************************************************************************************/ /* * 0. Parse parameters * Default, has to run */ /*************************************************************************************************/ po::variables_map vm; // current working directory std::string main_cwd; // boost property tree boost::property_tree::ptree pt; driver::parse_parameters(argc, argv, vm, main_cwd, pt); #if defined(__NO_USE_MPI_) if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(main_cwd, pt); #endif // __NO_USE_MPI_ #if defined(__USE_MPI_) boost::mpi::environment env(argc, argv); boost::mpi::communicator world; MyClock_us timer; if (world.rank() == 0) timer.begin(); /*************************************************************************************************/ /* * 1. Solve for concentration of Lokta-Voltera system or Dimerization or Michaelis Menten, using LSODE */ /*************************************************************************************************/ if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_LSODE")) driver::solve_ODEs_for_concentration_using_LSODE(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_SSA")) driver::solve_ODEs_for_concentration_using_SSA(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("write_concentration_at_time_to_file")) driver::write_concentration_at_time_to_file(world, main_cwd, pt); /*************************************************************************************************/ /* * 2. Generate pathway first, it might take some time, depends on what kinds of pathway you want */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); //2.1. else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); /*************************************************************************************************/ /* * 3. Evaluate pathway integral using Importance based Monte Carlo simulation */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(world, main_cwd, pt); /*************************************************************************************************/ /* * 4. For speciation, print out concentration at for different sets of rate constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("speciation_evaluate_concentrations_for_different_sets_rate_coefficients")) driver::speciation_evaluate_concentrations_for_different_sets_rate_coefficients(world, main_cwd, pt); /*************************************************************************************************/ /* * 5. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 2 * Monte Carlo simulation * not parallel code */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_single_core")) driver::ODE_solver_MC_trajectory_single_core(world, main_cwd, pt); /*************************************************************************************************/ /* * 6. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 4 * constant temperature, surface reactions, independent of pressure * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_s_ct_np_parallel")) driver::ODE_solver_MC_trajectory_s_ct_np_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 7. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 5 * varing temperature, varing pressure, constant volume, H2-O2 system, not working because the initiation * is actually a rare event, stochastic trajectory converge too slow * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_cv_parallel")) driver::ODE_solver_MC_trajectory_cv_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 8. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v2")) driver::ODE_solver_path_integral_parallel_s_ct_np_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v3")) driver::ODE_solver_path_integral_parallel_s_ct_np_v3(world, main_cwd, pt); /*************************************************************************************************/ /* * 9. Pathway based equation solver, solve differential equations derived from chemical mechanisms * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability * hold concentration of some species to be constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_cc1_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_cc1_v1(world, main_cwd, pt); /*************************************************************************************************/ /* * 10. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * constant volume, varying temperature, varying pressure * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v9")) driver::ODE_solver_path_integral_parallel_cv_v9(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v10")) driver::ODE_solver_path_integral_parallel_cv_v10(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v11")) driver::ODE_solver_path_integral_parallel_cv_v11(world, main_cwd, pt); /* * 11. constant volume, constant temperature */ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v1")) driver::ODE_solver_path_integral_parallel_cv_ct_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v2")) driver::ODE_solver_path_integral_parallel_cv_ct_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v3")) driver::ODE_solver_path_integral_parallel_cv_ct_v3(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v4")) driver::ODE_solver_path_integral_parallel_cv_ct_v4(world, main_cwd, pt); /*************************************************************************************************/ /* * 13. M-matrix test */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("M_matrix_R_matrix")) driver::M_matrix_R_matrix(world, main_cwd); /*************************************************************************************************/ /* * MISC */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("MISC")) driver::MISC(world, main_cwd); #endif // __USE_MPI_ return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Includes #include <Arduino.h> #include <Wire.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING 1 #define FILE_LOGGING 1 // Compile-Time Constants #define SD_CARD_PIN 10 #define RTC_PIN_1 4 #define RTC_PIN_2 5 #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; File log_file; File data_file; RTC_PCF8523 rtc; // To save memory, use global data point variables. DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; unsigned int latest_temperature; // Utility Methods void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) Serial.println(msg); else Serial.print(msg); } if (FILE_LOGGING) { if (!log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } } } } void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); while(1); // Loop forever } void update_formatted_timestamp() { sprintf(formatted_timestamp, "%u-%u-%uT%u:%u:%u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } // Main Methods void setup() { // TODO: Set up pins // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_file_000.txt"; for (uint8_t i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 32 to get ASCII number characters. log_file_name[6] = i / 100 + 32; log_file_name[7] = i / 10 + 32; log_file_name[8] = i % 10 + 32; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // TODO: Calibrate RTC // SET UP DATA FILE log("Creating data file..."); char data_file_name[] = "data_file_000.csv"; for (uint8_t i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 32 to get ASCII number characters. data_file_name[6] = i / 100 + 32; data_file_name[7] = i / 10 + 32; data_file_name[8] = i % 10 + 32; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp); } void loop() { // Main Loop // TODO: Main Loop delay(1000); } <commit_msg>Add work-in-progress methods for taking and saving readings.<commit_after>// Includes #include <Arduino.h> #include <Wire.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING 1 #define FILE_LOGGING 1 // Compile-Time Constants #define SD_CARD_PIN 10 #define RTC_PIN_1 4 #define RTC_PIN_2 5 #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; File log_file; File data_file; RTC_PCF8523 rtc; // To save memory, use global data point variables. DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); unsigned int latest_temperature; // Utility Methods void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) Serial.println(msg); else Serial.print(msg); } if (FILE_LOGGING) { if (!log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } } } } void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); while(1); // Loop forever } void update_formatted_timestamp() { sprintf(formatted_timestamp, "%u-%u-%uT%u:%u:%u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } void take_reading() { now = rtc.now(); // TODO: Take a temperature reading } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); sprintf(data_file_entry_buffer, "%u,%s", latest_temperature, formatted_timestamp); data_file.println(data_file_entry_buffer); } } // Main Methods void setup() { // TODO: Set up pins // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_file_000.txt"; for (uint8_t i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 32 to get ASCII number characters. log_file_name[6] = i / 100 + 32; log_file_name[7] = i / 10 + 32; log_file_name[8] = i % 10 + 32; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // TODO: Calibrate RTC // SET UP DATA FILE log("Creating data file..."); char data_file_name[] = "data_file_000.csv"; for (uint8_t i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 32 to get ASCII number characters. data_file_name[6] = i / 100 + 32; data_file_name[7] = i / 10 + 32; data_file_name[8] = i % 10 + 32; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temperature"); // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp); } void loop() { // TODO: (Optional) Exit sleep take_reading(); save_reading_to_card(); // TODO: (Optional) Enter sleep delay(1000); } <|endoftext|>
<commit_before>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "configuration.h" #include "script/script.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ static const int TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; void inc_speed_counter() { Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ Bitmap::setGfxModeText(); allegro_exit(); exit(0); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } static void close_paintown(){ exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode( SWITCH_BACKGROUND ); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <commit_msg>call allegro_exit in the close handler as well<commit_after>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "configuration.h" #include "script/script.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ static const int TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; void inc_speed_counter() { Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(0); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } static void close_paintown(){ Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode( SWITCH_BACKGROUND ); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <map> #include "util/Sysout.h" #include "util/Sysin.h" #include "language/Lexicographer.h" #include "command/CmdLexicographer.h" #include "Game.h" // Initialization put in a handy auxiliary function! void init() { // Legend Sysout::println("Fuzzy Computing Machine"); Sysout::println(); // Add words Lexicographer::graph(); // Add commands CmdLexicographer::graph(); } // This is where the magic happens! int main() { /* === Testing === */ // Put something here, k? /* === Actual program === */ // Initialize init(); // Game game; game.start(); // Died quietly return 0; } <commit_msg>Removed unnecessary #includes<commit_after>#include <string> #include "util/Sysout.h" #include "language/Lexicographer.h" #include "command/CmdLexicographer.h" #include "Game.h" // Initialization put in a handy auxiliary function! void init() { // Legend Sysout::println("Fuzzy Computing Machine"); Sysout::println(); // Add words Lexicographer::graph(); // Add commands CmdLexicographer::graph(); } // This is where the magic happens! int main() { // Initialize init(); // Put like, a main menu here or something // Reminds me of JME Game game; game.start(); // Died quietly return 0; } <|endoftext|>
<commit_before>//this is our main file // testing #include <iostream> #include <boost/tokenizer.hpp> #include <string> using namespace std; int main() { vector<string> parse; string str; cout << "$"; getline(cin, str); cout << endl; while(str != "exit") { typedef boost::toknizer<boost::char_separator<char> > Tok; boost::char_separator<shar> sep("", "|&#;"); Tok tok(str, sep); for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) { parse.push_back(*tok_iter); } //do class work here parse.clear(); cout << "$"; getline(cin, str); cout << endl; } return 0; } <commit_msg>updated the parsing function to display username and hostname (extra credit)<commit_after>//this is our main file // testing #include <unistd.h> #include <stdio.h> #include <vector> #include <iostream> #include <boost/tokenizer.hpp> #include <string> using namespace std; int main() { char hostname[150]; gethostname(hostname, sizeof hostname); vector<string> parse; string str; cout << getlogin() << "@" << hostname << "$ "; //cout << "$"; getline(cin, str); cout << endl; while(str != "exit") { typedef boost::tokenizer<boost::char_separator<char> > Tok; boost::char_separator<char> sep("", "|&#;"); Tok tok(str, sep); for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) { parse.push_back(*tok_iter); } //do class work here parse.clear(); cout << getlogin() << "@" << hostname << "$ "; //cout << "$"; getline(cin, str); cout << endl; } return 0; } <|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <sstream> #include "file_manager/FileManager.h" #include "p2p_network/p2p_manager/p2pnode.h" #include "app/app.h" using namespace std; int main(int argc, char * argv[]) { if (argc != 6) { std::cerr << "App port, File mgr port, Server port, Main server ip, Main server port\n"; return 1; } App::Settings settings; std::stringstream strm; for (int c = 1; c < argc; ++c) { strm << argv[c] << ' '; } strm >> settings.app_port >> settings.file_mgr_port >> settings.server_port >> settings.main_server >> settings.ms_port; App app( settings, std::unique_ptr<FileManagerInterface>(new FileManager(settings.file_mgr_port)), std::unique_ptr<P2PNetworkInterface>(new P2PNode(settings.ms_port, settings.server_port, settings.file_mgr_port))); app.run(); while (1) { std::string fileName, exportName; cout << "Enter file path to import:\n"; std::getline(cin, fileName); cout << "Enter file path to export:\n"; std::getline(cin, exportName); if (!app.importFile(fileName)) { std::cerr << "Failed to add file to storage\n"; continue; } else { std::cout << "Imported!\n"; } auto r = app.isFileInStorage(fileName); if (r == App::FileAvailability::None) { std::cerr << "File should be in in High availability... continuing\n"; } else if (r != App::FileAvailability::High) { std::cerr << "File not available ! \n"; continue; } else { std::cout << "Available!\n"; } if (!app.exportFile(fileName, exportName)) { std::cerr << "Failed to export file from storage"; } else { std::cout << "Exported!\n"; } } std::cout << "\n\nAll good exiting"; std::cin.get(); return 0; } <commit_msg>Remove unused settings from cmd<commit_after>#include <memory> #include <iostream> #include <sstream> #include "file_manager/FileManager.h" #include "p2p_network/p2p_manager/p2pnode.h" #include "app/app.h" using namespace std; int main(int argc, char * argv[]) { if (argc != 4) { std::cerr << "File mgr port, Server port, Main server ip\n"; return 1; } App::Settings settings; std::stringstream strm; for (int c = 1; c < argc; ++c) { strm << argv[c] << ' '; } strm >> settings.file_mgr_port >> settings.server_port >> settings.main_server; settings.main_server = "127.0.0.1"; settings.ms_port = 5005; settings.app_port = -1; App app( settings, std::unique_ptr<FileManagerInterface>(new FileManager(settings.file_mgr_port)), std::unique_ptr<P2PNetworkInterface>(new P2PNode(settings.ms_port, settings.server_port, settings.file_mgr_port))); app.run(); while (1) { std::string fileName, exportName; cout << "Enter file path to import:\n"; std::getline(cin, fileName); cout << "Enter file path to export:\n"; std::getline(cin, exportName); if (!app.importFile(fileName)) { std::cerr << "Failed to add file to storage\n"; continue; } else { std::cout << "Imported!\n"; } auto r = app.isFileInStorage(fileName); if (r == App::FileAvailability::None) { std::cerr << "File should be in in High availability... continuing\n"; } else if (r != App::FileAvailability::High) { std::cerr << "File not available ! \n"; continue; } else { std::cout << "Available!\n"; } if (!app.exportFile(fileName, exportName)) { std::cerr << "Failed to export file from storage"; } else { std::cout << "Exported!\n"; } } std::cout << "\n\nAll good exiting"; std::cin.get(); return 0; } <|endoftext|>
<commit_before>// MAIN SOURCE #include <iostream> #include <fstream> #include "checker.h" #include "include/configuration.h" #include "gflags/gflags.h" namespace sqlcheck { Configuration state; } // namespace sqlcheck DEFINE_bool(c, false, "Display warnings in color mode"); DEFINE_bool(color_mode, false, "Display warnings in color mode"); DEFINE_bool(v, false, "Display verbose warnings"); DEFINE_bool(verbose, false, "Display verbose warnings"); DEFINE_string(d, "", "Query delimiter string (default -- ;)"); DEFINE_string(delimiter, "", "Query delimiter string (default -- ;)"); DEFINE_bool(h, false, "Print help message"); DEFINE_uint64(r, sqlcheck::RISK_LEVEL_ALL, "Set of anti-patterns to check \n" "1 (all anti-patterns, default) \n" "2 (only medium and high risk anti-patterns) \n" "3 (only high risk anti-patterns) \n"); DEFINE_uint64(risk_level, sqlcheck::RISK_LEVEL_ALL, "Set of anti-patterns to check \n" "1 (all anti-patterns, default) \n" "2 (only medium and high risk anti-patterns) \n" "3 (only high risk anti-patterns) \n"); DEFINE_string(f, "", "SQL file name"); // standard input DEFINE_string(file_name, "", "SQL file name"); // standard input void ConfigureChecker(sqlcheck::Configuration &state) { // Default Values state.risk_level = sqlcheck::RISK_LEVEL_ALL; state.file_name = ""; state.delimiter = ";"; state.testing_mode = false; state.verbose = false; state.color_mode = false; // Configure checker state.color_mode = FLAGS_c || FLAGS_color_mode; state.verbose = FLAGS_v || FLAGS_verbose; if(FLAGS_f.empty() == false){ state.file_name = FLAGS_f; } if(FLAGS_file_name.empty() == false){ state.file_name = FLAGS_file_name; } if(FLAGS_d.empty() == false){ state.delimiter = FLAGS_f; } if(FLAGS_delimiter.empty() == false){ state.delimiter = FLAGS_delimiter; } if(FLAGS_r != 0){ state.risk_level = (sqlcheck::RiskLevel) FLAGS_r; } if(FLAGS_risk_level != 0){ state.risk_level = (sqlcheck::RiskLevel) FLAGS_risk_level; } // Run validators std::cout << "+-------------------------------------------------+\n" << "| SQLCHECK |\n" << "+-------------------------------------------------+\n"; ValidateRiskLevel(state); ValidateFileName(state); ValidateColorMode(state); ValidateVerbose(state); ValidateDelimiter(state); std::cout << "-------------------------------------------------\n"; } void Usage() { std::cout << "Command line options : sqlcheck <options>\n" " -f -file_name : SQL file name\n" " -r -risk_level : Set of anti-patterns to check\n" " : 1 (all anti-patterns, default) \n" " : 2 (only medium and high risk anti-patterns) \n" " : 3 (only high risk anti-patterns) \n" " -c -color_mode : Display warnings in color mode \n" " -v -verbose : Display verbose warnings \n" " -d -delimiter : Query delimiter string (; by default) \n" " -h -help : Print help message \n"; exit(EXIT_SUCCESS); } int main(int argc, char **argv) { try { // Parse the input arguments from the user gflags::SetUsageMessage(""); gflags::SetVersionString("1.2"); gflags::ParseCommandLineFlags(&argc, &argv, true); // Print help message if(FLAGS_h == true){ FLAGS_h = false; Usage(); gflags::ShutDownCommandLineFlags(); return (EXIT_SUCCESS); } // Customize the checker configuration ConfigureChecker(sqlcheck::state); // Invoke the checker sqlcheck::Check(sqlcheck::state); } // Catching at the top level ensures that // destructors are always called catch (std::exception& exc) { std::cerr << exc.what() << std::endl; gflags::ShutDownCommandLineFlags(); exit(EXIT_FAILURE); } gflags::ShutDownCommandLineFlags(); return (EXIT_SUCCESS); } <commit_msg>fix V779 from PSV-Studio<commit_after>// MAIN SOURCE #include <iostream> #include <fstream> #include "checker.h" #include "include/configuration.h" #include "gflags/gflags.h" namespace sqlcheck { Configuration state; } // namespace sqlcheck DEFINE_bool(c, false, "Display warnings in color mode"); DEFINE_bool(color_mode, false, "Display warnings in color mode"); DEFINE_bool(v, false, "Display verbose warnings"); DEFINE_bool(verbose, false, "Display verbose warnings"); DEFINE_string(d, "", "Query delimiter string (default -- ;)"); DEFINE_string(delimiter, "", "Query delimiter string (default -- ;)"); DEFINE_bool(h, false, "Print help message"); DEFINE_uint64(r, sqlcheck::RISK_LEVEL_ALL, "Set of anti-patterns to check \n" "1 (all anti-patterns, default) \n" "2 (only medium and high risk anti-patterns) \n" "3 (only high risk anti-patterns) \n"); DEFINE_uint64(risk_level, sqlcheck::RISK_LEVEL_ALL, "Set of anti-patterns to check \n" "1 (all anti-patterns, default) \n" "2 (only medium and high risk anti-patterns) \n" "3 (only high risk anti-patterns) \n"); DEFINE_string(f, "", "SQL file name"); // standard input DEFINE_string(file_name, "", "SQL file name"); // standard input void ConfigureChecker(sqlcheck::Configuration &state) { // Default Values state.risk_level = sqlcheck::RISK_LEVEL_ALL; state.file_name = ""; state.delimiter = ";"; state.testing_mode = false; state.verbose = false; state.color_mode = false; // Configure checker state.color_mode = FLAGS_c || FLAGS_color_mode; state.verbose = FLAGS_v || FLAGS_verbose; if(FLAGS_f.empty() == false){ state.file_name = FLAGS_f; } if(FLAGS_file_name.empty() == false){ state.file_name = FLAGS_file_name; } if(FLAGS_d.empty() == false){ state.delimiter = FLAGS_f; } if(FLAGS_delimiter.empty() == false){ state.delimiter = FLAGS_delimiter; } if(FLAGS_r != 0){ state.risk_level = (sqlcheck::RiskLevel) FLAGS_r; } if(FLAGS_risk_level != 0){ state.risk_level = (sqlcheck::RiskLevel) FLAGS_risk_level; } // Run validators std::cout << "+-------------------------------------------------+\n" << "| SQLCHECK |\n" << "+-------------------------------------------------+\n"; ValidateRiskLevel(state); ValidateFileName(state); ValidateColorMode(state); ValidateVerbose(state); ValidateDelimiter(state); std::cout << "-------------------------------------------------\n"; } void Usage() { std::cout << "Command line options : sqlcheck <options>\n" " -f -file_name : SQL file name\n" " -r -risk_level : Set of anti-patterns to check\n" " : 1 (all anti-patterns, default) \n" " : 2 (only medium and high risk anti-patterns) \n" " : 3 (only high risk anti-patterns) \n" " -c -color_mode : Display warnings in color mode \n" " -v -verbose : Display verbose warnings \n" " -d -delimiter : Query delimiter string (; by default) \n" " -h -help : Print help message \n"; } int main(int argc, char **argv) { try { // Parse the input arguments from the user gflags::SetUsageMessage(""); gflags::SetVersionString("1.2"); gflags::ParseCommandLineFlags(&argc, &argv, true); // Print help message if(FLAGS_h == true){ FLAGS_h = false; Usage(); gflags::ShutDownCommandLineFlags(); return (EXIT_SUCCESS); } // Customize the checker configuration ConfigureChecker(sqlcheck::state); // Invoke the checker sqlcheck::Check(sqlcheck::state); } // Catching at the top level ensures that // destructors are always called catch (std::exception& exc) { std::cerr << exc.what() << std::endl; gflags::ShutDownCommandLineFlags(); exit(EXIT_FAILURE); } gflags::ShutDownCommandLineFlags(); return (EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include <cstring> #include <iostream> using namespace std; int main(int argc, const char* argv[]) { // Print help if (argc == 1 || strcmp(argv[0], "--help") == 0) { cout << "GLSLPreprocessor is a simple preprocessor for GLSL files." << endl << "Usage:" << endl << "GLSLPreprocessor input output" << endl; return 0; } return 0; } <commit_msg>Get input and output names<commit_after>#include <cstring> #include <iostream> #include <string> using namespace std; int main(int argc, const char* argv[]) { // Print help if (argc == 1 || strcmp(argv[0], "--help") == 0) { cout << "GLSLPreprocessor is a simple preprocessor for GLSL files." << endl << "Usage:" << endl << "GLSLPreprocessor input output" << endl; return 0; } // Get input and output names. string inputName = argv[1]; string outputName; if (argc > 2) outputName = argv[2]; else outputName = inputName; return 0; } <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <iostream> #include <stdexcept> using namespace sf; Texture texture; Sprite sprite; void Load() { if (!texture.loadFromFile("res/img/spaceship1.png")) { throw std::invalid_argument("Loading error!"); } } void Update() { Vector2f move; if (Keyboard::isKeyPressed(Keyboard::Left)) { move.x--; } if (Keyboard::isKeyPressed(Keyboard::Right)) { move.x++; } sprite.move(move); } void Render(RenderWindow &window) { window.draw(sprite); } int main() { RenderWindow window(VideoMode(400, 400), "SFML works!"); try { Load(); } catch (const std::exception &) { std::cerr << "Load error" << std::endl; return 1; } sprite.setTexture(texture); sprite.setScale(Vector2f(2.f, 2.f)); while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } window.clear(); // Update(); Render(window); // window.display(); } return 0; }<commit_msg>deltatime<commit_after>#include <SFML/Graphics.hpp> #include <iostream> #include <stdexcept> using namespace sf; Texture texture; Sprite sprite; void Load() { if (!texture.loadFromFile("res/img/spaceship1.png")) { throw std::invalid_argument("Loading error!"); } } void Update() { static sf::Clock clock; float dt = clock.restart().asSeconds(); Vector2f move; if (Keyboard::isKeyPressed(Keyboard::Left)) { move.x--; } if (Keyboard::isKeyPressed(Keyboard::Right)) { move.x++; } sprite.move(move*300.0f*dt); } void Render(RenderWindow &window) { window.draw(sprite); } int main() { RenderWindow window(VideoMode(400, 400), "SFML works!"); try { Load(); } catch (const std::exception &) { std::cerr << "Load error" << std::endl; return 1; } sprite.setTexture(texture); sprite.setScale(Vector2f(2.f, 2.f)); while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed){ window.close(); } } if (Keyboard::isKeyPressed(Keyboard::Escape)) { window.close(); } window.clear(); Update(); Render(window); window.display(); } return 0; }<|endoftext|>
<commit_before>#include "ExecutionEngine.h" #include <chrono> #include <cstdlib> // env options #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #pragma warning(push) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #pragma warning(pop) #pragma GCC diagnostic pop #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Host.h> #include "Runtime.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { namespace { typedef ReturnCode(*EntryFuncPtr)(Runtime*); ReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime) { // That function uses long jumps to handle "execeptions". // Do not create any non-POD objects here ReturnCode returnCode{}; auto sj = setjmp(_runtime->getJmpBuf()); if (sj == 0) returnCode = _mainFunc(_runtime); else returnCode = static_cast<ReturnCode>(sj); return returnCode; } std::string codeHash(bytes const& _code) { uint32_t hash = 0; for (auto b : _code) { hash += b; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return std::to_string(hash); } bool getEnvOption(char const* _name, bool _default) { auto var = std::getenv(_name); if (!var) return _default; return std::strtol(var, nullptr, 10) != 0; } } ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { static std::unique_ptr<llvm::ExecutionEngine> ee; // TODO: Use Managed Objects from LLVM? static auto debugDumpModule = getEnvOption("EVMJIT_DUMP", false); static auto objectCacheEnabled = getEnvOption("EVMJIT_CACHE", true); auto mainFuncName = codeHash(_code); EntryFuncPtr entryFuncPtr{}; Runtime runtime(_data, _env); // TODO: I don't know why but it must be created before getFunctionAddress() calls if (ee && (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName))) { } else { auto objectCache = objectCacheEnabled ? Cache::getObjectCache() : nullptr; std::unique_ptr<llvm::Module> module; if (objectCache) module = Cache::getObject(mainFuncName); if (!module) module = Compiler({}).compile(_code, mainFuncName); if (debugDumpModule) module->dump(); if (!ee) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::EngineBuilder builder(module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager); builder.setMCJITMemoryManager(memoryManager.get()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ee.reset(builder.create()); if (!ee) return ReturnCode::LLVMConfigError; module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module memoryManager.release(); // and memory manager if (objectCache) ee->setObjectCache(objectCache); entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); } else { if (!entryFuncPtr) { ee->addModule(module.get()); module.release(); entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); } } } assert(entryFuncPtr); auto executionStartTime = std::chrono::high_resolution_clock::now(); auto returnCode = runEntryFunc(entryFuncPtr, &runtime); if (returnCode == ReturnCode::Return) { returnData = runtime.getReturnData(); // Save reference to return data std::swap(m_memory, runtime.getMemory()); // Take ownership of memory } auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms\n"; return returnCode; } } } } <commit_msg>change typedef to using according to preferred coding style<commit_after>#include "ExecutionEngine.h" #include <chrono> #include <cstdlib> // env options #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #pragma warning(push) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #pragma warning(pop) #pragma GCC diagnostic pop #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Host.h> #include "Runtime.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { namespace { using EntryFuncPtr = ReturnCode(*)(Runtime*); ReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime) { // That function uses long jumps to handle "execeptions". // Do not create any non-POD objects here ReturnCode returnCode{}; auto sj = setjmp(_runtime->getJmpBuf()); if (sj == 0) returnCode = _mainFunc(_runtime); else returnCode = static_cast<ReturnCode>(sj); return returnCode; } std::string codeHash(bytes const& _code) { uint32_t hash = 0; for (auto b : _code) { hash += b; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return std::to_string(hash); } bool getEnvOption(char const* _name, bool _default) { auto var = std::getenv(_name); if (!var) return _default; return std::strtol(var, nullptr, 10) != 0; } } ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { static std::unique_ptr<llvm::ExecutionEngine> ee; // TODO: Use Managed Objects from LLVM? static auto debugDumpModule = getEnvOption("EVMJIT_DUMP", false); static auto objectCacheEnabled = getEnvOption("EVMJIT_CACHE", true); auto mainFuncName = codeHash(_code); EntryFuncPtr entryFuncPtr{}; Runtime runtime(_data, _env); // TODO: I don't know why but it must be created before getFunctionAddress() calls if (ee && (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName))) { } else { auto objectCache = objectCacheEnabled ? Cache::getObjectCache() : nullptr; std::unique_ptr<llvm::Module> module; if (objectCache) module = Cache::getObject(mainFuncName); if (!module) module = Compiler({}).compile(_code, mainFuncName); if (debugDumpModule) module->dump(); if (!ee) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::EngineBuilder builder(module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager); builder.setMCJITMemoryManager(memoryManager.get()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ee.reset(builder.create()); if (!ee) return ReturnCode::LLVMConfigError; module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module memoryManager.release(); // and memory manager if (objectCache) ee->setObjectCache(objectCache); entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); } else { if (!entryFuncPtr) { ee->addModule(module.get()); module.release(); entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName); } } } assert(entryFuncPtr); auto executionStartTime = std::chrono::high_resolution_clock::now(); auto returnCode = runEntryFunc(entryFuncPtr, &runtime); if (returnCode == ReturnCode::Return) { returnData = runtime.getReturnData(); // Save reference to return data std::swap(m_memory, runtime.getMemory()); // Take ownership of memory } auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms\n"; return returnCode; } } } } <|endoftext|>
<commit_before>/*! \file main.cpp * \brief Program to run the grid code. */ #ifdef MPI_CHOLLA #include <mpi.h> #include "mpi_routines.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "global.h" #include "grid3D.h" #include "io.h" #include "error_handling.h" #define OUTPUT //#define CPU_TIME int main(int argc, char *argv[]) { // timing variables double start_total, stop_total, start_step, stop_step; #ifdef CPU_TIME double stop_init, init_min, init_max, init_avg; double start_bound, stop_bound, bound_min, bound_max, bound_avg; double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg; double init, bound, hydro; init = bound = hydro = 0; #endif //CPU_TIME // start the total time start_total = get_time(); /* Initialize MPI communication */ #ifdef MPI_CHOLLA InitializeChollaMPI(&argc, &argv); #endif /*MPI_CHOLLA*/ Real dti = 0; // inverse time step, 1.0 / dt // input parameter variables char *param_file; struct parameters P; int nfile = 0; // number of output files Real outtime = 0; // current output time // read in command line arguments if (argc != 2) { chprintf("usage: %s <parameter_file>\n", argv[0]); chexit(-1); } else { param_file = argv[1]; } // create the grid Grid3D G; // read in the parameters parse_params (param_file, &P); // and output to screen chprintf ("Parameter values: nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n", P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd); chprintf ("Output directory: %s\n", P.outdir); // initialize the grid G.Initialize(&P); chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells); // Set initial conditions and calculate first dt chprintf("Setting initial conditions...\n"); G.Set_Initial_Conditions(P); chprintf("Initial conditions set.\n"); // set main variables for Read_Grid inital conditions if (strcmp(P.init, "Read_Grid") == 0) { dti = C_cfl / G.H.dt; outtime += G.H.t; nfile = P.nfile*P.nfull; } #ifdef CPU_TIME G.Timer.Initialize(); #endif #ifdef GRAVITY G.Initialize_Gravity(&P); G.Compute_Gravitational_Potential(); #endif // set boundary conditions (assign appropriate values to ghost cells) chprintf("Setting boundary conditions...\n"); G.Set_Boundary_Conditions(P); chprintf("Boundary conditions set.\n"); chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz); chprintf("Ratio of specific heats gamma = %f\n",gama); chprintf("Nstep = %d Timestep = %f Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t); #ifdef OUTPUT if (strcmp(P.init, "Read_Grid") != 0) { // write the initial conditions to file chprintf("Writing initial conditions to file...\n"); WriteData(G, P, nfile); } // add one to the output file count nfile++; #endif //OUTPUT // increment the next output time outtime += P.outstep; #ifdef CPU_TIME stop_init = get_time(); init = stop_init - start_total; #ifdef MPI_CHOLLA init_min = ReduceRealMin(init); init_max = ReduceRealMax(init); init_avg = ReduceRealAvg(init); chprintf("Init min: %9.4f max: %9.4f avg: %9.4f\n", init_min, init_max, init_avg); #else printf("Init %9.4f\n", init); #endif //MPI_CHOLLA #endif //CPU_TIME // Evolve the grid, one timestep at a time chprintf("Starting calculations.\n"); while (G.H.t < P.tout) //while (G.H.n_step < 1) { // get the start time start_step = get_time(); // calculate the timestep G.set_dt(dti); if (G.H.t + G.H.dt > outtime) { G.H.dt = outtime - G.H.t; } #ifdef MPI_CHOLLA G.H.dt = ReduceRealMin(G.H.dt); #endif // Advance the grid by one timestep #ifdef CPU_TIME start_hydro = get_time(); #endif //CPU_TIME dti = G.Update_Grid(); #ifdef CPU_TIME stop_hydro = get_time(); hydro = stop_hydro - start_hydro; #ifdef MPI_CHOLLA hydro_min = ReduceRealMin(hydro); hydro_max = ReduceRealMax(hydro); hydro_avg = ReduceRealAvg(hydro); #endif //MPI_CHOLLA #endif //CPU_TIME //printf("%d After Grid Update: %f %f\n", procID, G.H.dt, dti); // update the time G.H.t += G.H.dt; // add one to the timestep count G.H.n_step++; // set boundary conditions for next time step #ifdef CPU_TIME start_bound = get_time(); #endif //CPU_TIME G.Set_Boundary_Conditions(P); #ifdef CPU_TIME stop_bound = get_time(); bound = stop_bound - start_bound; #ifdef MPI_CHOLLA bound_min = ReduceRealMin(bound); bound_max = ReduceRealMax(bound); bound_avg = ReduceRealAvg(bound); #endif //MPI_CHOLLA #endif //CPU_TIME #ifdef CPU_TIME #ifdef MPI_CHOLLA chprintf("hydro min: %9.4f max: %9.4f avg: %9.4f\n", hydro_min, hydro_max, hydro_avg); chprintf("bound min: %9.4f max: %9.4f avg: %9.4f\n", bound_min, bound_max, bound_avg); #endif //MPI_CHOLLA #endif //CPU_TIME // get the time to compute the total timestep stop_step = get_time(); stop_total = get_time(); G.H.t_wall = stop_total-start_total; #ifdef MPI_CHOLLA G.H.t_wall = ReduceRealMax(G.H.t_wall); #endif chprintf("n_step: %d sim time: %10.7f sim timestep: %7.4e timestep time = %9.3f ms total time = %9.4f s\n", G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall); if (G.H.t == outtime) { #ifdef OUTPUT /*output the grid data*/ WriteData(G, P, nfile); // add one to the output file count nfile++; #endif //OUTPUT // update to the next output time outtime += P.outstep; } /* // check for failures for (int i=G.H.n_ghost; i<G.H.nx-G.H.n_ghost; i++) { for (int j=G.H.n_ghost; j<G.H.ny-G.H.n_ghost; j++) { for (int k=G.H.n_ghost; k<G.H.nz-G.H.n_ghost; k++) { int id = i + j*G.H.nx + k*G.H.nx*G.H.ny; if (G.C.density[id] < 0.0 || G.C.density[id] != G.C.density[id]) { printf("Failure in cell %d %d %d. Density %e\n", i, j, k, G.C.density[id]); #ifdef MPI_CHOLLA MPI_Finalize(); chexit(-1); #endif exit(0); } } } } */ } /*end loop over timesteps*/ // free the grid G.Reset(); #ifdef MPI_CHOLLA MPI_Finalize(); #endif /*MPI_CHOLLA*/ return 0; } <commit_msg>update_hydro and set_boundaries now have separated functions<commit_after>/*! \file main.cpp * \brief Program to run the grid code. */ #ifdef MPI_CHOLLA #include <mpi.h> #include "mpi_routines.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "global.h" #include "grid3D.h" #include "io.h" #include "error_handling.h" #define OUTPUT //#define CPU_TIME int main(int argc, char *argv[]) { // timing variables double start_total, stop_total, start_step, stop_step; #ifdef CPU_TIME double stop_init, init_min, init_max, init_avg; double start_bound, stop_bound, bound_min, bound_max, bound_avg; double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg; double init, bound, hydro; init = bound = hydro = 0; #endif //CPU_TIME // start the total time start_total = get_time(); /* Initialize MPI communication */ #ifdef MPI_CHOLLA InitializeChollaMPI(&argc, &argv); #endif /*MPI_CHOLLA*/ Real dti = 0; // inverse time step, 1.0 / dt // input parameter variables char *param_file; struct parameters P; int nfile = 0; // number of output files Real outtime = 0; // current output time // read in command line arguments if (argc != 2) { chprintf("usage: %s <parameter_file>\n", argv[0]); chexit(-1); } else { param_file = argv[1]; } // create the grid Grid3D G; // read in the parameters parse_params (param_file, &P); // and output to screen chprintf ("Parameter values: nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n", P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd); chprintf ("Output directory: %s\n", P.outdir); // initialize the grid G.Initialize(&P); chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells); // Set initial conditions and calculate first dt chprintf("Setting initial conditions...\n"); G.Set_Initial_Conditions(P); chprintf("Initial conditions set.\n"); // set main variables for Read_Grid inital conditions if (strcmp(P.init, "Read_Grid") == 0) { dti = C_cfl / G.H.dt; outtime += G.H.t; nfile = P.nfile*P.nfull; } #ifdef CPU_TIME G.Timer.Initialize(); #endif #ifdef GRAVITY G.Initialize_Gravity(&P); G.Compute_Gravitational_Potential(); #endif // set boundary conditions (assign appropriate values to ghost cells) chprintf("Setting boundary conditions...\n"); G.Set_Boundary_Conditions(P); chprintf("Boundary conditions set.\n"); chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz); chprintf("Ratio of specific heats gamma = %f\n",gama); chprintf("Nstep = %d Timestep = %f Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t); #ifdef OUTPUT if (strcmp(P.init, "Read_Grid") != 0) { // write the initial conditions to file chprintf("Writing initial conditions to file...\n"); WriteData(G, P, nfile); } // add one to the output file count nfile++; #endif //OUTPUT // increment the next output time outtime += P.outstep; #ifdef CPU_TIME stop_init = get_time(); init = stop_init - start_total; #ifdef MPI_CHOLLA init_min = ReduceRealMin(init); init_max = ReduceRealMax(init); init_avg = ReduceRealAvg(init); chprintf("Init min: %9.4f max: %9.4f avg: %9.4f\n", init_min, init_max, init_avg); #else printf("Init %9.4f\n", init); #endif //MPI_CHOLLA #endif //CPU_TIME // Evolve the grid, one timestep at a time chprintf("Starting calculations.\n"); while (G.H.t < P.tout) //while (G.H.n_step < 1) { chprintf("n_step: %d \n", G.H.n_step + 1 ); // get the start time start_step = get_time(); // calculate the timestep G.set_dt(dti); if (G.H.t + G.H.dt > outtime) { G.H.dt = outtime - G.H.t; } #ifdef MPI_CHOLLA G.H.dt = ReduceRealMin(G.H.dt); #endif // Advance the grid by one timestep dti = G.Update_Hydro_Grid(); // update the time G.H.t += G.H.dt; // add one to the timestep count G.H.n_step++; // set boundary conditions for next time step G.Set_Boundary_Conditions_All(P); #ifdef CPU_TIME G.Timer.Print_Times(); #endif // get the time to compute the total timestep stop_step = get_time(); stop_total = get_time(); G.H.t_wall = stop_total-start_total; #ifdef MPI_CHOLLA G.H.t_wall = ReduceRealMax(G.H.t_wall); #endif chprintf("n_step: %d sim time: %10.7f sim timestep: %7.4e timestep time = %9.3f ms total time = %9.4f s\n\n", G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall); if (G.H.t == outtime) { #ifdef OUTPUT /*output the grid data*/ WriteData(G, P, nfile); // add one to the output file count nfile++; #endif //OUTPUT // update to the next output time outtime += P.outstep; } /* // check for failures for (int i=G.H.n_ghost; i<G.H.nx-G.H.n_ghost; i++) { for (int j=G.H.n_ghost; j<G.H.ny-G.H.n_ghost; j++) { for (int k=G.H.n_ghost; k<G.H.nz-G.H.n_ghost; k++) { int id = i + j*G.H.nx + k*G.H.nx*G.H.ny; if (G.C.density[id] < 0.0 || G.C.density[id] != G.C.density[id]) { printf("Failure in cell %d %d %d. Density %e\n", i, j, k, G.C.density[id]); #ifdef MPI_CHOLLA MPI_Finalize(); chexit(-1); #endif exit(0); } } } } */ } /*end loop over timesteps*/ // free the grid G.Reset(); #ifdef MPI_CHOLLA MPI_Finalize(); #endif /*MPI_CHOLLA*/ return 0; } <|endoftext|>
<commit_before>#include "ExecutionEngine.h" #include <chrono> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Signals.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Host.h> #pragma GCC diagnostic pop #include "Runtime.h" #include "Memory.h" #include "Stack.h" #include "Type.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; /*if (auto cachedExec = Cache::findExec(key)) { return run(*cachedExec, _data, _env); }*/ auto module = Compiler({}).compile(_code); return run(std::move(module), _data, _env, _code); } ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code) { auto module = _module.get(); // Keep ownership of the module in _module llvm::sys::PrintStackTraceOnErrorSignal(); static const auto program = "EVM JIT"; llvm::PrettyStackTraceProgram X(1, &program); llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); llvm::EngineBuilder builder(module); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager); builder.setMCJITMemoryManager(memoryManager.get()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ExecBundle exec; exec.engine.reset(builder.create()); if (!exec.engine) return ReturnCode::LLVMConfigError; _module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module memoryManager.release(); // and memory manager // TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used //auto finalizationStartTime = std::chrono::high_resolution_clock::now(); //exec.engine->finalizeObject(); //auto finalizationEndTime = std::chrono::high_resolution_clock::now(); //clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count(); auto executionStartTime = std::chrono::high_resolution_clock::now(); std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; //auto& cachedExec = Cache::registerExec(key, std::move(exec)); auto returnCode = run(exec, _data, _env); auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms "; //clog(JIT) << "Max stack size: " << Stack::maxStackSize; clog(JIT) << "\n"; return returnCode; } namespace { ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime) { // That function uses long jumps to handle "execeptions". // Do not create any non-POD objects here // TODO: // Getting pointer to function seems to be cachable, // but it looks like getPointerToFunction() method does something special // to allow function to be executed. // That might be related to memory manager. Can we share one? typedef ReturnCode(*EntryFuncPtr)(Runtime*); auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress("main"); ReturnCode returnCode{}; auto sj = setjmp(_runtime->getJmpBuf()); if (sj == 0) returnCode = entryFuncPtr(_runtime); else returnCode = static_cast<ReturnCode>(sj); return returnCode; } } ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env) { Runtime runtime(_data, _env); auto returnCode = runEntryFunc(_exec, &runtime); if (returnCode == ReturnCode::Return) this->returnData = runtime.getReturnData(); return returnCode; } } } } <commit_msg>Execution Engine cleanups<commit_after>#include "ExecutionEngine.h" #include <chrono> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Signals.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Host.h> #pragma GCC diagnostic pop #include "Runtime.h" #include "Memory.h" #include "Stack.h" #include "Type.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; /*if (auto cachedExec = Cache::findExec(key)) { return run(*cachedExec, _data, _env); }*/ auto module = Compiler({}).compile(_code); return run(std::move(module), _data, _env, _code); } ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code) { llvm::sys::PrintStackTraceOnErrorSignal(); static const auto program = "EVM JIT"; llvm::PrettyStackTraceProgram X(1, &program); llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::EngineBuilder builder(_module.get()); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager); builder.setMCJITMemoryManager(memoryManager.get()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format _module->setTargetTriple(triple.str()); ExecBundle exec; exec.engine.reset(builder.create()); if (!exec.engine) return ReturnCode::LLVMConfigError; _module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module memoryManager.release(); // and memory manager // TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used //auto finalizationStartTime = std::chrono::high_resolution_clock::now(); //exec.engine->finalizeObject(); //auto finalizationEndTime = std::chrono::high_resolution_clock::now(); //clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count(); auto executionStartTime = std::chrono::high_resolution_clock::now(); std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; //auto& cachedExec = Cache::registerExec(key, std::move(exec)); auto returnCode = run(exec, _data, _env); auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms "; //clog(JIT) << "Max stack size: " << Stack::maxStackSize; clog(JIT) << "\n"; return returnCode; } namespace { ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime) { // That function uses long jumps to handle "execeptions". // Do not create any non-POD objects here // TODO: // Getting pointer to function seems to be cachable, // but it looks like getPointerToFunction() method does something special // to allow function to be executed. // That might be related to memory manager. Can we share one? typedef ReturnCode(*EntryFuncPtr)(Runtime*); auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress("main"); ReturnCode returnCode{}; auto sj = setjmp(_runtime->getJmpBuf()); if (sj == 0) returnCode = entryFuncPtr(_runtime); else returnCode = static_cast<ReturnCode>(sj); return returnCode; } } ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env) { Runtime runtime(_data, _env); auto returnCode = runEntryFunc(_exec, &runtime); if (returnCode == ReturnCode::Return) this->returnData = runtime.getReturnData(); return returnCode; } } } } <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <pwd.h> #include <vector> #include <string> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> using namespace std; //function to convert a vector of char * to a //char * [] for use as an execvp argument char ** conv_vec(vector<char*> v) { //create a char * [] of proper size char ** t = new char* [v.size() + 1]; //counter to keep track of the position //for entering char* unsigned i = 0; for (; i < v.size(); ++i) { //first make char[] entry of the right length t[i] = new char[strlen(v.at(i))]; //then copy the entire string from the vector //into the char *[] strcpy(t[i], v.at(i)); } //set the last position to a null character t[i] = '\0'; return t; } char ** get_command(string& a, int& flag) { //cout << a << endl; //first make a copy of the command string //so that we can check what delimiter strtok //stopped at char * copy = new char [a.length() + 1]; strcpy(copy, a.c_str()); //create a vector because we do not know //how many tokens are in the command entered vector<char *> temp; //create an empty char * [] to return. It can //either be empty if there is no input or //filled later when we convert the vector //into an array char ** vec = NULL; //bool done = false; //set a starting position to reference when //finding the position of the delimiter found char * begin = copy; //take the first token char * token = strtok(copy, " ;|&#"); //for position of delimiter unsigned int pos; while (token != 0) { // cout << token << endl; //the position of the delimiter with respect //to the beginning of the array pos = token - begin + strlen(token); //put the token at the end of the vector temp.push_back(token); //cout << pos << endl; //to find out which delimiter was found //if it was the end, it will not go through this if (pos < a.size()) { //store delimiter character found char delim = a.at(pos); // cout << delim << endl; if (delim == ' ') { while (pos < a.size() - 1 && delim == ' ') { ++pos; delim = a.at(pos); } } //Now we know delim is either a delimiter //that signifies the end of a command //or is the first char of the next one //so we check if (delim == '|' || delim == '&' || delim == ';' || delim == '#') { //so we are done with this command //now we convert it to a char** vec = conv_vec(temp); // for (unsigned i = 0; vec[i] != 0; ++i) // { // cout << i << endl; // cout << vec[i] << endl; // } //remember to get rid of the dynamically allocated delete copy; //reset flag ('#' and ';' use 0 so reset it for //those and change for '|' and '&' flag = 0; if (delim == '|') { //set flag bit flag = 1; } else if (delim == '&') { //set flag bit to 2 flag = 2; } else if(delim == '#') { pos = 0; a = ""; } // cout << flag << endl; a = a.substr(pos + 1, a.size() - pos + 1); return vec; } //this means that delim == a character //for the next argument so continue } token = strtok(NULL, " ;|&"); } //so we have reached the end, set a to empty a = ""; //convert to proper char** vec = conv_vec(temp); //get rid of dynamically allocated delete copy; //we got to the end so the flag should be 0 flag = 0; return vec; } void display_prompt() { char host[50]; int host_flag = gethostname(host, sizeof host); if(host_flag == -1) { perror("gethostname"); } char *login = (getpwuid(getuid()))->pw_name; if (login == 0) { perror("getlogin"); } cout << login << '@' << host << "$ "; } int main() { int flag = 0; int error_flag; while (1) { display_prompt(); string command; getline(cin, command); //first try to find a '#' sign to indicate //a comment int p = command.find('#'); if (p != -1) { command = command.substr(0, p); } while(flag != 0 || command != "") { char ** argv = get_command(command, flag); // cout << command << endl; // cout << flag << endl; if (argv[0] == NULL) { break; } else if (strcmp(argv[0], "exit") == 0) { return 0; } // for (int i = 0; argv[i] != 0; ++i) // { // cout << argv[i] << endl; // } error_flag = 0; int fork_flag = fork(); if (fork_flag == -1) { perror("fork"); exit(1); } else if (fork_flag == 0) { int execvp_flag = execvp(argv[0], argv); if (execvp_flag == -1) { perror("execvp"); exit(1); } } int wait_flag = wait(&error_flag); if (wait_flag == -1) { perror("wait"); exit(1); } // cout << "Error flag is " << error_flag << endl; if (error_flag != 0) { if (flag == 2) { break; } } else if (flag == 1) { break; } } } return 0; } <commit_msg>Made it so that it only recognizes two || or &&<commit_after>#include <iostream> #include <stdlib.h> #include <pwd.h> #include <vector> #include <string> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> using namespace std; //function to convert a vector of char * to a //char * [] for use as an execvp argument char ** conv_vec(vector<char*> v) { //create a char * [] of proper size char ** t = new char* [v.size() + 1]; //counter to keep track of the position //for entering char* unsigned i = 0; for (; i < v.size(); ++i) { //first make char[] entry of the right length t[i] = new char[strlen(v.at(i))]; //then copy the entire string from the vector //into the char *[] strcpy(t[i], v.at(i)); } //set the last position to a null character t[i] = '\0'; return t; } char ** get_command(string& a, int& flag) { //cout << a << endl; //first make a copy of the command string //so that we can check what delimiter strtok //stopped at char * copy = new char [a.length() + 1]; strcpy(copy, a.c_str()); //create a vector because we do not know //how many tokens are in the command entered vector<char *> temp; //create an empty char * [] to return. It can //either be empty if there is no input or //filled later when we convert the vector //into an array char ** vec = NULL; //bool done = false; //set a starting position to reference when //finding the position of the delimiter found char * begin = copy; //take the first token char * token = strtok(copy, " ;|&#"); //for position of delimiter unsigned int pos; while (token != 0) { // cout << token << endl; //the position of the delimiter with respect //to the beginning of the array pos = token - begin + strlen(token); //put the token at the end of the vector temp.push_back(token); //cout << pos << endl; //to find out which delimiter was found //if it was the end, it will not go through this if (pos < a.size()) { //store delimiter character found char delim = a.at(pos); // cout << delim << endl; if (delim == ' ') { while (pos < a.size() - 1 && delim == ' ') { ++pos; delim = a.at(pos); } } //checking to see if there are two of the '|' //or '&' if (delim == '|' || delim == '&') { //increment this n as long as it is not the //end and they are equal int n = 1; while (pos + n < a.size() && delim == a.at(pos + n)) { ++n; } //if it is not 2, give an error message and clear //the vector so that no commands are executed if (n != 2) { cerr << "Rshell: Syntax error near '" << delim << "'" << endl; temp.clear(); } } //Now we know delim is either a delimiter //that signifies the end of a command //or is the first char of an argument //so we check if (delim == '|' || delim == '&' || delim == ';') { //so we are done with this command //now we convert it to a char** vec = conv_vec(temp); // for (unsigned i = 0; vec[i] != 0; ++i) // { // cout << i << endl; // cout << vec[i] << endl; // } //remember to get rid of the dynamically allocated delete copy; //reset flag ('#' and ';' use 0 so reset it for //those and change for '|' and '&' flag = 0; if (delim == '|') { //set flag bit flag = 1; } else if (delim == '&') { //set flag bit to 2 flag = 2; } // cout << flag << endl; a = a.substr(pos + 1, a.size() - pos + 1); return vec; } //this means that delim == a character //for the next argument so continue } token = strtok(NULL, " ;|&"); } //so we have reached the end, set a to empty a = ""; //convert to proper char** vec = conv_vec(temp); //get rid of dynamically allocated delete copy; //we got to the end so the flag should be 0 flag = 0; return vec; } void display_prompt() { //set size of hostname char host[50]; //get the hostname and check to see if there was //an error int host_flag = gethostname(host, sizeof host); if(host_flag == -1) { perror("gethostname"); } //get login and if there was an error give message char *login = (getpwuid(getuid()))->pw_name; if (login == 0) { perror("getlogin"); } cout << login << '@' << host << "$ "; } int main() { int flag = 0; int error_flag; while (1) { display_prompt(); string command; getline(cin, command); //first try to find a '#' sign to indicate //a comment int p = command.find('#'); //if there was a comment then delete everything //after that AKA set a substring from 0 to the '#' if (p != -1) { command = command.substr(0, p); } //so continue doing and getting while there is //still an && or || or until the end of the //commands while(flag != 0 || command != "") { //get the command in argv char ** argv = get_command(command, flag); // cout << command << endl; // cout << flag << endl; //if it is empty, then go back to prompt if (argv[0] == NULL) { break; } //if the command is exit, exit program else if (strcmp(argv[0], "exit") == 0) { return 0; } // for (int i = 0; argv[i] != 0; ++i) // { // cout << argv[i] << endl; // } error_flag = 0; //call the fork and check for error int fork_flag = fork(); if (fork_flag == -1) { perror("fork"); exit(1); } //if it is the child do the command while checking //for error else if (fork_flag == 0) { int execvp_flag = execvp(argv[0], argv); if (execvp_flag == -1) { perror("execvp"); exit(1); } } //if parent then wait for child int wait_flag = wait(&error_flag); if (wait_flag == -1) { perror("wait"); exit(1); } // cout << "Error flag is " << error_flag << endl; //if there was an error if (error_flag != 0) { //if it was the first in an &&, go back //to prompt if (flag == 2) { break; } } else if (flag == 1) { break; } } } return 0; } <|endoftext|>
<commit_before>/* ** buffer.cpp ** Login : <hcuche@hcuche-de> ** ** Author(s): ** - hcuche <hcuche@aldebaran-robotics.com> */ #include <qimessaging/buffer.hpp> #include <cstdio> #include <cstring> #include <ctype.h> #include "src/buffer_p.hpp" #include <iostream> namespace qi { BufferPrivate::BufferPrivate() { size = 0; cursor = 0; } Buffer::Buffer() : _p(new BufferPrivate) // TODO: add allocation-on-write. { } size_t Buffer::write(const void *data, size_t size) { if (sizeof(_p->data) - _p->cursor < size) { return -1; } memcpy(_p->data + _p->size, data, size); _p->size += size; _p->cursor += _p->size; return size; } size_t Buffer::read(void *data, size_t size) { if (_p->size - _p->cursor < size) { size = _p->size - _p->cursor; } memcpy(data, _p->data + _p->cursor, size); _p->cursor += size; return size; } void *Buffer::read(size_t size) { void *p = 0; if ((p = peek(size))) { seek(size); } return p; } size_t Buffer::size() const { return _p->size; } void *Buffer::reserve(size_t size) { void *p = _p->data + _p->cursor; _p->size = size; return p; } size_t Buffer::seek(long offset) { if (_p->cursor + offset <= _p->size) { _p->cursor += offset; return _p->cursor; } else { return -1; } } void *Buffer::peek(size_t size) const { return _p->cursor + _p->data; } void *Buffer::data() const { return _p->data; } void Buffer::dump() const { unsigned int i = 0; while (i < _p->size) { printf("%02x ", _p->data[i]); i++; if (i % 8 == 0) printf(" "); if (i % 16 == 0) { for (unsigned int j = i - 16; j < i ; j++) { printf("%c", isgraph(_p->data[j]) ? _p->data[j] : '.'); } printf("\n"); } } while (i % 16 != 0) { printf(" "); if (i % 8 == 0) printf(" "); i++; } printf(" "); for (unsigned int j = i - 16; j < _p->size; j++) { printf("%c", isgraph(_p->data[j]) ? _p->data[j] : '.'); } printf("\n"); } } // !qi <commit_msg>Use initialization list for BufferPrivate.<commit_after>/* ** buffer.cpp ** Login : <hcuche@hcuche-de> ** ** Author(s): ** - hcuche <hcuche@aldebaran-robotics.com> */ #include <qimessaging/buffer.hpp> #include <cstdio> #include <cstring> #include <ctype.h> #include "src/buffer_p.hpp" #include <iostream> namespace qi { BufferPrivate::BufferPrivate() : size(0) , cursor(0) { } Buffer::Buffer() : _p(new BufferPrivate) // TODO: add allocation-on-write. { } size_t Buffer::write(const void *data, size_t size) { if (sizeof(_p->data) - _p->cursor < size) { return -1; } memcpy(_p->data + _p->size, data, size); _p->size += size; _p->cursor += _p->size; return size; } size_t Buffer::read(void *data, size_t size) { if (_p->size - _p->cursor < size) { size = _p->size - _p->cursor; } memcpy(data, _p->data + _p->cursor, size); _p->cursor += size; return size; } void *Buffer::read(size_t size) { void *p = 0; if ((p = peek(size))) { seek(size); } return p; } size_t Buffer::size() const { return _p->size; } void *Buffer::reserve(size_t size) { void *p = _p->data + _p->cursor; _p->size = size; return p; } size_t Buffer::seek(long offset) { if (_p->cursor + offset <= _p->size) { _p->cursor += offset; return _p->cursor; } else { return -1; } } void *Buffer::peek(size_t size) const { return _p->cursor + _p->data; } void *Buffer::data() const { return _p->data; } void Buffer::dump() const { unsigned int i = 0; while (i < _p->size) { printf("%02x ", _p->data[i]); i++; if (i % 8 == 0) printf(" "); if (i % 16 == 0) { for (unsigned int j = i - 16; j < i ; j++) { printf("%c", isgraph(_p->data[j]) ? _p->data[j] : '.'); } printf("\n"); } } while (i % 16 != 0) { printf(" "); if (i % 8 == 0) printf(" "); i++; } printf(" "); for (unsigned int j = i - 16; j < _p->size; j++) { printf("%c", isgraph(_p->data[j]) ? _p->data[j] : '.'); } printf("\n"); } } // !qi <|endoftext|>
<commit_before>// // Created by Mark van der Broek on 27/02/2017. // #include "main.h" int main() { // LOAD DATA std::string fileName = "/Users/markvanderbroek/CLionProjects/ORACS/src/data/instanceA_10_input.txt"; Init init{fileName}; init.show(); // Create empty solution Solution solution{init}; // Construct initial solution solution.initialSolution(); }<commit_msg>Added support for arguments to program.<commit_after>// // Created by Mark van der Broek on 27/02/2017. // #include "main.h" int main(int argc, char* argv[]) { // LOAD DATA if (argc != 2) { cerr << "Usage: " << argv[0] << " <FILENAME>\n"; return 1; } std::string fileName{argv[1]}; Init init{fileName}; init.show(); // Create empty solution Solution solution{init}; // Construct initial solution solution.initialSolution(); }<|endoftext|>
<commit_before>#include <QtQuick/QQuickView> #include <QtGui/QGuiApplication> #include <QtQml> #if QT_VERSION > QT_VERSION_CHECK(5, 1, 0) #include <QQmlApplicationEngine> #endif #include "qhttpserver/src/qhttpserver.h" #include "qhttpserver/src/qhttprequest.h" #include "qhttpserver/src/qhttpresponse.h" #include "qhttpserver/src/qhttpconnection.h" #include "documenthandler.h" #include "quickitemgrabber.h" #if USE_WEBENGINE #include <qtwebengineglobal.h> #endif int main(int argc, char *argv[]) { QStringList imports; QGuiApplication app(argc, argv); app.setApplicationName("Terrarium"); app.setOrganizationName("terrariumapp"); app.setOrganizationDomain("terrariumapp.com"); #if defined(Q_OS_MACX) int platformId = 0; #elif defined(Q_OS_IOS) int platformId = 1; #elif defined(Q_OS_ANDROID) int platformId = 2; #elif defined(Q_OS_LINUX) int platformId = 3; #else int platformId = 4; #endif qmlRegisterType<QHttpServer>("HttpServer", 1, 0, "HttpServer"); qmlRegisterType<DocumentHandler>("DocumentHandler", 1, 0, "DocumentHandler"); qmlRegisterUncreatableType<QHttpRequest>("HttpServer", 1, 0, "HttpRequest", "Do not create HttpRequest directly"); qmlRegisterUncreatableType<QHttpResponse>("HttpServer", 1, 0, "HttpResponse", "Do not create HttpResponse directly"); QString platformIP; foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) platformIP = address.toString(); } // Handle command line arguments const QStringList arguments = QCoreApplication::arguments(); for (int i = 1, size = arguments.size(); i < size; ++i) { const QString lowerArgument = arguments.at(i).toLower(); if (lowerArgument == QLatin1String("-i") && i + 1 < size) { imports.append(arguments.at(++i)); } } #if USE_WEBENGINE QtWebEngine::initialize(); #endif #if QT_VERSION > QT_VERSION_CHECK(5, 1, 0) QQmlApplicationEngine engine; for(int i = 0; i < imports.size(); ++i) { engine.addImportPath(imports[i]); } engine.rootContext()->setContextProperty("platform", QVariant::fromValue(platformId)); engine.rootContext()->setContextProperty("platformIP", QVariant::fromValue(platformIP)); engine.rootContext()->setContextProperty("Grabber",new QuickItemGrabber(&app)); engine.load(QUrl("qrc:///main.qml")); #else QQuickView view; view.engine()->rootContext()->setContextProperty("platform", QVariant::fromValue(platformId)); view.engine()->rootContext()->setContextProperty("platformIP", QVariant::fromValue(platformIP)); view.setSource(QUrl("qrc:///main.qml")); view.show(); #endif return app.exec(); } <commit_msg>also add plugin path<commit_after>#include <QtQuick/QQuickView> #include <QtGui/QGuiApplication> #include <QtQml> #if QT_VERSION > QT_VERSION_CHECK(5, 1, 0) #include <QQmlApplicationEngine> #endif #include "qhttpserver/src/qhttpserver.h" #include "qhttpserver/src/qhttprequest.h" #include "qhttpserver/src/qhttpresponse.h" #include "qhttpserver/src/qhttpconnection.h" #include "documenthandler.h" #include "quickitemgrabber.h" #if USE_WEBENGINE #include <qtwebengineglobal.h> #endif int main(int argc, char *argv[]) { QStringList imports, plugins; QGuiApplication app(argc, argv); app.setApplicationName("Terrarium"); app.setOrganizationName("terrariumapp"); app.setOrganizationDomain("terrariumapp.com"); #if defined(Q_OS_MACX) int platformId = 0; #elif defined(Q_OS_IOS) int platformId = 1; #elif defined(Q_OS_ANDROID) int platformId = 2; #elif defined(Q_OS_LINUX) int platformId = 3; #else int platformId = 4; #endif qmlRegisterType<QHttpServer>("HttpServer", 1, 0, "HttpServer"); qmlRegisterType<DocumentHandler>("DocumentHandler", 1, 0, "DocumentHandler"); qmlRegisterUncreatableType<QHttpRequest>("HttpServer", 1, 0, "HttpRequest", "Do not create HttpRequest directly"); qmlRegisterUncreatableType<QHttpResponse>("HttpServer", 1, 0, "HttpResponse", "Do not create HttpResponse directly"); QString platformIP; foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) platformIP = address.toString(); } // Handle command line arguments const QStringList arguments = QCoreApplication::arguments(); for (int i = 1, size = arguments.size(); i < size; ++i) { const QString lowerArgument = arguments.at(i).toLower(); if (lowerArgument == QLatin1String("-i") && i + 1 < size) { imports.append(arguments.at(++i)); } else if (lowerArgument == QLatin1String("-p") && i + 1 < size) { plugins.append(arguments.at(++i)); } } #if USE_WEBENGINE QtWebEngine::initialize(); #endif #if QT_VERSION > QT_VERSION_CHECK(5, 1, 0) QQmlApplicationEngine engine; for(int i = 0; i < imports.size(); ++i) { engine.addImportPath(imports[i]); } for(int i = 0; i < plugins.size(); ++i) { engine.addPluginPath(plugins[i]); } engine.rootContext()->setContextProperty("platform", QVariant::fromValue(platformId)); engine.rootContext()->setContextProperty("platformIP", QVariant::fromValue(platformIP)); engine.rootContext()->setContextProperty("Grabber",new QuickItemGrabber(&app)); engine.load(QUrl("qrc:///main.qml")); #else QQuickView view; view.engine()->rootContext()->setContextProperty("platform", QVariant::fromValue(platformId)); view.engine()->rootContext()->setContextProperty("platformIP", QVariant::fromValue(platformIP)); view.setSource(QUrl("qrc:///main.qml")); view.show(); #endif return app.exec(); } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 <glog/logging.h> #include <sstream> #include "pybind11/numpy.h" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "segy_file.h" #include "stack_file.h" #include "test/test_base.h" namespace py = pybind11; using namespace py::literals; using namespace segystack; void init_common(py::module* m) { py::class_<UTMZone> utm(*m, "UTMZone"); utm.def(py::init<>()); utm.def(py::init<int, char>()); utm.def_property("number", &UTMZone::number, &UTMZone::setNumber); utm.def_property( "letter", &UTMZone::letter, [](UTMZone& self, const std::string& val) { if (val.size() != 1) throw py::type_error("Zone must consist of a single character!"); self.setLetter(val[0]); }); utm.def("__repr__", [](const UTMZone& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }); } void init_segy_file(py::module* m) { py::class_<SegyFile> sgy(*m, "SegyFile"); sgy.def(py::init<const std::string&>()); sgy.def("open", [](SegyFile& self, const std::string& mode) { std::ios_base::openmode open_mode = 0; if (mode.find('r') != std::string::npos) open_mode |= std::ios_base::in; if (mode.find('w') != std::string::npos) open_mode |= std::ios_base::out; self.open(open_mode); }); sgy.def("name", &SegyFile::name); sgy.def("close", &SegyFile::close); sgy.def("guess_trace_header_offsets", &SegyFile::guessTraceHeaderOffsets); py::class_<SegyFile::Trace> trace(sgy, "Trace"); trace.def(py::init<>()); trace.def("header", [](const SegyFile::Trace& self) { return self.header(); }); py::class_<SegyFile::Trace::Header> hdr(trace, "Header"); hdr.def(py::init<>()); py::enum_<SegyFile::Trace::Header::Attribute>(hdr, "Attribute") .value("INLINE_NUMBER", SegyFile::Trace::Header::Attribute::INLINE_NUMBER) .value("CROSSLINE_NUMBER", SegyFile::Trace::Header::Attribute::CROSSLINE_NUMBER) .value("X_COORDINATE", SegyFile::Trace::Header::Attribute::X_COORDINATE) .value("Y_COORDINATE", SegyFile::Trace::Header::Attribute::Y_COORDINATE) .export_values(); } void init_stack_file(py::module* m) { py::class_<StackFile> sf(*m, "StackFile"); sf.def(py::init<const std::string&, const SegyFile&, const StackFile::SegyOptions&>()); sf.def(py::init<const std::string&, const SegyFile&>()); sf.def(py::init<const std::string&>()); sf.def("name", &StackFile::name); sf.def("grid", &StackFile::grid, py::return_value_policy::reference); sf.def("read_inline", [](const StackFile& self, int il, float fill_value) -> py::array_t<float> { py::array::ShapeContainer shape( {self.grid().numCrosslines(), self.grid().numSamples()}); py::array_t<float> data(shape); float* buffer = data.mutable_data(); self.readInline(il, buffer, data.size(), fill_value); return data; }); sf.def("read_crossline", [](const StackFile& self, int xl, float fill_value) -> py::array_t<float> { py::array::ShapeContainer shape( {self.grid().numInlines(), self.grid().numSamples()}); py::array_t<float> data(shape); float* buffer = data.mutable_data(); self.readCrossline(xl, buffer, data.size(), fill_value); return data; }); sf.def("read_depth_slice", [](const StackFile& self, int sample_index, float fill_value) -> py::array_t<float> { py::array::ShapeContainer shape( {self.grid().numInlines(), self.grid().numCrosslines()}); py::array_t<float> data(shape); float* buffer = data.mutable_data(); self.readDepthSlice(sample_index, buffer, data.size(), fill_value); return data; }); sf.def("set_crossline_access_opt", &StackFile::setCrosslineAccessOptimization); sf.def("set_depth_slice_access_opt", &StackFile::setDepthSliceAccessOptimization); py::class_<StackFile::Grid> grid(sf, "Grid"); grid.def(py::init<>()); grid.def("utm_zone", &StackFile::Grid::utmZone); grid.def("bounding_box", &StackFile::Grid::boundingBox); grid.def("is_bin_active", &StackFile::Grid::isBinActive); grid.def("get_coordinate", &StackFile::Grid::getCoordinate); grid.def_property("inline_min", &StackFile::Grid::inlineMin, &StackFile::Grid::setInlineMin); grid.def_property("inline_max", &StackFile::Grid::inlineMax, &StackFile::Grid::setInlineMax); grid.def_property("inline_increment", &StackFile::Grid::inlineIncrement, &StackFile::Grid::setInlineIncrement); grid.def_property("inline_spacing", &StackFile::Grid::inlineSpacing, &StackFile::Grid::setInlineSpacing); grid.def_property("crossline_min", &StackFile::Grid::crosslineMin, &StackFile::Grid::setCrosslineMin); grid.def_property("crossline_max", &StackFile::Grid::crosslineMax, &StackFile::Grid::setCrosslineMax); grid.def_property("crossline_increment", &StackFile::Grid::crosslineIncrement, &StackFile::Grid::setCrosslineIncrement); grid.def_property("crossline_spacing", &StackFile::Grid::crosslineSpacing, &StackFile::Grid::setCrosslineSpacing); grid.def_property("num_inlines", &StackFile::Grid::numInlines, &StackFile::Grid::setNumInlines); grid.def_property("num_crosslines", &StackFile::Grid::numCrosslines, &StackFile::Grid::setNumCrosslines); grid.def_property("sampling_interval", &StackFile::Grid::samplingInterval, &StackFile::Grid::setSamplingInterval); grid.def_property("num_samples", &StackFile::Grid::numSamples, &StackFile::Grid::setNumSamples); grid.def_property("units", &StackFile::Grid::units, &StackFile::Grid::setUnits); grid.def_property( "inline_numbers", [](const StackFile::Grid& self) { py::tuple ils(self.numInlines()); for (int il = self.inlineMin(), idx = 0; il <= self.inlineMax(); il += self.inlineIncrement(), ++idx) { ils[idx] = il; } return ils; }, [](const StackFile::Grid&, const py::object&) { throw py::type_error("Read only attribute"); }); grid.def_property( "crossline_numbers", [](const StackFile::Grid& self) { py::tuple xls(self.numCrosslines()); for (int xl = self.crosslineMin(), idx = 0; xl <= self.crosslineMax(); xl += self.crosslineIncrement(), ++idx) { xls[idx] = xl; } return xls; }, [](const StackFile::Grid&, const py::object&) { throw py::type_error("Read only attribute"); }); grid.def("__repr__", [](const StackFile::Grid& grid) { std::ostringstream ostr; ostr << grid; return ostr.str(); }); py::enum_<StackFile::Grid::Units>(grid, "Units") .value("METERS", StackFile::Grid::METERS) .value("FEET", StackFile::Grid::FEET) .export_values(); py::class_<StackFile::Grid::Coordinate> coord(grid, "Coordinate"); coord.def(py::init<>()); coord.def_property( "x", [](const StackFile::Grid::Coordinate& self) { return self.x; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "y", [](const StackFile::Grid::Coordinate& self) { return self.y; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "inline_num", [](const StackFile::Grid::Coordinate& self) { return self.inline_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "crossline_num", [](const StackFile::Grid::Coordinate& self) { return self.crossline_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "ensemble_num", [](const StackFile::Grid::Coordinate& self) { return self.ensemble_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "shotpoint_num", [](const StackFile::Grid::Coordinate& self) { return self.shotpoint_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "latitude", [](const StackFile::Grid::Coordinate& self) { return self.lat; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "longitude", [](const StackFile::Grid::Coordinate& self) { return self.lon; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def("__repr__", [](const StackFile::Grid::Coordinate& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }); py::class_<StackFile::Grid::BoundingBox> bbox(grid, "BoundingBox"); bbox.def(py::init<>()); bbox.def_property( "c1", [](const StackFile::Grid::BoundingBox& self) { return self.c1; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def_property( "c2", [](const StackFile::Grid::BoundingBox& self) { return self.c2; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def_property( "c3", [](const StackFile::Grid::BoundingBox& self) { return self.c3; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def_property( "c4", [](const StackFile::Grid::BoundingBox& self) { return self.c4; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def("__repr__", [](const StackFile::Grid::BoundingBox& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }); py::class_<StackFile::SegyOptions> opts(sf, "SegyOptions"); opts.def(py::init<>()); opts.def("set_utm_zone", [](StackFile::SegyOptions& self, int number, char v) { try { self.setUtmZone(number, v); } catch (const std::runtime_error& e) { throw py::type_error(e.what()); } }); opts.def("utm_zone", &StackFile::SegyOptions::getUtmZone); opts.def("set_trace_header_offset", &StackFile::SegyOptions::setTraceHeaderOffset); opts.def("set_trace_header_offsets", &StackFile::SegyOptions::setTraceHeaderOffsets); opts.def("trace_header_offset", &StackFile::SegyOptions::getTraceHeaderOffset); opts.def("set_is_2D", &StackFile::SegyOptions::setIs2D); opts.def("is_2D", &StackFile::SegyOptions::is2D); opts.def("__repr__", [](const StackFile::SegyOptions& opts) { std::ostringstream ostr; ostr << opts; return ostr.str(); }); } PYBIND11_MODULE(segystack, m) { google::InitGoogleLogging("segystack"); m.doc() = "segystack python interface"; init_common(&m); init_segy_file(&m); init_stack_file(&m); py::module test_mod = m.def_submodule("test", "Testing utility methods"); test_mod.def( "create_test_segy", &segystack::test::create_test_segy, "Helper function to create test SEG-Y files.", py::arg("outfile"), py::arg("num_samples"), py::arg("sampling_interval"), py::arg("num_il"), py::arg("il_increment"), py::arg("num_xl"), py::arg("xl_increment"), py::arg("x_origin"), py::arg("y_origin"), py::arg("il_spacing"), py::arg("xl_spacing"), py::arg("opts")); } <commit_msg>fix openmode initialization.<commit_after>// Copyright 2020 Google LLC // // 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 <glog/logging.h> #include <sstream> #include "pybind11/numpy.h" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "segy_file.h" #include "stack_file.h" #include "test/test_base.h" namespace py = pybind11; using namespace py::literals; using namespace segystack; void init_common(py::module* m) { py::class_<UTMZone> utm(*m, "UTMZone"); utm.def(py::init<>()); utm.def(py::init<int, char>()); utm.def_property("number", &UTMZone::number, &UTMZone::setNumber); utm.def_property( "letter", &UTMZone::letter, [](UTMZone& self, const std::string& val) { if (val.size() != 1) throw py::type_error("Zone must consist of a single character!"); self.setLetter(val[0]); }); utm.def("__repr__", [](const UTMZone& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }); } void init_segy_file(py::module* m) { py::class_<SegyFile> sgy(*m, "SegyFile"); sgy.def(py::init<const std::string&>()); sgy.def("open", [](SegyFile& self, const std::string& mode) { std::ios_base::openmode open_mode = std::ios_base::in; if (mode.find('r') != std::string::npos) open_mode |= std::ios_base::in; if (mode.find('w') != std::string::npos) open_mode |= std::ios_base::out; self.open(open_mode); }); sgy.def("name", &SegyFile::name); sgy.def("close", &SegyFile::close); sgy.def("guess_trace_header_offsets", &SegyFile::guessTraceHeaderOffsets); py::class_<SegyFile::Trace> trace(sgy, "Trace"); trace.def(py::init<>()); trace.def("header", [](const SegyFile::Trace& self) { return self.header(); }); py::class_<SegyFile::Trace::Header> hdr(trace, "Header"); hdr.def(py::init<>()); py::enum_<SegyFile::Trace::Header::Attribute>(hdr, "Attribute") .value("INLINE_NUMBER", SegyFile::Trace::Header::Attribute::INLINE_NUMBER) .value("CROSSLINE_NUMBER", SegyFile::Trace::Header::Attribute::CROSSLINE_NUMBER) .value("X_COORDINATE", SegyFile::Trace::Header::Attribute::X_COORDINATE) .value("Y_COORDINATE", SegyFile::Trace::Header::Attribute::Y_COORDINATE) .export_values(); } void init_stack_file(py::module* m) { py::class_<StackFile> sf(*m, "StackFile"); sf.def(py::init<const std::string&, const SegyFile&, const StackFile::SegyOptions&>()); sf.def(py::init<const std::string&, const SegyFile&>()); sf.def(py::init<const std::string&>()); sf.def("name", &StackFile::name); sf.def("grid", &StackFile::grid, py::return_value_policy::reference); sf.def("read_inline", [](const StackFile& self, int il, float fill_value) -> py::array_t<float> { py::array::ShapeContainer shape( {self.grid().numCrosslines(), self.grid().numSamples()}); py::array_t<float> data(shape); float* buffer = data.mutable_data(); self.readInline(il, buffer, data.size(), fill_value); return data; }); sf.def("read_crossline", [](const StackFile& self, int xl, float fill_value) -> py::array_t<float> { py::array::ShapeContainer shape( {self.grid().numInlines(), self.grid().numSamples()}); py::array_t<float> data(shape); float* buffer = data.mutable_data(); self.readCrossline(xl, buffer, data.size(), fill_value); return data; }); sf.def("read_depth_slice", [](const StackFile& self, int sample_index, float fill_value) -> py::array_t<float> { py::array::ShapeContainer shape( {self.grid().numInlines(), self.grid().numCrosslines()}); py::array_t<float> data(shape); float* buffer = data.mutable_data(); self.readDepthSlice(sample_index, buffer, data.size(), fill_value); return data; }); sf.def("set_crossline_access_opt", &StackFile::setCrosslineAccessOptimization); sf.def("set_depth_slice_access_opt", &StackFile::setDepthSliceAccessOptimization); py::class_<StackFile::Grid> grid(sf, "Grid"); grid.def(py::init<>()); grid.def("utm_zone", &StackFile::Grid::utmZone); grid.def("bounding_box", &StackFile::Grid::boundingBox); grid.def("is_bin_active", &StackFile::Grid::isBinActive); grid.def("get_coordinate", &StackFile::Grid::getCoordinate); grid.def_property("inline_min", &StackFile::Grid::inlineMin, &StackFile::Grid::setInlineMin); grid.def_property("inline_max", &StackFile::Grid::inlineMax, &StackFile::Grid::setInlineMax); grid.def_property("inline_increment", &StackFile::Grid::inlineIncrement, &StackFile::Grid::setInlineIncrement); grid.def_property("inline_spacing", &StackFile::Grid::inlineSpacing, &StackFile::Grid::setInlineSpacing); grid.def_property("crossline_min", &StackFile::Grid::crosslineMin, &StackFile::Grid::setCrosslineMin); grid.def_property("crossline_max", &StackFile::Grid::crosslineMax, &StackFile::Grid::setCrosslineMax); grid.def_property("crossline_increment", &StackFile::Grid::crosslineIncrement, &StackFile::Grid::setCrosslineIncrement); grid.def_property("crossline_spacing", &StackFile::Grid::crosslineSpacing, &StackFile::Grid::setCrosslineSpacing); grid.def_property("num_inlines", &StackFile::Grid::numInlines, &StackFile::Grid::setNumInlines); grid.def_property("num_crosslines", &StackFile::Grid::numCrosslines, &StackFile::Grid::setNumCrosslines); grid.def_property("sampling_interval", &StackFile::Grid::samplingInterval, &StackFile::Grid::setSamplingInterval); grid.def_property("num_samples", &StackFile::Grid::numSamples, &StackFile::Grid::setNumSamples); grid.def_property("units", &StackFile::Grid::units, &StackFile::Grid::setUnits); grid.def_property( "inline_numbers", [](const StackFile::Grid& self) { py::tuple ils(self.numInlines()); for (int il = self.inlineMin(), idx = 0; il <= self.inlineMax(); il += self.inlineIncrement(), ++idx) { ils[idx] = il; } return ils; }, [](const StackFile::Grid&, const py::object&) { throw py::type_error("Read only attribute"); }); grid.def_property( "crossline_numbers", [](const StackFile::Grid& self) { py::tuple xls(self.numCrosslines()); for (int xl = self.crosslineMin(), idx = 0; xl <= self.crosslineMax(); xl += self.crosslineIncrement(), ++idx) { xls[idx] = xl; } return xls; }, [](const StackFile::Grid&, const py::object&) { throw py::type_error("Read only attribute"); }); grid.def("__repr__", [](const StackFile::Grid& grid) { std::ostringstream ostr; ostr << grid; return ostr.str(); }); py::enum_<StackFile::Grid::Units>(grid, "Units") .value("METERS", StackFile::Grid::METERS) .value("FEET", StackFile::Grid::FEET) .export_values(); py::class_<StackFile::Grid::Coordinate> coord(grid, "Coordinate"); coord.def(py::init<>()); coord.def_property( "x", [](const StackFile::Grid::Coordinate& self) { return self.x; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "y", [](const StackFile::Grid::Coordinate& self) { return self.y; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "inline_num", [](const StackFile::Grid::Coordinate& self) { return self.inline_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "crossline_num", [](const StackFile::Grid::Coordinate& self) { return self.crossline_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "ensemble_num", [](const StackFile::Grid::Coordinate& self) { return self.ensemble_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "shotpoint_num", [](const StackFile::Grid::Coordinate& self) { return self.shotpoint_num; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "latitude", [](const StackFile::Grid::Coordinate& self) { return self.lat; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def_property( "longitude", [](const StackFile::Grid::Coordinate& self) { return self.lon; }, [](StackFile::Grid::Coordinate&, const py::object&) { throw py::type_error("Read only attribute"); }); coord.def("__repr__", [](const StackFile::Grid::Coordinate& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }); py::class_<StackFile::Grid::BoundingBox> bbox(grid, "BoundingBox"); bbox.def(py::init<>()); bbox.def_property( "c1", [](const StackFile::Grid::BoundingBox& self) { return self.c1; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def_property( "c2", [](const StackFile::Grid::BoundingBox& self) { return self.c2; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def_property( "c3", [](const StackFile::Grid::BoundingBox& self) { return self.c3; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def_property( "c4", [](const StackFile::Grid::BoundingBox& self) { return self.c4; }, [](StackFile::Grid::BoundingBox&, const py::object&) { throw py::type_error("Read only attribute"); }); bbox.def("__repr__", [](const StackFile::Grid::BoundingBox& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }); py::class_<StackFile::SegyOptions> opts(sf, "SegyOptions"); opts.def(py::init<>()); opts.def("set_utm_zone", [](StackFile::SegyOptions& self, int number, char v) { try { self.setUtmZone(number, v); } catch (const std::runtime_error& e) { throw py::type_error(e.what()); } }); opts.def("utm_zone", &StackFile::SegyOptions::getUtmZone); opts.def("set_trace_header_offset", &StackFile::SegyOptions::setTraceHeaderOffset); opts.def("set_trace_header_offsets", &StackFile::SegyOptions::setTraceHeaderOffsets); opts.def("trace_header_offset", &StackFile::SegyOptions::getTraceHeaderOffset); opts.def("set_is_2D", &StackFile::SegyOptions::setIs2D); opts.def("is_2D", &StackFile::SegyOptions::is2D); opts.def("__repr__", [](const StackFile::SegyOptions& opts) { std::ostringstream ostr; ostr << opts; return ostr.str(); }); } PYBIND11_MODULE(segystack, m) { google::InitGoogleLogging("segystack"); m.doc() = "segystack python interface"; init_common(&m); init_segy_file(&m); init_stack_file(&m); py::module test_mod = m.def_submodule("test", "Testing utility methods"); test_mod.def( "create_test_segy", &segystack::test::create_test_segy, "Helper function to create test SEG-Y files.", py::arg("outfile"), py::arg("num_samples"), py::arg("sampling_interval"), py::arg("num_il"), py::arg("il_increment"), py::arg("num_xl"), py::arg("xl_increment"), py::arg("x_origin"), py::arg("y_origin"), py::arg("il_spacing"), py::arg("xl_spacing"), py::arg("opts")); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <shlwapi.h> #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/environment.h" #include "base/file_version_info.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/version.h" #include "chrome/app/breakpad_win.h" #include "chrome/app/chrome_breakpad_client.h" #include "chrome/app/client_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/env_vars.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/channel_info.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/util_constants.h" #include "components/breakpad/breakpad_client.h" namespace { // The entry point signature of chrome.dll. typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*); typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)(); base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER; // Expects that |dir| has a trailing backslash. |dir| is modified so it // contains the full path that was tried. Caller must check for the return // value not being null to determine if this path contains a valid dll. HMODULE LoadChromeWithDirectory(string16* dir) { ::SetCurrentDirectoryW(dir->c_str()); dir->append(installer::kChromeDll); return ::LoadLibraryExW(dir->c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } void RecordDidRun(const string16& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(true, system_level); } void ClearDidRun(const string16& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(false, system_level); } #if defined(CHROME_SPLIT_DLL) // Deferred initialization entry point for chrome1.dll. typedef BOOL (__stdcall *DoDeferredCrtInitFunc)(HINSTANCE hinstance); bool InitSplitChromeDll(HMODULE mod) { if (!mod) return false; DoDeferredCrtInitFunc init = reinterpret_cast<DoDeferredCrtInitFunc>( ::GetProcAddress(mod, "_DoDeferredCrtInit@4")); return (init(mod) == TRUE); } #endif } // namespace string16 GetExecutablePath() { wchar_t path[MAX_PATH]; ::GetModuleFileNameW(NULL, path, MAX_PATH); if (!::PathRemoveFileSpecW(path)) return string16(); string16 exe_path(path); return exe_path.append(1, L'\\'); } string16 GetCurrentModuleVersion() { scoped_ptr<FileVersionInfo> file_version_info( FileVersionInfo::CreateFileVersionInfoForCurrentModule()); if (file_version_info.get()) { string16 version_string(file_version_info->file_version()); if (Version(WideToASCII(version_string)).IsValid()) return version_string; } return string16(); } //============================================================================= MainDllLoader::MainDllLoader() : dll_(NULL) { } MainDllLoader::~MainDllLoader() { } // Loading chrome is an interesting affair. First we try loading from the // current directory to support run-what-you-compile and other development // scenarios. // If that fails then we look at the --chrome-version command line flag to // determine if we should stick with an older dll version even if a new one is // available to support upgrade-in-place scenarios. // If that fails then finally we look at the version resource in the current // module. This is the expected path for chrome.exe browser instances in an // installed build. HMODULE MainDllLoader::Load(string16* out_version, string16* out_file) { const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); const string16 dir(GetExecutablePath()); *out_file = dir; HMODULE dll = LoadChromeWithDirectory(out_file); if (!dll) { // Loading from same directory (for developers) failed. string16 version_string; if (cmd_line.HasSwitch(switches::kChromeVersion)) { // This is used to support Chrome Frame, see http://crbug.com/88589. version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion); if (!Version(WideToASCII(version_string)).IsValid()) { // If a bogus command line flag was given, then abort. LOG(ERROR) << "Invalid command line version: " << version_string; return NULL; } } // If no version on the command line, then look at the version resource in // the current module and try loading that. if (version_string.empty()) version_string = GetCurrentModuleVersion(); if (version_string.empty()) { LOG(ERROR) << "No valid Chrome version found"; return NULL; } *out_file = dir; *out_version = version_string; out_file->append(*out_version).append(1, L'\\'); dll = LoadChromeWithDirectory(out_file); if (!dll) { PLOG(ERROR) << "Failed to load Chrome DLL from " << *out_file; return NULL; } } DCHECK(dll); #if defined(CHROME_SPLIT_DLL) // In split dlls mode, we need to manually initialize both DLLs because // the circular dependencies between them make the loader not call the // Dllmain for DLL_PROCESS_ATTACH. InitSplitChromeDll(dll); InitSplitChromeDll(::GetModuleHandleA("chrome1.dll")); #endif return dll; } // Launching is a matter of loading the right dll, setting the CHROME_VERSION // environment variable and just calling the entry point. Derived classes can // add custom code in the OnBeforeLaunch callback. int MainDllLoader::Launch(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sbox_info) { string16 version; string16 file; dll_ = Load(&version, &file); if (!dll_) return chrome::RESULT_CODE_MISSING_DATA; scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version)); // TODO(erikwright): Remove this when http://crbug.com/174953 is fixed and // widely deployed. env->UnSetVar(env_vars::kGoogleUpdateIsMachineEnvVar); breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer()); InitCrashReporter(); OnBeforeLaunch(file); DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain")); if (!entry_point) return chrome::RESULT_CODE_BAD_PROCESS_TYPE; int rc = entry_point(instance, sbox_info); return OnBeforeExit(rc, file); } void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() { RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function = reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>( ::GetProcAddress(dll_, "RelaunchChromeBrowserWithNewCommandLineIfNeeded")); if (!relaunch_function) { LOG(ERROR) << "Could not find exported function " << "RelaunchChromeBrowserWithNewCommandLineIfNeeded"; } else { relaunch_function(); } } //============================================================================= class ChromeDllLoader : public MainDllLoader { public: virtual string16 GetRegistryPath() { string16 key(google_update::kRegPathClients); BrowserDistribution* dist = BrowserDistribution::GetDistribution(); key.append(L"\\").append(dist->GetAppGuid()); return key; } virtual void OnBeforeLaunch(const string16& dll_path) { RecordDidRun(dll_path); } virtual int OnBeforeExit(int return_code, const string16& dll_path) { // NORMAL_EXIT_CANCEL is used for experiments when the user cancels // so we need to reset the did_run signal so omaha does not count // this run as active usage. if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) { ClearDidRun(dll_path); } return return_code; } }; //============================================================================= class ChromiumDllLoader : public MainDllLoader { public: virtual string16 GetRegistryPath() { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); return dist->GetVersionKey(); } }; MainDllLoader* MakeMainDllLoader() { #if defined(GOOGLE_CHROME_BUILD) return new ChromeDllLoader(); #else return new ChromiumDllLoader(); #endif } <commit_msg>Putting back pre read for chrome.dll, fixed at 25%<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <shlwapi.h> #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/environment.h" #include "base/file_version_info.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/version.h" #include "base/win/windows_version.h" #include "chrome/app/breakpad_win.h" #include "chrome/app/chrome_breakpad_client.h" #include "chrome/app/client_util.h" #include "chrome/app/image_pre_reader_win.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/env_vars.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/channel_info.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/util_constants.h" #include "components/breakpad/breakpad_client.h" namespace { // The entry point signature of chrome.dll. typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*); typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)(); base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER; // Expects that |dir| has a trailing backslash. |dir| is modified so it // contains the full path that was tried. Caller must check for the return // value not being null to determine if this path contains a valid dll. HMODULE LoadChromeWithDirectory(string16* dir) { ::SetCurrentDirectoryW(dir->c_str()); dir->append(installer::kChromeDll); #if !defined(WIN_DISABLE_PREREAD) // On Win7 with Syzygy, pre-read is a win. There've very little difference // between 25% and 100%. For cold starts, with or without prefetch 25% // performs slightly better than 100%. On XP, pre-read is generally a // performance loss. const size_t kStepSize = 1024 * 1024; uint8 percent = base::win::GetVersion() > base::win::VERSION_XP ? 25 : 0; ImagePreReader::PartialPreReadImage(dir->c_str(), percent, kStepSize); #endif return ::LoadLibraryExW(dir->c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } void RecordDidRun(const string16& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(true, system_level); } void ClearDidRun(const string16& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(false, system_level); } #if defined(CHROME_SPLIT_DLL) // Deferred initialization entry point for chrome1.dll. typedef BOOL (__stdcall *DoDeferredCrtInitFunc)(HINSTANCE hinstance); bool InitSplitChromeDll(HMODULE mod) { if (!mod) return false; DoDeferredCrtInitFunc init = reinterpret_cast<DoDeferredCrtInitFunc>( ::GetProcAddress(mod, "_DoDeferredCrtInit@4")); return (init(mod) == TRUE); } #endif } // namespace string16 GetExecutablePath() { wchar_t path[MAX_PATH]; ::GetModuleFileNameW(NULL, path, MAX_PATH); if (!::PathRemoveFileSpecW(path)) return string16(); string16 exe_path(path); return exe_path.append(1, L'\\'); } string16 GetCurrentModuleVersion() { scoped_ptr<FileVersionInfo> file_version_info( FileVersionInfo::CreateFileVersionInfoForCurrentModule()); if (file_version_info.get()) { string16 version_string(file_version_info->file_version()); if (Version(WideToASCII(version_string)).IsValid()) return version_string; } return string16(); } //============================================================================= MainDllLoader::MainDllLoader() : dll_(NULL) { } MainDllLoader::~MainDllLoader() { } // Loading chrome is an interesting affair. First we try loading from the // current directory to support run-what-you-compile and other development // scenarios. // If that fails then we look at the --chrome-version command line flag to // determine if we should stick with an older dll version even if a new one is // available to support upgrade-in-place scenarios. // If that fails then finally we look at the version resource in the current // module. This is the expected path for chrome.exe browser instances in an // installed build. HMODULE MainDllLoader::Load(string16* out_version, string16* out_file) { const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); const string16 dir(GetExecutablePath()); *out_file = dir; HMODULE dll = LoadChromeWithDirectory(out_file); if (!dll) { // Loading from same directory (for developers) failed. string16 version_string; if (cmd_line.HasSwitch(switches::kChromeVersion)) { // This is used to support Chrome Frame, see http://crbug.com/88589. version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion); if (!Version(WideToASCII(version_string)).IsValid()) { // If a bogus command line flag was given, then abort. LOG(ERROR) << "Invalid command line version: " << version_string; return NULL; } } // If no version on the command line, then look at the version resource in // the current module and try loading that. if (version_string.empty()) version_string = GetCurrentModuleVersion(); if (version_string.empty()) { LOG(ERROR) << "No valid Chrome version found"; return NULL; } *out_file = dir; *out_version = version_string; out_file->append(*out_version).append(1, L'\\'); dll = LoadChromeWithDirectory(out_file); if (!dll) { PLOG(ERROR) << "Failed to load Chrome DLL from " << *out_file; return NULL; } } DCHECK(dll); #if defined(CHROME_SPLIT_DLL) // In split dlls mode, we need to manually initialize both DLLs because // the circular dependencies between them make the loader not call the // Dllmain for DLL_PROCESS_ATTACH. InitSplitChromeDll(dll); InitSplitChromeDll(::GetModuleHandleA("chrome1.dll")); #endif return dll; } // Launching is a matter of loading the right dll, setting the CHROME_VERSION // environment variable and just calling the entry point. Derived classes can // add custom code in the OnBeforeLaunch callback. int MainDllLoader::Launch(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sbox_info) { string16 version; string16 file; dll_ = Load(&version, &file); if (!dll_) return chrome::RESULT_CODE_MISSING_DATA; scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version)); // TODO(erikwright): Remove this when http://crbug.com/174953 is fixed and // widely deployed. env->UnSetVar(env_vars::kGoogleUpdateIsMachineEnvVar); breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer()); InitCrashReporter(); OnBeforeLaunch(file); DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain")); if (!entry_point) return chrome::RESULT_CODE_BAD_PROCESS_TYPE; int rc = entry_point(instance, sbox_info); return OnBeforeExit(rc, file); } void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() { RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function = reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>( ::GetProcAddress(dll_, "RelaunchChromeBrowserWithNewCommandLineIfNeeded")); if (!relaunch_function) { LOG(ERROR) << "Could not find exported function " << "RelaunchChromeBrowserWithNewCommandLineIfNeeded"; } else { relaunch_function(); } } //============================================================================= class ChromeDllLoader : public MainDllLoader { public: virtual string16 GetRegistryPath() { string16 key(google_update::kRegPathClients); BrowserDistribution* dist = BrowserDistribution::GetDistribution(); key.append(L"\\").append(dist->GetAppGuid()); return key; } virtual void OnBeforeLaunch(const string16& dll_path) { RecordDidRun(dll_path); } virtual int OnBeforeExit(int return_code, const string16& dll_path) { // NORMAL_EXIT_CANCEL is used for experiments when the user cancels // so we need to reset the did_run signal so omaha does not count // this run as active usage. if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) { ClearDidRun(dll_path); } return return_code; } }; //============================================================================= class ChromiumDllLoader : public MainDllLoader { public: virtual string16 GetRegistryPath() { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); return dist->GetVersionKey(); } }; MainDllLoader* MakeMainDllLoader() { #if defined(GOOGLE_CHROME_BUILD) return new ChromeDllLoader(); #else return new ChromiumDllLoader(); #endif } <|endoftext|>
<commit_before>#include <irrlicht.h> #include "events.h" #include "gui_game.h" using namespace irr; namespace ic = irr::core; namespace is = irr::scene; namespace iv = irr::video; namespace ig = irr::gui; int main() { // Le gestionnaire d'événements EventReceiver receiver; std::vector<iv::ITexture*> textures; // Création de la fenêtre et du système de rendu. IrrlichtDevice *device = createDevice(iv::EDT_OPENGL, ic::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); is::ISceneManager *smgr = device->getSceneManager(); iv::IVideoDriver *driver = device->getVideoDriver(); ig::IGUIEnvironment *gui_game = device->getGUIEnvironment(); // Chargement du cube is::IAnimatedMesh *mesh = smgr->getMesh("data/cube.3ds"); // Ajout du cube à la scène is::IAnimatedMeshSceneNode *node; int id = 0; int Ni = 50; int Nj = 50; for (int i = 0 ; i < Ni ; i ++) { for (int j = 0 ; j < Nj ; j ++) { node = smgr->addAnimatedMeshSceneNode(mesh,nullptr,id); node->setMaterialFlag(irr::video::EMF_LIGHTING, false); node->setPosition (core::vector3df(i,0,j)); id++; textures.push_back(driver->getTexture("data/TXsQk.png")); node->setMaterialTexture(0, textures[0]); receiver.set_node(node); receiver.set_textures(textures); } } // Ajout du cube à la scène is::IAnimatedMeshSceneNode *node_personnage; node_personnage = smgr->addAnimatedMeshSceneNode(mesh); node_personnage->setMaterialFlag(irr::video::EMF_LIGHTING, false); node_personnage->setPosition(core::vector3df(20, 2, 20)); textures.push_back(driver->getTexture("data/rouge.jpg")); node_personnage->setMaterialTexture(0, textures.back()); receiver.set_node(node_personnage); receiver.set_textures(textures); receiver.set_gui(gui_game); //smgr->addCameraSceneNode(nullptr, ic::vector3df(0, 30, -40), ic::vector3df(0, 5, 0)); is::ICameraSceneNode *camera = smgr->addCameraSceneNodeMaya(); camera->setTarget(node_personnage->getPosition()); // La barre de menu gui_game::create_menu(gui_game); while(device->run()) { driver->beginScene(true, true, iv::SColor(0,50,100,255)); // Dessin de la scène : smgr->drawAll(); // Dessin de l'interface utilisateur : gui_game->drawAll(); driver->endScene(); } device->drop(); return 0; } <commit_msg>fonction arbre qui creer un autre node<commit_after>#include <irrlicht.h> #include "events.h" #include "gui_game.h" using namespace irr; namespace ic = irr::core; namespace is = irr::scene; namespace iv = irr::video; namespace ig = irr::gui; void createtree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver *driver); int main() { // Le gestionnaire d'événements EventReceiver receiver; std::vector<iv::ITexture*> textures; // Création de la fenêtre et du système de rendu. IrrlichtDevice *device = createDevice(iv::EDT_OPENGL, ic::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); is::ISceneManager *smgr = device->getSceneManager(); iv::IVideoDriver *driver = device->getVideoDriver(); ig::IGUIEnvironment *gui_game = device->getGUIEnvironment(); // Chargement du cube is::IAnimatedMesh *mesh = smgr->getMesh("data/cube.3ds"); // Ajout du cube à la scène is::IAnimatedMeshSceneNode *node; int id = 0; int Ni = 50; int Nj = 50; for (int i = 0 ; i < Ni ; i ++) { for (int j = 0 ; j < Nj ; j ++) { node = smgr->addAnimatedMeshSceneNode(mesh,nullptr,id); node->setMaterialFlag(irr::video::EMF_LIGHTING, false); node->setPosition (core::vector3df(i,0,j)); id++; textures.push_back(driver->getTexture("data/TXsQk.png")); node->setMaterialTexture(0, textures[0]); receiver.set_node(node); receiver.set_textures(textures); } } //ajout arbre via une fonction createtree(mesh, smgr,receiver,driver); // Ajout du cube à la scène is::IAnimatedMeshSceneNode *node_personnage; node_personnage = smgr->addAnimatedMeshSceneNode(mesh); node_personnage->setMaterialFlag(irr::video::EMF_LIGHTING, false); node_personnage->setPosition(core::vector3df(20, 2, 20)); textures.push_back(driver->getTexture("data/rouge.jpg")); node_personnage->setMaterialTexture(0, textures.back()); receiver.set_node(node_personnage); receiver.set_textures(textures); receiver.set_gui(gui_game); //smgr->addCameraSceneNode(nullptr, ic::vector3df(0, 30, -40), ic::vector3df(0, 5, 0)); is::ICameraSceneNode *camera = smgr->addCameraSceneNodeMaya(); camera->setTarget(node_personnage->getPosition()); // La barre de menu gui_game::create_menu(gui_game); while(device->run()) { driver->beginScene(true, true, iv::SColor(0,50,100,255)); // Dessin de la scène : smgr->drawAll(); // Dessin de l'interface utilisateur : gui_game->drawAll(); driver->endScene(); } device->drop(); return 0; } void createtree(is::IAnimatedMesh *mesh, is::ISceneManager *smgr, EventReceiver receiver, iv::IVideoDriver *driver) { std::vector<iv::ITexture*> textures; is::IAnimatedMeshSceneNode *node_arbre; int i = 10; int j = 10; int id=0; for (int k = 0 ; k < 15 ; k ++) { node_arbre = smgr->addAnimatedMeshSceneNode(mesh,nullptr,id); node_arbre->setMaterialFlag(irr::video::EMF_LIGHTING, false); node_arbre->setPosition (core::vector3df(i,k,j)); textures.push_back(driver->getTexture("data/tree.jpg")); node_arbre->setMaterialTexture(0, textures[0]); receiver.set_node(node_arbre); receiver.set_textures(textures); id++; } } <|endoftext|>
<commit_before><commit_msg>Change PipelineImplTest in media_unittests to workaround gmock bug<commit_after><|endoftext|>
<commit_before>#include "mainwindow.h" #include <QApplication> #include <QFile> #include <QStyle> #include <QDebug> #include "sprite.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; QFile styleSheet(":/style.qss"); styleSheet.open(QFile::ReadOnly); QString _styleSheet = QLatin1String(styleSheet.readAll()); w.setStyleSheet(_styleSheet); w.showFullScreen(); return a.exec(); } <commit_msg>- Pull GUI<commit_after>#include "mainwindow.h" #include "sprite.h" #include <QApplication> #include <QFile> #include <QStyle> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; QFile styleSheet(":/style.qss"); styleSheet.open(QFile::ReadOnly); QString _styleSheet = QLatin1String(styleSheet.readAll()); w.setStyleSheet(_styleSheet); w.showFullScreen(); return a.exec(); } <|endoftext|>
<commit_before>#include <StdAfx.h> #include <UI/Dialogs/Editors/HexEditor.h> #include <UI/FileDialogEx.h> #include <UI/ViewPane/CountedTextPane.h> #include <UI/ViewPane/SmartViewPane.h> #include <UI/ViewPane/SplitterPane.h> #include <UI/ViewPane/TreePane.h> #include <MAPI/Cache/GlobalCache.h> #include <MAPI/MAPIFunctions.h> namespace dialog { namespace editor { static std::wstring CLASS = L"CHexEditor"; enum __HexEditorFields { HEXED_TEXT, HEXED_ANSI, HEXED_UNICODE, HEXED_BASE64, HEXED_HEX, HEXED_SMARTVIEW, HEXED_SPLITTER2, HEXED_TREE }; CHexEditor::CHexEditor(_In_ ui::CParentWnd* pParentWnd, _In_ cache::CMapiObjects* lpMapiObjects) : CEditor( pParentWnd, IDS_HEXEDITOR, NULL, CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_ACTION2 | CEDITOR_BUTTON_ACTION3, IDS_IMPORT, IDS_EXPORT, IDS_CLOSE) { TRACE_CONSTRUCTOR(CLASS); m_lpMapiObjects = lpMapiObjects; if (m_lpMapiObjects) m_lpMapiObjects->AddRef(); auto splitter = viewpane::SplitterPane::CreateHorizontalPane(HEXED_TEXT, IDS_TEXTANSIUNICODE); AddPane(splitter); splitter->SetPaneOne(viewpane::TextPane::CreateMultiLinePane(HEXED_ANSI, NULL, false)); splitter->SetPaneTwo(viewpane::TextPane::CreateMultiLinePane(HEXED_UNICODE, NULL, false)); AddPane(viewpane::CountedTextPane::Create(HEXED_BASE64, IDS_BASE64STRING, false, IDS_CCH)); auto tree = viewpane::TreePane::Create(HEXED_TREE, IDS_HEX, true); tree->InitializeCallback = [&](controls::StyleTreeCtrl& tree) { tree.ItemSelectedCallback = [&](auto hItem) { { WCHAR szText[255] = {}; auto item = TVITEMEXW{}; item.mask = TVIF_TEXT; item.pszText = szText; item.cchTextMax = _countof(szText); item.hItem = hItem; WC_B_S(::SendMessage(tree.GetSafeHwnd(), TVM_GETITEMW, 0, reinterpret_cast<LPARAM>(&item))); SetStringW(HEXED_ANSI, szText); } }; const auto root = tree.AddChildNode(L"ROOT", nullptr, 0, nullptr); auto child1 = tree.AddChildNode(L"child1", root, 0, nullptr); (void) tree.AddChildNode(L"child2", child1, 0, nullptr); auto child3 = tree.AddChildNode(L"child3", root, 0, nullptr); (void) tree.AddChildNode(L"child4", child3, 0, nullptr); (void) tree.AddChildNode(L"child5", child3, 0, nullptr); }; auto splitter2 = viewpane::SplitterPane::CreateHorizontalPane(HEXED_SPLITTER2, IDS_TEXTANSIUNICODE); AddPane(splitter2); splitter2->SetPaneOne(tree); splitter2->SetPaneTwo(viewpane::SmartViewPane::Create(HEXED_SMARTVIEW, IDS_SMARTVIEW)); AddPane(viewpane::CountedTextPane::Create(HEXED_HEX, IDS_HEX, false, IDS_CB)); DisplayParentedDialog(pParentWnd, 1000); } CHexEditor::~CHexEditor() { TRACE_DESTRUCTOR(CLASS); if (m_lpMapiObjects) m_lpMapiObjects->Release(); } void CHexEditor::OnOK() { ShowWindow(SW_HIDE); delete this; } void CHexEditor::OnCancel() { OnOK(); } _Check_return_ ULONG CHexEditor::HandleChange(const UINT nID) { const auto paneID = CEditor::HandleChange(nID); if (paneID == static_cast<ULONG>(-1)) return static_cast<ULONG>(-1); auto lpb = LPBYTE{}; size_t cb = 0; std::wstring szEncodeStr; size_t cchEncodeStr = 0; switch (paneID) { case HEXED_ANSI: { auto text = GetStringA(HEXED_ANSI); SetStringA(HEXED_UNICODE, text); lpb = LPBYTE(text.c_str()); cb = text.length() * sizeof(CHAR); szEncodeStr = strings::Base64Encode(cb, lpb); cchEncodeStr = szEncodeStr.length(); SetStringW(HEXED_BASE64, szEncodeStr); SetBinary(HEXED_HEX, lpb, cb); } break; case HEXED_UNICODE: // Unicode string changed { auto text = GetStringW(HEXED_UNICODE); SetStringW(HEXED_ANSI, text); lpb = LPBYTE(text.c_str()); cb = text.length() * sizeof(WCHAR); szEncodeStr = strings::Base64Encode(cb, lpb); cchEncodeStr = szEncodeStr.length(); SetStringW(HEXED_BASE64, szEncodeStr); SetBinary(HEXED_HEX, lpb, cb); } break; case HEXED_BASE64: // base64 changed { auto szTmpString = GetStringW(HEXED_BASE64); // remove any whitespace before decoding szTmpString = strings::StripCRLF(szTmpString); cchEncodeStr = szTmpString.length(); auto bin = strings::Base64Decode(szTmpString); lpb = bin.data(); cb = bin.size(); SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb)); if (!(cb % 2)) // Set Unicode String { SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR))); } else { SetStringW(HEXED_UNICODE, L""); } SetBinary(HEXED_HEX, lpb, cb); } break; case HEXED_HEX: // binary changed { auto bin = GetBinary(HEXED_HEX); lpb = bin.data(); cb = bin.size(); SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb)); // ansi string if (!(cb % 2)) // Set Unicode String { SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR))); } else { SetStringW(HEXED_UNICODE, L""); } szEncodeStr = strings::Base64Encode(cb, lpb); cchEncodeStr = szEncodeStr.length(); SetStringW(HEXED_BASE64, szEncodeStr); } break; default: break; } if (HEXED_SMARTVIEW != paneID) { // length of base64 encoded string auto lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_BASE64)); if (lpPane) { lpPane->SetCount(cchEncodeStr); } lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_HEX)); if (lpPane) { lpPane->SetCount(cb); } } // Update any parsing we've got: UpdateParser(); // Force the new layout OnRecalcLayout(); return paneID; } void CHexEditor::UpdateParser() const { // Find out how to interpret the data auto lpPane = dynamic_cast<viewpane::SmartViewPane*>(GetPane(HEXED_SMARTVIEW)); if (lpPane) { auto bin = GetBinary(HEXED_HEX); lpPane->Parse(SBinary{ULONG(bin.size()), bin.data()}); } } // Import void CHexEditor::OnEditAction1() { auto file = file::CFileDialogExW::OpenFile( strings::emptystring, strings::emptystring, OFN_FILEMUSTEXIST, strings::loadstring(IDS_ALLFILES), this); if (!file.empty()) { cache::CGlobalCache::getInstance().MAPIInitialize(NULL); LPSTREAM lpStream = nullptr; // Get a Stream interface on the input file EC_H_S(mapi::MyOpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_READ, file, &lpStream)); if (lpStream) { auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX)); if (lpPane) { lpPane->SetBinaryStream(lpStream); } lpStream->Release(); } } } // Export void CHexEditor::OnEditAction2() { auto file = file::CFileDialogExW::SaveAs( strings::emptystring, strings::emptystring, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strings::loadstring(IDS_ALLFILES), this); if (!file.empty()) { cache::CGlobalCache::getInstance().MAPIInitialize(NULL); LPSTREAM lpStream = nullptr; // Get a Stream interface on the output file EC_H_S(mapi::MyOpenStreamOnFile( MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE | STGM_READWRITE, file, &lpStream)); if (lpStream) { const auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX)); if (lpPane) { lpPane->GetBinaryStream(lpStream); } lpStream->Release(); } } } // Close void CHexEditor::OnEditAction3() { OnOK(); } } // namespace editor } // namespace dialog <commit_msg>Remove test code<commit_after>#include <StdAfx.h> #include <UI/Dialogs/Editors/HexEditor.h> #include <UI/FileDialogEx.h> #include <UI/ViewPane/CountedTextPane.h> #include <UI/ViewPane/SmartViewPane.h> #include <UI/ViewPane/SplitterPane.h> #include <MAPI/Cache/GlobalCache.h> #include <MAPI/MAPIFunctions.h> namespace dialog { namespace editor { static std::wstring CLASS = L"CHexEditor"; enum __HexEditorFields { HEXED_TEXT, HEXED_ANSI, HEXED_UNICODE, HEXED_BASE64, HEXED_HEX, HEXED_SMARTVIEW }; CHexEditor::CHexEditor(_In_ ui::CParentWnd* pParentWnd, _In_ cache::CMapiObjects* lpMapiObjects) : CEditor( pParentWnd, IDS_HEXEDITOR, NULL, CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_ACTION2 | CEDITOR_BUTTON_ACTION3, IDS_IMPORT, IDS_EXPORT, IDS_CLOSE) { TRACE_CONSTRUCTOR(CLASS); m_lpMapiObjects = lpMapiObjects; if (m_lpMapiObjects) m_lpMapiObjects->AddRef(); auto splitter = viewpane::SplitterPane::CreateHorizontalPane(HEXED_TEXT, IDS_TEXTANSIUNICODE); AddPane(splitter); splitter->SetPaneOne(viewpane::TextPane::CreateMultiLinePane(HEXED_ANSI, NULL, false)); splitter->SetPaneTwo(viewpane::TextPane::CreateMultiLinePane(HEXED_UNICODE, NULL, false)); AddPane(viewpane::CountedTextPane::Create(HEXED_BASE64, IDS_BASE64STRING, false, IDS_CCH)); AddPane(viewpane::CountedTextPane::Create(HEXED_HEX, IDS_HEX, false, IDS_CB)); AddPane(viewpane::SmartViewPane::Create(HEXED_SMARTVIEW, IDS_SMARTVIEW)); DisplayParentedDialog(pParentWnd, 1000); } CHexEditor::~CHexEditor() { TRACE_DESTRUCTOR(CLASS); if (m_lpMapiObjects) m_lpMapiObjects->Release(); } void CHexEditor::OnOK() { ShowWindow(SW_HIDE); delete this; } void CHexEditor::OnCancel() { OnOK(); } _Check_return_ ULONG CHexEditor::HandleChange(const UINT nID) { const auto paneID = CEditor::HandleChange(nID); if (paneID == static_cast<ULONG>(-1)) return static_cast<ULONG>(-1); auto lpb = LPBYTE{}; size_t cb = 0; std::wstring szEncodeStr; size_t cchEncodeStr = 0; switch (paneID) { case HEXED_ANSI: { auto text = GetStringA(HEXED_ANSI); SetStringA(HEXED_UNICODE, text); lpb = LPBYTE(text.c_str()); cb = text.length() * sizeof(CHAR); szEncodeStr = strings::Base64Encode(cb, lpb); cchEncodeStr = szEncodeStr.length(); SetStringW(HEXED_BASE64, szEncodeStr); SetBinary(HEXED_HEX, lpb, cb); } break; case HEXED_UNICODE: // Unicode string changed { auto text = GetStringW(HEXED_UNICODE); SetStringW(HEXED_ANSI, text); lpb = LPBYTE(text.c_str()); cb = text.length() * sizeof(WCHAR); szEncodeStr = strings::Base64Encode(cb, lpb); cchEncodeStr = szEncodeStr.length(); SetStringW(HEXED_BASE64, szEncodeStr); SetBinary(HEXED_HEX, lpb, cb); } break; case HEXED_BASE64: // base64 changed { auto szTmpString = GetStringW(HEXED_BASE64); // remove any whitespace before decoding szTmpString = strings::StripCRLF(szTmpString); cchEncodeStr = szTmpString.length(); auto bin = strings::Base64Decode(szTmpString); lpb = bin.data(); cb = bin.size(); SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb)); if (!(cb % 2)) // Set Unicode String { SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR))); } else { SetStringW(HEXED_UNICODE, L""); } SetBinary(HEXED_HEX, lpb, cb); } break; case HEXED_HEX: // binary changed { auto bin = GetBinary(HEXED_HEX); lpb = bin.data(); cb = bin.size(); SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb)); // ansi string if (!(cb % 2)) // Set Unicode String { SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR))); } else { SetStringW(HEXED_UNICODE, L""); } szEncodeStr = strings::Base64Encode(cb, lpb); cchEncodeStr = szEncodeStr.length(); SetStringW(HEXED_BASE64, szEncodeStr); } break; default: break; } if (HEXED_SMARTVIEW != paneID) { // length of base64 encoded string auto lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_BASE64)); if (lpPane) { lpPane->SetCount(cchEncodeStr); } lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_HEX)); if (lpPane) { lpPane->SetCount(cb); } } // Update any parsing we've got: UpdateParser(); // Force the new layout OnRecalcLayout(); return paneID; } void CHexEditor::UpdateParser() const { // Find out how to interpret the data auto lpPane = dynamic_cast<viewpane::SmartViewPane*>(GetPane(HEXED_SMARTVIEW)); if (lpPane) { auto bin = GetBinary(HEXED_HEX); lpPane->Parse(SBinary{ULONG(bin.size()), bin.data()}); } } // Import void CHexEditor::OnEditAction1() { auto file = file::CFileDialogExW::OpenFile( strings::emptystring, strings::emptystring, OFN_FILEMUSTEXIST, strings::loadstring(IDS_ALLFILES), this); if (!file.empty()) { cache::CGlobalCache::getInstance().MAPIInitialize(NULL); LPSTREAM lpStream = nullptr; // Get a Stream interface on the input file EC_H_S(mapi::MyOpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_READ, file, &lpStream)); if (lpStream) { auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX)); if (lpPane) { lpPane->SetBinaryStream(lpStream); } lpStream->Release(); } } } // Export void CHexEditor::OnEditAction2() { auto file = file::CFileDialogExW::SaveAs( strings::emptystring, strings::emptystring, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strings::loadstring(IDS_ALLFILES), this); if (!file.empty()) { cache::CGlobalCache::getInstance().MAPIInitialize(NULL); LPSTREAM lpStream = nullptr; // Get a Stream interface on the output file EC_H_S(mapi::MyOpenStreamOnFile( MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE | STGM_READWRITE, file, &lpStream)); if (lpStream) { const auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX)); if (lpPane) { lpPane->GetBinaryStream(lpStream); } lpStream->Release(); } } } // Close void CHexEditor::OnEditAction3() { OnOK(); } } // namespace editor } // namespace dialog <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <algorithm> using namespace std; #define MAX_PAIR_NUM 1000 typedef struct Record { int pos; int pixel; } Record; int pixel_pair[MAX_PAIR_NUM][2]; int img_width; Record result[MAX_PAIR_NUM * 9]; bool cmp(const Record& a, const Record& b); int get_pixel_via_pos(int pos, int pair_cnt); int encode_pixel(int pos, int pixel_cnt, int pair_cnt); int main() { while (cin >> img_width && img_width > 0) { int num, pixel; int pair_cnt = 0; int pixel_cnt = 0; int start_pos = 1; while (cin >> pixel >> num && num != 0 && pixel != 0) { pixel_pair[pair_cnt][0] = pixel; pixel_pair[pair_cnt][1] = start_pos; pixel_cnt += num; start_pos += num; pair_cnt++; } int idx = 0; for (int k = 0; k < pair_cnt; k++) { int center = pixel_pair[k][1]; int row = (center - 1) / img_width; int col = (center - 1) % img_width; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int pos = i * img_width + j + 1; if (i < 0 || pos > pixel_cnt || j < 0 || j == img_width) continue; result[idx].pos = pos; result[idx].pixel = encode_pixel(pos, pixel_cnt, pair_cnt); idx++; } } sort(result, result + idx, cmp); /* for (int i = 0; i < idx; i++) cout << result[i].pixel << " " << result[i].pos << endl; */ Record prev = result[0]; if (idx > 1) { for (int i = 1; i < idx; i++) { if (prev.pixel != result[i].pixel) { cout << prev.pixel << " " << result[i - 1].pos - prev.pos << endl; prev = result[i]; } } cout << result[idx - 1].pixel << " " << result[idx - 1].pos - prev.pos << endl; } else cout << prev.pixel << " " << prev.pos << endl; cout << "0 0" << endl; /* for (int i = 0; i < pair_cnt; i++) cout << pixel_pair[i][0] << " " << pixel_pair[i][1] << endl; cout << pixel_cnt << endl; */ } cout << 0 << endl; } bool cmp(const Record& a, const Record& b) { return a.pos < b.pos; } int get_pixel_via_pos(int pos, int pair_cnt) { if (pair_cnt == 1) return pixel_pair[0][0]; int prev = pixel_pair[0][1]; for (int i = 1; i < pair_cnt; i++) { if (pos >= prev && pos < pixel_pair[i][1]) return pixel_pair[i - 1][0]; } return pixel_pair[pair_cnt - 1][0]; } int encode_pixel(int pos, int pixel_cnt, int pair_cnt) { int row = (pos - 1) / img_width; int col = (pos - 1) % img_width; int ret = 0; int tmp = 0; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int curr = i * img_width + j + 1; if (i < 0 || curr > pixel_cnt || j == img_width || j < 0 || curr == pos) continue; tmp = abs(get_pixel_via_pos(pos, pair_cnt) - get_pixel_via_pos(curr, pair_cnt)); if (tmp > ret) ret = tmp; } return ret; } <commit_msg>p1009b<commit_after>#include <iostream> #include <cmath> #include <algorithm> using namespace std; #define MAX_PAIR_NUM 1000 typedef struct Record { int pos; int pixel; } Record; int pixel_pair[MAX_PAIR_NUM][2]; int img_width; Record result[MAX_PAIR_NUM * 9]; bool cmp(const Record& a, const Record& b); int get_pixel_via_pos(int pos, int pair_cnt); int encode_pixel(int pos, int pixel_cnt, int pair_cnt); int main() { while (cin >> img_width && img_width > 0) { int num, pixel; int pair_cnt = 0; int pixel_cnt = 0; int start_pos = 1; while (cin >> pixel >> num && num != 0 && pixel != 0) { pixel_pair[pair_cnt][0] = pixel; pixel_pair[pair_cnt][1] = start_pos; pixel_cnt += num; start_pos += num; pair_cnt++; } int idx = 0; for (int k = 0; k < pair_cnt; k++) { int center = pixel_pair[k][1]; int row = (center - 1) / img_width; int col = (center - 1) % img_width; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int pos = i * img_width + j + 1; if (i < 0 || pos > pixel_cnt || j < 0 || j == img_width) continue; result[idx].pos = pos; result[idx].pixel = encode_pixel(pos, pixel_cnt, pair_cnt); idx++; } } sort(result, result + idx, cmp); /* for (int i = 0; i < idx; i++) cout << result[i].pixel << " " << result[i].pos << endl; */ Record prev = result[0]; if (idx > 1) { for (int i = 1; i < idx; i++) { if (prev.pixel != result[i].pixel) { cout << prev.pixel << " " << result[i].pos - prev.pos << endl; prev = result[i]; } } cout << result[idx - 1].pixel << " " << pixel_cnt - prev.pos + 1 << endl; } else cout << prev.pixel << " " << prev.pos << endl; cout << "0 0" << endl; /* for (int i = 0; i < pair_cnt; i++) cout << pixel_pair[i][0] << " " << pixel_pair[i][1] << endl; cout << pixel_cnt << endl; */ } cout << 0 << endl; } bool cmp(const Record& a, const Record& b) { return a.pos < b.pos; } int get_pixel_via_pos(int pos, int pair_cnt) { if (pair_cnt == 1) return pixel_pair[0][0]; int prev = pixel_pair[0][1]; for (int i = 1; i < pair_cnt; i++) { if (pos >= prev && pos < pixel_pair[i][1]) return pixel_pair[i - 1][0]; } return pixel_pair[pair_cnt - 1][0]; } int encode_pixel(int pos, int pixel_cnt, int pair_cnt) { int row = (pos - 1) / img_width; int col = (pos - 1) % img_width; int ret = 0; int tmp = 0; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { int curr = i * img_width + j + 1; if (i < 0 || curr > pixel_cnt || j == img_width || j < 0 || curr == pos) continue; tmp = abs(get_pixel_via_pos(pos, pair_cnt) - get_pixel_via_pos(curr, pair_cnt)); if (tmp > ret) ret = tmp; } return ret; } <|endoftext|>
<commit_before>// remove duplicates from sorted array // 10.29.2016 #include <iostream> #include <cassert> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { if (n == 0 || n == 1) return n; int index = 0; for (int i = 1; i < n; i++) { if (A[i] != A[index]) A[++index] = A[i]; } return index + 1; } }; void print(int A[], int n) { for (int i = 0; i < n; i++) cout << A[i] << " "; cout << endl; } void test(int A[], int n, int B[], int size) { static int counter = 0; cout << "test:" << ++counter << endl; print(A, n); Solution s; int len = s.removeDuplicates(A, n); print(A, len); assert(len == size); for (int i = 0; i < len; i++) assert(A[i] == B[i]); cout << "OK\n"; } int main() { { int A[3] = {1,1,2}; int B[2] = {1,2}; test(A, 3, B, 2); } { int A[] = {}; int B[] = {}; test(A, 0, B, 0); } { int A[] = {1}; int B[] = {1}; test(A, 1, B, 1); } { int A[] = {1,2,3}; int B[] = {1,2,3}; test(A, 3, B, 3); } return 0; } <commit_msg>add description<commit_after>// remove duplicates from sorted array // Given a sorted array, remove the duplicates in place such that each element appear only once // and return the new length. // Do not allocate extra space for another array, you must do this in place with constant memory. // For example, Given input array A = [1,1,2], // Your function should return length = 2, and A is now [1,2]. // 10.29.2016 #include <iostream> #include <cassert> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { if (n == 0 || n == 1) return n; int index = 0; for (int i = 1; i < n; i++) { if (A[i] != A[index]) A[++index] = A[i]; } return index + 1; } }; void print(int A[], int n) { for (int i = 0; i < n; i++) cout << A[i] << " "; cout << endl; } void test(int A[], int n, int B[], int size) { static int counter = 0; cout << "test:" << ++counter << endl; print(A, n); Solution s; int len = s.removeDuplicates(A, n); print(A, len); assert(len == size); for (int i = 0; i < len; i++) assert(A[i] == B[i]); cout << "OK\n"; } int main() { { int A[3] = {1,1,2}; int B[2] = {1,2}; test(A, 3, B, 2); } { int A[] = {}; int B[] = {}; test(A, 0, B, 0); } { int A[] = {1}; int B[] = {1}; test(A, 1, B, 1); } { int A[] = {1,2,3}; int B[] = {1,2,3}; test(A, 3, B, 3); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "CertificateUtils.h" #include <fcntl.h> #include <folly/portability/Fcntl.h> #include <folly/portability/SysStat.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <cstring> namespace facebook { namespace flipper { void free( EVP_PKEY* pKey, X509_REQ* x509_req, BIGNUM* bne, BIO* privateKey, BIO* csrBio); bool generateCertSigningRequest( const char* appId, const char* csrFile, const char* privateKeyFile) { int ret = 0; BIGNUM* bne = NULL; int nVersion = 1; int bits = 2048; // Using 65537 as exponent unsigned long e = RSA_F4; X509_NAME* x509_name = NULL; const char* subjectCountry = "US"; const char* subjectProvince = "CA"; const char* subjectCity = "Menlo Park"; const char* subjectOrganization = "Flipper"; const char* subjectCommon = appId; X509_REQ* x509_req = X509_REQ_new(); EVP_PKEY* pKey = EVP_PKEY_new(); RSA* rsa = RSA_new(); BIO* privateKey = NULL; BIO* csrBio = NULL; EVP_PKEY_assign_RSA(pKey, rsa); // Generate rsa key bne = BN_new(); BN_set_flags(bne, BN_FLG_CONSTTIME); ret = BN_set_word(bne, e); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = RSA_generate_key_ex(rsa, bits, bne, NULL); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } { // Write private key to a file int privateKeyFd = open(privateKeyFile, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR); if (privateKeyFd < 0) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } FILE* privateKeyFp = fdopen(privateKeyFd, "w"); if (privateKeyFp == NULL) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } privateKey = BIO_new_fp(privateKeyFp, BIO_CLOSE); ret = PEM_write_bio_RSAPrivateKey(privateKey, rsa, NULL, NULL, 0, NULL, NULL); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } } rsa = NULL; ret = BIO_flush(privateKey); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_REQ_set_version(x509_req, nVersion); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } x509_name = X509_REQ_get_subject_name(x509_req); ret = X509_NAME_add_entry_by_txt( x509_name, "C", MBSTRING_ASC, (const unsigned char*)subjectCountry, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "ST", MBSTRING_ASC, (const unsigned char*)subjectProvince, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "L", MBSTRING_ASC, (const unsigned char*)subjectCity, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "O", MBSTRING_ASC, (const unsigned char*)subjectOrganization, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "CN", MBSTRING_ASC, (const unsigned char*)subjectCommon, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_REQ_set_pubkey(x509_req, pKey); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_REQ_sign( x509_req, pKey, EVP_sha256()); // returns x509_req->signature->length if (ret <= 0) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } { // Write CSR to a file int csrFd = open(csrFile, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR); if (csrFd < 0) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } FILE* csrFp = fdopen(csrFd, "w"); if (csrFp == NULL) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } csrBio = BIO_new_fp(csrFp, BIO_CLOSE); ret = PEM_write_bio_X509_REQ(csrBio, x509_req); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } } ret = BIO_flush(csrBio); free(pKey, x509_req, bne, privateKey, csrBio); return (ret == 1); } void free( EVP_PKEY* pKey, X509_REQ* x509_req, BIGNUM* bne, BIO* privateKey, BIO* csrBio) { BN_free(bne); X509_REQ_free(x509_req); EVP_PKEY_free(pKey); BIO_free_all(privateKey); BIO_free_all(csrBio); } } // namespace flipper } // namespace facebook <commit_msg>Handle CN greater than 64 character length<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "CertificateUtils.h" #include <fcntl.h> #include <folly/portability/Fcntl.h> #include <folly/portability/SysStat.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <cstring> namespace facebook { namespace flipper { void free( EVP_PKEY* pKey, X509_REQ* x509_req, BIGNUM* bne, BIO* privateKey, BIO* csrBio); bool generateCertSigningRequest( const char* appId, const char* csrFile, const char* privateKeyFile) { int ret = 0; BIGNUM* bne = NULL; int nVersion = 1; int bits = 2048; // Using 65537 as exponent unsigned long e = RSA_F4; X509_NAME* x509_name = NULL; const char* subjectCountry = "US"; const char* subjectProvince = "CA"; const char* subjectCity = "Menlo Park"; const char* subjectOrganization = "Flipper"; const char* subjectCommon = strlen(appId) >= 64 ? "com.flipper" : appId; X509_REQ* x509_req = X509_REQ_new(); EVP_PKEY* pKey = EVP_PKEY_new(); RSA* rsa = RSA_new(); BIO* privateKey = NULL; BIO* csrBio = NULL; EVP_PKEY_assign_RSA(pKey, rsa); // Generate rsa key bne = BN_new(); BN_set_flags(bne, BN_FLG_CONSTTIME); ret = BN_set_word(bne, e); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = RSA_generate_key_ex(rsa, bits, bne, NULL); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } { // Write private key to a file int privateKeyFd = open(privateKeyFile, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR); if (privateKeyFd < 0) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } FILE* privateKeyFp = fdopen(privateKeyFd, "w"); if (privateKeyFp == NULL) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } privateKey = BIO_new_fp(privateKeyFp, BIO_CLOSE); ret = PEM_write_bio_RSAPrivateKey(privateKey, rsa, NULL, NULL, 0, NULL, NULL); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } } rsa = NULL; ret = BIO_flush(privateKey); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_REQ_set_version(x509_req, nVersion); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } x509_name = X509_REQ_get_subject_name(x509_req); ret = X509_NAME_add_entry_by_txt( x509_name, "C", MBSTRING_ASC, (const unsigned char*)subjectCountry, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "ST", MBSTRING_ASC, (const unsigned char*)subjectProvince, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "L", MBSTRING_ASC, (const unsigned char*)subjectCity, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "O", MBSTRING_ASC, (const unsigned char*)subjectOrganization, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_NAME_add_entry_by_txt( x509_name, "CN", MBSTRING_ASC, (const unsigned char*)subjectCommon, -1, -1, 0); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_REQ_set_pubkey(x509_req, pKey); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } ret = X509_REQ_sign( x509_req, pKey, EVP_sha256()); // returns x509_req->signature->length if (ret <= 0) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } { // Write CSR to a file int csrFd = open(csrFile, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR); if (csrFd < 0) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } FILE* csrFp = fdopen(csrFd, "w"); if (csrFp == NULL) { free(pKey, x509_req, bne, privateKey, csrBio); return -1; } csrBio = BIO_new_fp(csrFp, BIO_CLOSE); ret = PEM_write_bio_X509_REQ(csrBio, x509_req); if (ret != 1) { free(pKey, x509_req, bne, privateKey, csrBio); return ret; } } ret = BIO_flush(csrBio); free(pKey, x509_req, bne, privateKey, csrBio); return (ret == 1); } void free( EVP_PKEY* pKey, X509_REQ* x509_req, BIGNUM* bne, BIO* privateKey, BIO* csrBio) { BN_free(bne); X509_REQ_free(x509_req); EVP_PKEY_free(pKey); BIO_free_all(privateKey); BIO_free_all(csrBio); } } // namespace flipper } // namespace facebook <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief dispatcher thread for JavaScript actions /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "JavascriptDispatcherThread.h" #include "Actions/actions.h" #include "Logger/Logger.h" #include "V8/v8-conv.h" #include "V8/v8-shell.h" #include "V8/v8-utils.h" #include "V8Server/v8-actions.h" #include "V8Server/v8-query.h" #include "V8Server/v8-vocbase.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- class ActionDispatcherThread // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a new dispatcher thread //////////////////////////////////////////////////////////////////////////////// JavascriptDispatcherThread::JavascriptDispatcherThread (rest::DispatcherQueue* queue, TRI_vocbase_t* vocbase, uint64_t gcInterval, string const& actionQueue, set<string> const& allowedContexts, string startupModules, JSLoader* startupLoader, JSLoader* actionLoader) : ActionDispatcherThread(queue), _vocbase(vocbase), _gcInterval(gcInterval), _gc(0), _isolate(0), _context(), _actionQueue(actionQueue), _allowedContexts(allowedContexts), _startupModules(startupModules), _startupLoader(startupLoader), _actionLoader(actionLoader) { } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ActionDispatcherThread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void* JavascriptDispatcherThread::context () { return (void*) _isolate; // the isolate is the execution context } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- DispatcherThread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::reportStatus () { } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::tick (bool idle) { _gc += (idle ? 10 : 1); if (_gc > _gcInterval) { LOGGER_TRACE << "collecting garbage..."; while (! v8::V8::IdleNotification()) { } _gc = 0; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- Thread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::run () { initialise(); _isolate->Enter(); _context->Enter(); DispatcherThread::run(); // free memory for this thread TRI_v8_global_t* v8g = (TRI_v8_global_t*) _isolate->GetData(); if (v8g) { delete v8g; } _context->Exit(); _context.Dispose(); while (!v8::V8::IdleNotification()) { } _isolate->Exit(); _isolate->Dispose(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief initialises the isolate and context //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::initialise () { bool ok; char const* files[] = { "common/bootstrap/modules.js", "common/bootstrap/print.js", "common/bootstrap/errors.js", "server/ahuacatl.js", "server/server.js" }; size_t i; // enter a new isolate _isolate = v8::Isolate::New(); _isolate->Enter(); // create the context _context = v8::Context::New(0); if (_context.IsEmpty()) { LOGGER_FATAL << "cannot initialize V8 engine"; _isolate->Exit(); TRI_FlushLogging(); exit(EXIT_FAILURE); } _context->Enter(); TRI_InitV8VocBridge(_context, _vocbase); TRI_InitV8Queries(_context); TRI_InitV8Actions(_context, _actionQueue, _allowedContexts); TRI_InitV8Conversions(_context); TRI_InitV8Utils(_context, _startupModules); TRI_InitV8Shell(_context); // load all init files for (i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { ok = _startupLoader->loadScript(_context, files[i]); if (! ok) { LOGGER_FATAL << "cannot load JavaScript utilities from file '" << files[i] << "'"; _context->Exit(); _isolate->Exit(); TRI_FlushLogging(); exit(EXIT_FAILURE); } } // load all actions if (_actionLoader == 0) { LOGGER_WARNING << "no action loader has been defined"; } else { ok = _actionLoader->executeAllScripts(_context); if (! ok) { LOGGER_FATAL << "cannot load JavaScript actions from directory '" << _actionLoader->getDirectory() << "'"; } } // and return from the context _context->Exit(); _isolate->Exit(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>fixed potential segfault on shutdown<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief dispatcher thread for JavaScript actions /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "JavascriptDispatcherThread.h" #include "Actions/actions.h" #include "Logger/Logger.h" #include "V8/v8-conv.h" #include "V8/v8-shell.h" #include "V8/v8-utils.h" #include "V8Server/v8-actions.h" #include "V8Server/v8-query.h" #include "V8Server/v8-vocbase.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- class ActionDispatcherThread // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a new dispatcher thread //////////////////////////////////////////////////////////////////////////////// JavascriptDispatcherThread::JavascriptDispatcherThread (rest::DispatcherQueue* queue, TRI_vocbase_t* vocbase, uint64_t gcInterval, string const& actionQueue, set<string> const& allowedContexts, string startupModules, JSLoader* startupLoader, JSLoader* actionLoader) : ActionDispatcherThread(queue), _vocbase(vocbase), _gcInterval(gcInterval), _gc(0), _isolate(0), _context(), _actionQueue(actionQueue), _allowedContexts(allowedContexts), _startupModules(startupModules), _startupLoader(startupLoader), _actionLoader(actionLoader) { } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ActionDispatcherThread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void* JavascriptDispatcherThread::context () { return (void*) _isolate; // the isolate is the execution context } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- DispatcherThread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::reportStatus () { } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::tick (bool idle) { _gc += (idle ? 10 : 1); if (_gc > _gcInterval) { LOGGER_TRACE << "collecting garbage..."; while (! v8::V8::IdleNotification()) { } _gc = 0; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- Thread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::run () { initialise(); _isolate->Enter(); _context->Enter(); DispatcherThread::run(); _context->Exit(); _context.Dispose(); while (!v8::V8::IdleNotification()) { } _isolate->Exit(); _isolate->Dispose(); // free memory for this thread TRI_v8_global_t* v8g = (TRI_v8_global_t*) _isolate->GetData(); if (v8g) { delete v8g; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief initialises the isolate and context //////////////////////////////////////////////////////////////////////////////// void JavascriptDispatcherThread::initialise () { bool ok; char const* files[] = { "common/bootstrap/modules.js", "common/bootstrap/print.js", "common/bootstrap/errors.js", "server/ahuacatl.js", "server/server.js" }; size_t i; // enter a new isolate _isolate = v8::Isolate::New(); _isolate->Enter(); // create the context _context = v8::Context::New(0); if (_context.IsEmpty()) { LOGGER_FATAL << "cannot initialize V8 engine"; _isolate->Exit(); TRI_FlushLogging(); exit(EXIT_FAILURE); } _context->Enter(); TRI_InitV8VocBridge(_context, _vocbase); TRI_InitV8Queries(_context); TRI_InitV8Actions(_context, _actionQueue, _allowedContexts); TRI_InitV8Conversions(_context); TRI_InitV8Utils(_context, _startupModules); TRI_InitV8Shell(_context); // load all init files for (i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { ok = _startupLoader->loadScript(_context, files[i]); if (! ok) { LOGGER_FATAL << "cannot load JavaScript utilities from file '" << files[i] << "'"; _context->Exit(); _isolate->Exit(); TRI_FlushLogging(); exit(EXIT_FAILURE); } } // load all actions if (_actionLoader == 0) { LOGGER_WARNING << "no action loader has been defined"; } else { ok = _actionLoader->executeAllScripts(_context); if (! ok) { LOGGER_FATAL << "cannot load JavaScript actions from directory '" << _actionLoader->getDirectory() << "'"; } } // and return from the context _context->Exit(); _isolate->Exit(); } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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 "os/os_specific.h" #include <stdarg.h> #include "serialise/string_utils.h" using std::string; int utf8printf(char *buf, size_t bufsize, const char *fmt, va_list args); namespace StringFormat { int snprintf(char *str, size_t bufSize, const char *fmt, ...) { va_list args; va_start(args, fmt); int ret = StringFormat::vsnprintf(str, bufSize, fmt, args); va_end(args); return ret; } int vsnprintf(char *str, size_t bufSize, const char *format, va_list args) { return ::utf8printf(str, bufSize, format, args); } string Fmt(const char *format, ...) { va_list args; va_start(args, format); va_list args2; va_copy(args2, args); int size = StringFormat::vsnprintf(NULL, 0, format, args2); char *buf = new char[size + 1]; StringFormat::vsnprintf(buf, size + 1, format, args); buf[size] = 0; va_end(args); va_end(args2); string ret = buf; delete[] buf; return ret; } int Wide2UTF8(wchar_t chr, char mbchr[4]) { // U+00000 -> U+00007F 1 byte 0xxxxxxx // U+00080 -> U+0007FF 2 bytes 110xxxxx 10xxxxxx // U+00800 -> U+00FFFF 3 bytes 1110xxxx 10xxxxxx 10xxxxxx // U+10000 -> U+1FFFFF 4 bytes 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // upcast to uint32_t, so we do the same processing on windows where // sizeof(wchar_t) == 2 uint32_t wc = (uint32_t)chr; if(wc > 0x10FFFF) wc = 0xFFFD; // replacement character if(wc <= 0x7f) { mbchr[0] = (char)wc; return 1; } else if(wc <= 0x7ff) { mbchr[1] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[0] = 0xC0 | (char)(wc & 0x1f); return 2; } else if(wc <= 0xffff) { mbchr[2] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[1] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[0] = 0xE0 | (char)(wc & 0x0f); wc >>= 4; return 3; } else { // invalid codepoints above 0x10FFFF were replaced above mbchr[3] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[2] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[1] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[0] = 0xF0 | (char)(wc & 0x07); wc >>= 3; return 4; } } }; // namespace StringFormat string Callstack::AddressDetails::formattedString(const char *commonPath) { char fmt[512] = {0}; const char *f = filename.c_str(); if(commonPath) { string common = strlower(string(commonPath)); string fn = strlower(filename.substr(0, common.length())); if(common == fn) { f += common.length(); } } if(line > 0) StringFormat::snprintf(fmt, 511, "%s line %d", function.c_str(), line); else StringFormat::snprintf(fmt, 511, "%s", function.c_str()); return fmt; } string OSUtility::MakeMachineIdentString(uint64_t ident) { string ret = ""; if(ident & MachineIdent_Windows) ret += "Windows "; else if(ident & MachineIdent_Linux) ret += "Linux "; else if(ident & MachineIdent_macOS) ret += "macOS "; else if(ident & MachineIdent_Android) ret += "Android "; else if(ident & MachineIdent_iOS) ret += "iOS "; if(ident & MachineIdent_Arch_x86) ret += "x86 "; else if(ident & MachineIdent_Arch_ARM) ret += "ARM "; if(ident & MachineIdent_32bit) ret += "32-bit "; else if(ident & MachineIdent_64bit) ret += "64-bit "; switch(ident & MachineIdent_GPU_Mask) { case MachineIdent_GPU_ARM: ret += "ARM GPU "; break; case MachineIdent_GPU_AMD: ret += "AMD GPU "; break; case MachineIdent_GPU_IMG: ret += "Imagination GPU "; break; case MachineIdent_GPU_Intel: ret += "Intel GPU "; break; case MachineIdent_GPU_NV: ret += "nVidia GPU "; break; case MachineIdent_GPU_QUALCOMM: ret += "QUALCOMM GPU "; break; case MachineIdent_GPU_Samsung: ret += "Samsung GPU "; break; case MachineIdent_GPU_Verisilicon: ret += "Verisilicon GPU "; break; default: break; } return ret; } #if ENABLED(ENABLE_UNIT_TESTS) #include "3rdparty/catch/catch.hpp" TEST_CASE("Test Process functions", "[osspecific]") { SECTION("Environment Variables") { const char *var = Process::GetEnvVariable("TMP"); if(!var) var = Process::GetEnvVariable("TEMP"); if(!var) var = Process::GetEnvVariable("HOME"); CHECK(var); CHECK(strlen(var) > 1); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK_FALSE(var); EnvironmentModification mod; mod.name = "__renderdoc__unit_test_var"; mod.value = "test_value"; mod.sep = EnvSep::SemiColon; mod.mod = EnvMod::Append; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("test_value")); Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("test_value;test_value")); mod.sep = EnvSep::Colon; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("test_value;test_value:test_value")); mod.value = "prepend"; mod.sep = EnvSep::SemiColon; mod.mod = EnvMod::Prepend; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("prepend;test_value;test_value:test_value")); mod.value = "reset"; mod.sep = EnvSep::SemiColon; mod.mod = EnvMod::Set; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("reset")); }; }; #endif // ENABLED(ENABLE_UNIT_TESTS)<commit_msg>Add tests of timing functions<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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 "os/os_specific.h" #include <stdarg.h> #include "serialise/string_utils.h" using std::string; int utf8printf(char *buf, size_t bufsize, const char *fmt, va_list args); namespace StringFormat { int snprintf(char *str, size_t bufSize, const char *fmt, ...) { va_list args; va_start(args, fmt); int ret = StringFormat::vsnprintf(str, bufSize, fmt, args); va_end(args); return ret; } int vsnprintf(char *str, size_t bufSize, const char *format, va_list args) { return ::utf8printf(str, bufSize, format, args); } string Fmt(const char *format, ...) { va_list args; va_start(args, format); va_list args2; va_copy(args2, args); int size = StringFormat::vsnprintf(NULL, 0, format, args2); char *buf = new char[size + 1]; StringFormat::vsnprintf(buf, size + 1, format, args); buf[size] = 0; va_end(args); va_end(args2); string ret = buf; delete[] buf; return ret; } int Wide2UTF8(wchar_t chr, char mbchr[4]) { // U+00000 -> U+00007F 1 byte 0xxxxxxx // U+00080 -> U+0007FF 2 bytes 110xxxxx 10xxxxxx // U+00800 -> U+00FFFF 3 bytes 1110xxxx 10xxxxxx 10xxxxxx // U+10000 -> U+1FFFFF 4 bytes 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // upcast to uint32_t, so we do the same processing on windows where // sizeof(wchar_t) == 2 uint32_t wc = (uint32_t)chr; if(wc > 0x10FFFF) wc = 0xFFFD; // replacement character if(wc <= 0x7f) { mbchr[0] = (char)wc; return 1; } else if(wc <= 0x7ff) { mbchr[1] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[0] = 0xC0 | (char)(wc & 0x1f); return 2; } else if(wc <= 0xffff) { mbchr[2] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[1] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[0] = 0xE0 | (char)(wc & 0x0f); wc >>= 4; return 3; } else { // invalid codepoints above 0x10FFFF were replaced above mbchr[3] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[2] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[1] = 0x80 | (char)(wc & 0x3f); wc >>= 6; mbchr[0] = 0xF0 | (char)(wc & 0x07); wc >>= 3; return 4; } } }; // namespace StringFormat string Callstack::AddressDetails::formattedString(const char *commonPath) { char fmt[512] = {0}; const char *f = filename.c_str(); if(commonPath) { string common = strlower(string(commonPath)); string fn = strlower(filename.substr(0, common.length())); if(common == fn) { f += common.length(); } } if(line > 0) StringFormat::snprintf(fmt, 511, "%s line %d", function.c_str(), line); else StringFormat::snprintf(fmt, 511, "%s", function.c_str()); return fmt; } string OSUtility::MakeMachineIdentString(uint64_t ident) { string ret = ""; if(ident & MachineIdent_Windows) ret += "Windows "; else if(ident & MachineIdent_Linux) ret += "Linux "; else if(ident & MachineIdent_macOS) ret += "macOS "; else if(ident & MachineIdent_Android) ret += "Android "; else if(ident & MachineIdent_iOS) ret += "iOS "; if(ident & MachineIdent_Arch_x86) ret += "x86 "; else if(ident & MachineIdent_Arch_ARM) ret += "ARM "; if(ident & MachineIdent_32bit) ret += "32-bit "; else if(ident & MachineIdent_64bit) ret += "64-bit "; switch(ident & MachineIdent_GPU_Mask) { case MachineIdent_GPU_ARM: ret += "ARM GPU "; break; case MachineIdent_GPU_AMD: ret += "AMD GPU "; break; case MachineIdent_GPU_IMG: ret += "Imagination GPU "; break; case MachineIdent_GPU_Intel: ret += "Intel GPU "; break; case MachineIdent_GPU_NV: ret += "nVidia GPU "; break; case MachineIdent_GPU_QUALCOMM: ret += "QUALCOMM GPU "; break; case MachineIdent_GPU_Samsung: ret += "Samsung GPU "; break; case MachineIdent_GPU_Verisilicon: ret += "Verisilicon GPU "; break; default: break; } return ret; } #if ENABLED(ENABLE_UNIT_TESTS) #include "3rdparty/catch/catch.hpp" TEST_CASE("Test Process functions", "[osspecific]") { SECTION("Environment Variables") { const char *var = Process::GetEnvVariable("TMP"); if(!var) var = Process::GetEnvVariable("TEMP"); if(!var) var = Process::GetEnvVariable("HOME"); CHECK(var); CHECK(strlen(var) > 1); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK_FALSE(var); EnvironmentModification mod; mod.name = "__renderdoc__unit_test_var"; mod.value = "test_value"; mod.sep = EnvSep::SemiColon; mod.mod = EnvMod::Append; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("test_value")); Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("test_value;test_value")); mod.sep = EnvSep::Colon; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("test_value;test_value:test_value")); mod.value = "prepend"; mod.sep = EnvSep::SemiColon; mod.mod = EnvMod::Prepend; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("prepend;test_value;test_value:test_value")); mod.value = "reset"; mod.sep = EnvSep::SemiColon; mod.mod = EnvMod::Set; Process::RegisterEnvironmentModification(mod); Process::ApplyEnvironmentModification(); var = Process::GetEnvVariable("__renderdoc__unit_test_var"); CHECK(var); CHECK(var == std::string("reset")); }; SECTION("Timing") { double freq = Timing::GetTickFrequency(); REQUIRE(freq > 0.0); { uint64_t startTick = Timing::GetTick(); CHECK(startTick > 0); uint64_t firstTick = Timing::GetTick(); Threading::Sleep(500); uint64_t lastTick = Timing::GetTick(); double milliseconds1 = double(firstTick - startTick) / freq; double milliseconds2 = double(lastTick - firstTick) / freq; CHECK(milliseconds1 > 0.0); CHECK(milliseconds1 < 1.0); CHECK(milliseconds2 > 490.0); CHECK(milliseconds2 < 510.0); } // timestamp as of the creation of this test CHECK(Timing::GetUnixTimestamp() > 1504519614); }; }; #endif // ENABLED(ENABLE_UNIT_TESTS)<|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/ime/xkeyboard.h" #include <cstdlib> #include <cstring> #include <queue> #include <set> #include <utility> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/process/launch.h" #include "base/process/process_handle.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/sys_info.h" #include "base/threading/thread_checker.h" // These includes conflict with base/tracked_objects.h so must come last. #include <X11/XKBlib.h> #include <X11/Xlib.h> #include <glib.h> namespace chromeos { namespace input_method { namespace { Display* GetXDisplay() { return base::MessagePumpForUI::GetDefaultXDisplay(); } // The command we use to set the current XKB layout and modifier key mapping. // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105) const char kSetxkbmapCommand[] = "/usr/bin/setxkbmap"; // A string for obtaining a mask value for Num Lock. const char kNumLockVirtualModifierString[] = "NumLock"; // Returns false if |layout_name| contains a bad character. bool CheckLayoutName(const std::string& layout_name) { static const char kValidLayoutNameCharacters[] = "abcdefghijklmnopqrstuvwxyz0123456789()-_"; if (layout_name.empty()) { DVLOG(1) << "Invalid layout_name: " << layout_name; return false; } if (layout_name.find_first_not_of(kValidLayoutNameCharacters) != std::string::npos) { DVLOG(1) << "Invalid layout_name: " << layout_name; return false; } return true; } class XKeyboardImpl : public XKeyboard { public: XKeyboardImpl(); virtual ~XKeyboardImpl() {} // Overridden from XKeyboard: virtual bool SetCurrentKeyboardLayoutByName( const std::string& layout_name) OVERRIDE; virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE; virtual void ReapplyCurrentModifierLockStatus() OVERRIDE; virtual void SetLockedModifiers( ModifierLockStatus new_caps_lock_status, ModifierLockStatus new_num_lock_status) OVERRIDE; virtual void SetNumLockEnabled(bool enable_num_lock) OVERRIDE; virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE; virtual bool NumLockIsEnabled() OVERRIDE; virtual bool CapsLockIsEnabled() OVERRIDE; virtual unsigned int GetNumLockMask() OVERRIDE; virtual void GetLockedModifiers(bool* out_caps_lock_enabled, bool* out_num_lock_enabled) OVERRIDE; private: // This function is used by SetLayout() and RemapModifierKeys(). Calls // setxkbmap command if needed, and updates the last_full_layout_name_ cache. bool SetLayoutInternal(const std::string& layout_name, bool force); // Executes 'setxkbmap -layout ...' command asynchronously using a layout name // in the |execute_queue_|. Do nothing if the queue is empty. // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105) void MaybeExecuteSetLayoutCommand(); // Called when execve'd setxkbmap process exits. static void OnSetLayoutFinish(pid_t pid, int status, XKeyboardImpl* self); const bool is_running_on_chrome_os_; unsigned int num_lock_mask_; // The current Num Lock and Caps Lock status. If true, enabled. bool current_num_lock_status_; bool current_caps_lock_status_; // The XKB layout name which we set last time like "us" and "us(dvorak)". std::string current_layout_name_; // A queue for executing setxkbmap one by one. std::queue<std::string> execute_queue_; base::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl); }; XKeyboardImpl::XKeyboardImpl() : is_running_on_chrome_os_(base::SysInfo::IsRunningOnChromeOS()) { num_lock_mask_ = GetNumLockMask(); // web_input_event_aurax11.cc seems to assume that Mod2Mask is always assigned // to Num Lock. // TODO(yusukes): Check the assumption is really okay. If not, modify the Aura // code, and then remove the CHECK below. CHECK(!is_running_on_chrome_os_ || (num_lock_mask_ == Mod2Mask)); GetLockedModifiers(&current_caps_lock_status_, &current_num_lock_status_); } bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name, bool force) { if (!is_running_on_chrome_os_) { // We should not try to change a layout on Linux or inside ui_tests. Just // return true. return true; } if (!CheckLayoutName(layout_name)) return false; if (!force && (current_layout_name_ == layout_name)) { DVLOG(1) << "The requested layout is already set: " << layout_name; return true; } DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name; const bool start_execution = execute_queue_.empty(); // If no setxkbmap command is in flight (i.e. start_execution is true), // start the first one by explicitly calling MaybeExecuteSetLayoutCommand(). // If one or more setxkbmap commands are already in flight, just push the // layout name to the queue. setxkbmap command for the layout will be called // via OnSetLayoutFinish() callback later. execute_queue_.push(layout_name); if (start_execution) MaybeExecuteSetLayoutCommand(); return true; } // Executes 'setxkbmap -layout ...' command asynchronously using a layout name // in the |execute_queue_|. Do nothing if the queue is empty. // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105) void XKeyboardImpl::MaybeExecuteSetLayoutCommand() { if (execute_queue_.empty()) return; const std::string layout_to_set = execute_queue_.front(); std::vector<std::string> argv; base::ProcessHandle handle = base::kNullProcessHandle; argv.push_back(kSetxkbmapCommand); argv.push_back("-layout"); argv.push_back(layout_to_set); argv.push_back("-synch"); if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) { DVLOG(1) << "Failed to execute setxkbmap: " << layout_to_set; execute_queue_ = std::queue<std::string>(); // clear the queue. return; } // g_child_watch_add is necessary to prevent the process from becoming a // zombie. const base::ProcessId pid = base::GetProcId(handle); g_child_watch_add(pid, reinterpret_cast<GChildWatchFunc>(OnSetLayoutFinish), this); DVLOG(1) << "ExecuteSetLayoutCommand: " << layout_to_set << ": pid=" << pid; } bool XKeyboardImpl::NumLockIsEnabled() { bool num_lock_enabled = false; GetLockedModifiers(NULL /* Caps Lock */, &num_lock_enabled); return num_lock_enabled; } bool XKeyboardImpl::CapsLockIsEnabled() { bool caps_lock_enabled = false; GetLockedModifiers(&caps_lock_enabled, NULL /* Num Lock */); return caps_lock_enabled; } unsigned int XKeyboardImpl::GetNumLockMask() { DCHECK(thread_checker_.CalledOnValidThread()); static const unsigned int kBadMask = 0; unsigned int real_mask = kBadMask; XkbDescPtr xkb_desc = XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd); if (!xkb_desc) return kBadMask; if (xkb_desc->dpy && xkb_desc->names && xkb_desc->names->vmods) { const std::string string_to_find(kNumLockVirtualModifierString); for (size_t i = 0; i < XkbNumVirtualMods; ++i) { const unsigned int virtual_mod_mask = 1U << i; char* virtual_mod_str_raw_ptr = XGetAtomName(xkb_desc->dpy, xkb_desc->names->vmods[i]); if (!virtual_mod_str_raw_ptr) continue; const std::string virtual_mod_str = virtual_mod_str_raw_ptr; XFree(virtual_mod_str_raw_ptr); if (string_to_find == virtual_mod_str) { if (!XkbVirtualModsToReal(xkb_desc, virtual_mod_mask, &real_mask)) { DVLOG(1) << "XkbVirtualModsToReal failed"; real_mask = kBadMask; // reset the return value, just in case. } break; } } } XkbFreeKeyboard(xkb_desc, 0, True /* free all components */); return real_mask; } void XKeyboardImpl::GetLockedModifiers(bool* out_caps_lock_enabled, bool* out_num_lock_enabled) { DCHECK(thread_checker_.CalledOnValidThread()); if (out_num_lock_enabled && !num_lock_mask_) { DVLOG(1) << "Cannot get locked modifiers. Num Lock mask unknown."; if (out_caps_lock_enabled) *out_caps_lock_enabled = false; if (out_num_lock_enabled) *out_num_lock_enabled = false; return; } XkbStateRec status; XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status); if (out_caps_lock_enabled) *out_caps_lock_enabled = status.locked_mods & LockMask; if (out_num_lock_enabled) *out_num_lock_enabled = status.locked_mods & num_lock_mask_; } void XKeyboardImpl::SetLockedModifiers(ModifierLockStatus new_caps_lock_status, ModifierLockStatus new_num_lock_status) { DCHECK(thread_checker_.CalledOnValidThread()); if (!num_lock_mask_) { DVLOG(1) << "Cannot set locked modifiers. Num Lock mask unknown."; return; } unsigned int affect_mask = 0; unsigned int value_mask = 0; if (new_caps_lock_status != kDontChange) { affect_mask |= LockMask; value_mask |= ((new_caps_lock_status == kEnableLock) ? LockMask : 0); current_caps_lock_status_ = (new_caps_lock_status == kEnableLock); } if (new_num_lock_status != kDontChange) { affect_mask |= num_lock_mask_; value_mask |= ((new_num_lock_status == kEnableLock) ? num_lock_mask_ : 0); current_num_lock_status_ = (new_num_lock_status == kEnableLock); } if (affect_mask) XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask); } void XKeyboardImpl::SetNumLockEnabled(bool enable_num_lock) { SetLockedModifiers( kDontChange, enable_num_lock ? kEnableLock : kDisableLock); } void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) { SetLockedModifiers( enable_caps_lock ? kEnableLock : kDisableLock, kDontChange); } bool XKeyboardImpl::SetCurrentKeyboardLayoutByName( const std::string& layout_name) { if (SetLayoutInternal(layout_name, false)) { current_layout_name_ = layout_name; return true; } return false; } bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() { if (current_layout_name_.empty()) { DVLOG(1) << "Can't reapply XKB layout: layout unknown"; return false; } return SetLayoutInternal(current_layout_name_, true /* force */); } void XKeyboardImpl::ReapplyCurrentModifierLockStatus() { SetLockedModifiers(current_caps_lock_status_ ? kEnableLock : kDisableLock, current_num_lock_status_ ? kEnableLock : kDisableLock); } // static void XKeyboardImpl::OnSetLayoutFinish(pid_t pid, int status, XKeyboardImpl* self) { DVLOG(1) << "OnSetLayoutFinish: pid=" << pid; if (self->execute_queue_.empty()) { DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. " << "base::LaunchProcess failed? pid=" << pid; return; } self->execute_queue_.pop(); self->MaybeExecuteSetLayoutCommand(); } } // namespace // static bool XKeyboard::SetAutoRepeatEnabled(bool enabled) { if (enabled) XAutoRepeatOn(GetXDisplay()); else XAutoRepeatOff(GetXDisplay()); DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off"); return true; } // static bool XKeyboard::SetAutoRepeatRate(const AutoRepeatRate& rate) { DVLOG(1) << "Set auto-repeat rate to: " << rate.initial_delay_in_ms << " ms delay, " << rate.repeat_interval_in_ms << " ms interval"; if (XkbSetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd, rate.initial_delay_in_ms, rate.repeat_interval_in_ms) != True) { DVLOG(1) << "Failed to set auto-repeat rate"; return false; } return true; } // static bool XKeyboard::GetAutoRepeatEnabledForTesting() { XKeyboardState state = {}; XGetKeyboardControl(GetXDisplay(), &state); return state.global_auto_repeat != AutoRepeatModeOff; } // static bool XKeyboard::GetAutoRepeatRateForTesting(AutoRepeatRate* out_rate) { return XkbGetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd, &(out_rate->initial_delay_in_ms), &(out_rate->repeat_interval_in_ms)) == True; } // static bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) { return CheckLayoutName(layout_name); } // static XKeyboard* XKeyboard::Create() { return new XKeyboardImpl(); } } // namespace input_method } // namespace chromeos <commit_msg>Check if X is initialied instead of checking the return value of X utils.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/ime/xkeyboard.h" #include <cstdlib> #include <cstring> #include <queue> #include <set> #include <utility> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/process/launch.h" #include "base/process/process_handle.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/sys_info.h" #include "base/threading/thread_checker.h" // These includes conflict with base/tracked_objects.h so must come last. #include <X11/XKBlib.h> #include <X11/Xlib.h> #include <glib.h> namespace chromeos { namespace input_method { namespace { Display* GetXDisplay() { return base::MessagePumpForUI::GetDefaultXDisplay(); } // The command we use to set the current XKB layout and modifier key mapping. // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105) const char kSetxkbmapCommand[] = "/usr/bin/setxkbmap"; // A string for obtaining a mask value for Num Lock. const char kNumLockVirtualModifierString[] = "NumLock"; // Returns false if |layout_name| contains a bad character. bool CheckLayoutName(const std::string& layout_name) { static const char kValidLayoutNameCharacters[] = "abcdefghijklmnopqrstuvwxyz0123456789()-_"; if (layout_name.empty()) { DVLOG(1) << "Invalid layout_name: " << layout_name; return false; } if (layout_name.find_first_not_of(kValidLayoutNameCharacters) != std::string::npos) { DVLOG(1) << "Invalid layout_name: " << layout_name; return false; } return true; } class XKeyboardImpl : public XKeyboard { public: XKeyboardImpl(); virtual ~XKeyboardImpl() {} // Overridden from XKeyboard: virtual bool SetCurrentKeyboardLayoutByName( const std::string& layout_name) OVERRIDE; virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE; virtual void ReapplyCurrentModifierLockStatus() OVERRIDE; virtual void SetLockedModifiers( ModifierLockStatus new_caps_lock_status, ModifierLockStatus new_num_lock_status) OVERRIDE; virtual void SetNumLockEnabled(bool enable_num_lock) OVERRIDE; virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE; virtual bool NumLockIsEnabled() OVERRIDE; virtual bool CapsLockIsEnabled() OVERRIDE; virtual unsigned int GetNumLockMask() OVERRIDE; virtual void GetLockedModifiers(bool* out_caps_lock_enabled, bool* out_num_lock_enabled) OVERRIDE; private: // This function is used by SetLayout() and RemapModifierKeys(). Calls // setxkbmap command if needed, and updates the last_full_layout_name_ cache. bool SetLayoutInternal(const std::string& layout_name, bool force); // Executes 'setxkbmap -layout ...' command asynchronously using a layout name // in the |execute_queue_|. Do nothing if the queue is empty. // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105) void MaybeExecuteSetLayoutCommand(); // Called when execve'd setxkbmap process exits. static void OnSetLayoutFinish(pid_t pid, int status, XKeyboardImpl* self); const bool is_running_on_chrome_os_; unsigned int num_lock_mask_; // The current Num Lock and Caps Lock status. If true, enabled. bool current_num_lock_status_; bool current_caps_lock_status_; // The XKB layout name which we set last time like "us" and "us(dvorak)". std::string current_layout_name_; // A queue for executing setxkbmap one by one. std::queue<std::string> execute_queue_; base::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN(XKeyboardImpl); }; XKeyboardImpl::XKeyboardImpl() : is_running_on_chrome_os_(base::SysInfo::IsRunningOnChromeOS()) { // X must be already initialized. CHECK(GetXDisplay()); num_lock_mask_ = GetNumLockMask(); if (is_running_on_chrome_os_) { // Some code seems to assume that Mod2Mask is always assigned to // Num Lock. // // TODO(yusukes): Check the assumption is really okay. If not, // modify the Aura code, and then remove the CHECK below. LOG_IF(ERROR, num_lock_mask_ != Mod2Mask) << "NumLock is not assigned to Mod2Mask. : " << num_lock_mask_; } GetLockedModifiers(&current_caps_lock_status_, &current_num_lock_status_); } bool XKeyboardImpl::SetLayoutInternal(const std::string& layout_name, bool force) { if (!is_running_on_chrome_os_) { // We should not try to change a layout on Linux or inside ui_tests. Just // return true. return true; } if (!CheckLayoutName(layout_name)) return false; if (!force && (current_layout_name_ == layout_name)) { DVLOG(1) << "The requested layout is already set: " << layout_name; return true; } DVLOG(1) << (force ? "Reapply" : "Set") << " layout: " << layout_name; const bool start_execution = execute_queue_.empty(); // If no setxkbmap command is in flight (i.e. start_execution is true), // start the first one by explicitly calling MaybeExecuteSetLayoutCommand(). // If one or more setxkbmap commands are already in flight, just push the // layout name to the queue. setxkbmap command for the layout will be called // via OnSetLayoutFinish() callback later. execute_queue_.push(layout_name); if (start_execution) MaybeExecuteSetLayoutCommand(); return true; } // Executes 'setxkbmap -layout ...' command asynchronously using a layout name // in the |execute_queue_|. Do nothing if the queue is empty. // TODO(yusukes): Use libxkbfile.so instead of the command (crosbug.com/13105) void XKeyboardImpl::MaybeExecuteSetLayoutCommand() { if (execute_queue_.empty()) return; const std::string layout_to_set = execute_queue_.front(); std::vector<std::string> argv; base::ProcessHandle handle = base::kNullProcessHandle; argv.push_back(kSetxkbmapCommand); argv.push_back("-layout"); argv.push_back(layout_to_set); argv.push_back("-synch"); if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) { DVLOG(1) << "Failed to execute setxkbmap: " << layout_to_set; execute_queue_ = std::queue<std::string>(); // clear the queue. return; } // g_child_watch_add is necessary to prevent the process from becoming a // zombie. const base::ProcessId pid = base::GetProcId(handle); g_child_watch_add(pid, reinterpret_cast<GChildWatchFunc>(OnSetLayoutFinish), this); DVLOG(1) << "ExecuteSetLayoutCommand: " << layout_to_set << ": pid=" << pid; } bool XKeyboardImpl::NumLockIsEnabled() { bool num_lock_enabled = false; GetLockedModifiers(NULL /* Caps Lock */, &num_lock_enabled); return num_lock_enabled; } bool XKeyboardImpl::CapsLockIsEnabled() { bool caps_lock_enabled = false; GetLockedModifiers(&caps_lock_enabled, NULL /* Num Lock */); return caps_lock_enabled; } unsigned int XKeyboardImpl::GetNumLockMask() { DCHECK(thread_checker_.CalledOnValidThread()); static const unsigned int kBadMask = 0; unsigned int real_mask = kBadMask; XkbDescPtr xkb_desc = XkbGetKeyboard(GetXDisplay(), XkbAllComponentsMask, XkbUseCoreKbd); if (!xkb_desc) return kBadMask; if (xkb_desc->dpy && xkb_desc->names && xkb_desc->names->vmods) { const std::string string_to_find(kNumLockVirtualModifierString); for (size_t i = 0; i < XkbNumVirtualMods; ++i) { const unsigned int virtual_mod_mask = 1U << i; char* virtual_mod_str_raw_ptr = XGetAtomName(xkb_desc->dpy, xkb_desc->names->vmods[i]); if (!virtual_mod_str_raw_ptr) continue; const std::string virtual_mod_str = virtual_mod_str_raw_ptr; XFree(virtual_mod_str_raw_ptr); if (string_to_find == virtual_mod_str) { if (!XkbVirtualModsToReal(xkb_desc, virtual_mod_mask, &real_mask)) { DVLOG(1) << "XkbVirtualModsToReal failed"; real_mask = kBadMask; // reset the return value, just in case. } break; } } } XkbFreeKeyboard(xkb_desc, 0, True /* free all components */); return real_mask; } void XKeyboardImpl::GetLockedModifiers(bool* out_caps_lock_enabled, bool* out_num_lock_enabled) { DCHECK(thread_checker_.CalledOnValidThread()); if (out_num_lock_enabled && !num_lock_mask_) { DVLOG(1) << "Cannot get locked modifiers. Num Lock mask unknown."; if (out_caps_lock_enabled) *out_caps_lock_enabled = false; if (out_num_lock_enabled) *out_num_lock_enabled = false; return; } XkbStateRec status; XkbGetState(GetXDisplay(), XkbUseCoreKbd, &status); if (out_caps_lock_enabled) *out_caps_lock_enabled = status.locked_mods & LockMask; if (out_num_lock_enabled) *out_num_lock_enabled = status.locked_mods & num_lock_mask_; } void XKeyboardImpl::SetLockedModifiers(ModifierLockStatus new_caps_lock_status, ModifierLockStatus new_num_lock_status) { DCHECK(thread_checker_.CalledOnValidThread()); if (!num_lock_mask_) { DVLOG(1) << "Cannot set locked modifiers. Num Lock mask unknown."; return; } unsigned int affect_mask = 0; unsigned int value_mask = 0; if (new_caps_lock_status != kDontChange) { affect_mask |= LockMask; value_mask |= ((new_caps_lock_status == kEnableLock) ? LockMask : 0); current_caps_lock_status_ = (new_caps_lock_status == kEnableLock); } if (new_num_lock_status != kDontChange) { affect_mask |= num_lock_mask_; value_mask |= ((new_num_lock_status == kEnableLock) ? num_lock_mask_ : 0); current_num_lock_status_ = (new_num_lock_status == kEnableLock); } if (affect_mask) XkbLockModifiers(GetXDisplay(), XkbUseCoreKbd, affect_mask, value_mask); } void XKeyboardImpl::SetNumLockEnabled(bool enable_num_lock) { SetLockedModifiers( kDontChange, enable_num_lock ? kEnableLock : kDisableLock); } void XKeyboardImpl::SetCapsLockEnabled(bool enable_caps_lock) { SetLockedModifiers( enable_caps_lock ? kEnableLock : kDisableLock, kDontChange); } bool XKeyboardImpl::SetCurrentKeyboardLayoutByName( const std::string& layout_name) { if (SetLayoutInternal(layout_name, false)) { current_layout_name_ = layout_name; return true; } return false; } bool XKeyboardImpl::ReapplyCurrentKeyboardLayout() { if (current_layout_name_.empty()) { DVLOG(1) << "Can't reapply XKB layout: layout unknown"; return false; } return SetLayoutInternal(current_layout_name_, true /* force */); } void XKeyboardImpl::ReapplyCurrentModifierLockStatus() { SetLockedModifiers(current_caps_lock_status_ ? kEnableLock : kDisableLock, current_num_lock_status_ ? kEnableLock : kDisableLock); } // static void XKeyboardImpl::OnSetLayoutFinish(pid_t pid, int status, XKeyboardImpl* self) { DVLOG(1) << "OnSetLayoutFinish: pid=" << pid; if (self->execute_queue_.empty()) { DVLOG(1) << "OnSetLayoutFinish: execute_queue_ is empty. " << "base::LaunchProcess failed? pid=" << pid; return; } self->execute_queue_.pop(); self->MaybeExecuteSetLayoutCommand(); } } // namespace // static bool XKeyboard::SetAutoRepeatEnabled(bool enabled) { if (enabled) XAutoRepeatOn(GetXDisplay()); else XAutoRepeatOff(GetXDisplay()); DVLOG(1) << "Set auto-repeat mode to: " << (enabled ? "on" : "off"); return true; } // static bool XKeyboard::SetAutoRepeatRate(const AutoRepeatRate& rate) { DVLOG(1) << "Set auto-repeat rate to: " << rate.initial_delay_in_ms << " ms delay, " << rate.repeat_interval_in_ms << " ms interval"; if (XkbSetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd, rate.initial_delay_in_ms, rate.repeat_interval_in_ms) != True) { DVLOG(1) << "Failed to set auto-repeat rate"; return false; } return true; } // static bool XKeyboard::GetAutoRepeatEnabledForTesting() { XKeyboardState state = {}; XGetKeyboardControl(GetXDisplay(), &state); return state.global_auto_repeat != AutoRepeatModeOff; } // static bool XKeyboard::GetAutoRepeatRateForTesting(AutoRepeatRate* out_rate) { return XkbGetAutoRepeatRate(GetXDisplay(), XkbUseCoreKbd, &(out_rate->initial_delay_in_ms), &(out_rate->repeat_interval_in_ms)) == True; } // static bool XKeyboard::CheckLayoutNameForTesting(const std::string& layout_name) { return CheckLayoutName(layout_name); } // static XKeyboard* XKeyboard::Create() { return new XKeyboardImpl(); } } // namespace input_method } // namespace chromeos <|endoftext|>
<commit_before>#include "net/http/HttpContext.h" #include "net/NetBuffer.h" #include "base/Timestamp.h" using zl::base::Timestamp; NAMESPACE_ZL_NET_START /// parse: /// request line \r\n /// request header \r\n /// \r\n /// request body // 使用chorme浏览器请求127.0.0.1:8888/index.html时,server收到的http消息头 // GET /index.html HTTP/1.1 // Host: 127.0.0.1:8888 // Connection: keep-alive // Cache-Control: max-age=0 // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8 // User - Agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like // Gecko) Chrome / 35.0.1916.153 Safari / 537.36 // Accept - Encoding : gzip, deflate, sdch // Accept - Language : zh - CN, zh; q = 0.8 // RA - Ver: 2.2.22 // RA - Sid : 7B747245 - 20140622 - 042030 - f79ea7 - 5f07a8 bool HttpContext::parseRequest(NetBuffer *buf, Timestamp receiveTime) { static int count = 0; HttpContext *context = this; assert(context); printf("----------------parseRequest------------[%d]\n", ++count); bool ok = true; bool hasMore = true; while (hasMore) { if (context->expectRequestLine()) { const char* crlf = buf->findCRLF(); if (crlf) { ok = processRequestLine(buf->peek(), crlf); // 解析请求行 if (ok) { //context->request().setReceiveTime(receiveTime); buf->retrieveUntil(crlf + 2); context->receiveRequestLine(); // 请求行解析完成,下一步要解析消息头中的参数 } else { hasMore = false; } } else { hasMore = false; } } else if (context->expectHeaders()) // 解析消息头中的参数 { printf("context->expectHeaders() [%d]\n", context); const char* crlf = buf->findCRLF(); if (crlf) //按行添加消息头中的参数 { const char *colon = std::find(buf->peek(), crlf, ':'); //一行一行遍历 if (colon != crlf) { const char *end = crlf; string field(buf->peek(), colon); ++colon; while (colon < end && isspace(*colon)) { ++colon; } string value(colon, end); while (!value.empty() && isspace(value[value.size()-1])) { value.resize(value.size()-1); } context->request().addHeader(field, value); } else { // empty line, end of header context->receiveHeaders(); // 消息头解析完成,下一步应该按get/post来区分是否解析消息体 hasMore = !context->gotAll(); printf("parse headers [%d]\n", hasMore); map<string, string> headers = context->request().headers(); for(map<string, string>::iterator it = headers.begin(); it!=headers.end(); ++it) std::cout << it->first << " : " << it->second << "\n"; } buf->retrieveUntil(crlf + 2); } else { hasMore = false; } } else if (context->expectBody()) // 解析消息体 { // FIXME: printf("context->expectBody() [%d]\n", context); } } return ok; } /// request line: httpmethod path httpversion bool HttpContext::processRequestLine(const char *begin, const char *end) { bool succeed = false; const char* start = begin; const char* space = std::find(start, end, ' '); HttpRequest& request = this->request(); string method(start, space); if (space != end && request.setMethod(method)) { start = space+1; space = std::find(start, end, ' '); if (space != end) { const char* question = std::find(start, space, '?'); if (question != space) { string u(start, question); request.setPath(u); u.assign(question, space); request.setQuery(u); } else { string u(start, question); request.setPath(u); } start = space+1; succeed = end-start == 8 && std::equal(start, end-1, "HTTP/1."); if (succeed) { if (*(end-1) == '1') { request.setVersion(HTTP_VERSION_1_1); } else if (*(end-1) == '0') { request.setVersion(HTTP_VERSION_1_0); } else { succeed = false; } } } } printf("-----%d %s %d----\n", request.method(), request.path().c_str(), request.version()); return succeed; } /// request header bool HttpContext::processReqestHeader(const char *begin, const char *end) { return true; } NAMESPACE_ZL_NET_END <commit_msg>update<commit_after>#include "net/http/HttpContext.h" #include "net/NetBuffer.h" #include "base/Timestamp.h" using zl::base::Timestamp; NAMESPACE_ZL_NET_START /// parse: /// request line \r\n /// request header \r\n /// \r\n /// request body // 使用chorme浏览器请求127.0.0.1:8888/index.html时,server收到的http消息头 // GET /index.html HTTP/1.1 // Host: 127.0.0.1:8888 // Connection: keep-alive // Cache-Control: max-age=0 // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8 // User - Agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like // Gecko) Chrome / 35.0.1916.153 Safari / 537.36 // Accept - Encoding : gzip, deflate, sdch // Accept - Language : zh - CN, zh; q = 0.8 // RA - Ver: 2.2.22 // RA - Sid : 7B747245 - 20140622 - 042030 - f79ea7 - 5f07a8 bool HttpContext::parseRequest(NetBuffer *buf, Timestamp receiveTime) { static int count = 0; HttpContext *context = this; assert(context); printf("----------------parseRequest------------[%d]\n", ++count); bool ok = true; bool hasMore = true; while (hasMore) { if (context->expectRequestLine()) { const char* crlf = buf->findCRLF(); if (crlf) { ok = processRequestLine(buf->peek(), crlf); // 解析请求行 if (ok) { //context->request().setReceiveTime(receiveTime); buf->retrieveUntil(crlf + 2); context->receiveRequestLine(); // 请求行解析完成,下一步要解析消息头中的参数 } else { hasMore = false; } } else { hasMore = false; } } else if (context->expectHeaders()) // 解析消息头中的参数 { printf("context->expectHeaders() [%d]\n", context); const char* crlf = buf->findCRLF(); if (crlf) //按行添加消息头中的参数 { const char *colon = std::find(buf->peek(), crlf, ':'); //一行一行遍历 if(!processReqestHeader(buf->peek(), crlf)) { // empty line, end of header context->receiveHeaders(); // 消息头解析完成,下一步应该按get/post来区分是否解析消息体 hasMore = !context->gotAll(); printf("parse headers [%d]\n", hasMore); map<string, string> headers = context->request().headers(); for(map<string, string>::iterator it = headers.begin(); it!=headers.end(); ++it) std::cout << it->first << " : " << it->second << "\n"; } buf->retrieveUntil(crlf + 2); } else { hasMore = false; } } else if (context->expectBody()) // 解析消息体 { // FIXME: printf("context->expectBody() [%d]\n", context); } } return ok; } /// request line: httpmethod path httpversion bool HttpContext::processRequestLine(const char *begin, const char *end) { bool succeed = false; const char* start = begin; const char* space = std::find(start, end, ' '); HttpRequest& request = this->request(); string method(start, space); if (space != end && request.setMethod(method)) { start = space+1; space = std::find(start, end, ' '); if (space != end) { const char* question = std::find(start, space, '?'); if (question != space) { string u(start, question); request.setPath(u); u.assign(question, space); request.setQuery(u); } else { string u(start, question); request.setPath(u); } start = space+1; succeed = end-start == 8 && std::equal(start, end-1, "HTTP/1."); if (succeed) { if (*(end-1) == '1') { request.setVersion(HTTP_VERSION_1_1); } else if (*(end-1) == '0') { request.setVersion(HTTP_VERSION_1_0); } else { succeed = false; } } } } printf("-----%d %s %d----\n", request.method(), request.path().c_str(), request.version()); return succeed; } /// request header bool HttpContext::processReqestHeader(const char *begin, const char *end) { const char *colon = std::find(begin, end, ':'); //一行一行遍历 if (colon != end) { string field(begin, colon); ++colon; while (colon < end && isspace(*colon)) { ++colon; } string value(colon, end); while (!value.empty() && isspace(value[value.size()-1])) { value.resize(value.size()-1); } request_.addHeader(field, value); return true; } else { // empty line, end of header return false; } } NAMESPACE_ZL_NET_END <|endoftext|>
<commit_before>#include "AppInfo.h" #include "FileUtils.h" #include "Log.h" #include "Platform.h" #include "ProcessUtils.h" #include "StringUtils.h" #include "UpdateScript.h" #include "UpdaterOptions.h" #include "tinythread.h" #if defined(PLATFORM_LINUX) #include "UpdateDialogGtkWrapper.h" #include "UpdateDialogAscii.h" #endif #if defined(PLATFORM_MAC) #include "MacBundle.h" #include "UpdateDialogCocoa.h" #endif #if defined(PLATFORM_WINDOWS) #include "UpdateDialogWin32.h" #endif #include <iostream> #define UPDATER_VERSION "0.12" void runWithUi(int argc, char** argv, UpdateInstaller* installer); void runUpdaterThread(void* arg) { #ifdef PLATFORM_MAC // create an autorelease pool to free any temporary objects // created by Cocoa whilst handling notifications from the UpdateInstaller void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif try { UpdateInstaller* installer = static_cast<UpdateInstaller*>(arg); installer->run(); } catch (const std::exception& ex) { LOG(Error,"Unexpected exception " + std::string(ex.what())); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif } #ifdef PLATFORM_MAC extern unsigned char Info_plist[]; extern unsigned int Info_plist_len; extern unsigned char mac_icns[]; extern unsigned int mac_icns_len; bool unpackBundle(int argc, char** argv) { MacBundle bundle(FileUtils::tempPath(),AppInfo::name()); std::string currentExePath = ProcessUtils::currentProcessPath(); if (currentExePath.find(bundle.bundlePath()) != std::string::npos) { // already running from a bundle return false; } LOG(Info,"Creating bundle " + bundle.bundlePath()); // create a Mac app bundle std::string plistContent(reinterpret_cast<const char*>(Info_plist),Info_plist_len); std::string iconContent(reinterpret_cast<const char*>(mac_icns),mac_icns_len); bundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath()); std::list<std::string> args; for (int i = 1; i < argc; i++) { args.push_back(argv[i]); } ProcessUtils::runSync(bundle.executablePath(),args); return true; } #endif void setupConsole() { #ifdef PLATFORM_WINDOWS // see http://stackoverflow.com/questions/587767/how-to-output-to-console-in-c-windows // and http://www.libsdl.org/cgi/docwiki.cgi/FAQ_Console AttachConsole(ATTACH_PARENT_PROCESS); freopen( "CON", "w", stdout ); freopen( "CON", "w", stderr ); #endif } int main(int argc, char** argv) { #ifdef PLATFORM_MAC void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif Log::instance()->open(AppInfo::logFilePath()); #ifdef PLATFORM_MAC // when the updater is run for the first time, create a Mac app bundle // and re-launch the application from the bundle. This permits // setting up bundle properties (such as application icon) if (unpackBundle(argc,argv)) { return 0; } #endif UpdaterOptions options; options.parse(argc,argv); if (options.showVersion) { setupConsole(); std::cout << "Update installer version " << UPDATER_VERSION << std::endl; return 0; } UpdateInstaller installer; UpdateScript script; if (!options.scriptPath.empty()) { script.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str())); } LOG(Info,"started updater. install-dir: " + options.installDir + ", package-dir: " + options.packageDir + ", wait-pid: " + intToStr(options.waitPid) + ", script-path: " + options.scriptPath + ", mode: " + intToStr(options.mode)); installer.setMode(options.mode); installer.setInstallDir(options.installDir); installer.setPackageDir(options.packageDir); installer.setScript(&script); installer.setWaitPid(options.waitPid); installer.setForceElevated(options.forceElevated); if (options.mode == UpdateInstaller::Main) { runWithUi(argc,argv,&installer); } else { installer.run(); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif return 0; } #ifdef PLATFORM_LINUX void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogAscii asciiDialog; UpdateDialogGtkWrapper dialog; bool useGtk = dialog.init(argc,argv); if (useGtk) { installer->setObserver(&dialog); } else { asciiDialog.init(); installer->setObserver(&asciiDialog); } tthread::thread updaterThread(runUpdaterThread,installer); if (useGtk) { dialog.exec(); } updaterThread.join(); } #endif #ifdef PLATFORM_MAC void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogCocoa dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif #ifdef PLATFORM_WINDOWS // application entry point under Windows int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = 0; char** argv; ProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv); return main(argc,argv); } void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogWin32 dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif <commit_msg>Bump updater version to 0.13<commit_after>#include "AppInfo.h" #include "FileUtils.h" #include "Log.h" #include "Platform.h" #include "ProcessUtils.h" #include "StringUtils.h" #include "UpdateScript.h" #include "UpdaterOptions.h" #include "tinythread.h" #if defined(PLATFORM_LINUX) #include "UpdateDialogGtkWrapper.h" #include "UpdateDialogAscii.h" #endif #if defined(PLATFORM_MAC) #include "MacBundle.h" #include "UpdateDialogCocoa.h" #endif #if defined(PLATFORM_WINDOWS) #include "UpdateDialogWin32.h" #endif #include <iostream> #define UPDATER_VERSION "0.13" void runWithUi(int argc, char** argv, UpdateInstaller* installer); void runUpdaterThread(void* arg) { #ifdef PLATFORM_MAC // create an autorelease pool to free any temporary objects // created by Cocoa whilst handling notifications from the UpdateInstaller void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif try { UpdateInstaller* installer = static_cast<UpdateInstaller*>(arg); installer->run(); } catch (const std::exception& ex) { LOG(Error,"Unexpected exception " + std::string(ex.what())); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif } #ifdef PLATFORM_MAC extern unsigned char Info_plist[]; extern unsigned int Info_plist_len; extern unsigned char mac_icns[]; extern unsigned int mac_icns_len; bool unpackBundle(int argc, char** argv) { MacBundle bundle(FileUtils::tempPath(),AppInfo::name()); std::string currentExePath = ProcessUtils::currentProcessPath(); if (currentExePath.find(bundle.bundlePath()) != std::string::npos) { // already running from a bundle return false; } LOG(Info,"Creating bundle " + bundle.bundlePath()); // create a Mac app bundle std::string plistContent(reinterpret_cast<const char*>(Info_plist),Info_plist_len); std::string iconContent(reinterpret_cast<const char*>(mac_icns),mac_icns_len); bundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath()); std::list<std::string> args; for (int i = 1; i < argc; i++) { args.push_back(argv[i]); } ProcessUtils::runSync(bundle.executablePath(),args); return true; } #endif void setupConsole() { #ifdef PLATFORM_WINDOWS // see http://stackoverflow.com/questions/587767/how-to-output-to-console-in-c-windows // and http://www.libsdl.org/cgi/docwiki.cgi/FAQ_Console AttachConsole(ATTACH_PARENT_PROCESS); freopen( "CON", "w", stdout ); freopen( "CON", "w", stderr ); #endif } int main(int argc, char** argv) { #ifdef PLATFORM_MAC void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif Log::instance()->open(AppInfo::logFilePath()); #ifdef PLATFORM_MAC // when the updater is run for the first time, create a Mac app bundle // and re-launch the application from the bundle. This permits // setting up bundle properties (such as application icon) if (unpackBundle(argc,argv)) { return 0; } #endif UpdaterOptions options; options.parse(argc,argv); if (options.showVersion) { setupConsole(); std::cout << "Update installer version " << UPDATER_VERSION << std::endl; return 0; } UpdateInstaller installer; UpdateScript script; if (!options.scriptPath.empty()) { script.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str())); } LOG(Info,"started updater. install-dir: " + options.installDir + ", package-dir: " + options.packageDir + ", wait-pid: " + intToStr(options.waitPid) + ", script-path: " + options.scriptPath + ", mode: " + intToStr(options.mode)); installer.setMode(options.mode); installer.setInstallDir(options.installDir); installer.setPackageDir(options.packageDir); installer.setScript(&script); installer.setWaitPid(options.waitPid); installer.setForceElevated(options.forceElevated); if (options.mode == UpdateInstaller::Main) { runWithUi(argc,argv,&installer); } else { installer.run(); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif return 0; } #ifdef PLATFORM_LINUX void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogAscii asciiDialog; UpdateDialogGtkWrapper dialog; bool useGtk = dialog.init(argc,argv); if (useGtk) { installer->setObserver(&dialog); } else { asciiDialog.init(); installer->setObserver(&asciiDialog); } tthread::thread updaterThread(runUpdaterThread,installer); if (useGtk) { dialog.exec(); } updaterThread.join(); } #endif #ifdef PLATFORM_MAC void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogCocoa dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif #ifdef PLATFORM_WINDOWS // application entry point under Windows int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = 0; char** argv; ProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv); return main(argc,argv); } void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogWin32 dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <pwd.h> #include <vector> #include <string> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> using namespace std; //function to convert a vector of char * to a //char * [] for use as an execvp argument char ** conv_vec(vector<char*> v) { //create a char * [] of proper size char ** t = new char* [v.size() + 1]; //counter to keep track of the position //for entering char* unsigned i = 0; for (; i < v.size(); ++i) { //first make char[] entry of the right length t[i] = new char[strlen(v.at(i))]; //then copy the entire string from the vector //into the char *[] strcpy(t[i], v.at(i)); } //set the last position to a null character t[i] = '\0'; return t; } char ** get_command(string& a, int& flag) { //cout << a << endl; //first make a copy of the command string //so that we can check what delimiter strtok //stopped at char * copy = new char [a.length() + 1]; strcpy(copy, a.c_str()); //create a vector because we do not know //how many tokens are in the command entered vector<char *> temp; //create an empty char * [] to return. It can //either be empty if there is no input or //filled later when we convert the vector //into an array char ** vec = NULL; //bool done = false; //set a starting position to reference when //finding the position of the delimiter found char * begin = copy; //take the first token char * token = strtok(copy, " ;|&#"); //for position of delimiter unsigned int pos; while (token != 0) { // cout << token << endl; //the position of the delimiter with respect //to the beginning of the array pos = token - begin + strlen(token); //put the token at the end of the vector temp.push_back(token); //cout << pos << endl; //to find out which delimiter was found //if it was the end, it will not go through this if (pos < a.size()) { //store delimiter character found char delim = a.at(pos); // cout << delim << endl; if (delim == ' ') { while (pos < a.size() - 1 && delim == ' ') { ++pos; delim = a.at(pos); } } //checking to see if there are two of the '|' //or '&' if (delim == '|' || delim == '&') { //increment this n as long as it is not the //end and they are equal int n = 1; while (pos + n < a.size() && delim == a.at(pos + n)) { ++n; } //if it is not 2, give an error message and clear //the vector so that no commands are executed if (n != 2) { cerr << "Rshell: Syntax error near '" << delim << "'" << endl; temp.clear(); } } //Now we know delim is either a delimiter //that signifies the end of a command //or is the first char of an argument //so we check if (delim == '|' || delim == '&' || delim == ';') { //so we are done with this command //now we convert it to a char** vec = conv_vec(temp); // for (unsigned i = 0; vec[i] != 0; ++i) // { // cout << i << endl; // cout << vec[i] << endl; // } //remember to get rid of the dynamically allocated delete copy; //reset flag ('#' and ';' use 0 so reset it for //those and change for '|' and '&' flag = 0; if (delim == '|') { //set flag bit flag = 1; } else if (delim == '&') { //set flag bit to 2 flag = 2; } // cout << flag << endl; a = a.substr(pos + 1, a.size() - pos + 1); return vec; } //this means that delim == a character //for the next argument so continue } token = strtok(NULL, " ;|&"); } //so we have reached the end, set a to empty a = ""; //convert to proper char** vec = conv_vec(temp); //get rid of dynamically allocated delete copy; //we got to the end so the flag should be 0 flag = 0; return vec; } void display_prompt() { //set size of hostname char host[50]; //get the hostname and check to see if there was //an error int host_flag = gethostname(host, sizeof host); if(host_flag == -1) { perror("gethostname"); } //get login and if there was an error give message char *login = (getpwuid(getuid()))->pw_name; if (login == 0) { perror("getlogin"); } cout << login << '@' << host << "$ "; } int main() { int flag = 0; int error_flag; while (1) { display_prompt(); string command; getline(cin, command); //first try to find a '#' sign to indicate //a comment int p = command.find('#'); //if there was a comment then delete everything //after that AKA set a substring from 0 to the '#' if (p != -1) { command = command.substr(0, p); } //so continue doing and getting while there is //still an && or || or until the end of the //commands while(flag != 0 || command != "") { //get the command in argv char ** argv = get_command(command, flag); // cout << command << endl; // cout << flag << endl; //if it is empty, then go back to prompt if (argv[0] == NULL) { break; } //if the command is exit, exit program else if (strcmp(argv[0], "exit") == 0) { return 0; } // for (int i = 0; argv[i] != 0; ++i) // { // cout << argv[i] << endl; // } error_flag = 0; //call the fork and check for error int fork_flag = fork(); if (fork_flag == -1) { perror("fork"); exit(1); } //if it is the child do the command while checking //for error else if (fork_flag == 0) { int execvp_flag = execvp(argv[0], argv); if (execvp_flag == -1) { perror("execvp"); exit(1); } } //if parent then wait for child int wait_flag = wait(&error_flag); if (wait_flag == -1) { perror("wait"); exit(1); } // cout << "Error flag is " << error_flag << endl; //if there was an error if (error_flag != 0) { //if it was the first in an &&, go back //to prompt if (flag == 2) { break; } } //if there wasn't an error and it was in an || //statement then go back to prompt else if (flag == 1) { break; } } } return 0; } <commit_msg>did multiple && and || with another dlimiter behind it<commit_after>#include <iostream> #include <stdlib.h> #include <pwd.h> #include <vector> #include <string> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> using namespace std; //function to convert a vector of char * to a //char * [] for use as an execvp argument char ** conv_vec(vector<char*> v) { //create a char * [] of proper size char ** t = new char* [v.size() + 1]; //counter to keep track of the position //for entering char* unsigned i = 0; for (; i < v.size(); ++i) { //first make char[] entry of the right length t[i] = new char[strlen(v.at(i))]; //then copy the entire string from the vector //into the char *[] strcpy(t[i], v.at(i)); } //set the last position to a null character t[i] = '\0'; return t; } char ** get_command(string& a, int& flag) { //cout << a << endl; //first make a copy of the command string //so that we can check what delimiter strtok //stopped at char * copy = new char [a.length() + 1]; strcpy(copy, a.c_str()); //create a vector because we do not know //how many tokens are in the command entered vector<char *> temp; //create an empty char * [] to return. It can //either be empty if there is no input or //filled later when we convert the vector //into an array char ** vec = NULL; //bool done = false; //set a starting position to reference when //finding the position of the delimiter found char * begin = copy; //take the first token char * token = strtok(copy, " ;|&#"); //for position of delimiter unsigned int pos; while (token != 0) { // cout << token << endl; //the position of the delimiter with respect //to the beginning of the array pos = token - begin + strlen(token); //put the token at the end of the vector temp.push_back(token); //cout << pos << endl; //to find out which delimiter was found //if it was the end, it will not go through this if (pos < a.size()) { //store delimiter character found char delim = a.at(pos); // cout << delim << endl; if (delim == ' ') { while (pos < a.size() - 1 && delim == ' ') { ++pos; delim = a.at(pos); } } //checking to see if there are two of the '|' //or '&' if (delim == '|' || delim == '&') { //increment this n as long as it is not the //end and they are equal int n = 1; while (pos + n < a.size() && delim == a.at(pos + n)) { ++n; } //if it is not 2, give an error message and clear //the vector so that no commands are executed if (n != 2 || pos + n == a.size() || a.at(pos + n) == ';' || a.at(pos + n) == '|' || a.at(pos + n) == '&') { cerr << "Rshell: Syntax error near '" << delim << "'" << endl; temp.clear(); } } //Now we know delim is either a delimiter //that signifies the end of a command //or is the first char of an argument //so we check if (delim == '|' || delim == '&' || delim == ';') { //so we are done with this command //now we convert it to a char** vec = conv_vec(temp); // for (unsigned i = 0; vec[i] != 0; ++i) // { // cout << i << endl; // cout << vec[i] << endl; // } //remember to get rid of the dynamically allocated delete copy; //reset flag ('#' and ';' use 0 so reset it for //those and change for '|' and '&' flag = 0; if (delim == '|') { //set flag bit flag = 1; } else if (delim == '&') { //set flag bit to 2 flag = 2; } // cout << flag << endl; a = a.substr(pos + 1, a.size() - pos + 1); return vec; } //this means that delim == a character //for the next argument so continue } token = strtok(NULL, " ;|&"); } //so we have reached the end, set a to empty a = ""; //convert to proper char** vec = conv_vec(temp); //get rid of dynamically allocated delete copy; //we got to the end so the flag should be 0 flag = 0; return vec; } void display_prompt() { //set size of hostname char host[50]; //get the hostname and check to see if there was //an error int host_flag = gethostname(host, sizeof host); if(host_flag == -1) { perror("gethostname"); } //get login and if there was an error give message char *login = (getpwuid(getuid()))->pw_name; if (login == 0) { perror("getlogin"); } cout << login << '@' << host << "$ "; } int main() { int flag = 0; int error_flag; while (1) { display_prompt(); string command; getline(cin, command); //first try to find a '#' sign to indicate //a comment int p = command.find('#'); //if there was a comment then delete everything //after that AKA set a substring from 0 to the '#' if (p != -1) { command = command.substr(0, p); } //so continue doing and getting while there is //still an && or || or until the end of the //commands while(flag != 0 || command != "") { //get the command in argv char ** argv = get_command(command, flag); // cout << command << endl; // cout << flag << endl; //if it is empty, then go back to prompt if (argv[0] == NULL) { break; } //if the command is exit, exit program else if (strcmp(argv[0], "exit") == 0) { return 0; } // for (int i = 0; argv[i] != 0; ++i) // { // cout << argv[i] << endl; // } error_flag = 0; //call the fork and check for error int fork_flag = fork(); if (fork_flag == -1) { perror("fork"); exit(1); } //if it is the child do the command while checking //for error else if (fork_flag == 0) { int execvp_flag = execvp(argv[0], argv); if (execvp_flag == -1) { perror("execvp"); exit(1); } } //if parent then wait for child int wait_flag = wait(&error_flag); if (wait_flag == -1) { perror("wait"); exit(1); } // cout << "Error flag is " << error_flag << endl; //if there was an error if (error_flag != 0) { //if it was the first in an &&, go back //to prompt if (flag == 2) { break; } } //if there wasn't an error and it was in an || //statement then go back to prompt else if (flag == 1) { break; } } } return 0; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // CoinVault // // main.cpp // // Copyright (c) 2013 Eric Lombrozo // // All Rights Reserved. #include "settings.h" #include <QApplication> #include <QDateTime> #include "splashscreen.h" #include "mainwindow.h" #include "commandserver.h" #include "severitylogger.h" int main(int argc, char* argv[]) { INIT_LOGGER((APPDATADIR + "/debug.log").toStdString().c_str()); LOGGER(debug) << std::endl << std::endl << std::endl << std::endl << QDateTime::currentDateTime().toString().toStdString() << std::endl; Q_INIT_RESOURCE(coinvault); QApplication app(argc, argv); app.setOrganizationName("Ciphrex"); app.setApplicationName(APPNAME); CommandServer commandServer(&app); if (commandServer.processArgs(argc, argv)) exit(0); LOGGER(debug) << "Vault started." << std::endl; SplashScreen splash; splash.show(); splash.setAutoFillBackground(true); app.processEvents(); splash.showMessage("\n Loading settings..."); app.processEvents(); MainWindow mainWin; // constructor loads settings QObject::connect(&mainWin, &MainWindow::status, [&](const QString& message) { splash.showMessage(message); }); splash.showMessage("\n Starting command server..."); app.processEvents(); if (!commandServer.start()) { LOGGER(debug) << "Could not start command server." << std::endl; } else { app.connect(&commandServer, SIGNAL(gotUrl(const QUrl&)), &mainWin, SLOT(processUrl(const QUrl&))); app.connect(&commandServer, SIGNAL(gotFile(const QString&)), &mainWin, SLOT(processFile(const QString&))); } splash.showMessage("\n Loading block headers..."); app.processEvents(); mainWin.loadBlockTree(); app.processEvents(); mainWin.tryConnect(); mainWin.show(); splash.finish(&mainWin); commandServer.uiReady(); int rval = app.exec(); LOGGER(debug) << "Program stopped with code " << rval << std::endl; return rval; } <commit_msg>Update splash screen message fix.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // CoinVault // // main.cpp // // Copyright (c) 2013 Eric Lombrozo // // All Rights Reserved. #include "settings.h" #include <QApplication> #include <QDateTime> #include "splashscreen.h" #include "mainwindow.h" #include "commandserver.h" #include "severitylogger.h" int main(int argc, char* argv[]) { INIT_LOGGER((APPDATADIR + "/debug.log").toStdString().c_str()); LOGGER(debug) << std::endl << std::endl << std::endl << std::endl << QDateTime::currentDateTime().toString().toStdString() << std::endl; Q_INIT_RESOURCE(coinvault); QApplication app(argc, argv); app.setOrganizationName("Ciphrex"); app.setApplicationName(APPNAME); CommandServer commandServer(&app); if (commandServer.processArgs(argc, argv)) exit(0); LOGGER(debug) << "Vault started." << std::endl; SplashScreen splash; splash.show(); splash.setAutoFillBackground(true); app.processEvents(); splash.showMessage("\n Loading settings..."); MainWindow mainWin; // constructor loads settings QObject::connect(&mainWin, &MainWindow::status, [&](const QString& message) { splash.showMessage(message); }); splash.showMessage("\n Starting command server..."); if (!commandServer.start()) { LOGGER(debug) << "Could not start command server." << std::endl; } else { app.connect(&commandServer, SIGNAL(gotUrl(const QUrl&)), &mainWin, SLOT(processUrl(const QUrl&))); app.connect(&commandServer, SIGNAL(gotFile(const QString&)), &mainWin, SLOT(processFile(const QString&))); } app.processEvents(); splash.showMessage("\n Loading block headers..."); app.processEvents(); mainWin.loadBlockTree(); mainWin.tryConnect(); mainWin.show(); splash.finish(&mainWin); commandServer.uiReady(); int rval = app.exec(); LOGGER(debug) << "Program stopped with code " << rval << std::endl; return rval; } <|endoftext|>
<commit_before>#include "GarrysMod\Lua\Interface.h" #include "Leap.h" using namespace GarrysMod; using namespace Leap; Controller *controller = nullptr; void *fake_heap[sizeof(Controller)]; int leap_IsConnected(lua_State *state) { LUA->PushBool(controller->isConnected()); return 1; } int leap_Frame(lua_State *state) { Frame frame; if (LUA->Top() > 0) { frame = controller->frame(LUA->CheckNumber()); } else { frame = controller->frame(); } Lua::UserData* ud = (Lua::UserData*)LUA->NewUserdata(sizeof(Lua::UserData)); ud->data = &frame; ud->type = Lua::Type::USERDATA; LUA->CreateMetaTableType("LeapFrame", Lua::Type::USERDATA); LUA->SetMetaTable(-2); return 1; } //LeapFrame Metamethods int LeapFrame_tostring(lua_State* state) { Lua::UserData* ud = (Lua::UserData*)LUA->GetUserdata(); Frame* frame = (Frame*)ud->data; LUA->PushString(frame->toString().c_str()); return 1; } int LeapFrame_Serialize(lua_State* state) { Lua::UserData* ud = (Lua::UserData*)LUA->GetUserdata(); Frame* frame = (Frame*)ud->data; LUA->PushString(frame->serialize().c_str()); return 1; } GMOD_MODULE_OPEN() { controller = new (fake_heap) Controller; LUA->PushSpecial(Lua::SPECIAL_GLOB); LUA->CreateTable(); LUA->PushCFunction(leap_IsConnected); LUA->SetField(-2, "IsConnected"); LUA->PushCFunction(leap_Frame); LUA->SetField(-2, "Frame"); LUA->SetField(-2, "leap"); LUA->CreateMetaTableType("LeapFrame", Lua::Type::USERDATA); LUA->Push(-1); LUA->SetField(-2, "__index"); LUA->PushCFunction(LeapFrame_tostring); LUA->SetField(-2, "__tostring"); LUA->PushString("LeapFrame"); LUA->SetField(-2, "__type"); LUA->PushCFunction(LeapFrame_Serialize); LUA->SetField(-2, "Serialize"); LUA->Pop(); LUA->Pop(); return 0; } GMOD_MODULE_CLOSE() { if ( controller ){ controller->~Controller(); controller = nullptr; } return 0; }<commit_msg>Fixed crashing<commit_after>#include "GarrysMod\Lua\Interface.h" #include "Leap.h" using namespace GarrysMod; using namespace Leap; Controller *controller = nullptr; void *fake_heap[sizeof(Controller)]; int leap_IsConnected(lua_State *state) { LUA->PushBool(controller->isConnected()); return 1; } int leap_Frame(lua_State *state) { //Jvs: I'm using the copy constructor due to the controller cleaning up the history after a few ticks // we're gonna have to add a __gc method to the frame, but this also stops the crashing bullshit Frame * frame; if (LUA->Top() > 0) { frame = new Frame( controller->frame(LUA->CheckNumber()) ); } else { frame = new Frame( controller->frame() ); } Lua::UserData* ud = (Lua::UserData*)LUA->NewUserdata(sizeof(Lua::UserData)); ud->data = frame; ud->type = 99; LUA->CreateMetaTableType("LeapFrame", 99 ); LUA->SetMetaTable( -2 ); return 1; } //LeapFrame Metamethods int LeapFrame_tostring(lua_State* state) { Lua::UserData* ud = (Lua::UserData*)LUA->GetUserdata(); if ( !ud ) return 0; Frame* frame = (Frame*)ud->data; if ( !frame || !frame->isValid() ) { return 0; } LUA->PushString(frame->toString().c_str()); return 1; } int LeapFrame_Serialize(lua_State* state) { Lua::UserData* ud = (Lua::UserData*)LUA->GetUserdata(); if ( !ud ) return 0; Frame* frame = (Frame*)ud->data; if ( !frame || !frame->isValid() ) { return 0; } LUA->PushString(frame->serialize().c_str()); return 1; } int LeapFrame_IsValid(lua_State* state) { Lua::UserData* ud = (Lua::UserData*)LUA->GetUserdata(); if ( !ud ) return 0; Frame* frame = (Frame*)ud->data; if ( !frame ) { return 0; } LUA->PushBool( frame->isValid() ); return 1; } GMOD_MODULE_OPEN() { controller = new (fake_heap) Controller; LUA->PushSpecial(Lua::SPECIAL_GLOB); LUA->CreateTable(); LUA->PushCFunction(leap_IsConnected); LUA->SetField(-2, "IsConnected"); LUA->PushCFunction(leap_Frame); LUA->SetField(-2, "Frame"); LUA->SetField(-2, "leap"); LUA->CreateMetaTableType("LeapFrame", Lua::Type::USERDATA); LUA->Push(-1); LUA->SetField(-2, "__index"); LUA->PushCFunction(LeapFrame_tostring); LUA->SetField(-2, "__tostring"); LUA->PushString("LeapFrame"); LUA->SetField(-2, "__type"); LUA->PushCFunction(LeapFrame_Serialize); LUA->SetField(-2, "Serialize"); LUA->PushCFunction(LeapFrame_IsValid); LUA->SetField(-2, "IsValid"); LUA->Pop(); LUA->Pop(); return 0; } GMOD_MODULE_CLOSE() { if ( controller ){ controller->~Controller(); controller = nullptr; } return 0; }<|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include "gn_encoder.h" #include "gn_playlist.h" #include "gn_playlist_item.h" using namespace v8; GNEncoder::GNEncoder() {}; GNEncoder::~GNEncoder() { groove_encoder_destroy(encoder); }; Persistent<Function> GNEncoder::constructor; template <typename target_t, typename func_t> static void AddMethod(target_t tpl, const char* name, func_t fn) { tpl->PrototypeTemplate()->Set(String::NewSymbol(name), FunctionTemplate::New(fn)->GetFunction()); } void GNEncoder::Init() { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("GrooveEncoder")); tpl->InstanceTemplate()->SetInternalFieldCount(2); // Methods AddMethod(tpl, "attach", Attach); AddMethod(tpl, "detach", Detach); AddMethod(tpl, "getBuffer", GetBuffer); AddMethod(tpl, "position", Position); constructor = Persistent<Function>::New(tpl->GetFunction()); } Handle<Value> GNEncoder::New(const Arguments& args) { HandleScope scope; GNEncoder *obj = new GNEncoder(); obj->Wrap(args.This()); return scope.Close(args.This()); } Handle<Value> GNEncoder::NewInstance(GrooveEncoder *encoder) { HandleScope scope; Local<Object> instance = constructor->NewInstance(); GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(instance); gn_encoder->encoder = encoder; return scope.Close(instance); } struct AttachReq { uv_work_t req; Persistent<Function> callback; GrooveEncoder *encoder; GroovePlaylist *playlist; int errcode; Persistent<Object> instance; String::Utf8Value *format_short_name; String::Utf8Value *codec_short_name; String::Utf8Value *filename; String::Utf8Value *mime_type; GNEncoder::EventContext *event_context; }; static void EventAsyncCb(uv_async_t *handle, int status) { HandleScope scope; GNEncoder::EventContext *context = reinterpret_cast<GNEncoder::EventContext *>(handle->data); const unsigned argc = 1; Handle<Value> argv[argc]; argv[0] = Undefined(); TryCatch try_catch; context->event_cb->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } uv_cond_signal(&context->cond); } static void EventThreadEntry(void *arg) { GNEncoder::EventContext *context = reinterpret_cast<GNEncoder::EventContext *>(arg); while (groove_encoder_buffer_peek(context->encoder, 1) > 0) { uv_async_send(&context->event_async); uv_mutex_lock(&context->mutex); uv_cond_wait(&context->cond, &context->mutex); uv_mutex_unlock(&context->mutex); } } static void AttachAsync(uv_work_t *req) { AttachReq *r = reinterpret_cast<AttachReq *>(req->data); r->encoder->format_short_name = r->format_short_name ? **r->format_short_name : NULL; r->encoder->codec_short_name = r->codec_short_name ? **r->codec_short_name : NULL; r->encoder->filename = r->filename ? **r->filename : NULL; r->encoder->mime_type = r->mime_type ? **r->mime_type : NULL; r->errcode = groove_encoder_attach(r->encoder, r->playlist); if (r->format_short_name) { delete r->format_short_name; r->format_short_name = NULL; } if (r->codec_short_name) { delete r->codec_short_name; r->codec_short_name = NULL; } if (r->filename) { delete r->filename; r->filename = NULL; } if (r->mime_type) { delete r->mime_type; r->mime_type = NULL; } GNEncoder::EventContext *context = r->event_context; uv_cond_init(&context->cond); uv_mutex_init(&context->mutex); uv_async_init(uv_default_loop(), &context->event_async, EventAsyncCb); context->event_async.data = context; uv_thread_create(&context->event_thread, EventThreadEntry, context); } static void AttachAfter(uv_work_t *req) { HandleScope scope; AttachReq *r = reinterpret_cast<AttachReq *>(req->data); const unsigned argc = 1; Handle<Value> argv[argc]; if (r->errcode < 0) { argv[0] = Exception::Error(String::New("encoder attach failed")); } else { argv[0] = Null(); Local<Object> actualAudioFormat = Object::New(); actualAudioFormat->Set(String::NewSymbol("sampleRate"), Number::New(r->encoder->actual_audio_format.sample_rate)); actualAudioFormat->Set(String::NewSymbol("channelLayout"), Number::New(r->encoder->actual_audio_format.channel_layout)); actualAudioFormat->Set(String::NewSymbol("sampleFormat"), Number::New(r->encoder->actual_audio_format.sample_fmt)); r->instance->Set(String::NewSymbol("actualAudioFormat"), actualAudioFormat); } TryCatch try_catch; r->callback->Call(Context::GetCurrent()->Global(), argc, argv); delete r; if (try_catch.HasCaught()) { node::FatalException(try_catch); } } Handle<Value> GNEncoder::Create(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Expected function arg[0]"))); return scope.Close(Undefined()); } GrooveEncoder *encoder = groove_encoder_create(); Handle<Object> instance = NewInstance(encoder)->ToObject(); GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(instance); EventContext *context = new EventContext; gn_encoder->event_context = context; context->event_cb = Persistent<Function>::New(Local<Function>::Cast(args[0])); context->encoder = encoder; // set properties on the instance with default values from // GrooveEncoder struct Local<Object> targetAudioFormat = Object::New(); targetAudioFormat->Set(String::NewSymbol("sampleRate"), Number::New(encoder->target_audio_format.sample_rate)); targetAudioFormat->Set(String::NewSymbol("channelLayout"), Number::New(encoder->target_audio_format.channel_layout)); targetAudioFormat->Set(String::NewSymbol("sampleFormat"), Number::New(encoder->target_audio_format.sample_fmt)); instance->Set(String::NewSymbol("bitRate"), Number::New(encoder->bit_rate)); instance->Set(String::NewSymbol("actualAudioFormat"), Null()); instance->Set(String::NewSymbol("targetAudioFormat"), targetAudioFormat); instance->Set(String::NewSymbol("formatShortName"), Null()); instance->Set(String::NewSymbol("codecShortName"), Null()); instance->Set(String::NewSymbol("filename"), Null()); instance->Set(String::NewSymbol("mimeType"), Null()); return scope.Close(instance); } Handle<Value> GNEncoder::Attach(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); if (args.Length() < 1 || !args[0]->IsObject()) { ThrowException(Exception::TypeError(String::New("Expected object arg[0]"))); return scope.Close(Undefined()); } if (args.Length() < 2 || !args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Expected function arg[1]"))); return scope.Close(Undefined()); } Local<Object> instance = args.This(); Local<Value> targetAudioFormatValue = instance->Get(String::NewSymbol("targetAudioFormat")); if (!targetAudioFormatValue->IsObject()) { ThrowException(Exception::TypeError(String::New("Expected targetAudioFormat to be an object"))); return scope.Close(Undefined()); } GNPlaylist *gn_playlist = node::ObjectWrap::Unwrap<GNPlaylist>(args[0]->ToObject()); AttachReq *request = new AttachReq; request->req.data = request; request->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); request->instance = Persistent<Object>::New(args.This()); request->playlist = gn_playlist->playlist; request->event_context = gn_encoder->event_context; GrooveEncoder *encoder = gn_encoder->encoder; request->encoder = encoder; // copy the properties from our instance to the encoder Local<Value> formatShortName = instance->Get(String::NewSymbol("formatShortName")); if (formatShortName->IsNull() || formatShortName->IsUndefined()) { request->format_short_name = NULL; } else { request->format_short_name = new String::Utf8Value(formatShortName->ToString()); } Local<Value> codecShortName = instance->Get(String::NewSymbol("codecShortName")); if (codecShortName->IsNull() || codecShortName->IsUndefined()) { request->codec_short_name = NULL; } else { request->codec_short_name = new String::Utf8Value(codecShortName->ToString()); } Local<Value> filenameStr = instance->Get(String::NewSymbol("filename")); if (filenameStr->IsNull() || filenameStr->IsUndefined()) { request->filename = NULL; } else { request->filename = new String::Utf8Value(filenameStr->ToString()); } Local<Value> mimeType = instance->Get(String::NewSymbol("mimeType")); if (mimeType->IsNull() || mimeType->IsUndefined()) { request->mime_type = NULL; } else { request->mime_type = new String::Utf8Value(mimeType->ToString()); } Local<Object> targetAudioFormat = targetAudioFormatValue->ToObject(); Local<Value> sampleRate = targetAudioFormat->Get(String::NewSymbol("sampleRate")); double sample_rate = sampleRate->NumberValue(); double channel_layout = targetAudioFormat->Get(String::NewSymbol("channelLayout"))->NumberValue(); double sample_fmt = targetAudioFormat->Get(String::NewSymbol("sampleFormat"))->NumberValue(); encoder->target_audio_format.sample_rate = (int)sample_rate; encoder->target_audio_format.channel_layout = (int)channel_layout; encoder->target_audio_format.sample_fmt = (enum GrooveSampleFormat)(int)sample_fmt; double bit_rate = instance->Get(String::NewSymbol("bitRate"))->NumberValue(); encoder->bit_rate = (int)bit_rate; uv_queue_work(uv_default_loop(), &request->req, AttachAsync, (uv_after_work_cb)AttachAfter); return scope.Close(Undefined()); } struct DetachReq { uv_work_t req; GrooveEncoder *encoder; Persistent<Function> callback; int errcode; GNEncoder::EventContext *event_context; }; static void DetachAsyncFree(uv_handle_t *handle) { GNEncoder::EventContext *context = reinterpret_cast<GNEncoder::EventContext *>(handle->data); delete context; } static void DetachAsync(uv_work_t *req) { DetachReq *r = reinterpret_cast<DetachReq *>(req->data); r->errcode = groove_encoder_detach(r->encoder); uv_cond_signal(&r->event_context->cond); uv_thread_join(&r->event_context->event_thread); uv_cond_destroy(&r->event_context->cond); uv_mutex_destroy(&r->event_context->mutex); uv_close(reinterpret_cast<uv_handle_t*>(&r->event_context->event_async), DetachAsyncFree); } static void DetachAfter(uv_work_t *req) { HandleScope scope; DetachReq *r = reinterpret_cast<DetachReq *>(req->data); const unsigned argc = 1; Handle<Value> argv[argc]; if (r->errcode < 0) { argv[0] = Exception::Error(String::New("encoder detach failed")); } else { argv[0] = Null(); } TryCatch try_catch; r->callback->Call(Context::GetCurrent()->Global(), argc, argv); delete r; if (try_catch.HasCaught()) { node::FatalException(try_catch); } } Handle<Value> GNEncoder::Detach(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); if (args.Length() < 1 || !args[0]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Expected function arg[0]"))); return scope.Close(Undefined()); } GrooveEncoder *encoder = gn_encoder->encoder; if (!encoder->playlist) { ThrowException(Exception::Error(String::New("detach: not attached"))); return scope.Close(Undefined()); } DetachReq *request = new DetachReq; request->req.data = request; request->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); request->encoder = encoder; request->event_context = gn_encoder->event_context; uv_queue_work(uv_default_loop(), &request->req, DetachAsync, (uv_after_work_cb)DetachAfter); return scope.Close(Undefined()); } static void buffer_free(char *data, void *hint) { GrooveBuffer *buffer = reinterpret_cast<GrooveBuffer*>(hint); groove_buffer_unref(buffer); } Handle<Value> GNEncoder::GetBuffer(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); GrooveEncoder *encoder = gn_encoder->encoder; GrooveBuffer *buffer; switch (groove_encoder_buffer_get(encoder, &buffer, 0)) { case GROOVE_BUFFER_YES: { Local<Object> object = Object::New(); Handle<Object> bufferObject = node::Buffer::New( reinterpret_cast<char*>(buffer->data[0]), buffer->size, buffer_free, buffer)->handle_; object->Set(String::NewSymbol("buffer"), bufferObject); if (buffer->item) { object->Set(String::NewSymbol("item"), GNPlaylistItem::NewInstance(buffer->item)); } else { object->Set(String::NewSymbol("item"), Null()); } object->Set(String::NewSymbol("pos"), Number::New(buffer->pos)); return scope.Close(object); } case GROOVE_BUFFER_END: { Local<Object> object = Object::New(); object->Set(String::NewSymbol("buffer"), Null()); object->Set(String::NewSymbol("item"), Null()); object->Set(String::NewSymbol("pos"), Null()); return scope.Close(object); } default: return scope.Close(Null()); } } Handle<Value> GNEncoder::Position(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); GrooveEncoder *encoder = gn_encoder->encoder; GroovePlaylistItem *item; double pos; groove_encoder_position(encoder, &item, &pos); Local<Object> obj = Object::New(); obj->Set(String::NewSymbol("pos"), Number::New(pos)); if (item) { obj->Set(String::NewSymbol("item"), GNPlaylistItem::NewInstance(item)); } else { obj->Set(String::NewSymbol("item"), Null()); } return scope.Close(obj); } <commit_msg>fix segfault when detaching and re-attaching an encoder<commit_after>#include <node.h> #include <node_buffer.h> #include "gn_encoder.h" #include "gn_playlist.h" #include "gn_playlist_item.h" using namespace v8; GNEncoder::GNEncoder() {}; GNEncoder::~GNEncoder() { groove_encoder_destroy(encoder); delete event_context; }; Persistent<Function> GNEncoder::constructor; template <typename target_t, typename func_t> static void AddMethod(target_t tpl, const char* name, func_t fn) { tpl->PrototypeTemplate()->Set(String::NewSymbol(name), FunctionTemplate::New(fn)->GetFunction()); } void GNEncoder::Init() { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("GrooveEncoder")); tpl->InstanceTemplate()->SetInternalFieldCount(2); // Methods AddMethod(tpl, "attach", Attach); AddMethod(tpl, "detach", Detach); AddMethod(tpl, "getBuffer", GetBuffer); AddMethod(tpl, "position", Position); constructor = Persistent<Function>::New(tpl->GetFunction()); } Handle<Value> GNEncoder::New(const Arguments& args) { HandleScope scope; GNEncoder *obj = new GNEncoder(); obj->Wrap(args.This()); return scope.Close(args.This()); } Handle<Value> GNEncoder::NewInstance(GrooveEncoder *encoder) { HandleScope scope; Local<Object> instance = constructor->NewInstance(); GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(instance); gn_encoder->encoder = encoder; return scope.Close(instance); } struct AttachReq { uv_work_t req; Persistent<Function> callback; GrooveEncoder *encoder; GroovePlaylist *playlist; int errcode; Persistent<Object> instance; String::Utf8Value *format_short_name; String::Utf8Value *codec_short_name; String::Utf8Value *filename; String::Utf8Value *mime_type; GNEncoder::EventContext *event_context; }; static void EventAsyncCb(uv_async_t *handle, int status) { HandleScope scope; GNEncoder::EventContext *context = reinterpret_cast<GNEncoder::EventContext *>(handle->data); const unsigned argc = 1; Handle<Value> argv[argc]; argv[0] = Undefined(); TryCatch try_catch; context->event_cb->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } uv_cond_signal(&context->cond); } static void EventThreadEntry(void *arg) { GNEncoder::EventContext *context = reinterpret_cast<GNEncoder::EventContext *>(arg); while (groove_encoder_buffer_peek(context->encoder, 1) > 0) { uv_async_send(&context->event_async); uv_mutex_lock(&context->mutex); uv_cond_wait(&context->cond, &context->mutex); uv_mutex_unlock(&context->mutex); } } static void AttachAsync(uv_work_t *req) { AttachReq *r = reinterpret_cast<AttachReq *>(req->data); r->encoder->format_short_name = r->format_short_name ? **r->format_short_name : NULL; r->encoder->codec_short_name = r->codec_short_name ? **r->codec_short_name : NULL; r->encoder->filename = r->filename ? **r->filename : NULL; r->encoder->mime_type = r->mime_type ? **r->mime_type : NULL; r->errcode = groove_encoder_attach(r->encoder, r->playlist); if (r->format_short_name) { delete r->format_short_name; r->format_short_name = NULL; } if (r->codec_short_name) { delete r->codec_short_name; r->codec_short_name = NULL; } if (r->filename) { delete r->filename; r->filename = NULL; } if (r->mime_type) { delete r->mime_type; r->mime_type = NULL; } GNEncoder::EventContext *context = r->event_context; uv_cond_init(&context->cond); uv_mutex_init(&context->mutex); uv_async_init(uv_default_loop(), &context->event_async, EventAsyncCb); context->event_async.data = context; uv_thread_create(&context->event_thread, EventThreadEntry, context); } static void AttachAfter(uv_work_t *req) { HandleScope scope; AttachReq *r = reinterpret_cast<AttachReq *>(req->data); const unsigned argc = 1; Handle<Value> argv[argc]; if (r->errcode < 0) { argv[0] = Exception::Error(String::New("encoder attach failed")); } else { argv[0] = Null(); Local<Object> actualAudioFormat = Object::New(); actualAudioFormat->Set(String::NewSymbol("sampleRate"), Number::New(r->encoder->actual_audio_format.sample_rate)); actualAudioFormat->Set(String::NewSymbol("channelLayout"), Number::New(r->encoder->actual_audio_format.channel_layout)); actualAudioFormat->Set(String::NewSymbol("sampleFormat"), Number::New(r->encoder->actual_audio_format.sample_fmt)); r->instance->Set(String::NewSymbol("actualAudioFormat"), actualAudioFormat); } TryCatch try_catch; r->callback->Call(Context::GetCurrent()->Global(), argc, argv); delete r; if (try_catch.HasCaught()) { node::FatalException(try_catch); } } Handle<Value> GNEncoder::Create(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Expected function arg[0]"))); return scope.Close(Undefined()); } GrooveEncoder *encoder = groove_encoder_create(); Handle<Object> instance = NewInstance(encoder)->ToObject(); GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(instance); EventContext *context = new EventContext; gn_encoder->event_context = context; context->event_cb = Persistent<Function>::New(Local<Function>::Cast(args[0])); context->encoder = encoder; // set properties on the instance with default values from // GrooveEncoder struct Local<Object> targetAudioFormat = Object::New(); targetAudioFormat->Set(String::NewSymbol("sampleRate"), Number::New(encoder->target_audio_format.sample_rate)); targetAudioFormat->Set(String::NewSymbol("channelLayout"), Number::New(encoder->target_audio_format.channel_layout)); targetAudioFormat->Set(String::NewSymbol("sampleFormat"), Number::New(encoder->target_audio_format.sample_fmt)); instance->Set(String::NewSymbol("bitRate"), Number::New(encoder->bit_rate)); instance->Set(String::NewSymbol("actualAudioFormat"), Null()); instance->Set(String::NewSymbol("targetAudioFormat"), targetAudioFormat); instance->Set(String::NewSymbol("formatShortName"), Null()); instance->Set(String::NewSymbol("codecShortName"), Null()); instance->Set(String::NewSymbol("filename"), Null()); instance->Set(String::NewSymbol("mimeType"), Null()); return scope.Close(instance); } Handle<Value> GNEncoder::Attach(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); if (args.Length() < 1 || !args[0]->IsObject()) { ThrowException(Exception::TypeError(String::New("Expected object arg[0]"))); return scope.Close(Undefined()); } if (args.Length() < 2 || !args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Expected function arg[1]"))); return scope.Close(Undefined()); } Local<Object> instance = args.This(); Local<Value> targetAudioFormatValue = instance->Get(String::NewSymbol("targetAudioFormat")); if (!targetAudioFormatValue->IsObject()) { ThrowException(Exception::TypeError(String::New("Expected targetAudioFormat to be an object"))); return scope.Close(Undefined()); } GNPlaylist *gn_playlist = node::ObjectWrap::Unwrap<GNPlaylist>(args[0]->ToObject()); AttachReq *request = new AttachReq; request->req.data = request; request->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); request->instance = Persistent<Object>::New(args.This()); request->playlist = gn_playlist->playlist; request->event_context = gn_encoder->event_context; GrooveEncoder *encoder = gn_encoder->encoder; request->encoder = encoder; // copy the properties from our instance to the encoder Local<Value> formatShortName = instance->Get(String::NewSymbol("formatShortName")); if (formatShortName->IsNull() || formatShortName->IsUndefined()) { request->format_short_name = NULL; } else { request->format_short_name = new String::Utf8Value(formatShortName->ToString()); } Local<Value> codecShortName = instance->Get(String::NewSymbol("codecShortName")); if (codecShortName->IsNull() || codecShortName->IsUndefined()) { request->codec_short_name = NULL; } else { request->codec_short_name = new String::Utf8Value(codecShortName->ToString()); } Local<Value> filenameStr = instance->Get(String::NewSymbol("filename")); if (filenameStr->IsNull() || filenameStr->IsUndefined()) { request->filename = NULL; } else { request->filename = new String::Utf8Value(filenameStr->ToString()); } Local<Value> mimeType = instance->Get(String::NewSymbol("mimeType")); if (mimeType->IsNull() || mimeType->IsUndefined()) { request->mime_type = NULL; } else { request->mime_type = new String::Utf8Value(mimeType->ToString()); } Local<Object> targetAudioFormat = targetAudioFormatValue->ToObject(); Local<Value> sampleRate = targetAudioFormat->Get(String::NewSymbol("sampleRate")); double sample_rate = sampleRate->NumberValue(); double channel_layout = targetAudioFormat->Get(String::NewSymbol("channelLayout"))->NumberValue(); double sample_fmt = targetAudioFormat->Get(String::NewSymbol("sampleFormat"))->NumberValue(); encoder->target_audio_format.sample_rate = (int)sample_rate; encoder->target_audio_format.channel_layout = (int)channel_layout; encoder->target_audio_format.sample_fmt = (enum GrooveSampleFormat)(int)sample_fmt; double bit_rate = instance->Get(String::NewSymbol("bitRate"))->NumberValue(); encoder->bit_rate = (int)bit_rate; uv_queue_work(uv_default_loop(), &request->req, AttachAsync, (uv_after_work_cb)AttachAfter); return scope.Close(Undefined()); } struct DetachReq { uv_work_t req; GrooveEncoder *encoder; Persistent<Function> callback; int errcode; GNEncoder::EventContext *event_context; }; static void DetachAsyncFree(uv_handle_t *handle) { } static void DetachAsync(uv_work_t *req) { DetachReq *r = reinterpret_cast<DetachReq *>(req->data); r->errcode = groove_encoder_detach(r->encoder); uv_cond_signal(&r->event_context->cond); uv_thread_join(&r->event_context->event_thread); uv_cond_destroy(&r->event_context->cond); uv_mutex_destroy(&r->event_context->mutex); uv_close(reinterpret_cast<uv_handle_t*>(&r->event_context->event_async), DetachAsyncFree); } static void DetachAfter(uv_work_t *req) { HandleScope scope; DetachReq *r = reinterpret_cast<DetachReq *>(req->data); const unsigned argc = 1; Handle<Value> argv[argc]; if (r->errcode < 0) { argv[0] = Exception::Error(String::New("encoder detach failed")); } else { argv[0] = Null(); } TryCatch try_catch; r->callback->Call(Context::GetCurrent()->Global(), argc, argv); delete r; if (try_catch.HasCaught()) { node::FatalException(try_catch); } } Handle<Value> GNEncoder::Detach(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); if (args.Length() < 1 || !args[0]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Expected function arg[0]"))); return scope.Close(Undefined()); } GrooveEncoder *encoder = gn_encoder->encoder; if (!encoder->playlist) { ThrowException(Exception::Error(String::New("detach: not attached"))); return scope.Close(Undefined()); } DetachReq *request = new DetachReq; request->req.data = request; request->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); request->encoder = encoder; request->event_context = gn_encoder->event_context; uv_queue_work(uv_default_loop(), &request->req, DetachAsync, (uv_after_work_cb)DetachAfter); return scope.Close(Undefined()); } static void buffer_free(char *data, void *hint) { GrooveBuffer *buffer = reinterpret_cast<GrooveBuffer*>(hint); groove_buffer_unref(buffer); } Handle<Value> GNEncoder::GetBuffer(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); GrooveEncoder *encoder = gn_encoder->encoder; GrooveBuffer *buffer; switch (groove_encoder_buffer_get(encoder, &buffer, 0)) { case GROOVE_BUFFER_YES: { Local<Object> object = Object::New(); Handle<Object> bufferObject = node::Buffer::New( reinterpret_cast<char*>(buffer->data[0]), buffer->size, buffer_free, buffer)->handle_; object->Set(String::NewSymbol("buffer"), bufferObject); if (buffer->item) { object->Set(String::NewSymbol("item"), GNPlaylistItem::NewInstance(buffer->item)); } else { object->Set(String::NewSymbol("item"), Null()); } object->Set(String::NewSymbol("pos"), Number::New(buffer->pos)); return scope.Close(object); } case GROOVE_BUFFER_END: { Local<Object> object = Object::New(); object->Set(String::NewSymbol("buffer"), Null()); object->Set(String::NewSymbol("item"), Null()); object->Set(String::NewSymbol("pos"), Null()); return scope.Close(object); } default: return scope.Close(Null()); } } Handle<Value> GNEncoder::Position(const Arguments& args) { HandleScope scope; GNEncoder *gn_encoder = node::ObjectWrap::Unwrap<GNEncoder>(args.This()); GrooveEncoder *encoder = gn_encoder->encoder; GroovePlaylistItem *item; double pos; groove_encoder_position(encoder, &item, &pos); Local<Object> obj = Object::New(); obj->Set(String::NewSymbol("pos"), Number::New(pos)); if (item) { obj->Set(String::NewSymbol("item"), GNPlaylistItem::NewInstance(item)); } else { obj->Set(String::NewSymbol("item"), Null()); } return scope.Close(obj); } <|endoftext|>
<commit_before>////////////// // Includes // #include <SDL_image.h> #include <SDL.h> #include "rectangle.hpp" #include "sprite.hpp" #include "window.hpp" #include "game.hpp" ////////// // Code // // Entry point! int main() { Window w("Hello World!", 640, 480, false); Sprite s(w.getRenderer(), "res/test.png"); SDL_SetRenderDrawColor(w.getRenderer(), 255, 0, 255, 255); SDL_RenderClear(w.getRenderer()); Rectangle r(640 / 2 - 450 / 2, 480 / 2 - 150 / 2, 450, 150); SDL_RenderCopy(w.getRenderer(), s.getTexture(), nullptr, &r.sdlRect); SDL_RenderPresent(w.getRenderer()); SDL_Event e; while (SDL_WaitEvent(&e)) { if (e.type == SDL_QUIT) break; } return 0; } <commit_msg>Made the thing use the assets object.<commit_after>////////////// // Includes // #include <SDL_image.h> #include <SDL.h> #include "rectangle.hpp" #include "sprite.hpp" #include "window.hpp" #include "game.hpp" ////////// // Code // // The assets! void initAssets(Assets& a) { a.addAssetLoad("res/test.png", HC_SPRITE_ASSET); } // Entry point! int main() { // Opening the window. Window w("Hello World!", 640, 480, false); // Loading and initializing assets. Assets a; initAssets(a); a.performLoads(w); SDL_SetRenderDrawColor(w.getRenderer(), 255, 0, 255, 255); SDL_RenderClear(w.getRenderer()); Rectangle r(640 / 2 - 450 / 2, 480 / 2 - 150 / 2, 450, 150); SDL_RenderCopy(w.getRenderer(), a.getSprite("res/test.png").getTexture(), nullptr, &r.sdlRect); SDL_RenderPresent(w.getRenderer()); SDL_Event e; while (SDL_WaitEvent(&e)) { if (e.type == SDL_QUIT) break; } return 0; } <|endoftext|>
<commit_before>#include <QFont> #include <QSettings> #include <QVariant> #include <cstdlib> #include <iostream> #include <stdexcept> extern "C" { #include <libxslt/xslt.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <libexslt/exslt.h> } #include "DactApplication.hh" namespace { void usage(char const *progname) { std::cerr << "Usage: " << progname << " [file]" << std::endl; std::exit(1); } } int main(int argc, char *argv[]) { xmlInitMemory(); xmlInitParser(); // EXSLT extensions exsltRegisterAll(); // XPath xmlXPathInit(); int r = 0; try { QCoreApplication::setOrganizationName("RUG"); QCoreApplication::setOrganizationDomain("rug.nl"); QCoreApplication::setApplicationName("Dact"); QScopedPointer<DactApplication> a(new DactApplication(argc, argv)); QSettings settings; QVariant fontValue = settings.value("appFont", qApp->font().toString()); #ifndef __APPLE__ QFont appFont; appFont.fromString(fontValue.toString()); a->setFont(appFont); #endif a->init(); QStringList corpusPaths, macroPaths; QStringList args = a->arguments(); for (int i = 1; i < args.size(); ++i) { if (args[i] == "-m") { // please do follow with a path after -m switch. if (i + 1 >= args.size()) usage(argv[0]); macroPaths.append(args[++i]); } else corpusPaths.append(args[i]); } a->openCorpora(corpusPaths); a->openMacros(macroPaths); r = a->exec(); } catch (std::logic_error const &e) { std::cerr << "dact: internal logic error: please report at\n" " https://github.com/rug-compling/dact/issues, citing" << e.what() << std::endl; r = 1; } // must be called after the DactApplication is deleted xsltCleanupGlobals(); xmlCleanupParser(); return r; } <commit_msg>Open corpora specified on the command-line.<commit_after>#include <QFont> #include <QSettings> #include <QVariant> #include <cstdlib> #include <iostream> #include <stdexcept> extern "C" { #include <libxslt/xslt.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <libexslt/exslt.h> } #include "DactApplication.hh" namespace { void usage(char const *progname) { std::cerr << "Usage: " << progname << " [file]" << std::endl; std::exit(1); } } int main(int argc, char *argv[]) { xmlInitMemory(); xmlInitParser(); // EXSLT extensions exsltRegisterAll(); // XPath xmlXPathInit(); int r = 0; try { QCoreApplication::setOrganizationName("RUG"); QCoreApplication::setOrganizationDomain("rug.nl"); QCoreApplication::setApplicationName("Dact"); QScopedPointer<DactApplication> a(new DactApplication(argc, argv)); QSettings settings; QVariant fontValue = settings.value("appFont", qApp->font().toString()); #ifndef __APPLE__ QFont appFont; appFont.fromString(fontValue.toString()); a->setFont(appFont); #endif a->init(); QStringList corpusPaths, macroPaths; QStringList args = a->arguments(); for (int i = 1; i < args.size(); ++i) { if (args[i] == "-m") { // please do follow with a path after -m switch. if (i + 1 >= args.size()) usage(argv[0]); macroPaths.append(args[++i]); } else corpusPaths.append(args[i]); } if (corpusPaths.size() != 0) a->openCorpora(corpusPaths); a->openMacros(macroPaths); r = a->exec(); } catch (std::logic_error const &e) { std::cerr << "dact: internal logic error: please report at\n" " https://github.com/rug-compling/dact/issues, citing" << e.what() << std::endl; r = 1; } // must be called after the DactApplication is deleted xsltCleanupGlobals(); xmlCleanupParser(); return r; } <|endoftext|>
<commit_before> // // SlicerSnake // main.cpp // https://github.com/adisib // #include <cstdlib> // srand #include <ctime> // srand(time(NULL)) #include "display.h" #include "game.h" // Allows the player to select a game mode ssnake::Game_t gameSelectMenu(ssnake::Display* display, ssnake::PlayerInput& input); int main() { // std::srand(static_cast<unsigned int>(std::time(NULL))); ssnake::Display* display = new ssnake::Display(); bool play = true; while (play) { ssnake::PlayerInput input; ssnake::SnakeGame game(display); display->clearScreen(); ssnake::Game_t gameTypeSelected = gameSelectMenu(display, input); game.startGame(gameTypeSelected); display->printTextLine(display->getSize_y() / 2 - 2, "GAME OVER"); display->printTextLine(display->getSize_y() / 2 - 1, "R: Restart | Enter: Quit"); display->update(); do { input.collectInput(-1); } while (!input.getEnter() && !input.getRestart()); if (!input.getRestart()) { play = false; } } delete display; return 0; } ssnake::Game_t gameSelectMenu(ssnake::Display* display, ssnake::PlayerInput& input) { bool initialSelect = true; ssnake::Game_t typeSelected; ssnake::DirectionalKey_t direction; display->printTextLine(7, "Arrow keys move, enter key pauses"); do { if (initialSelect) { direction = ssnake::LEFT_KEY; typeSelected = ssnake::GM_SLICER; initialSelect = false; } else { input.collectInput(-1); direction = input.getDirection(); } if (direction == ssnake::LEFT_KEY) { display->printTextLine(4, "Get as long as you can"); display->printTextLine(5, "But don't let the other snake eat you!"); typeSelected = ssnake::GM_SLICER; display->printTextLine(display->getSize_y() / 2, "[ Slicer Snake ] Classic "); display->update(); } else if (direction == ssnake::RIGHT_KEY) { display->printTextLine(4, "Classic Snake"); display->printTextLine(5, "Get the food but don't hit yourself!"); typeSelected = ssnake::GM_CLASSIC; display->printTextLine(display->getSize_y() / 2, " Slicer Snake [ Classic ]"); display->update(); } } while (!input.getEnter() && !input.getQuit()); return typeSelected; } <commit_msg>Set display size explicitly<commit_after> // // SlicerSnake // main.cpp // https://github.com/adisib // #include <cstdlib> // srand #include <ctime> // srand(time(NULL)) #include "display.h" #include "game.h" // Allows the player to select a game mode ssnake::Game_t gameSelectMenu(ssnake::Display* display, ssnake::PlayerInput& input); int main() { // std::srand(static_cast<unsigned int>(std::time(NULL))); ssnake::Display* display = new ssnake::Display(27, 30); bool play = true; while (play) { ssnake::PlayerInput input; ssnake::SnakeGame game(display); display->clearScreen(); ssnake::Game_t gameTypeSelected = gameSelectMenu(display, input); game.startGame(gameTypeSelected); display->printTextLine(display->getSize_y() / 2 - 2, "GAME OVER"); display->printTextLine(display->getSize_y() / 2 - 1, "R: Restart | Enter: Quit"); display->update(); do { input.collectInput(-1); } while (!input.getEnter() && !input.getRestart()); if (!input.getRestart()) { play = false; } } delete display; return 0; } ssnake::Game_t gameSelectMenu(ssnake::Display* display, ssnake::PlayerInput& input) { bool initialSelect = true; ssnake::Game_t typeSelected; ssnake::DirectionalKey_t direction; display->printTextLine(7, "Arrow keys move, enter key pauses"); do { if (initialSelect) { direction = ssnake::LEFT_KEY; typeSelected = ssnake::GM_SLICER; initialSelect = false; } else { input.collectInput(-1); direction = input.getDirection(); } if (direction == ssnake::LEFT_KEY) { display->printTextLine(4, "Get as long as you can"); display->printTextLine(5, "But don't let the other snake eat you!"); typeSelected = ssnake::GM_SLICER; display->printTextLine(display->getSize_y() / 2, "[ Slicer Snake ] Classic "); display->update(); } else if (direction == ssnake::RIGHT_KEY) { display->printTextLine(4, "Classic Snake"); display->printTextLine(5, "Get the food but don't hit yourself!"); typeSelected = ssnake::GM_CLASSIC; display->printTextLine(display->getSize_y() / 2, " Slicer Snake [ Classic ]"); display->update(); } } while (!input.getEnter() && !input.getQuit()); return typeSelected; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.1 1999/12/17 22:24:03 rahulj * Added missing UnixWare files to the repository. * * Created by Ron Record (rr@sco.com) based on SolarisDefs * 13-Nov-1999 */ // --------------------------------------------------------------------------- // UnixWare runs in little endian mode // --------------------------------------------------------------------------- #define ENDIANMODE_LITTLW typedef void* FileHandle; #ifndef UNIXWARE #define UNIXWARE #endif <commit_msg>Fixed the typo in Little endian #define.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.2 1999/12/17 23:31:29 rahulj * Fixed the typo in Little endian #define. * * Revision 1.1 1999/12/17 22:24:03 rahulj * Added missing UnixWare files to the repository. * * Created by Ron Record (rr@sco.com) based on SolarisDefs * 13-Nov-1999 */ // --------------------------------------------------------------------------- // UnixWare runs in little endian mode // --------------------------------------------------------------------------- #define ENDIANMODE_LITTLE typedef void* FileHandle; #ifndef UNIXWARE #define UNIXWARE #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/idriver_ui_adapter.h" #include "common/software_texture.h" #include "common/texture_load.h" #include "common/software_mesh.h" #include "common/mesh_load.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/json_structure.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Make an isometric camera. auto cam = gfx::make_isometric_camera(); use_camera(driver, cam); // Build our main mesh using our flat terrain. auto terrain_obj = gfx::Object{}; make_terrain_mesh(*terrain_obj.mesh, make_flat_terrain(0, 25, 25), .01, 1); terrain_obj.material->diffuse_color = colors::white; load_png("tex/grass.png", *terrain_obj.material->texture); terrain_obj.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(-12.5, 0.0, -12.5)); prepare_object(driver, terrain_obj); // Load our house structure auto house_struct = Json_Structure{"structure/house.json"}; // This is code smell, right here. The fact that before, we were preparing // a temporary but it still worked because of the implementation of // Json_Structure and the object sharing mechanism. auto house_obj = house_struct.make_obj(); prepare_object(driver, house_obj); std::vector<Structure_Instance> house_instances; Structure_Instance moveable_instance{house_struct, Orient::N}; int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_button")->add_click_listener([](auto const& pt) { log_i("BUILD!"); }); hud->layout(driver.window_extents()); controller.add_click_listener([&](auto const&) { // Commit the current position of our moveable instance. house_instances.push_back(moveable_instance); }); controller.add_hover_listener([&](auto const& pt) { if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0) { moveable_instance.obj.model_matrix = glm::mat4(1.0); } else { // Find our depth. GLfloat z; glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); // Unproject our depth. auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z), camera_view_matrix(cam), camera_proj_matrix(cam), glm::vec4(0.0, 0.0, 1000.0, 1000.0)); // We have our position, render a single house there. moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val); } // Move the house by however much the structure *type* requires. moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix * house_struct.make_obj().model_matrix; }); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); render_object(driver, terrain_obj); // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); // Render our movable instance of a house. render_object(driver, moveable_instance.obj); // Render all of our other house instances. for(auto const& instance : house_instances) { render_object(driver, instance.obj); } { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } } } glfwTerminate(); return 0; } <commit_msg>Added a function to log some opengl stats.<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/idriver_ui_adapter.h" #include "common/software_texture.h" #include "common/texture_load.h" #include "common/software_mesh.h" #include "common/mesh_load.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/json_structure.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Make an isometric camera. auto cam = gfx::make_isometric_camera(); use_camera(driver, cam); // Build our main mesh using our flat terrain. auto terrain_obj = gfx::Object{}; make_terrain_mesh(*terrain_obj.mesh, make_flat_terrain(0, 25, 25), .01, 1); terrain_obj.material->diffuse_color = colors::white; load_png("tex/grass.png", *terrain_obj.material->texture); terrain_obj.model_matrix = glm::translate(glm::mat4(1.0), glm::vec3(-12.5, 0.0, -12.5)); prepare_object(driver, terrain_obj); // Load our house structure auto house_struct = Json_Structure{"structure/house.json"}; // This is code smell, right here. The fact that before, we were preparing // a temporary but it still worked because of the implementation of // Json_Structure and the object sharing mechanism. auto house_obj = house_struct.make_obj(); prepare_object(driver, house_obj); std::vector<Structure_Instance> house_instances; Structure_Instance moveable_instance{house_struct, Orient::N}; int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_button")->add_click_listener([](auto const& pt) { log_i("BUILD!"); }); hud->layout(driver.window_extents()); controller.add_click_listener([&](auto const&) { // Commit the current position of our moveable instance. house_instances.push_back(moveable_instance); }); controller.add_hover_listener([&](auto const& pt) { if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0) { moveable_instance.obj.model_matrix = glm::mat4(1.0); } else { // Find our depth. GLfloat z; glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); // Unproject our depth. auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z), camera_view_matrix(cam), camera_proj_matrix(cam), glm::vec4(0.0, 0.0, 1000.0, 1000.0)); // We have our position, render a single house there. moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val); } // Move the house by however much the structure *type* requires. moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix * house_struct.make_obj().model_matrix; }); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); render_object(driver, terrain_obj); // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); // Render our movable instance of a house. render_object(driver, moveable_instance.obj); // Render all of our other house instances. for(auto const& instance : house_instances) { render_object(driver, instance.obj); } { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#pragma once namespace gsl { template<typename T> using owner = T; } // namespace gsl <commit_msg>dead code<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <getopt.h> #include <string> #include <vector> #include "sequence.hpp" #include "polisher.hpp" #ifdef CUDA_ENABLED #include "cuda/cudapolisher.hpp" #endif static const char* version = "v1.4.0"; static const int32_t CUDAALIGNER_INPUT_CODE = 10000; static struct option options[] = { {"include-unpolished", no_argument, 0, 'u'}, {"fragment-correction", no_argument, 0, 'f'}, {"window-length", required_argument, 0, 'w'}, {"quality-threshold", required_argument, 0, 'q'}, {"error-threshold", required_argument, 0, 'e'}, {"match", required_argument, 0, 'm'}, {"mismatch", required_argument, 0, 'x'}, {"gap", required_argument, 0, 'g'}, {"threads", required_argument, 0, 't'}, {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, #ifdef CUDA_ENABLED {"cudapoa-batches", optional_argument, 0, 'c'}, {"cuda-banded-alignment", no_argument, 0, 'b'}, {"cudaaligner-batches", required_argument, 0, CUDAALIGNER_INPUT_CODE}, #endif {0, 0, 0, 0} }; void help(); int main(int argc, char** argv) { std::vector<std::string> input_paths; uint32_t window_length = 500; double quality_threshold = 10.0; double error_threshold = 0.3; int8_t match = 5; int8_t mismatch = -4; int8_t gap = -8; uint32_t type = 0; bool drop_unpolished_sequences = true; uint32_t num_threads = 1; uint32_t cudapoa_batches = 0; uint32_t cudaaligner_batches = 0; bool cuda_banded_alignment = false; std::string optstring = "ufw:q:e:m:x:g:t:h"; #ifdef CUDA_ENABLED optstring += "bc::"; #endif int32_t argument; while ((argument = getopt_long(argc, argv, optstring.c_str(), options, nullptr)) != -1) { switch (argument) { case 'u': drop_unpolished_sequences = false; break; case 'f': type = 1; break; case 'w': window_length = atoi(optarg); break; case 'q': quality_threshold = atof(optarg); break; case 'e': error_threshold = atof(optarg); break; case 'm': match = atoi(optarg); break; case 'x': mismatch = atoi(optarg); break; case 'g': gap = atoi(optarg); break; case 't': num_threads = atoi(optarg); break; case 'v': printf("%s\n", version); exit(0); case 'h': help(); exit(0); #ifdef CUDA_ENABLED case 'c': //if option c encountered, cudapoa_batches initialized with a default value of 1. cudapoa_batches = 1; // next text entry is not an option, assuming it's the arg for option 'c' if (optarg == NULL && argv[optind] != NULL && argv[optind][0] != '-') { cudapoa_batches = atoi(argv[optind++]); } // optional argument provided in the ususal way if (optarg != NULL) { cudapoa_batches = atoi(optarg); } break; case 'b': cuda_banded_alignment = true; break; case CUDAALIGNER_INPUT_CODE: // cudaaligner-batches cudaaligner_batches = atoi(optarg); break; #endif default: exit(1); } } for (int32_t i = optind; i < argc; ++i) { input_paths.emplace_back(argv[i]); } if (input_paths.size() < 3) { fprintf(stderr, "[racon::] error: missing input file(s)!\n"); help(); exit(1); } auto polisher = racon::createPolisher(input_paths[0], input_paths[1], input_paths[2], type == 0 ? racon::PolisherType::kC : racon::PolisherType::kF, window_length, quality_threshold, error_threshold, match, mismatch, gap, num_threads, cudapoa_batches, cuda_banded_alignment, cudaaligner_batches); polisher->initialize(); std::vector<std::unique_ptr<racon::Sequence>> polished_sequences; polisher->polish(polished_sequences, drop_unpolished_sequences); for (const auto& it: polished_sequences) { fprintf(stdout, ">%s\n%s\n", it->name().c_str(), it->data().c_str()); } return 0; } void help() { printf( "usage: racon [options ...] <sequences> <overlaps> <target sequences>\n" "\n" " <sequences>\n" " input file in FASTA/FASTQ format (can be compressed with gzip)\n" " containing sequences used for correction\n" " <overlaps>\n" " input file in MHAP/PAF/SAM format (can be compressed with gzip)\n" " containing overlaps between sequences and target sequences\n" " <target sequences>\n" " input file in FASTA/FASTQ format (can be compressed with gzip)\n" " containing sequences which will be corrected\n" "\n" " options:\n" " -u, --include-unpolished\n" " output unpolished target sequences\n" " -f, --fragment-correction\n" " perform fragment correction instead of contig polishing\n" " (overlaps file should contain dual/self overlaps!)\n" " -w, --window-length <int>\n" " default: 500\n" " size of window on which POA is performed\n" " -q, --quality-threshold <float>\n" " default: 10.0\n" " threshold for average base quality of windows used in POA\n" " -e, --error-threshold <float>\n" " default: 0.3\n" " maximum allowed error rate used for filtering overlaps\n" " -m, --match <int>\n" " default: 5\n" " score for matching bases\n" " -x, --mismatch <int>\n" " default: -4\n" " score for mismatching bases\n" " -g, --gap <int>\n" " default: -8\n" " gap penalty (must be negative)\n" " -t, --threads <int>\n" " default: 1\n" " number of threads\n" " --version\n" " prints the version number\n" " -h, --help\n" " prints the usage\n" #ifdef CUDA_ENABLED " -c, --cudapoa-batches\n" " default: 1\n" " number of batches for CUDA accelerated polishing\n" " -b, --cuda-banded-alignment\n" " use banding approximation for alignment on GPU\n" " --cudaaligner-batches (experimental)\n" " Number of batches for CUDA accelerated alignment\n" #endif ); } <commit_msg>Bump version number<commit_after>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <getopt.h> #include <string> #include <vector> #include "sequence.hpp" #include "polisher.hpp" #ifdef CUDA_ENABLED #include "cuda/cudapolisher.hpp" #endif static const char* version = "v1.4.1"; static const int32_t CUDAALIGNER_INPUT_CODE = 10000; static struct option options[] = { {"include-unpolished", no_argument, 0, 'u'}, {"fragment-correction", no_argument, 0, 'f'}, {"window-length", required_argument, 0, 'w'}, {"quality-threshold", required_argument, 0, 'q'}, {"error-threshold", required_argument, 0, 'e'}, {"match", required_argument, 0, 'm'}, {"mismatch", required_argument, 0, 'x'}, {"gap", required_argument, 0, 'g'}, {"threads", required_argument, 0, 't'}, {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, #ifdef CUDA_ENABLED {"cudapoa-batches", optional_argument, 0, 'c'}, {"cuda-banded-alignment", no_argument, 0, 'b'}, {"cudaaligner-batches", required_argument, 0, CUDAALIGNER_INPUT_CODE}, #endif {0, 0, 0, 0} }; void help(); int main(int argc, char** argv) { std::vector<std::string> input_paths; uint32_t window_length = 500; double quality_threshold = 10.0; double error_threshold = 0.3; int8_t match = 5; int8_t mismatch = -4; int8_t gap = -8; uint32_t type = 0; bool drop_unpolished_sequences = true; uint32_t num_threads = 1; uint32_t cudapoa_batches = 0; uint32_t cudaaligner_batches = 0; bool cuda_banded_alignment = false; std::string optstring = "ufw:q:e:m:x:g:t:h"; #ifdef CUDA_ENABLED optstring += "bc::"; #endif int32_t argument; while ((argument = getopt_long(argc, argv, optstring.c_str(), options, nullptr)) != -1) { switch (argument) { case 'u': drop_unpolished_sequences = false; break; case 'f': type = 1; break; case 'w': window_length = atoi(optarg); break; case 'q': quality_threshold = atof(optarg); break; case 'e': error_threshold = atof(optarg); break; case 'm': match = atoi(optarg); break; case 'x': mismatch = atoi(optarg); break; case 'g': gap = atoi(optarg); break; case 't': num_threads = atoi(optarg); break; case 'v': printf("%s\n", version); exit(0); case 'h': help(); exit(0); #ifdef CUDA_ENABLED case 'c': //if option c encountered, cudapoa_batches initialized with a default value of 1. cudapoa_batches = 1; // next text entry is not an option, assuming it's the arg for option 'c' if (optarg == NULL && argv[optind] != NULL && argv[optind][0] != '-') { cudapoa_batches = atoi(argv[optind++]); } // optional argument provided in the ususal way if (optarg != NULL) { cudapoa_batches = atoi(optarg); } break; case 'b': cuda_banded_alignment = true; break; case CUDAALIGNER_INPUT_CODE: // cudaaligner-batches cudaaligner_batches = atoi(optarg); break; #endif default: exit(1); } } for (int32_t i = optind; i < argc; ++i) { input_paths.emplace_back(argv[i]); } if (input_paths.size() < 3) { fprintf(stderr, "[racon::] error: missing input file(s)!\n"); help(); exit(1); } auto polisher = racon::createPolisher(input_paths[0], input_paths[1], input_paths[2], type == 0 ? racon::PolisherType::kC : racon::PolisherType::kF, window_length, quality_threshold, error_threshold, match, mismatch, gap, num_threads, cudapoa_batches, cuda_banded_alignment, cudaaligner_batches); polisher->initialize(); std::vector<std::unique_ptr<racon::Sequence>> polished_sequences; polisher->polish(polished_sequences, drop_unpolished_sequences); for (const auto& it: polished_sequences) { fprintf(stdout, ">%s\n%s\n", it->name().c_str(), it->data().c_str()); } return 0; } void help() { printf( "usage: racon [options ...] <sequences> <overlaps> <target sequences>\n" "\n" " <sequences>\n" " input file in FASTA/FASTQ format (can be compressed with gzip)\n" " containing sequences used for correction\n" " <overlaps>\n" " input file in MHAP/PAF/SAM format (can be compressed with gzip)\n" " containing overlaps between sequences and target sequences\n" " <target sequences>\n" " input file in FASTA/FASTQ format (can be compressed with gzip)\n" " containing sequences which will be corrected\n" "\n" " options:\n" " -u, --include-unpolished\n" " output unpolished target sequences\n" " -f, --fragment-correction\n" " perform fragment correction instead of contig polishing\n" " (overlaps file should contain dual/self overlaps!)\n" " -w, --window-length <int>\n" " default: 500\n" " size of window on which POA is performed\n" " -q, --quality-threshold <float>\n" " default: 10.0\n" " threshold for average base quality of windows used in POA\n" " -e, --error-threshold <float>\n" " default: 0.3\n" " maximum allowed error rate used for filtering overlaps\n" " -m, --match <int>\n" " default: 5\n" " score for matching bases\n" " -x, --mismatch <int>\n" " default: -4\n" " score for mismatching bases\n" " -g, --gap <int>\n" " default: -8\n" " gap penalty (must be negative)\n" " -t, --threads <int>\n" " default: 1\n" " number of threads\n" " --version\n" " prints the version number\n" " -h, --help\n" " prints the usage\n" #ifdef CUDA_ENABLED " -c, --cudapoa-batches\n" " default: 1\n" " number of batches for CUDA accelerated polishing\n" " -b, --cuda-banded-alignment\n" " use banding approximation for alignment on GPU\n" " --cudaaligner-batches (experimental)\n" " Number of batches for CUDA accelerated alignment\n" #endif ); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/form_structure.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/sha1.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/field_types.h" #include "chrome/browser/autofill/form_field.h" #include "third_party/libjingle/files/talk/xmllite/xmlelement.h" #include "webkit/glue/form_data.h" #include "webkit/glue/form_field.h" #include "webkit/glue/form_field_values.h" const char* kFormMethodGet = "get"; const char* kFormMethodPost = "post"; // XML attribute names const char* const kAttributeClientVersion = "clientversion"; const char* const kAttributeAutoFillUsed = "autofillused"; const char* const kAttributeSignature = "signature"; const char* const kAttributeFormSignature = "formsignature"; const char* const kAttributeDataPresent = "datapresent"; const char* const kXMLElementForm = "form"; const char* const kXMLElementField = "field"; const char* const kAttributeAutoFillType = "autofilltype"; namespace { static std::string Hash64Bit(const std::string& str) { std::string hash_bin = base::SHA1HashString(str); DCHECK_EQ(20U, hash_bin.length()); uint64 hash64 = (((static_cast<uint64>(hash_bin[0])) & 0xFF) << 56) | (((static_cast<uint64>(hash_bin[1])) & 0xFF) << 48) | (((static_cast<uint64>(hash_bin[2])) & 0xFF) << 40) | (((static_cast<uint64>(hash_bin[3])) & 0xFF) << 32) | (((static_cast<uint64>(hash_bin[4])) & 0xFF) << 24) | (((static_cast<uint64>(hash_bin[5])) & 0xFF) << 16) | (((static_cast<uint64>(hash_bin[6])) & 0xFF) << 8) | ((static_cast<uint64>(hash_bin[7])) & 0xFF); return Uint64ToString(hash64); } } // namespace FormStructure::FormStructure(const webkit_glue::FormFieldValues& values) : form_name_(UTF16ToUTF8(values.form_name)), source_url_(values.source_url), target_url_(values.target_url) { // Copy the form fields. std::vector<webkit_glue::FormField>::const_iterator field; for (field = values.elements.begin(); field != values.elements.end(); field++) { // Generate a unique name for this field by appending a counter to the name. string16 unique_name = field->name() + IntToString16(fields_.size() + 1); fields_.push_back(new AutoFillField(*field, unique_name)); } // Terminate the vector with a NULL item. fields_.push_back(NULL); std::string method = UTF16ToUTF8(values.method); if (method == kFormMethodPost) { method_ = POST; } else { // Either the method is 'get', or we don't know. In this case we default // to GET. method_ = GET; } } bool FormStructure::EncodeUploadRequest(bool auto_fill_used, std::string* encoded_xml) const { bool auto_fillable = IsAutoFillable(); DCHECK(auto_fillable); // Caller should've checked for search pages. if (!auto_fillable) return false; buzz::XmlElement autofill_upload(buzz::QName("autofillupload")); // Attributes for the <autofillupload> element. // // TODO(jhawkins): Work with toolbar devs to make a spec for autofill clients. // For now these values are hacked from the toolbar code. autofill_upload.SetAttr(buzz::QName(kAttributeClientVersion), "6.1.1715.1442/en (GGLL)"); autofill_upload.SetAttr(buzz::QName(kAttributeFormSignature), FormSignature()); autofill_upload.SetAttr(buzz::QName(kAttributeAutoFillUsed), auto_fill_used ? "true" : "false"); // TODO(jhawkins): Hook this up to the personal data manager. // personaldata_manager_->GetDataPresent(); autofill_upload.SetAttr(buzz::QName(kAttributeDataPresent), ""); // Add the child nodes for the form fields. for (size_t index = 0; index < field_count(); index++) { const AutoFillField* field = fields_[index]; FieldTypeSet types = field->possible_types(); for (FieldTypeSet::const_iterator type = types.begin(); type != types.end(); type++) { buzz::XmlElement *field_element = new buzz::XmlElement( buzz::QName(kXMLElementField)); field_element->SetAttr(buzz::QName(kAttributeSignature), field->FieldSignature()); field_element->SetAttr(buzz::QName(kAttributeAutoFillType), IntToString(*type)); autofill_upload.AddElement(field_element); } } // Obtain the XML structure as a string. *encoded_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; *encoded_xml += autofill_upload.Str().c_str(); return true; } void FormStructure::GetHeuristicAutoFillTypes() { has_credit_card_field_ = false; has_autofillable_field_ = false; FieldTypeMap field_type_map; GetHeuristicFieldInfo(&field_type_map); for (size_t index = 0; index < field_count(); index++) { AutoFillField* field = fields_[index]; FieldTypeMap::iterator iter = field_type_map.find(field->unique_name()); AutoFillFieldType heuristic_auto_fill_type; if (iter == field_type_map.end()) heuristic_auto_fill_type = UNKNOWN_TYPE; else heuristic_auto_fill_type = iter->second; field->set_heuristic_type(heuristic_auto_fill_type); AutoFillType autofill_type(field->type()); if (autofill_type.group() == AutoFillType::CREDIT_CARD) has_credit_card_field_ = true; if (autofill_type.field_type() != UNKNOWN_TYPE) has_autofillable_field_ = true; } } std::string FormStructure::FormSignature() const { std::string form_string = target_url_.host() + "&" + form_name_ + form_signature_field_names_; return Hash64Bit(form_string); } bool FormStructure::IsAutoFillable() const { if (fields_.size() == 0) return false; // Rule out http(s)://*/search?... // e.g. http://www.google.com/search?q=... // http://search.yahoo.com/search?p=... if (target_url_.path() == "/search") return false; // Disqualify all forms that are likely to be search boxes (like google.com). if (fields_.size() == 1) { std::string name = UTF16ToUTF8(fields_[0]->name()); if (name == "q") return false; } if (method_ == GET) return false; return true; } void FormStructure::set_possible_types(int index, const FieldTypeSet& types) { int num_fields = static_cast<int>(fields_.size()); DCHECK(index >= 0 && index < num_fields); if (index >= 0 && index < num_fields) fields_[index]->set_possible_types(types); } const AutoFillField* FormStructure::field(int index) const { return fields_[index]; } size_t FormStructure::field_count() const { // Don't count the NULL terminator. return fields_.size() - 1; } bool FormStructure::operator!=(const FormData& form) const { // TODO(jhawkins): Is this enough to differentiate a form? if (UTF8ToUTF16(form_name_) != form.name || source_url_ != form.origin || target_url_ != form.action) { return true; } // TODO(jhawkins): Compare field names, IDs and labels once we have labels // set up. return false; } void FormStructure::GetHeuristicFieldInfo(FieldTypeMap* field_type_map) { FormFieldSet fields = FormFieldSet(this); FormFieldSet::const_iterator field; for (field = fields.begin(); field != fields.end(); field++) { bool ok = (*field)->GetFieldInfo(field_type_map); DCHECK(ok); } } <commit_msg>Fix a crash in FormStructure when parsing a form with zero fields. Use field_count() instead of directly accessing the size of |fields_| because we NULL-terminate the field vector.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/form_structure.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/sha1.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/field_types.h" #include "chrome/browser/autofill/form_field.h" #include "third_party/libjingle/files/talk/xmllite/xmlelement.h" #include "webkit/glue/form_data.h" #include "webkit/glue/form_field.h" #include "webkit/glue/form_field_values.h" const char* kFormMethodGet = "get"; const char* kFormMethodPost = "post"; // XML attribute names const char* const kAttributeClientVersion = "clientversion"; const char* const kAttributeAutoFillUsed = "autofillused"; const char* const kAttributeSignature = "signature"; const char* const kAttributeFormSignature = "formsignature"; const char* const kAttributeDataPresent = "datapresent"; const char* const kXMLElementForm = "form"; const char* const kXMLElementField = "field"; const char* const kAttributeAutoFillType = "autofilltype"; namespace { static std::string Hash64Bit(const std::string& str) { std::string hash_bin = base::SHA1HashString(str); DCHECK_EQ(20U, hash_bin.length()); uint64 hash64 = (((static_cast<uint64>(hash_bin[0])) & 0xFF) << 56) | (((static_cast<uint64>(hash_bin[1])) & 0xFF) << 48) | (((static_cast<uint64>(hash_bin[2])) & 0xFF) << 40) | (((static_cast<uint64>(hash_bin[3])) & 0xFF) << 32) | (((static_cast<uint64>(hash_bin[4])) & 0xFF) << 24) | (((static_cast<uint64>(hash_bin[5])) & 0xFF) << 16) | (((static_cast<uint64>(hash_bin[6])) & 0xFF) << 8) | ((static_cast<uint64>(hash_bin[7])) & 0xFF); return Uint64ToString(hash64); } } // namespace FormStructure::FormStructure(const webkit_glue::FormFieldValues& values) : form_name_(UTF16ToUTF8(values.form_name)), source_url_(values.source_url), target_url_(values.target_url) { // Copy the form fields. std::vector<webkit_glue::FormField>::const_iterator field; for (field = values.elements.begin(); field != values.elements.end(); field++) { // Generate a unique name for this field by appending a counter to the name. string16 unique_name = field->name() + IntToString16(fields_.size() + 1); fields_.push_back(new AutoFillField(*field, unique_name)); } // Terminate the vector with a NULL item. fields_.push_back(NULL); std::string method = UTF16ToUTF8(values.method); if (method == kFormMethodPost) { method_ = POST; } else { // Either the method is 'get', or we don't know. In this case we default // to GET. method_ = GET; } } bool FormStructure::EncodeUploadRequest(bool auto_fill_used, std::string* encoded_xml) const { bool auto_fillable = IsAutoFillable(); DCHECK(auto_fillable); // Caller should've checked for search pages. if (!auto_fillable) return false; buzz::XmlElement autofill_upload(buzz::QName("autofillupload")); // Attributes for the <autofillupload> element. // // TODO(jhawkins): Work with toolbar devs to make a spec for autofill clients. // For now these values are hacked from the toolbar code. autofill_upload.SetAttr(buzz::QName(kAttributeClientVersion), "6.1.1715.1442/en (GGLL)"); autofill_upload.SetAttr(buzz::QName(kAttributeFormSignature), FormSignature()); autofill_upload.SetAttr(buzz::QName(kAttributeAutoFillUsed), auto_fill_used ? "true" : "false"); // TODO(jhawkins): Hook this up to the personal data manager. // personaldata_manager_->GetDataPresent(); autofill_upload.SetAttr(buzz::QName(kAttributeDataPresent), ""); // Add the child nodes for the form fields. for (size_t index = 0; index < field_count(); index++) { const AutoFillField* field = fields_[index]; FieldTypeSet types = field->possible_types(); for (FieldTypeSet::const_iterator type = types.begin(); type != types.end(); type++) { buzz::XmlElement *field_element = new buzz::XmlElement( buzz::QName(kXMLElementField)); field_element->SetAttr(buzz::QName(kAttributeSignature), field->FieldSignature()); field_element->SetAttr(buzz::QName(kAttributeAutoFillType), IntToString(*type)); autofill_upload.AddElement(field_element); } } // Obtain the XML structure as a string. *encoded_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; *encoded_xml += autofill_upload.Str().c_str(); return true; } void FormStructure::GetHeuristicAutoFillTypes() { has_credit_card_field_ = false; has_autofillable_field_ = false; FieldTypeMap field_type_map; GetHeuristicFieldInfo(&field_type_map); for (size_t index = 0; index < field_count(); index++) { AutoFillField* field = fields_[index]; FieldTypeMap::iterator iter = field_type_map.find(field->unique_name()); AutoFillFieldType heuristic_auto_fill_type; if (iter == field_type_map.end()) heuristic_auto_fill_type = UNKNOWN_TYPE; else heuristic_auto_fill_type = iter->second; field->set_heuristic_type(heuristic_auto_fill_type); AutoFillType autofill_type(field->type()); if (autofill_type.group() == AutoFillType::CREDIT_CARD) has_credit_card_field_ = true; if (autofill_type.field_type() != UNKNOWN_TYPE) has_autofillable_field_ = true; } } std::string FormStructure::FormSignature() const { std::string form_string = target_url_.host() + "&" + form_name_ + form_signature_field_names_; return Hash64Bit(form_string); } bool FormStructure::IsAutoFillable() const { if (field_count() == 0) return false; // Rule out http(s)://*/search?... // e.g. http://www.google.com/search?q=... // http://search.yahoo.com/search?p=... if (target_url_.path() == "/search") return false; // Disqualify all forms that are likely to be search boxes (like google.com). if (field_count() == 1) { std::string name = UTF16ToUTF8(fields_[0]->name()); if (name == "q") return false; } if (method_ == GET) return false; return true; } void FormStructure::set_possible_types(int index, const FieldTypeSet& types) { int num_fields = static_cast<int>(field_count()); DCHECK(index >= 0 && index < num_fields); if (index >= 0 && index < num_fields) fields_[index]->set_possible_types(types); } const AutoFillField* FormStructure::field(int index) const { return fields_[index]; } size_t FormStructure::field_count() const { // Don't count the NULL terminator. size_t field_size = fields_.size(); return (field_size == 0) ? 0 : field_size - 1; } bool FormStructure::operator!=(const FormData& form) const { // TODO(jhawkins): Is this enough to differentiate a form? if (UTF8ToUTF16(form_name_) != form.name || source_url_ != form.origin || target_url_ != form.action) { return true; } // TODO(jhawkins): Compare field names, IDs and labels once we have labels // set up. return false; } void FormStructure::GetHeuristicFieldInfo(FieldTypeMap* field_type_map) { FormFieldSet fields = FormFieldSet(this); FormFieldSet::const_iterator field; for (field = fields.begin(); field != fields.end(); field++) { bool ok = (*field)->GetFieldInfo(field_type_map); DCHECK(ok); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ * $Log$ * Revision 1.4 2002/11/22 14:25:59 tng * Got a number of compilation erros for those non-ANSI C++ compliant compiler like xlC v3. * Since the previous fix is just for fixing a "warning", I think it doesn't worth to break users who * are not ANSI C++ ready yet. * * Revision 1.3 2002/11/21 15:45:34 gareth * gcc 3.2 now issues a warning for use of iostream.h. Removed the .h and prefixed cout with std::. * * Revision 1.2 2002/11/04 15:00:21 tng * C++ Namespace Support. * * Revision 1.1 2002/05/28 22:40:46 peiyongz * DOM3 Save Interface: DOMWriter/DOMWriterFilter * */ #include <xercesc/framework/StdOutFormatTarget.hpp> #include <iostream.h> XERCES_CPP_NAMESPACE_BEGIN StdOutFormatTarget::StdOutFormatTarget() {} StdOutFormatTarget::~StdOutFormatTarget() {} void StdOutFormatTarget::writeChars(const XMLByte* const toWrite , const unsigned int count , XMLFormatter* const formatter) { // Surprisingly, Solaris was the only platform on which // required the char* cast to print out the string correctly. // Without the cast, it was printing the pointer value in hex. // Quite annoying, considering every other platform printed // the string with the explicit cast to char* below. cout.write((char *) toWrite, (int) count); } XERCES_CPP_NAMESPACE_END <commit_msg>[Bug 15427] DOMWriter dose not flush the output stream.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ * $Log$ * Revision 1.5 2003/01/09 18:58:29 tng * [Bug 15427] DOMWriter dose not flush the output stream. * * Revision 1.4 2002/11/22 14:25:59 tng * Got a number of compilation erros for those non-ANSI C++ compliant compiler like xlC v3. * Since the previous fix is just for fixing a "warning", I think it doesn't worth to break users who * are not ANSI C++ ready yet. * * Revision 1.3 2002/11/21 15:45:34 gareth * gcc 3.2 now issues a warning for use of iostream.h. Removed the .h and prefixed cout with std::. * * Revision 1.2 2002/11/04 15:00:21 tng * C++ Namespace Support. * * Revision 1.1 2002/05/28 22:40:46 peiyongz * DOM3 Save Interface: DOMWriter/DOMWriterFilter * */ #include <xercesc/framework/StdOutFormatTarget.hpp> #include <iostream.h> XERCES_CPP_NAMESPACE_BEGIN StdOutFormatTarget::StdOutFormatTarget() {} StdOutFormatTarget::~StdOutFormatTarget() {} void StdOutFormatTarget::writeChars(const XMLByte* const toWrite , const unsigned int count , XMLFormatter* const formatter) { // Surprisingly, Solaris was the only platform on which // required the char* cast to print out the string correctly. // Without the cast, it was printing the pointer value in hex. // Quite annoying, considering every other platform printed // the string with the explicit cast to char* below. cout.write((char *) toWrite, (int) count); cout.flush(); } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>/** * Name: Rebecca Hom * This is the main file that will be used to run the rshell. * Tests the system calls * * */ #include "rshell.h" #include <iostream> #include <string> using namespace std; int main(int arc, char* argv[]) { Rshell rshell = Rshell(); // Initial variables for taking in commands string input = ""; vector<string> inputs; // Gets the command(s) from user input until exit while(input != "exit") { cout << "$ "; getline(cin, input); rshell.removeSpace(input); // Removes whitespace from input string rshell.convertCommands(input, inputs); inputs.clear(); } return 0; } <commit_msg>added a test that looks at the vector of inputs/commands<commit_after>/** * Name: Rebecca Hom * This is the main file that will be used to run the rshell. * Tests the system calls * * */ #include "rshell.h" #include <iostream> #include <string> using namespace std; int main(int arc, char* argv[]) { Rshell rshell = Rshell(); // Initial variables for taking in commands string input = ""; vector<string> inputs; // Gets the command(s) from user input until exit while(input != "exit") { cout << "$ "; getline(cin, input); rshell.removeSpace(input); // Removes whitespace from input string rshell.convertCommands(input, inputs); // Gets all commands // Shows all of the inputs for(unsigned i = 0; i < inputs.size(); ++i) { cout << "Command" << i + 1 << inputs.at(i) << endl; } inputs.clear(); // Clears the commands in the vector } return 0; } <|endoftext|>
<commit_before>#include "stdsneezy.h" #include "obj_vehicle.h" #include "pathfinder.h" #include "obj_casino_chip.h" #include "games.h" int trolleyBoatCaptain(TBeing *, cmdTypeT cmd, const char *, TMonster *myself, TObj *) { const int trolleynum=15344; static int timer; TObj *trolley=NULL; int *job=NULL; int i; TVehicle *vehicle=NULL; TPathFinder path; path.setUsePortals(false); path.setThruDoors(true); if(cmd != CMD_GENERIC_PULSE) return FALSE; // find the trolley for(TObjIter iter=object_list.begin();iter!=object_list.end();++iter){ if((*iter)->objVnum() == trolleynum){ trolley=*iter; break; } } if(!trolley){ return FALSE; } if(!(vehicle=dynamic_cast<TVehicle *>(trolley))){ vlogf(LOG_BUG, "couldn't cast trolley to vehicle!"); return FALSE; } if(!has_key(myself, vehicle->getPortalKey())){ return FALSE; } if((--timer)>0) return FALSE; // ok, let's sail // first, get out action pointer, which tells us which way to go if (!myself->act_ptr) { if (!(myself->act_ptr = new int)) { perror("failed new of fishing trolley."); exit(0); } job = static_cast<int *>(myself->act_ptr); *job=1303; } else { job = static_cast<int *>(myself->act_ptr); } if(trolley->in_room == *job){ myself->doDrive("stop"); if(*job==100){ myself->doSay("Grimhaven stop, Grimhaven. Trolley will be departing for Brightmoon shortly."); *job=1303; } else { myself->doSay("Passengers, we have arrived in Brightmoon."); myself->doSay("If you're not heading for Grimhaven, then you'd better get off now."); *job=100; } timer=100; return TRUE; } int j; for(j=0;trolley_path[j].cur_room!=trolley->in_room;++j){ if(trolley_path[j].cur_room==-1){ vlogf(LOG_BUG, "fishing trolley jumped the tracks!"); return FALSE; } } if(*job==100){ i=rev_dir[trolley_path[j].direction]; } else { i=trolley_path[j+1].direction; } switch(::number(0,80)){ case 0: myself->doSay("Those damn cyclopses better stay off the tracks!"); break; case 1: myself->doSay("Keep your limbs inside the trolley please, unless you want to lose them."); break; case 2: myself->doAction("", CMD_YAWN); break; case 3: myself->doSay("Hold on a minute buddy, how many eyes do you have?"); myself->doAction("", CMD_PEER); myself->doSay("Oh, ok. You're fine."); break; case 4: myself->doEmote("hums a sea shanty."); break; } if(vehicle->getDir() != i) myself->doDrive(dirs[i]); myself->doDrive("fast"); return TRUE; } int fishingBoatCaptain(TBeing *, cmdTypeT cmd, const char *, TMonster *myself, TObj *) { const int cockpit=15349; const int boatnum=15345; static int timer; TObj *boat=NULL; TRoom *boatroom=real_roomp(cockpit); int *job=NULL; int i; TThing *tt; TVehicle *vehicle=NULL; TPathFinder path; path.setUsePortals(false); path.setThruDoors(false); if(cmd != CMD_GENERIC_PULSE) return FALSE; // find the boat for(TObjIter iter=object_list.begin();iter!=object_list.end();++iter){ if((*iter)->objVnum() == boatnum) break; } if(!boat) return FALSE; if(!(vehicle=dynamic_cast<TVehicle *>(boat))){ vlogf(LOG_BUG, "couldn't cast boat to vehicle!"); return FALSE; } if(!has_key(myself, vehicle->getPortalKey())){ return FALSE; } // wait until we have passengers before we leave the docks if(boat->in_room == 15150 && timer<=0 && vehicle->getSpeed()==0){ for(tt=boatroom->getStuff();tt;tt=tt->nextThing){ if(dynamic_cast<TPerson *>(tt)) break; } if(!tt) return FALSE; else timer=50; } if(timer == 40){ myself->doEmote("begins making preparations to leave port."); } else if(timer == 30){ myself->doSay("Crew, prepare to leave port!"); } else if(timer == 20){ myself->doSay("Passengers, we will be sailing soon."); myself->doSay("Please get your luggage and companions on board."); } else if(timer == 10){ myself->doSay("Last call for boarding, we will be departing shortly!"); } else if(timer == 1){ myself->doSay("Cast off the lines and push us away from dock!"); } if((--timer)>0) return FALSE; // ok, let's sail // first, get out action pointer, which tells us which way to go if (!myself->act_ptr) { if (!(myself->act_ptr = new int)) { perror("failed new of fishing boat."); exit(0); } job = static_cast<int *>(myself->act_ptr); *job=13108; } else { job = static_cast<int *>(myself->act_ptr); } if(boat->in_room == *job){ myself->doDrive("stop"); myself->doSay("Crew, pull us in to dock and hold her steady."); myself->doSay("Passengers, feel free to stick around for another sail."); if(*job==15150){ *job=13108; } else { timer=50; *job=15150; } return TRUE; } i=path.findPath(boat->in_room, findRoom(*job)); if(i==DIR_NONE){ vlogf(LOG_BUG, "fishing boat lost"); return FALSE; } switch(::number(0,99)){ case 0: myself->doEmote("whistles a sea shanty."); break; case 1: myself->doSay("Sailor, get over here and swab this deck!"); break; case 2: myself->doSay("Uh oh! I think I see a pirate sail!"); myself->doAction("", CMD_CHORTLE); myself->doSay("Just joking."); break; case 3: myself->doSay("So how's the fishing today?"); break; case 4: myself->doEmote("hums a sea shanty."); break; } if(vehicle->getDir() != i) myself->doDrive(dirs[i]); myself->doDrive("20"); return TRUE; } int casinoElevatorOperator(TBeing *, cmdTypeT cmd, const char *, TMonster *myself, TObj *) { const int elevatornum=2360; static int timer; TObj *elevator=NULL; int *job=NULL; int i; TVehicle *vehicle=NULL; TPathFinder path; path.setUsePortals(false); path.setThruDoors(false); if (cmd == CMD_GENERIC_DESTROYED) { delete static_cast<int *>(myself->act_ptr); myself->act_ptr = NULL; return FALSE; } if(cmd != CMD_GENERIC_PULSE) return FALSE; // find the elevator for(TObjIter iter=object_list.begin();iter!=object_list.end();++iter){ if((*iter)->objVnum() == elevatornum){ elevator=*iter; break; } } if(!elevator) return FALSE; if(!(vehicle=dynamic_cast<TVehicle *>(elevator))){ vlogf(LOG_BUG, "couldn't cast elevator to vehicle!"); return FALSE; } if(!has_key(myself, vehicle->getPortalKey())){ return FALSE; } if((--timer)>0) return FALSE; // first, get out action pointer, which tells us which way to go if (!myself->act_ptr) { if (!(myself->act_ptr = new int)) { perror("failed new of fishing elevator."); exit(0); } job = static_cast<int *>(myself->act_ptr); *job=2362; } else { job = static_cast<int *>(myself->act_ptr); } if(elevator->in_room == *job){ myself->doDrive("stop"); if(*job==2352){ timer=10; *job=2362; } else { timer=10; *job=2352; } return TRUE; } i=path.findPath(elevator->in_room, findRoom(*job)); if(i==DIR_NONE){ if(elevator->in_room==2374) i=DIR_UP; else if(elevator->in_room==2367) i=DIR_DOWN; else { vlogf(LOG_BUG, "fishing elevator lost"); return FALSE; } } if(vehicle->getDir() != i) myself->doDrive(dirs[i]); myself->doDrive("fast"); return TRUE; } int casinoElevatorGuard(TBeing *ch, cmdTypeT cmd, const char *, TMonster *myself, TObj *o) { if(cmd != CMD_ENTER && cmd != CMD_MOB_GIVEN_ITEM) return false; if(cmd == CMD_ENTER){ myself->doSay("Entering the elevator requires a 100 talen chip."); myself->doEmote("stretches out his hand expectantly."); return true; } if(!ch || !o) // something weird going on if this happens return false; if(o->objVnum() != CHIP_100){ myself->doSay("What the hell is this?"); myself->doDrop("", o); return false; } TVehicle *elevator; for(TThing *tt=myself->roomp->getStuff();tt;tt=tt->nextThing){ if((elevator=dynamic_cast<TVehicle *>(tt)) && elevator->objVnum()==2360){ myself->doSay("Thank you, enjoy your stay!"); ch->doEnter("", elevator); (*o)--; delete o; return true; } } myself->doSay("You'll have to wait for the elevator."); myself->doDrop("", o); return false; } <commit_msg>trolley, fishing boat and elevator operators now unlock and open their vehicles if needed<commit_after>#include "stdsneezy.h" #include "obj_vehicle.h" #include "pathfinder.h" #include "obj_casino_chip.h" #include "games.h" int trolleyBoatCaptain(TBeing *, cmdTypeT cmd, const char *, TMonster *myself, TObj *) { const int trolleynum=15344; static int timer; TObj *trolley=NULL; int *job=NULL; int i; TVehicle *vehicle=NULL; TPathFinder path; path.setUsePortals(false); path.setThruDoors(true); if(cmd != CMD_GENERIC_PULSE) return FALSE; // find the trolley for(TObjIter iter=object_list.begin();iter!=object_list.end();++iter){ if((*iter)->objVnum() == trolleynum){ trolley=*iter; break; } } if(!trolley){ return FALSE; } if(!(vehicle=dynamic_cast<TVehicle *>(trolley))){ vlogf(LOG_BUG, "couldn't cast trolley to vehicle!"); return FALSE; } if(!has_key(myself, vehicle->getPortalKey())){ return FALSE; } vehicle->unlockMe(myself); vehicle->openMe(myself); if((--timer)>0) return FALSE; // ok, let's sail // first, get out action pointer, which tells us which way to go if (!myself->act_ptr) { if (!(myself->act_ptr = new int)) { perror("failed new of fishing trolley."); exit(0); } job = static_cast<int *>(myself->act_ptr); *job=1303; } else { job = static_cast<int *>(myself->act_ptr); } if(trolley->in_room == *job){ myself->doDrive("stop"); if(*job==100){ myself->doSay("Grimhaven stop, Grimhaven. Trolley will be departing for Brightmoon shortly."); *job=1303; } else { myself->doSay("Passengers, we have arrived in Brightmoon."); myself->doSay("If you're not heading for Grimhaven, then you'd better get off now."); *job=100; } timer=100; return TRUE; } int j; for(j=0;trolley_path[j].cur_room!=trolley->in_room;++j){ if(trolley_path[j].cur_room==-1){ vlogf(LOG_BUG, "fishing trolley jumped the tracks!"); return FALSE; } } if(*job==100){ i=rev_dir[trolley_path[j].direction]; } else { i=trolley_path[j+1].direction; } switch(::number(0,80)){ case 0: myself->doSay("Those damn cyclopses better stay off the tracks!"); break; case 1: myself->doSay("Keep your limbs inside the trolley please, unless you want to lose them."); break; case 2: myself->doAction("", CMD_YAWN); break; case 3: myself->doSay("Hold on a minute buddy, how many eyes do you have?"); myself->doAction("", CMD_PEER); myself->doSay("Oh, ok. You're fine."); break; case 4: myself->doEmote("hums a sea shanty."); break; } if(vehicle->getDir() != i) myself->doDrive(dirs[i]); myself->doDrive("fast"); return TRUE; } int fishingBoatCaptain(TBeing *, cmdTypeT cmd, const char *, TMonster *myself, TObj *) { const int cockpit=15349; const int boatnum=15345; static int timer; TObj *boat=NULL; TRoom *boatroom=real_roomp(cockpit); int *job=NULL; int i; TThing *tt; TVehicle *vehicle=NULL; TPathFinder path; path.setUsePortals(false); path.setThruDoors(false); if(cmd != CMD_GENERIC_PULSE) return FALSE; // find the boat for(TObjIter iter=object_list.begin();iter!=object_list.end();++iter){ if((*iter)->objVnum() == boatnum) break; } if(!boat) return FALSE; if(!(vehicle=dynamic_cast<TVehicle *>(boat))){ vlogf(LOG_BUG, "couldn't cast boat to vehicle!"); return FALSE; } if(!has_key(myself, vehicle->getPortalKey())){ return FALSE; } vehicle->unlockMe(myself); vehicle->openMe(myself); // wait until we have passengers before we leave the docks if(boat->in_room == 15150 && timer<=0 && vehicle->getSpeed()==0){ for(tt=boatroom->getStuff();tt;tt=tt->nextThing){ if(dynamic_cast<TPerson *>(tt)) break; } if(!tt) return FALSE; else timer=50; } if(timer == 40){ myself->doEmote("begins making preparations to leave port."); } else if(timer == 30){ myself->doSay("Crew, prepare to leave port!"); } else if(timer == 20){ myself->doSay("Passengers, we will be sailing soon."); myself->doSay("Please get your luggage and companions on board."); } else if(timer == 10){ myself->doSay("Last call for boarding, we will be departing shortly!"); } else if(timer == 1){ myself->doSay("Cast off the lines and push us away from dock!"); } if((--timer)>0) return FALSE; // ok, let's sail // first, get out action pointer, which tells us which way to go if (!myself->act_ptr) { if (!(myself->act_ptr = new int)) { perror("failed new of fishing boat."); exit(0); } job = static_cast<int *>(myself->act_ptr); *job=13108; } else { job = static_cast<int *>(myself->act_ptr); } if(boat->in_room == *job){ myself->doDrive("stop"); myself->doSay("Crew, pull us in to dock and hold her steady."); myself->doSay("Passengers, feel free to stick around for another sail."); if(*job==15150){ *job=13108; } else { timer=50; *job=15150; } return TRUE; } i=path.findPath(boat->in_room, findRoom(*job)); if(i==DIR_NONE){ vlogf(LOG_BUG, "fishing boat lost"); return FALSE; } switch(::number(0,99)){ case 0: myself->doEmote("whistles a sea shanty."); break; case 1: myself->doSay("Sailor, get over here and swab this deck!"); break; case 2: myself->doSay("Uh oh! I think I see a pirate sail!"); myself->doAction("", CMD_CHORTLE); myself->doSay("Just joking."); break; case 3: myself->doSay("So how's the fishing today?"); break; case 4: myself->doEmote("hums a sea shanty."); break; } if(vehicle->getDir() != i) myself->doDrive(dirs[i]); myself->doDrive("20"); return TRUE; } int casinoElevatorOperator(TBeing *, cmdTypeT cmd, const char *, TMonster *myself, TObj *) { const int elevatornum=2360; static int timer; TObj *elevator=NULL; int *job=NULL; int i; TVehicle *vehicle=NULL; TPathFinder path; path.setUsePortals(false); path.setThruDoors(false); if (cmd == CMD_GENERIC_DESTROYED) { delete static_cast<int *>(myself->act_ptr); myself->act_ptr = NULL; return FALSE; } if(cmd != CMD_GENERIC_PULSE) return FALSE; // find the elevator for(TObjIter iter=object_list.begin();iter!=object_list.end();++iter){ if((*iter)->objVnum() == elevatornum){ elevator=*iter; break; } } if(!elevator) return FALSE; if(!(vehicle=dynamic_cast<TVehicle *>(elevator))){ vlogf(LOG_BUG, "couldn't cast elevator to vehicle!"); return FALSE; } if(!has_key(myself, vehicle->getPortalKey())){ return FALSE; } vehicle->unlockMe(myself); vehicle->openMe(myself); if((--timer)>0) return FALSE; // first, get out action pointer, which tells us which way to go if (!myself->act_ptr) { if (!(myself->act_ptr = new int)) { perror("failed new of fishing elevator."); exit(0); } job = static_cast<int *>(myself->act_ptr); *job=2362; } else { job = static_cast<int *>(myself->act_ptr); } if(elevator->in_room == *job){ myself->doDrive("stop"); if(*job==2352){ timer=10; *job=2362; } else { timer=10; *job=2352; } return TRUE; } i=path.findPath(elevator->in_room, findRoom(*job)); if(i==DIR_NONE){ if(elevator->in_room==2374) i=DIR_UP; else if(elevator->in_room==2367) i=DIR_DOWN; else { vlogf(LOG_BUG, "fishing elevator lost"); return FALSE; } } if(vehicle->getDir() != i) myself->doDrive(dirs[i]); myself->doDrive("fast"); return TRUE; } int casinoElevatorGuard(TBeing *ch, cmdTypeT cmd, const char *, TMonster *myself, TObj *o) { if(cmd != CMD_ENTER && cmd != CMD_MOB_GIVEN_ITEM) return false; if(cmd == CMD_ENTER){ myself->doSay("Entering the elevator requires a 100 talen chip."); myself->doEmote("stretches out his hand expectantly."); return true; } if(!ch || !o) // something weird going on if this happens return false; if(o->objVnum() != CHIP_100){ myself->doSay("What the hell is this?"); myself->doDrop("", o); return false; } TVehicle *elevator; for(TThing *tt=myself->roomp->getStuff();tt;tt=tt->nextThing){ if((elevator=dynamic_cast<TVehicle *>(tt)) && elevator->objVnum()==2360){ myself->doSay("Thank you, enjoy your stay!"); ch->doEnter("", elevator); (*o)--; delete o; return true; } } myself->doSay("You'll have to wait for the elevator."); myself->doDrop("", o); return false; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/default_apps.h" #include "base/command_line.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" const int DefaultApps::kAppsPromoCounterMax = 10; // static void DefaultApps::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDefaultAppsInstalled, false); prefs->RegisterIntegerPref(prefs::kAppsPromoCounter, 0); } DefaultApps::DefaultApps(PrefService* prefs) : prefs_(prefs) { // gmail, calendar, docs ids_.insert("pjkljhegncpnkpknbcohdijeoejaedia"); ids_.insert("ejjicmeblgpmajnghnpcppodonldlgfn"); ids_.insert("apdfllckaahabafndbhieahigkjlhalf"); } DefaultApps::~DefaultApps() {} const ExtensionIdSet* DefaultApps::GetAppsToInstall() const { if (GetDefaultAppsInstalled()) return NULL; else return &ids_; } const ExtensionIdSet* DefaultApps::GetDefaultApps() const { return &ids_; } void DefaultApps::DidInstallApp(const ExtensionIdSet& installed_ids) { // If all the default apps have been installed, stop trying to install them. // Note that we use std::includes here instead of == because apps might have // been manually installed while the the default apps were installing and we // wouldn't want to keep trying to install them in that case. if (!GetDefaultAppsInstalled() && std::includes(installed_ids.begin(), installed_ids.end(), ids_.begin(), ids_.end())) { SetDefaultAppsInstalled(true); } } bool DefaultApps::ShouldShowPromo(const ExtensionIdSet& installed_ids) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceAppsPromoVisible)) { return true; } if (GetDefaultAppsInstalled() && GetPromoCounter() < kAppsPromoCounterMax) { // If we have the exact set of default apps, show the promo. If we don't // have the exact set of default apps, this means that the user manually // installed one. The promo doesn't make sense if it shows apps the user // manually installed, so expire it immediately in that situation. if (installed_ids == ids_) return true; else SetPromoHidden(); } return false; } void DefaultApps::DidShowPromo() { if (!GetDefaultAppsInstalled()) { NOTREACHED() << "Should not show promo until default apps are installed."; return; } int promo_counter = GetPromoCounter(); if (promo_counter == kAppsPromoCounterMax) { NOTREACHED() << "Promo has already been shown the maximum number of times."; return; } if (promo_counter < kAppsPromoCounterMax) SetPromoCounter(++promo_counter); else SetPromoHidden(); } void DefaultApps::SetPromoHidden() { SetPromoCounter(kAppsPromoCounterMax); } int DefaultApps::GetPromoCounter() const { return prefs_->GetInteger(prefs::kAppsPromoCounter); } void DefaultApps::SetPromoCounter(int val) { prefs_->SetInteger(prefs::kAppsPromoCounter, val); prefs_->ScheduleSavePersistentPrefs(); } bool DefaultApps::GetDefaultAppsInstalled() const { return prefs_->GetBoolean(prefs::kDefaultAppsInstalled); } void DefaultApps::SetDefaultAppsInstalled(bool val) { prefs_->SetBoolean(prefs::kDefaultAppsInstalled, val); prefs_->ScheduleSavePersistentPrefs(); } <commit_msg>Remove component extensions Calendar and Docs<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/default_apps.h" #include "base/command_line.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" const int DefaultApps::kAppsPromoCounterMax = 10; // static void DefaultApps::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDefaultAppsInstalled, false); prefs->RegisterIntegerPref(prefs::kAppsPromoCounter, 0); } DefaultApps::DefaultApps(PrefService* prefs) : prefs_(prefs) { #if !defined(OS_CHROMEOS) // gmail, calendar, docs ids_.insert("pjkljhegncpnkpknbcohdijeoejaedia"); ids_.insert("ejjicmeblgpmajnghnpcppodonldlgfn"); ids_.insert("apdfllckaahabafndbhieahigkjlhalf"); #endif // OS_CHROMEOS } DefaultApps::~DefaultApps() {} const ExtensionIdSet* DefaultApps::GetAppsToInstall() const { if (GetDefaultAppsInstalled()) return NULL; else return &ids_; } const ExtensionIdSet* DefaultApps::GetDefaultApps() const { return &ids_; } void DefaultApps::DidInstallApp(const ExtensionIdSet& installed_ids) { // If all the default apps have been installed, stop trying to install them. // Note that we use std::includes here instead of == because apps might have // been manually installed while the the default apps were installing and we // wouldn't want to keep trying to install them in that case. if (!GetDefaultAppsInstalled() && std::includes(installed_ids.begin(), installed_ids.end(), ids_.begin(), ids_.end())) { SetDefaultAppsInstalled(true); } } bool DefaultApps::ShouldShowPromo(const ExtensionIdSet& installed_ids) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceAppsPromoVisible)) { return true; } if (GetDefaultAppsInstalled() && GetPromoCounter() < kAppsPromoCounterMax) { // If we have the exact set of default apps, show the promo. If we don't // have the exact set of default apps, this means that the user manually // installed one. The promo doesn't make sense if it shows apps the user // manually installed, so expire it immediately in that situation. if (installed_ids == ids_) return true; else SetPromoHidden(); } return false; } void DefaultApps::DidShowPromo() { if (!GetDefaultAppsInstalled()) { NOTREACHED() << "Should not show promo until default apps are installed."; return; } int promo_counter = GetPromoCounter(); if (promo_counter == kAppsPromoCounterMax) { NOTREACHED() << "Promo has already been shown the maximum number of times."; return; } if (promo_counter < kAppsPromoCounterMax) SetPromoCounter(++promo_counter); else SetPromoHidden(); } void DefaultApps::SetPromoHidden() { SetPromoCounter(kAppsPromoCounterMax); } int DefaultApps::GetPromoCounter() const { return prefs_->GetInteger(prefs::kAppsPromoCounter); } void DefaultApps::SetPromoCounter(int val) { prefs_->SetInteger(prefs::kAppsPromoCounter, val); prefs_->ScheduleSavePersistentPrefs(); } bool DefaultApps::GetDefaultAppsInstalled() const { return prefs_->GetBoolean(prefs::kDefaultAppsInstalled); } void DefaultApps::SetDefaultAppsInstalled(bool val) { prefs_->SetBoolean(prefs::kDefaultAppsInstalled, val); prefs_->ScheduleSavePersistentPrefs(); } <|endoftext|>
<commit_before> #include "input.h" #include <QDebug> namespace NeovimQt { InputConv Input; InputConv::InputConv() { // see :h key-notation // special keys i.e. no textual representation specialKeys.insert(Qt::Key_Up, "Up"); specialKeys.insert(Qt::Key_Down, "Down"); specialKeys.insert(Qt::Key_Left, "Left"); specialKeys.insert(Qt::Key_Right, "Right"); specialKeys.insert(Qt::Key_F1, "F1"); specialKeys.insert(Qt::Key_F2, "F2"); specialKeys.insert(Qt::Key_F3, "F3"); specialKeys.insert(Qt::Key_F4, "F4"); specialKeys.insert(Qt::Key_F5, "F5"); specialKeys.insert(Qt::Key_F6, "F6"); specialKeys.insert(Qt::Key_F7, "F7"); specialKeys.insert(Qt::Key_F8, "F8"); specialKeys.insert(Qt::Key_F9, "F9"); specialKeys.insert(Qt::Key_F10, "F10"); specialKeys.insert(Qt::Key_F11, "F11"); specialKeys.insert(Qt::Key_F12, "F12"); specialKeys.insert(Qt::Key_Backspace, "BS"); specialKeys.insert(Qt::Key_Delete, "Del"); specialKeys.insert(Qt::Key_Insert, "Insert"); specialKeys.insert(Qt::Key_Home, "Home"); specialKeys.insert(Qt::Key_End, "End"); specialKeys.insert(Qt::Key_PageUp, "PageUp"); specialKeys.insert(Qt::Key_PageDown, "PageDown"); specialKeys.insert(Qt::Key_Return, "Enter"); specialKeys.insert(Qt::Key_Enter, "Enter"); specialKeys.insert(Qt::Key_Tab, "Tab"); specialKeys.insert(Qt::Key_Backtab, "Tab"); specialKeys.insert(Qt::Key_Escape, "Esc"); specialKeys.insert(Qt::Key_Backslash, "Bslash"); specialKeys.insert(Qt::Key_Space, "Space"); } /** * Return keyboard modifier prefix * * e.g. C-, A- or C-S-A- * * WIN32: Ctrl+Alt are never passed together, since we can't distinguish * between Ctrl+Alt and AltGr (see Vim/os_win32.c). */ QString InputConv::modPrefix(Qt::KeyboardModifiers mod) { QString modprefix; #if defined(Q_OS_MAC) || defined(Q_OS_UNIX) if ( mod & CmdModifier ) { modprefix += "D-"; // like MacVim does } #endif if ( mod & ControlModifier #ifdef Q_OS_WIN32 && !(mod & AltModifier) #endif ) { modprefix += "C-"; } if ( mod & ShiftModifier ) { modprefix += "S-"; } if ( mod & AltModifier #ifdef Q_OS_WIN32 && !(mod & ControlModifier) #endif ) { modprefix += "A-"; } return modprefix; } /** * Convert mouse event information into Neovim key notation * * @type is one of the Qt mouse event types * @pos is in Neovim Coordinates * @clickCount is the number of consecutive mouse clicks * 1 for a single click, 2 for a double click, up to 4. * This value is only used for LeftMouse events. * * see QMouseEvent * * If the event is not valid for Neovim, returns an empty string */ QString InputConv::convertMouse(Qt::MouseButton bt, QEvent::Type type, Qt::KeyboardModifiers mod, QPoint pos, short clickCount) { QString buttonName; switch(bt) { case Qt::LeftButton: // In practice Neovim only supports the clickcount for Left // mouse presses, even if our shell can support other buttons if (clickCount > 1 && clickCount <= 4) { buttonName = QString("%1-Left").arg(clickCount); } else { buttonName += "Left"; } break; case Qt::RightButton: buttonName += "Right"; break; case Qt::MidButton: buttonName += "Middle"; break; case Qt::NoButton: break; default: return ""; } QString evType; switch(type) { case QEvent::MouseButtonDblClick: // Treat this as a regular MouseButtonPress. Repeated // clicks are handled above. case QEvent::MouseButtonPress: evType += "Mouse"; break; case QEvent::MouseButtonRelease: evType += "Release"; break; case QEvent::MouseMove: evType += "Drag"; break; default: return ""; } QString inp = QString("<%1%2%3><%4,%5>").arg(modPrefix(mod)).arg(buttonName).arg(evType).arg(pos.x()).arg(pos.y()); return inp; } /** * Convert Qt key input into Neovim key-notation * * see QKeyEvent */ QString InputConv::convertKey(const QString& text, int k, Qt::KeyboardModifiers mod) { if ( mod & Qt::KeypadModifier ) { switch (k) { case Qt::Key_Home: return QString("<%1kHome>").arg(modPrefix(mod)); case Qt::Key_End: return QString("<%1kEnd>").arg(modPrefix(mod)); case Qt::Key_PageUp: return QString("<%1kPageUp>").arg(modPrefix(mod)); case Qt::Key_PageDown: return QString("<%1kPageDown>").arg(modPrefix(mod)); case Qt::Key_Plus: return QString("<%1kPlus>").arg(modPrefix(mod)); case Qt::Key_Minus: return QString("<%1kMinus>").arg(modPrefix(mod)); case Qt::Key_multiply: return QString("<%1kMultiply>").arg(modPrefix(mod)); case Qt::Key_division: return QString("<%1kDivide>").arg(modPrefix(mod)); case Qt::Key_Enter: return QString("<%1kEnter>").arg(modPrefix(mod)); case Qt::Key_Period: return QString("<%1kPoint>").arg(modPrefix(mod)); case Qt::Key_0: return QString("<%1k0>").arg(modPrefix(mod)); case Qt::Key_1: return QString("<%1k1>").arg(modPrefix(mod)); case Qt::Key_2: return QString("<%1k2>").arg(modPrefix(mod)); case Qt::Key_3: return QString("<%1k3>").arg(modPrefix(mod)); case Qt::Key_4: return QString("<%1k4>").arg(modPrefix(mod)); case Qt::Key_5: return QString("<%1k5>").arg(modPrefix(mod)); case Qt::Key_6: return QString("<%1k6>").arg(modPrefix(mod)); case Qt::Key_7: return QString("<%1k7>").arg(modPrefix(mod)); case Qt::Key_8: return QString("<%1k8>").arg(modPrefix(mod)); case Qt::Key_9: return QString("<%1k9>").arg(modPrefix(mod)); } } if (specialKeys.contains(k)) { return QString("<%1%2>").arg(modPrefix(mod)).arg(specialKeys.value(k)); } QChar c; // Escape < and backslash if (text == "<") { return QString("<lt>"); } else if (text == "\\") { return QString("<%1%2>").arg(modPrefix(mod)).arg("Bslash"); } else if (text.isEmpty()) { // on macs, text is empty for ctrl+key and cmd+key combos (with or without alt) if (mod & ControlModifier || mod & CmdModifier) { // ignore ctrl, alt and cmd key combos by themselves QList<Qt::Key> keys = { Key_Control, Key_Alt, Key_Cmd }; if (keys.contains((Qt::Key)k)) { return QString(); } else { // key code will be the value of the char (hopefully) c = QChar(k); } } else { // This is a special key we can't handle return QString(); } } else { // Key event compression is disabled, text has one char c = text.at(0); } // Remove SHIFT if (c.unicode() >= 0x80 || (!c.isLetterOrNumber() && c.isPrint())) { mod &= ~ShiftModifier; } // Remove CTRL empty characters at the start of the ASCII range if (c.unicode() < 0x20) { mod &= ~ControlModifier; } // Format with prefix if necessary QString prefix = modPrefix(mod); if (!prefix.isEmpty()) { return QString("<%1%2>").arg(prefix).arg(c); } return QString(c); } } // Namespace <commit_msg>GUI: Add support for F13-F24 keys<commit_after> #include "input.h" #include <QDebug> namespace NeovimQt { InputConv Input; InputConv::InputConv() { // see :h key-notation // special keys i.e. no textual representation specialKeys.insert(Qt::Key_Up, "Up"); specialKeys.insert(Qt::Key_Down, "Down"); specialKeys.insert(Qt::Key_Left, "Left"); specialKeys.insert(Qt::Key_Right, "Right"); specialKeys.insert(Qt::Key_F1, "F1"); specialKeys.insert(Qt::Key_F2, "F2"); specialKeys.insert(Qt::Key_F3, "F3"); specialKeys.insert(Qt::Key_F4, "F4"); specialKeys.insert(Qt::Key_F5, "F5"); specialKeys.insert(Qt::Key_F6, "F6"); specialKeys.insert(Qt::Key_F7, "F7"); specialKeys.insert(Qt::Key_F8, "F8"); specialKeys.insert(Qt::Key_F9, "F9"); specialKeys.insert(Qt::Key_F10, "F10"); specialKeys.insert(Qt::Key_F11, "F11"); specialKeys.insert(Qt::Key_F12, "F12"); specialKeys.insert(Qt::Key_F13, "F13"); specialKeys.insert(Qt::Key_F14, "F14"); specialKeys.insert(Qt::Key_F15, "F15"); specialKeys.insert(Qt::Key_F16, "F16"); specialKeys.insert(Qt::Key_F17, "F17"); specialKeys.insert(Qt::Key_F18, "F18"); specialKeys.insert(Qt::Key_F19, "F19"); specialKeys.insert(Qt::Key_F20, "F20"); specialKeys.insert(Qt::Key_F21, "F21"); specialKeys.insert(Qt::Key_F22, "F22"); specialKeys.insert(Qt::Key_F23, "F23"); specialKeys.insert(Qt::Key_F24, "F24"); specialKeys.insert(Qt::Key_Backspace, "BS"); specialKeys.insert(Qt::Key_Delete, "Del"); specialKeys.insert(Qt::Key_Insert, "Insert"); specialKeys.insert(Qt::Key_Home, "Home"); specialKeys.insert(Qt::Key_End, "End"); specialKeys.insert(Qt::Key_PageUp, "PageUp"); specialKeys.insert(Qt::Key_PageDown, "PageDown"); specialKeys.insert(Qt::Key_Return, "Enter"); specialKeys.insert(Qt::Key_Enter, "Enter"); specialKeys.insert(Qt::Key_Tab, "Tab"); specialKeys.insert(Qt::Key_Backtab, "Tab"); specialKeys.insert(Qt::Key_Escape, "Esc"); specialKeys.insert(Qt::Key_Backslash, "Bslash"); specialKeys.insert(Qt::Key_Space, "Space"); } /** * Return keyboard modifier prefix * * e.g. C-, A- or C-S-A- * * WIN32: Ctrl+Alt are never passed together, since we can't distinguish * between Ctrl+Alt and AltGr (see Vim/os_win32.c). */ QString InputConv::modPrefix(Qt::KeyboardModifiers mod) { QString modprefix; #if defined(Q_OS_MAC) || defined(Q_OS_UNIX) if ( mod & CmdModifier ) { modprefix += "D-"; // like MacVim does } #endif if ( mod & ControlModifier #ifdef Q_OS_WIN32 && !(mod & AltModifier) #endif ) { modprefix += "C-"; } if ( mod & ShiftModifier ) { modprefix += "S-"; } if ( mod & AltModifier #ifdef Q_OS_WIN32 && !(mod & ControlModifier) #endif ) { modprefix += "A-"; } return modprefix; } /** * Convert mouse event information into Neovim key notation * * @type is one of the Qt mouse event types * @pos is in Neovim Coordinates * @clickCount is the number of consecutive mouse clicks * 1 for a single click, 2 for a double click, up to 4. * This value is only used for LeftMouse events. * * see QMouseEvent * * If the event is not valid for Neovim, returns an empty string */ QString InputConv::convertMouse(Qt::MouseButton bt, QEvent::Type type, Qt::KeyboardModifiers mod, QPoint pos, short clickCount) { QString buttonName; switch(bt) { case Qt::LeftButton: // In practice Neovim only supports the clickcount for Left // mouse presses, even if our shell can support other buttons if (clickCount > 1 && clickCount <= 4) { buttonName = QString("%1-Left").arg(clickCount); } else { buttonName += "Left"; } break; case Qt::RightButton: buttonName += "Right"; break; case Qt::MidButton: buttonName += "Middle"; break; case Qt::NoButton: break; default: return ""; } QString evType; switch(type) { case QEvent::MouseButtonDblClick: // Treat this as a regular MouseButtonPress. Repeated // clicks are handled above. case QEvent::MouseButtonPress: evType += "Mouse"; break; case QEvent::MouseButtonRelease: evType += "Release"; break; case QEvent::MouseMove: evType += "Drag"; break; default: return ""; } QString inp = QString("<%1%2%3><%4,%5>").arg(modPrefix(mod)).arg(buttonName).arg(evType).arg(pos.x()).arg(pos.y()); return inp; } /** * Convert Qt key input into Neovim key-notation * * see QKeyEvent */ QString InputConv::convertKey(const QString& text, int k, Qt::KeyboardModifiers mod) { if ( mod & Qt::KeypadModifier ) { switch (k) { case Qt::Key_Home: return QString("<%1kHome>").arg(modPrefix(mod)); case Qt::Key_End: return QString("<%1kEnd>").arg(modPrefix(mod)); case Qt::Key_PageUp: return QString("<%1kPageUp>").arg(modPrefix(mod)); case Qt::Key_PageDown: return QString("<%1kPageDown>").arg(modPrefix(mod)); case Qt::Key_Plus: return QString("<%1kPlus>").arg(modPrefix(mod)); case Qt::Key_Minus: return QString("<%1kMinus>").arg(modPrefix(mod)); case Qt::Key_multiply: return QString("<%1kMultiply>").arg(modPrefix(mod)); case Qt::Key_division: return QString("<%1kDivide>").arg(modPrefix(mod)); case Qt::Key_Enter: return QString("<%1kEnter>").arg(modPrefix(mod)); case Qt::Key_Period: return QString("<%1kPoint>").arg(modPrefix(mod)); case Qt::Key_0: return QString("<%1k0>").arg(modPrefix(mod)); case Qt::Key_1: return QString("<%1k1>").arg(modPrefix(mod)); case Qt::Key_2: return QString("<%1k2>").arg(modPrefix(mod)); case Qt::Key_3: return QString("<%1k3>").arg(modPrefix(mod)); case Qt::Key_4: return QString("<%1k4>").arg(modPrefix(mod)); case Qt::Key_5: return QString("<%1k5>").arg(modPrefix(mod)); case Qt::Key_6: return QString("<%1k6>").arg(modPrefix(mod)); case Qt::Key_7: return QString("<%1k7>").arg(modPrefix(mod)); case Qt::Key_8: return QString("<%1k8>").arg(modPrefix(mod)); case Qt::Key_9: return QString("<%1k9>").arg(modPrefix(mod)); } } if (specialKeys.contains(k)) { return QString("<%1%2>").arg(modPrefix(mod)).arg(specialKeys.value(k)); } QChar c; // Escape < and backslash if (text == "<") { return QString("<lt>"); } else if (text == "\\") { return QString("<%1%2>").arg(modPrefix(mod)).arg("Bslash"); } else if (text.isEmpty()) { // on macs, text is empty for ctrl+key and cmd+key combos (with or without alt) if (mod & ControlModifier || mod & CmdModifier) { // ignore ctrl, alt and cmd key combos by themselves QList<Qt::Key> keys = { Key_Control, Key_Alt, Key_Cmd }; if (keys.contains((Qt::Key)k)) { return QString(); } else { // key code will be the value of the char (hopefully) c = QChar(k); } } else { // This is a special key we can't handle return QString(); } } else { // Key event compression is disabled, text has one char c = text.at(0); } // Remove SHIFT if (c.unicode() >= 0x80 || (!c.isLetterOrNumber() && c.isPrint())) { mod &= ~ShiftModifier; } // Remove CTRL empty characters at the start of the ASCII range if (c.unicode() < 0x20) { mod &= ~ControlModifier; } // Format with prefix if necessary QString prefix = modPrefix(mod); if (!prefix.isEmpty()) { return QString("<%1%2>").arg(prefix).arg(c); } return QString(c); } } // Namespace <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_ERR_CHECK_LDLT_FACTOR_HPP #define STAN_MATH_PRIM_MAT_ERR_CHECK_LDLT_FACTOR_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/err/throw_domain_error.hpp> #include <stan/math/prim/mat/fun/LDLT_factor.hpp> #include <sstream> #include <string> namespace stan { namespace math { /** * Raise domain error if the specified LDLT factor is invalid. An * <code>LDLT_factor</code> is invalid if it was constructed from * a matrix that is not positive definite. The check is that the * <code>success()</code> method returns <code>true</code>. * @tparam T type of scalar * @tparam R number of rows or Eigen::Dynamic * @tparam C number of columns or Eigen::Dynamic * @param[in] function name of function for error messages * @param[in] name variable name for error messages * @param[in] A the LDLT factor to check for validity * @throws <code>std::domain_error</code> if the LDLT factor is invalid */ template <typename T, int R, int C> inline void check_ldlt_factor(const char* function, const char* name, LDLT_factor<T, R, C>& A) { if (!A.success()) { std::ostringstream msg; msg << "is not positive definite. last conditional variance is "; std::string msg_str(msg.str()); T too_small = A.vectorD().tail(1)(0); throw_domain_error(function, name, too_small, msg_str.c_str(), "."); } } } // namespace math } // namespace stan #endif <commit_msg>fix include<commit_after>#ifndef STAN_MATH_PRIM_MAT_ERR_CHECK_LDLT_FACTOR_HPP #define STAN_MATH_PRIM_MAT_ERR_CHECK_LDLT_FACTOR_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/err/throw_domain_error.hpp> #include <stan/math/prim/mat/fun/LDLT_factor.hpp> #include <sstream> #include <string> namespace stan { namespace math { /** * Raise domain error if the specified LDLT factor is invalid. An * <code>LDLT_factor</code> is invalid if it was constructed from * a matrix that is not positive definite. The check is that the * <code>success()</code> method returns <code>true</code>. * @tparam T type of scalar * @tparam R number of rows or Eigen::Dynamic * @tparam C number of columns or Eigen::Dynamic * @param[in] function name of function for error messages * @param[in] name variable name for error messages * @param[in] A the LDLT factor to check for validity * @throws <code>std::domain_error</code> if the LDLT factor is invalid */ template <typename T, int R, int C> inline void check_ldlt_factor(const char* function, const char* name, LDLT_factor<T, R, C>& A) { if (!A.success()) { std::ostringstream msg; msg << "is not positive definite. last conditional variance is "; std::string msg_str(msg.str()); T too_small = A.vectorD().tail(1)(0); throw_domain_error(function, name, too_small, msg_str.c_str(), "."); } } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping // TODO: write a timer class, tic/toc using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); // Display formatting std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; size_t N = 7000; cmat testmat = cmat::Random(N, N); // TIMING Timer t; cout << "The norm of a " << N << " x " << N << " random complex matrix is: " << norm(testmat) << endl; t.toc(); cout << "It took me " << t.ticks() << " ticks (" << t.secs() << " seconds) to compute the norm." << endl; // END TIMING t.reset(); // reset the clock for(size_t i=0;i<10000;i++); // wait a bit //t.toc(); cout << "New timer reading immediately after reset : " << t.ticks() << " ticks (" << t.secs() << " seconds)."; cout << endl << "Exiting qpp..." << endl; } <commit_msg>commit<commit_after>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping // TODO: write a timer class, tic/toc using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); // Display formatting std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; size_t N = 7000; cmat testmat = cmat::Random(N, N); // TIMING Timer t; // start the timer cout << "The norm of a " << N << " x " << N << " random complex matrix is: " << norm(testmat) << endl; t.toc(); // read the time cout << "It took me " << t.ticks() << " ticks (" << t.secs() << " seconds) to compute the norm." << endl; // END TIMING t.reset(); // reset the timer to current time for(size_t i=0;i<10000;i++); // wait a bit t.toc(); // read again cout << "New timer reading immediately after reset : " << t.ticks() << " ticks (" << t.secs() << " seconds)."; cout << endl << "Exiting qpp..." << endl; } <|endoftext|>
<commit_before>#include <iostream> #include <SDL.h> #include <SDL_net.h> #include <SDL_image.h> #include <string> #include <vector> #include <MsgStruct.h> #include "Player.h" #include "GameObject.h" #include "Enemy.h" #include "Cursor.h" #include "Tower.h" #include <unordered_map> using namespace std; int send(string); int send(MsgStruct*, int); int send(string, int); MsgStruct* createMsgStruct(int, bool); void setupMessages(); MsgStruct* newPacket(int); bool canHandleMsg(bool); MsgStruct* readPacket(bool); const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; SDLNet_SocketSet socketSet; TCPsocket sock; char buffer[512]; int bufferSize; map<int, MsgStruct*> outMsgStructs; map<int, MsgStruct*> inMsgStructs; string roomCode; vector<Tower*> listTower; vector<Enemy*> listEnemy; unordered_map<int,Player*> listPlayers; Level lvl1(640, 480); //User IO functions to be called from networking code? Player* getPlayerbyID(int id); void addPlayerbyID(int id, SDL_Renderer* r); int main() { if (SDL_Init(SDL_INIT_VIDEO) == -1) { std::cout << "ERROR, SDL_Init\n"; return -1; } cout << "SDL2 loaded.\n"; // The window we'll be rendering to SDL_Window* window = NULL; // The surface contained by the window SDL_Surface* screenSurface = NULL; window = SDL_CreateWindow("Party Towers", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); int flag = IMG_INIT_PNG; if ((IMG_Init(flag)&flag) != flag) { std::cout << "Error, SDL_image!\n"; return -1; } if (SDLNet_Init() == -1) { std::cout << "ERROR, SDLNet_Init\n"; return -1; } std::cout << "SDL_net loaded.\n"; IPaddress ip; if (SDLNet_ResolveHost(&ip, "localhost", atoi("8886")) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if (!(sock = SDLNet_TCP_Open(&ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); } socketSet = SDLNet_AllocSocketSet(1); SDLNet_TCP_AddSocket(socketSet, sock); setupMessages(); send("TCP"); bool waiting = true; while (waiting) { if (SDLNet_TCP_Recv(sock, buffer, 512) > 0) { waiting = false; if (string(buffer) == "1") { cout << "Handshake to server made.\n"; } } } send("9990000"); //Create Renderer SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); printf("This is what happens when Marcus writes a renderer %s\n",SDL_GetError()); if (renderer) { cout << "It works!\n"; } //Testing Images Player p1(0, 0, 0, &lvl1); p1.loadImg(renderer); listPlayers.emplace(0,&p1); GameObject go1; go1.loadImg("./res/BaseTower.png", renderer); SDL_Event e; bool running = true; int k = 0; Uint32 ctime = SDL_GetTicks(); int wave = 1; bool confirmed = false; while (running) { SDL_UpdateWindowSurface(window); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } } int ready = SDLNet_CheckSockets(socketSet, 15); if (ready > 0 && SDLNet_SocketReady(sock)) { int s = SDLNet_TCP_Recv(sock, buffer+bufferSize, 512); if (s > 0) { bufferSize += s; } } if (canHandleMsg(confirmed)) { MsgStruct* packet = readPacket(confirmed); int pID = packet->getPID(); int msgID = packet->getMsgID(); if (msgID == 999) { confirmed = true; roomCode = packet->read(); cout << "Room code: "+roomCode+"\n"; } else if (msgID == 998) { cout << "New player!\n"; addPlayerbyID(pID, renderer); } else if (msgID == 2) { string dir = packet->read(); // We have pID and dir Player* p = getPlayerbyID(pID); if(dir == "l") { p->moveLeft(); } else if (dir == "r") { p->moveRight(); } else if (dir == "u") { p->moveUp(); } else if (dir == "d") { p->moveDown(); } else { cout << "error, direction: " << dir << "\n"; } } else if (msgID == 3) { string t = packet->read(); MsgStruct* p = newPacket(3); p->write(t); send(p, pID); } } k +=1 ; if (SDL_GetTicks() - ctime > 1000) { //cout << k; k = 0; ctime = SDL_GetTicks(); //cout << "\n"; } //Drawing code SDL_RenderClear(renderer); //For each path item, draw //For each base tower, draw //For each object, get image, draw, SDL_RenderCopy SDL_Texture* t = go1.draw(); SDL_Rect txr; //img position txr.x = 0; txr.y = 0; //img size txr.w = 32; txr.h = 32; //For each player, get cursor, draw for(auto it : listPlayers) { Player* p = it.second; pair<int,int>player_pos = p->getPos(); txr.x = player_pos.first; txr.y = player_pos.second; SDL_Texture* t = p->getTexture(); SDL_RenderCopy(renderer, t, NULL, &txr); } for(auto t : listTower) { } //SDL_RenderCopy(renderer, t, NULL, &txr); SDL_RenderPresent(renderer); } SDL_FreeSurface( screenSurface ); SDL_DestroyWindow( window ); SDLNet_TCP_Close(sock); SDLNet_Quit(); SDL_Quit(); return 0; } void setupMessages() { MsgStruct* m1 = createMsgStruct(999, false); m1->addChars(4); MsgStruct* m998 = createMsgStruct(998, false); MsgStruct* m2 = createMsgStruct(2, false); m2->addChars(1); MsgStruct* m3 = createMsgStruct(3, false); m3->addChars(2); MsgStruct* o3 = createMsgStruct(3, true); o3->addChars(2); } bool canHandleMsg(bool confirmed) { if (bufferSize < 5) { return false; } string data = string(buffer); if (data.size() < 5) { return false; } //cout << "Handling message...\n"; int offset = 2; if (confirmed) { offset += 2; } //cout << data + "\n"; data = data.substr(offset); //cout << data + "\n"; string rawMsgID = data.substr(0, 3); //cout << rawMsgID + "\n"; int msgID = atoi(rawMsgID.c_str()); if (inMsgStructs.find(msgID) != inMsgStructs.end()) { return inMsgStructs[msgID]->canHandle(data); } cout << "Message ID does not exist " + rawMsgID+ "\n"; return false; } MsgStruct* readPacket(bool confirmed) { string data = string(buffer).substr(0,bufferSize); int offset = 2; if (confirmed) { offset += 2; } int msgID = atoi(data.substr(offset,3).c_str()); return inMsgStructs[msgID]->fillFromData(confirmed); } MsgStruct* createMsgStruct(int msgID, bool outgoing) { MsgStruct* packet = new MsgStruct(msgID); if (outgoing) { outMsgStructs[msgID] = packet; } else { inMsgStructs[msgID] = packet; } return packet; } MsgStruct* newPacket(int msgID) { return outMsgStructs[msgID]->reset(); } int send(string data) { send(data, 0); } int send(string data, int pID) { if (pID > 0) { data = extend(pID, 2) + data + "*"; } int len = data.size() + 1; int out = SDLNet_TCP_Send(sock, (void*)data.c_str(), len); if (out < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } return 0; } int send(MsgStruct* packet, int pID) { send(packet->getData(), pID); } Player* getPlayerbyID(int id) { auto it = listPlayers.find(id); if(it != listPlayers.end()) { return it->second; } return nullptr; } void addPlayerbyID(int id, SDL_Renderer* r) { auto it = listPlayers.find(id); if(it == listPlayers.end()) { Player* p = new Player(id, 0, 0, &lvl1); p->loadImg(r); listPlayers.emplace(id, p); } } <commit_msg>Added detection code<commit_after>#include <iostream> #include <SDL.h> #include <SDL_net.h> #include <SDL_image.h> #include <string> #include <vector> #include <MsgStruct.h> #include "Player.h" #include "GameObject.h" #include "Enemy.h" #include "Cursor.h" #include "Tower.h" #include <unordered_map> using namespace std; int send(string); int send(MsgStruct*, int); int send(string, int); MsgStruct* createMsgStruct(int, bool); void setupMessages(); MsgStruct* newPacket(int); bool canHandleMsg(bool); MsgStruct* readPacket(bool); const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; SDLNet_SocketSet socketSet; TCPsocket sock; char buffer[512]; int bufferSize; map<int, MsgStruct*> outMsgStructs; map<int, MsgStruct*> inMsgStructs; string roomCode; vector<Tower*> listTower; vector<Enemy*> listEnemy; unordered_map<int, Player*> listPlayers; Level lvl1(640, 480); // User IO functions to be called from networking code? Player* getPlayerbyID(int id); void addPlayerbyID(int id, SDL_Renderer* r); int main() { if (SDL_Init(SDL_INIT_VIDEO) == -1) { std::cout << "ERROR, SDL_Init\n"; return -1; } cout << "SDL2 loaded.\n"; // The window we'll be rendering to SDL_Window* window = NULL; // The surface contained by the window SDL_Surface* screenSurface = NULL; window = SDL_CreateWindow("Party Towers", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); int flag = IMG_INIT_PNG; if ((IMG_Init(flag) & flag) != flag) { std::cout << "Error, SDL_image!\n"; return -1; } if (SDLNet_Init() == -1) { std::cout << "ERROR, SDLNet_Init\n"; return -1; } std::cout << "SDL_net loaded.\n"; IPaddress ip; if (SDLNet_ResolveHost(&ip, "localhost", atoi("8886")) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if (!(sock = SDLNet_TCP_Open(&ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); } socketSet = SDLNet_AllocSocketSet(1); SDLNet_TCP_AddSocket(socketSet, sock); setupMessages(); send("TCP"); bool waiting = true; while (waiting) { if (SDLNet_TCP_Recv(sock, buffer, 512) > 0) { waiting = false; if (string(buffer) == "1") { cout << "Handshake to server made.\n"; } } } send("9990000"); // Create Renderer SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); printf("This is what happens when Marcus writes a renderer %s\n", SDL_GetError()); if (renderer) { cout << "It works!\n"; } // Testing Images Player p1(0, 0, 0, &lvl1); p1.loadImg(renderer); listPlayers.emplace(0, &p1); GameObject go1; go1.loadImg("./res/BaseTower.png", renderer); SDL_Event e; bool running = true; int k = 0; Uint32 ctime = SDL_GetTicks(); int wave = 1; bool confirmed = false; while (running) { SDL_UpdateWindowSurface(window); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } } int ready = SDLNet_CheckSockets(socketSet, 15); if (ready > 0 && SDLNet_SocketReady(sock)) { int s = SDLNet_TCP_Recv(sock, buffer + bufferSize, 512); if (s > 0) { bufferSize += s; } } if (canHandleMsg(confirmed)) { MsgStruct* packet = readPacket(confirmed); int pID = packet->getPID(); int msgID = packet->getMsgID(); if (msgID == 999) { confirmed = true; roomCode = packet->read(); cout << "Room code: " + roomCode + "\n"; } else if (msgID == 998) { cout << "New player!\n"; addPlayerbyID(pID, renderer); } else if (msgID == 2) { string dir = packet->read(); // We have pID and dir Player* p = getPlayerbyID(pID); if (dir == "l") { p->moveLeft(); } else if (dir == "r") { p->moveRight(); } else if (dir == "u") { p->moveUp(); } else if (dir == "d") { p->moveDown(); } else { cout << "error, direction: " << dir << "\n"; } } else if (msgID == 3) { string t = packet->read(); MsgStruct* p = newPacket(3); p->write(t); send(p, pID); } } k += 1; if (SDL_GetTicks() - ctime > 1000) { // cout << k; k = 0; ctime = SDL_GetTicks(); // cout << "\n"; } /*************** * Aiming Code **************/ Enemy attacked; int r, radius; for (auto t : listTower) { for (auto e : listEnemy) { r = t->getRange(); auto tpair = t->getPosition(); auto epair = e->getPosition(); radius = sqrt((epair.first - tpair.first) * (epair.first - tpair.first) + (epair.second - tpair.second) * (epair.second - tpair.second)); if(radius < r) { attacked = *e; } } // end of enemy loop } // end of tower loop // Drawing code SDL_RenderClear(renderer); // For each path item, draw // For each base tower, draw // For each object, get image, draw, SDL_RenderCopy SDL_Texture* t = go1.draw(); SDL_Rect txr; // img position txr.x = 0; txr.y = 0; // img size txr.w = 32; txr.h = 32; // For each player, get cursor, draw for (auto it : listPlayers) { Player* p = it.second; pair<int, int> player_pos = p->getPos(); txr.x = player_pos.first; txr.y = player_pos.second; SDL_Texture* t = p->getTexture(); SDL_RenderCopy(renderer, t, NULL, &txr); } // SDL_RenderCopy(renderer, t, NULL, &txr); SDL_RenderPresent(renderer); } SDL_FreeSurface(screenSurface); SDL_DestroyWindow(window); SDLNet_TCP_Close(sock); SDLNet_Quit(); SDL_Quit(); return 0; } void setupMessages() { MsgStruct* m1 = createMsgStruct(999, false); m1->addChars(4); MsgStruct* m998 = createMsgStruct(998, false); MsgStruct* m2 = createMsgStruct(2, false); m2->addChars(1); MsgStruct* m3 = createMsgStruct(3, false); m3->addChars(2); MsgStruct* o3 = createMsgStruct(3, true); o3->addChars(2); } bool canHandleMsg(bool confirmed) { if (bufferSize < 5) { return false; } string data = string(buffer); if (data.size() < 5) { return false; } // cout << "Handling message...\n"; int offset = 2; if (confirmed) { offset += 2; } // cout << data + "\n"; data = data.substr(offset); // cout << data + "\n"; string rawMsgID = data.substr(0, 3); // cout << rawMsgID + "\n"; int msgID = atoi(rawMsgID.c_str()); if (inMsgStructs.find(msgID) != inMsgStructs.end()) { return inMsgStructs[msgID]->canHandle(data); } cout << "Message ID does not exist " + rawMsgID + "\n"; return false; } MsgStruct* readPacket(bool confirmed) { string data = string(buffer).substr(0, bufferSize); int offset = 2; if (confirmed) { offset += 2; } int msgID = atoi(data.substr(offset, 3).c_str()); return inMsgStructs[msgID]->fillFromData(confirmed); } MsgStruct* createMsgStruct(int msgID, bool outgoing) { MsgStruct* packet = new MsgStruct(msgID); if (outgoing) { outMsgStructs[msgID] = packet; } else { inMsgStructs[msgID] = packet; } return packet; } MsgStruct* newPacket(int msgID) { return outMsgStructs[msgID]->reset(); } int send(string data) { send(data, 0); } int send(string data, int pID) { if (pID > 0) { data = extend(pID, 2) + data + "*"; } int len = data.size() + 1; int out = SDLNet_TCP_Send(sock, (void*)data.c_str(), len); if (out < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } return 0; } int send(MsgStruct* packet, int pID) { send(packet->getData(), pID); } Player* getPlayerbyID(int id) { auto it = listPlayers.find(id); if (it != listPlayers.end()) { return it->second; } return nullptr; } void addPlayerbyID(int id, SDL_Renderer* r) { auto it = listPlayers.find(id); if (it == listPlayers.end()) { Player* p = new Player(id, 0, 0, &lvl1); p->loadImg(r); listPlayers.emplace(id, p); } } <|endoftext|>
<commit_before><commit_msg>dynamically created labels in the breadcrumb<commit_after><|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <sstream> #include "analyzer.h" #include "ast.h" #include "cell.h" #include "compiler.h" #include "debuginfo.h" #include "disassembler.h" #include "exec.h" #include "lexer.h" #include "parser.h" #include "pt_dump.h" #include "support.h" bool dump_tokens = false; bool dump_parse = false; bool dump_ast = false; bool dump_listing = false; bool enable_assert = true; unsigned short debug_port = 0; bool repl_no_prompt = false; bool repl_stop_on_any_error = false; static TokenizedSource dump(const TokenizedSource &tokens) { for (auto t: tokens.tokens) { std::cerr << t.tostring() << "\n"; } return tokens; } static const pt::Program *dump(const pt::Program *parsetree) { pt::dump(std::cerr, parsetree); return parsetree; } static const Program *dump(const Program *program) { program->dump(std::cerr); return program; } static void repl(int argc, char *argv[]) { CompilerSupport compiler_support(""); RuntimeSupport runtime_support(""); if (not repl_no_prompt) { std::cout << "Neon 0.1\n"; std::cout << "Type \"help\" for more information, or \"exit\" to leave.\n"; } std::map<std::string, ExternalGlobalInfo> globals_ast; std::map<std::string, Cell *> globals_cells; std::vector<std::unique_ptr<TokenizedSource>> input; for (;;) { if (not repl_no_prompt) { std::cout << "> "; } std::string s; if (not std::getline(std::cin, s)) { if (not repl_no_prompt) { std::cout << std::endl; } break; } if (s == "help") { std::cout << "\n"; std::cout << "Welcome to Neon 0.1!\n"; std::cout << "\n"; std::cout << "See https://github.com/ghewgill/neon-lang for information.\n"; } else if (s == "exit" || s == "quit") { exit(0); } else { try { auto tokens = tokenize("", s); const Program *ast; try { auto parsetree = parse(*tokens); // Grab a copy of the globals and let analyze() modify the copy. // Some errors will be detected after things are added to the // global scope, and we don't want to capture those global // things if there was an error. (Errors are handled by exception // so the assignment back to globals_ast won't happen.) auto globals = globals_ast; ast = analyze(&compiler_support, parsetree.get(), &globals); globals_ast = globals; for (auto g: globals_ast) { if (globals_cells.find(g.first) == globals_cells.end()) { globals_cells[g.first] = new Cell(); } } } catch (CompilerError *) { auto exprtree = parseExpression(*tokens); std::vector<std::unique_ptr<pt::FunctionCallExpression::Argument>> print_args; print_args.emplace_back( std::unique_ptr<pt::FunctionCallExpression::Argument> { new pt::FunctionCallExpression::Argument( Token(IN, "IN"), Token(), std::unique_ptr<pt::Expression> { new pt::FunctionCallExpression( Token(), std::unique_ptr<pt::DotExpression> { new pt::DotExpression( Token(), std::move(exprtree), Token(IDENTIFIER, "toString") )}, {}, Token() )} )} ); std::vector<std::unique_ptr<pt::Statement>> statements; statements.emplace_back( std::unique_ptr<pt::Statement> { new pt::ExpressionStatement( Token(), std::unique_ptr<pt::Expression> { new pt::FunctionCallExpression( Token(), std::unique_ptr<pt::Expression> { new pt::IdentifierExpression( Token(), "print" )}, std::move(print_args), Token() )} )} ); auto parsetree = std::unique_ptr<pt::Program> { new pt::Program( Token(), std::move(statements), "", "00000000000000000000000000000000" )}; ast = analyze(&compiler_support, parsetree.get(), &globals_ast); } DebugInfo debug("-", s); auto bytecode = compile(ast, &debug); if (dump_listing) { disassemble(bytecode, std::cerr, &debug); } exec("-", bytecode, &debug, &runtime_support, false, 0, argc, argv, &globals_cells); input.emplace_back(std::move(tokens)); } catch (CompilerError *error) { error->write(std::cerr); if (repl_stop_on_any_error) { exit(1); } } } } exit(0); } int main(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "Usage: %s filename.neon\n", argv[0]); exit(1); } int a = 1; while (a < argc && argv[a][0] == '-' && argv[a][1] != '\0') { std::string arg = argv[a]; if (arg == "-c") { if (argv[a+1] == NULL) { fprintf(stderr, "%s: -c requires argument\n", argv[0]); exit(1); } break; } else if (arg == "-d") { a++; debug_port = static_cast<unsigned short>(std::stoul(argv[a])); } else if (arg == "-l") { dump_listing = true; } else if (arg == "-n") { enable_assert = false; } else if (arg == "--repl-no-prompt") { repl_no_prompt = true; } else if (arg == "--repl-stop-on-any-error") { repl_stop_on_any_error = true; } else { fprintf(stderr, "Unknown option: %s\n", arg.c_str()); exit(1); } a++; } if (a >= argc) { repl(argc, argv); } const std::string name = argv[a]; std::string source_path; std::stringstream buf; if (name == "-") { buf << std::cin.rdbuf(); } else if (name == "-c") { buf << argv[a+1]; } else { auto i = name.find_last_of("/:\\"); if (i != std::string::npos) { source_path = name.substr(0, i+1); } std::ifstream inf(name); if (not inf) { fprintf(stderr, "Source file not found: %s\n", name.c_str()); exit(1); } buf << inf.rdbuf(); } CompilerSupport compiler_support(source_path); RuntimeSupport runtime_support(source_path); std::vector<unsigned char> bytecode; // TODO - Allow reading debug information from file. DebugInfo debug(name, buf.str()); // Pretty hacky way of checking whether the input file is compiled or not. if (name[name.length()-1] != 'x') { try { auto tokens = tokenize(name, buf.str()); if (dump_tokens) { dump(*tokens); } auto parsetree = parse(*tokens); if (dump_parse) { dump(parsetree.get()); } auto ast = analyze(&compiler_support, parsetree.get()); if (dump_ast) { dump(ast); } bytecode = compile(ast, &debug); if (dump_listing) { disassemble(bytecode, std::cerr, &debug); } } catch (CompilerError *error) { error->write(std::cerr); exit(1); } } else { std::string s = buf.str(); std::copy(s.begin(), s.end(), std::back_inserter(bytecode)); } exec(name, bytecode, &debug, &runtime_support, enable_assert, debug_port, argc-a, argv+a); } <commit_msg>Fix crash in main.cpp on the debug port option<commit_after>#include <fstream> #include <iostream> #include <sstream> #include "analyzer.h" #include "ast.h" #include "cell.h" #include "compiler.h" #include "debuginfo.h" #include "disassembler.h" #include "exec.h" #include "lexer.h" #include "parser.h" #include "pt_dump.h" #include "support.h" bool dump_tokens = false; bool dump_parse = false; bool dump_ast = false; bool dump_listing = false; bool enable_assert = true; unsigned short debug_port = 0; bool repl_no_prompt = false; bool repl_stop_on_any_error = false; static TokenizedSource dump(const TokenizedSource &tokens) { for (auto t: tokens.tokens) { std::cerr << t.tostring() << "\n"; } return tokens; } static const pt::Program *dump(const pt::Program *parsetree) { pt::dump(std::cerr, parsetree); return parsetree; } static const Program *dump(const Program *program) { program->dump(std::cerr); return program; } static void repl(int argc, char *argv[]) { CompilerSupport compiler_support(""); RuntimeSupport runtime_support(""); if (not repl_no_prompt) { std::cout << "Neon 0.1\n"; std::cout << "Type \"help\" for more information, or \"exit\" to leave.\n"; } std::map<std::string, ExternalGlobalInfo> globals_ast; std::map<std::string, Cell *> globals_cells; std::vector<std::unique_ptr<TokenizedSource>> input; for (;;) { if (not repl_no_prompt) { std::cout << "> "; } std::string s; if (not std::getline(std::cin, s)) { if (not repl_no_prompt) { std::cout << std::endl; } break; } if (s == "help") { std::cout << "\n"; std::cout << "Welcome to Neon 0.1!\n"; std::cout << "\n"; std::cout << "See https://github.com/ghewgill/neon-lang for information.\n"; } else if (s == "exit" || s == "quit") { exit(0); } else { try { auto tokens = tokenize("", s); const Program *ast; try { auto parsetree = parse(*tokens); // Grab a copy of the globals and let analyze() modify the copy. // Some errors will be detected after things are added to the // global scope, and we don't want to capture those global // things if there was an error. (Errors are handled by exception // so the assignment back to globals_ast won't happen.) auto globals = globals_ast; ast = analyze(&compiler_support, parsetree.get(), &globals); globals_ast = globals; for (auto g: globals_ast) { if (globals_cells.find(g.first) == globals_cells.end()) { globals_cells[g.first] = new Cell(); } } } catch (CompilerError *) { auto exprtree = parseExpression(*tokens); std::vector<std::unique_ptr<pt::FunctionCallExpression::Argument>> print_args; print_args.emplace_back( std::unique_ptr<pt::FunctionCallExpression::Argument> { new pt::FunctionCallExpression::Argument( Token(IN, "IN"), Token(), std::unique_ptr<pt::Expression> { new pt::FunctionCallExpression( Token(), std::unique_ptr<pt::DotExpression> { new pt::DotExpression( Token(), std::move(exprtree), Token(IDENTIFIER, "toString") )}, {}, Token() )} )} ); std::vector<std::unique_ptr<pt::Statement>> statements; statements.emplace_back( std::unique_ptr<pt::Statement> { new pt::ExpressionStatement( Token(), std::unique_ptr<pt::Expression> { new pt::FunctionCallExpression( Token(), std::unique_ptr<pt::Expression> { new pt::IdentifierExpression( Token(), "print" )}, std::move(print_args), Token() )} )} ); auto parsetree = std::unique_ptr<pt::Program> { new pt::Program( Token(), std::move(statements), "", "00000000000000000000000000000000" )}; ast = analyze(&compiler_support, parsetree.get(), &globals_ast); } DebugInfo debug("-", s); auto bytecode = compile(ast, &debug); if (dump_listing) { disassemble(bytecode, std::cerr, &debug); } exec("-", bytecode, &debug, &runtime_support, false, 0, argc, argv, &globals_cells); input.emplace_back(std::move(tokens)); } catch (CompilerError *error) { error->write(std::cerr); if (repl_stop_on_any_error) { exit(1); } } } } exit(0); } int main(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "Usage: %s filename.neon\n", argv[0]); exit(1); } int a = 1; while (a < argc && argv[a][0] == '-' && argv[a][1] != '\0') { std::string arg = argv[a]; if (arg == "-c") { if (argv[a+1] == NULL) { fprintf(stderr, "%s: -c requires argument\n", argv[0]); exit(1); } break; } else if (arg == "-d") { a++; try { debug_port = static_cast<unsigned short>(std::stoul(argv[a])); } catch(std::invalid_argument) { fprintf(stderr, "%s: -d requires integer argument\n", argv[0]); exit(1); } } else if (arg == "-l") { dump_listing = true; } else if (arg == "-n") { enable_assert = false; } else if (arg == "--repl-no-prompt") { repl_no_prompt = true; } else if (arg == "--repl-stop-on-any-error") { repl_stop_on_any_error = true; } else { fprintf(stderr, "Unknown option: %s\n", arg.c_str()); exit(1); } a++; } if (a >= argc) { repl(argc, argv); } const std::string name = argv[a]; std::string source_path; std::stringstream buf; if (name == "-") { buf << std::cin.rdbuf(); } else if (name == "-c") { buf << argv[a+1]; } else { auto i = name.find_last_of("/:\\"); if (i != std::string::npos) { source_path = name.substr(0, i+1); } std::ifstream inf(name); if (not inf) { fprintf(stderr, "Source file not found: %s\n", name.c_str()); exit(1); } buf << inf.rdbuf(); } CompilerSupport compiler_support(source_path); RuntimeSupport runtime_support(source_path); std::vector<unsigned char> bytecode; // TODO - Allow reading debug information from file. DebugInfo debug(name, buf.str()); // Pretty hacky way of checking whether the input file is compiled or not. if (name[name.length()-1] != 'x') { try { auto tokens = tokenize(name, buf.str()); if (dump_tokens) { dump(*tokens); } auto parsetree = parse(*tokens); if (dump_parse) { dump(parsetree.get()); } auto ast = analyze(&compiler_support, parsetree.get()); if (dump_ast) { dump(ast); } bytecode = compile(ast, &debug); if (dump_listing) { disassemble(bytecode, std::cerr, &debug); } } catch (CompilerError *error) { error->write(std::cerr); exit(1); } } else { std::string s = buf.str(); std::copy(s.begin(), s.end(), std::back_inserter(bytecode)); } exec(name, bytecode, &debug, &runtime_support, enable_assert, debug_port, argc-a, argv+a); } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <map> #include <algorithm> #include <queue> #include "utils.h" #include "implicit_graph.h" #include "bit_vector.h" #include <limits.h> #include <unistd.h> std::string get_path(){ char result[ PATH_MAX ]; ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX ); return std::string( result, (count > 0) ? count : 0 ).substr(0, 38); } template <typename T> void debug(std::string what, T value){ std::cout << what << ": " << value << std::endl; } int main(int argc, char **argv){ std::string root_path = get_path(); std::string s = read(root_path + argv[1]); std::transform(s.begin(), s.end(), s.begin(), ::toupper); int n = s.size(); std::queue<u_int> q; std::vector<node> G(n); char bwt[n + 1]; std::vector< std::pair<bool, bool> > bit_vectors = create_bit_vectors(3, bwt, s, G, q); for(int i = 1; i < n+1; ++i) std::cout << bit_vectors[i].second << " " << bit_vectors[i].first << std::endl; //G = createImplicitGraph(3, bwt, s); return 0; }<commit_msg>bug fix<commit_after>#include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <map> #include <algorithm> #include <queue> #include "utils.h" #include "implicit_graph.h" #include "bit_vector.h" #include <limits.h> #include <unistd.h> std::string get_path(){ char result[ PATH_MAX ]; ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX ); return std::string( result, (count > 0) ? count : 0 ); } template <typename T> void debug(std::string what, T value){ std::cout << what << ": " << value << std::endl; } int main(int argc, char **argv){ std::string root_path = get_path(); root_path = root_path.substr(0, root_path.size()-8); std::string s = read(root_path + argv[1]); std::transform(s.begin(), s.end(), s.begin(), ::toupper); int n = s.size(); std::queue<u_int> q; std::vector<node> G(n); char bwt[n + 1]; std::vector< std::pair<bool, bool> > bit_vectors = create_bit_vectors(3, bwt, s, G, q); for(int i = 1; i < n+1; ++i) std::cout << bit_vectors[i].second << " " << bit_vectors[i].first << std::endl; G = createImplicitGraph(3, bwt, s); return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <Carbon/Carbon.h> #include "build/build_config.h" #include <vector> #include "base/logging.h" #include "base/mac_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/plugin_process_host.h" void PluginProcessHost::OnPluginSelectWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); } void PluginProcessHost::OnPluginShowWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); CGRect window_bounds = { { window_rect.x(), window_rect.y() }, { window_rect.width(), window_rect.height() } }; CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); if (CGRectEqualToRect(window_bounds, main_display_bounds)) { plugin_fullscreen_windows_set_.insert(window_id); // If the plugin has just shown a window that's the same dimensions as // the main display, hide the menubar so that it has the whole screen. ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::RequestFullScreen)); } } void PluginProcessHost::OnPluginHideWindow(uint32 window_id, gfx::Rect window_rect) { plugin_visible_windows_set_.erase(window_id); plugin_modal_windows_set_.erase(window_id); if (plugin_fullscreen_windows_set_.find(window_id) != plugin_fullscreen_windows_set_.end()) { plugin_fullscreen_windows_set_.erase(window_id); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ReleaseFullScreen)); } } void PluginProcessHost::OnPluginDisposeWindow(uint32 window_id, gfx::Rect window_rect) { OnPluginHideWindow(window_id, window_rect); } void PluginProcessHost::OnAppActivation() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); // If our plugin process has any modal windows up, we need to bring it forward // so that they act more like an in-process modal window would. if (!plugin_modal_windows_set_.empty()) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ActivateProcess, handle())); } } <commit_msg>Only request full-screen once per plugin window<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <Carbon/Carbon.h> #include "build/build_config.h" #include <vector> #include "base/logging.h" #include "base/mac_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/plugin_process_host.h" void PluginProcessHost::OnPluginSelectWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); } void PluginProcessHost::OnPluginShowWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); CGRect window_bounds = { { window_rect.x(), window_rect.y() }, { window_rect.width(), window_rect.height() } }; CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); if (CGRectEqualToRect(window_bounds, main_display_bounds) && (plugin_fullscreen_windows_set_.find(window_id) == plugin_fullscreen_windows_set_.end())) { plugin_fullscreen_windows_set_.insert(window_id); // If the plugin has just shown a window that's the same dimensions as // the main display, hide the menubar so that it has the whole screen. // (but only if we haven't already seen this fullscreen window, since // otherwise our refcounting can get skewed). ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::RequestFullScreen)); } } void PluginProcessHost::OnPluginHideWindow(uint32 window_id, gfx::Rect window_rect) { plugin_visible_windows_set_.erase(window_id); plugin_modal_windows_set_.erase(window_id); if (plugin_fullscreen_windows_set_.find(window_id) != plugin_fullscreen_windows_set_.end()) { plugin_fullscreen_windows_set_.erase(window_id); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ReleaseFullScreen)); } } void PluginProcessHost::OnPluginDisposeWindow(uint32 window_id, gfx::Rect window_rect) { OnPluginHideWindow(window_id, window_rect); } void PluginProcessHost::OnAppActivation() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); // If our plugin process has any modal windows up, we need to bring it forward // so that they act more like an in-process modal window would. if (!plugin_modal_windows_set_.empty()) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ActivateProcess, handle())); } } <|endoftext|>
<commit_before>#include <QApplication> #include <QFileInfo> #include <QCommandLineParser> #include "mainwindow.h" int main(int argc, char **argv) { QApplication app(argc, argv); QApplication::setApplicationName("ViewDown"); QApplication::setApplicationVersion("1.0"); app.setWindowIcon(QIcon("qrc:///viewdown.ico")); QCommandLineParser parser; parser.setApplicationDescription("Markdown viewer, reloading on changes."); parser.addPositionalArgument("file", "markdown file to view and reload on change."); parser.addPositionalArgument("watch", "files or directories to watch as trigger for reload.", "[watch...]"); const QCommandLineOption styleOption("s", "css file to use as stylesheet.", "css"); parser.addOption(styleOption); parser.addHelpOption(); parser.addVersionOption(); parser.process(app); QUrl styleUrl; if (parser.isSet(styleOption)) { const QString path = parser.value(styleOption); QFileInfo info = QFileInfo(path); if (info.exists()) styleUrl = QUrl("file://"+info.canonicalPath()+"/"); else qWarning("No such file: %s", qPrintable(path)); } if (styleUrl.isEmpty()) styleUrl = QUrl("qrc:///github.css"); MainWindow *browser = new MainWindow(parser.positionalArguments(), styleUrl); browser->show(); return app.exec(); } <commit_msg>fix style url<commit_after>#include <QApplication> #include <QFileInfo> #include <QCommandLineParser> #include "mainwindow.h" int main(int argc, char **argv) { QApplication app(argc, argv); QApplication::setApplicationName("ViewDown"); QApplication::setApplicationVersion("1.0"); app.setWindowIcon(QIcon("qrc:///viewdown.ico")); QCommandLineParser parser; parser.setApplicationDescription("Markdown viewer, reloading on changes."); parser.addPositionalArgument("file", "markdown file to view and reload on change."); parser.addPositionalArgument("watch", "files or directories to watch as trigger for reload.", "[watch...]"); const QCommandLineOption styleOption("s", "css file to use as stylesheet.", "css"); parser.addOption(styleOption); parser.addHelpOption(); parser.addVersionOption(); parser.process(app); QUrl styleUrl; if (parser.isSet(styleOption)) { const QString path = parser.value(styleOption); QFileInfo info = QFileInfo(path); if (info.exists()) styleUrl = QUrl::fromLocalFile(info.canonicalFilePath()); else qWarning("No such file: %s", qPrintable(path)); } if (styleUrl.isEmpty()) styleUrl = QUrl("qrc:///github.css"); MainWindow *browser = new MainWindow(parser.positionalArguments(), styleUrl); browser->show(); return app.exec(); } <|endoftext|>
<commit_before><commit_msg>WaE: unused variable 's_pAccessibleFactoryFunc'<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/touch/tabs/touch_tab.h" #include "app/resource_bundle.h" #include "chrome/browser/themes/browser_theme_provider.h" #include "gfx/canvas_skia.h" #include "gfx/favicon_size.h" #include "gfx/path.h" #include "gfx/skbitmap_operations.h" #include "grit/app_resources.h" #include "grit/theme_resources.h" static const int kLeftPadding = 16; static const int kRightPadding = 15; static const int kDropShadowHeight = 2; TouchTab::TouchTabImage TouchTab::tab_alpha = {0}; TouchTab::TouchTabImage TouchTab::tab_active = {0}; TouchTab::TouchTabImage TouchTab::tab_inactive = {0}; //////////////////////////////////////////////////////////////////////////////// // TouchTab, public: TouchTab::TouchTab(TabController* controller) : BaseTab(controller) { InitTabResources(); } TouchTab::~TouchTab() { } // static gfx::Size TouchTab::GetMinimumUnselectedSize() { InitTabResources(); gfx::Size minimum_size; minimum_size.set_width(kLeftPadding + kRightPadding); minimum_size.set_height(32); return minimum_size; } //////////////////////////////////////////////////////////////////////////////// // TouchTab, views::View overrides: void TouchTab::Paint(gfx::Canvas* canvas) { // Don't paint if we're narrower than we can render correctly. (This should // only happen during animations). if (width() < GetMinimumUnselectedSize().width() && !data().mini) return; PaintTabBackground(canvas); SkColor title_color = GetThemeProvider()-> GetColor(IsSelected() ? BrowserThemeProvider::COLOR_TAB_TEXT : BrowserThemeProvider::COLOR_BACKGROUND_TAB_TEXT); PaintTitle(canvas, title_color); PaintIcon(canvas); } void TouchTab::Layout() { gfx::Rect local_bounds = GetLocalBounds(false); TouchTabImage* tab_image = &tab_active; TouchTabImage* alpha = &tab_alpha; int image_height = alpha->image_l->height(); int x_base = tab_image->image_l->width(); int y_base = height() - image_height; int center_width = width() - tab_image->l_width - tab_image->r_width; if (center_width < 0) center_width = 0; title_bounds_ = gfx::Rect(x_base, y_base, center_width, image_height); favicon_bounds_ = local_bounds; } bool TouchTab::HasHitTestMask() const { return true; } void TouchTab::GetHitTestMask(gfx::Path* path) const { DCHECK(path); SkScalar h = SkIntToScalar(height()); SkScalar w = SkIntToScalar(width()); path->moveTo(0, h); path->lineTo(0, 0); path->lineTo(w, 0); path->lineTo(w, h); path->lineTo(0, h); path->close(); } //////////////////////////////////////////////////////////////////////////////// // TouchTab, private: void TouchTab::PaintTabBackground(gfx::Canvas* canvas) { if (IsSelected()) { PaintActiveTabBackground(canvas); } } void TouchTab::PaintActiveTabBackground(gfx::Canvas* canvas) { int offset = GetX(views::View::APPLY_MIRRORING_TRANSFORMATION) + background_offset_.x(); ThemeProvider* tp = GetThemeProvider(); if (!tp) NOTREACHED() << "Unable to get theme provider"; SkBitmap* tab_bg = GetThemeProvider()->GetBitmapNamed(IDR_THEME_TOOLBAR); TouchTabImage* tab_image = &tab_active; TouchTabImage* alpha = &tab_alpha; // Draw left edge. int image_height = alpha->image_l->height(); int y_base = height() - image_height; SkBitmap tab_l = SkBitmapOperations::CreateTiledBitmap( *tab_bg, offset, 0, tab_image->l_width, image_height); SkBitmap theme_l = SkBitmapOperations::CreateMaskedBitmap(tab_l, *alpha->image_l); canvas->DrawBitmapInt(theme_l, 0, y_base); // Draw right edge. SkBitmap tab_r = SkBitmapOperations::CreateTiledBitmap(*tab_bg, offset + width() - tab_image->r_width, 0, tab_image->r_width, image_height); SkBitmap theme_r = SkBitmapOperations::CreateMaskedBitmap(tab_r, *alpha->image_r); canvas->DrawBitmapInt(theme_r, width() - tab_image->r_width, y_base); // Draw center. Instead of masking out the top portion we simply skip over it // by incrementing by kDropShadowHeight, since it's a simple rectangle. canvas->TileImageInt(*tab_bg, offset + tab_image->l_width, kDropShadowHeight + tab_image->y_offset, tab_image->l_width, y_base + kDropShadowHeight + tab_image->y_offset, width() - tab_image->l_width - tab_image->r_width, height() - kDropShadowHeight - tab_image->y_offset); // Now draw the highlights/shadows around the tab edge. canvas->DrawBitmapInt(*tab_image->image_l, 0, y_base); canvas->TileImageInt(*tab_image->image_c, tab_image->l_width, y_base, width() - tab_image->l_width - tab_image->r_width, image_height); canvas->DrawBitmapInt(*tab_image->image_r, width() - tab_image->r_width, y_base); } void TouchTab::PaintIcon(gfx::Canvas* canvas) { // TODO(wyck): use thumbnailer to get better page images int x = favicon_bounds_.x(); int y = favicon_bounds_.y(); TouchTabImage* tab_image = &tab_active; int x_base = tab_image->image_l->width(); x += x_base; if (base::i18n::IsRTL()) { x = width() - x - (data().favicon.isNull() ? kFavIconSize : data().favicon.width()); } int favicon_x = x; if (!data().favicon.isNull() && data().favicon.width() != kFavIconSize) favicon_x += (data().favicon.width() - kFavIconSize) / 2; if (data().network_state != TabRendererData::NETWORK_STATE_NONE) { ThemeProvider* tp = GetThemeProvider(); SkBitmap frames(*tp->GetBitmapNamed( (data().network_state == TabRendererData::NETWORK_STATE_WAITING) ? IDR_THROBBER_WAITING : IDR_THROBBER)); int image_size = frames.height(); int image_offset = loading_animation_frame() * image_size; int dst_y = (height() - image_size) / 2; canvas->DrawBitmapInt(frames, image_offset, 0, image_size, image_size, favicon_x, dst_y, image_size, image_size, false); } else { canvas->Save(); canvas->ClipRectInt(0, 0, width(), height()); if (should_display_crashed_favicon()) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap crashed_fav_icon(*rb.GetBitmapNamed(IDR_SAD_FAVICON)); canvas->DrawBitmapInt(crashed_fav_icon, 0, 0, crashed_fav_icon.width(), crashed_fav_icon.height(), favicon_x, (height() - crashed_fav_icon.height()) / 2 + fav_icon_hiding_offset(), kFavIconSize, kFavIconSize, true); } else { if (!data().favicon.isNull()) { int size = 32; canvas->DrawBitmapInt(data().favicon, 0, 0, data().favicon.width(), data().favicon.height(), x, y + fav_icon_hiding_offset(), size, size, true); } } canvas->Restore(); } } // static void TouchTab::InitTabResources() { static bool initialized = false; if (initialized) return; initialized = true; // Load the tab images once now, and maybe again later if the theme changes. LoadTabImages(); } // static void TouchTab::LoadTabImages() { // We're not letting people override tab images just yet. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); tab_alpha.image_l = rb.GetBitmapNamed(IDR_TAB_ALPHA_LEFT); tab_alpha.image_r = rb.GetBitmapNamed(IDR_TAB_ALPHA_RIGHT); tab_active.image_l = rb.GetBitmapNamed(IDR_TAB_ACTIVE_LEFT); tab_active.image_c = rb.GetBitmapNamed(IDR_TAB_ACTIVE_CENTER); tab_active.image_r = rb.GetBitmapNamed(IDR_TAB_ACTIVE_RIGHT); tab_active.l_width = tab_active.image_l->width(); tab_active.r_width = tab_active.image_r->width(); tab_inactive.image_l = rb.GetBitmapNamed(IDR_TAB_INACTIVE_LEFT); tab_inactive.image_c = rb.GetBitmapNamed(IDR_TAB_INACTIVE_CENTER); tab_inactive.image_r = rb.GetBitmapNamed(IDR_TAB_INACTIVE_RIGHT); tab_inactive.l_width = tab_inactive.image_l->width(); tab_inactive.r_width = tab_inactive.image_r->width(); } <commit_msg>Compile fix: the file moved.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/touch/tabs/touch_tab.h" #include "chrome/browser/themes/browser_theme_provider.h" #include "gfx/canvas_skia.h" #include "gfx/favicon_size.h" #include "gfx/path.h" #include "gfx/skbitmap_operations.h" #include "grit/app_resources.h" #include "grit/theme_resources.h" #include "ui/base/resource/resource_bundle.h" static const int kLeftPadding = 16; static const int kRightPadding = 15; static const int kDropShadowHeight = 2; TouchTab::TouchTabImage TouchTab::tab_alpha = {0}; TouchTab::TouchTabImage TouchTab::tab_active = {0}; TouchTab::TouchTabImage TouchTab::tab_inactive = {0}; //////////////////////////////////////////////////////////////////////////////// // TouchTab, public: TouchTab::TouchTab(TabController* controller) : BaseTab(controller) { InitTabResources(); } TouchTab::~TouchTab() { } // static gfx::Size TouchTab::GetMinimumUnselectedSize() { InitTabResources(); gfx::Size minimum_size; minimum_size.set_width(kLeftPadding + kRightPadding); minimum_size.set_height(32); return minimum_size; } //////////////////////////////////////////////////////////////////////////////// // TouchTab, views::View overrides: void TouchTab::Paint(gfx::Canvas* canvas) { // Don't paint if we're narrower than we can render correctly. (This should // only happen during animations). if (width() < GetMinimumUnselectedSize().width() && !data().mini) return; PaintTabBackground(canvas); SkColor title_color = GetThemeProvider()-> GetColor(IsSelected() ? BrowserThemeProvider::COLOR_TAB_TEXT : BrowserThemeProvider::COLOR_BACKGROUND_TAB_TEXT); PaintTitle(canvas, title_color); PaintIcon(canvas); } void TouchTab::Layout() { gfx::Rect local_bounds = GetLocalBounds(false); TouchTabImage* tab_image = &tab_active; TouchTabImage* alpha = &tab_alpha; int image_height = alpha->image_l->height(); int x_base = tab_image->image_l->width(); int y_base = height() - image_height; int center_width = width() - tab_image->l_width - tab_image->r_width; if (center_width < 0) center_width = 0; title_bounds_ = gfx::Rect(x_base, y_base, center_width, image_height); favicon_bounds_ = local_bounds; } bool TouchTab::HasHitTestMask() const { return true; } void TouchTab::GetHitTestMask(gfx::Path* path) const { DCHECK(path); SkScalar h = SkIntToScalar(height()); SkScalar w = SkIntToScalar(width()); path->moveTo(0, h); path->lineTo(0, 0); path->lineTo(w, 0); path->lineTo(w, h); path->lineTo(0, h); path->close(); } //////////////////////////////////////////////////////////////////////////////// // TouchTab, private: void TouchTab::PaintTabBackground(gfx::Canvas* canvas) { if (IsSelected()) { PaintActiveTabBackground(canvas); } } void TouchTab::PaintActiveTabBackground(gfx::Canvas* canvas) { int offset = GetX(views::View::APPLY_MIRRORING_TRANSFORMATION) + background_offset_.x(); ThemeProvider* tp = GetThemeProvider(); if (!tp) NOTREACHED() << "Unable to get theme provider"; SkBitmap* tab_bg = GetThemeProvider()->GetBitmapNamed(IDR_THEME_TOOLBAR); TouchTabImage* tab_image = &tab_active; TouchTabImage* alpha = &tab_alpha; // Draw left edge. int image_height = alpha->image_l->height(); int y_base = height() - image_height; SkBitmap tab_l = SkBitmapOperations::CreateTiledBitmap( *tab_bg, offset, 0, tab_image->l_width, image_height); SkBitmap theme_l = SkBitmapOperations::CreateMaskedBitmap(tab_l, *alpha->image_l); canvas->DrawBitmapInt(theme_l, 0, y_base); // Draw right edge. SkBitmap tab_r = SkBitmapOperations::CreateTiledBitmap(*tab_bg, offset + width() - tab_image->r_width, 0, tab_image->r_width, image_height); SkBitmap theme_r = SkBitmapOperations::CreateMaskedBitmap(tab_r, *alpha->image_r); canvas->DrawBitmapInt(theme_r, width() - tab_image->r_width, y_base); // Draw center. Instead of masking out the top portion we simply skip over it // by incrementing by kDropShadowHeight, since it's a simple rectangle. canvas->TileImageInt(*tab_bg, offset + tab_image->l_width, kDropShadowHeight + tab_image->y_offset, tab_image->l_width, y_base + kDropShadowHeight + tab_image->y_offset, width() - tab_image->l_width - tab_image->r_width, height() - kDropShadowHeight - tab_image->y_offset); // Now draw the highlights/shadows around the tab edge. canvas->DrawBitmapInt(*tab_image->image_l, 0, y_base); canvas->TileImageInt(*tab_image->image_c, tab_image->l_width, y_base, width() - tab_image->l_width - tab_image->r_width, image_height); canvas->DrawBitmapInt(*tab_image->image_r, width() - tab_image->r_width, y_base); } void TouchTab::PaintIcon(gfx::Canvas* canvas) { // TODO(wyck): use thumbnailer to get better page images int x = favicon_bounds_.x(); int y = favicon_bounds_.y(); TouchTabImage* tab_image = &tab_active; int x_base = tab_image->image_l->width(); x += x_base; if (base::i18n::IsRTL()) { x = width() - x - (data().favicon.isNull() ? kFavIconSize : data().favicon.width()); } int favicon_x = x; if (!data().favicon.isNull() && data().favicon.width() != kFavIconSize) favicon_x += (data().favicon.width() - kFavIconSize) / 2; if (data().network_state != TabRendererData::NETWORK_STATE_NONE) { ThemeProvider* tp = GetThemeProvider(); SkBitmap frames(*tp->GetBitmapNamed( (data().network_state == TabRendererData::NETWORK_STATE_WAITING) ? IDR_THROBBER_WAITING : IDR_THROBBER)); int image_size = frames.height(); int image_offset = loading_animation_frame() * image_size; int dst_y = (height() - image_size) / 2; canvas->DrawBitmapInt(frames, image_offset, 0, image_size, image_size, favicon_x, dst_y, image_size, image_size, false); } else { canvas->Save(); canvas->ClipRectInt(0, 0, width(), height()); if (should_display_crashed_favicon()) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap crashed_fav_icon(*rb.GetBitmapNamed(IDR_SAD_FAVICON)); canvas->DrawBitmapInt(crashed_fav_icon, 0, 0, crashed_fav_icon.width(), crashed_fav_icon.height(), favicon_x, (height() - crashed_fav_icon.height()) / 2 + fav_icon_hiding_offset(), kFavIconSize, kFavIconSize, true); } else { if (!data().favicon.isNull()) { int size = 32; canvas->DrawBitmapInt(data().favicon, 0, 0, data().favicon.width(), data().favicon.height(), x, y + fav_icon_hiding_offset(), size, size, true); } } canvas->Restore(); } } // static void TouchTab::InitTabResources() { static bool initialized = false; if (initialized) return; initialized = true; // Load the tab images once now, and maybe again later if the theme changes. LoadTabImages(); } // static void TouchTab::LoadTabImages() { // We're not letting people override tab images just yet. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); tab_alpha.image_l = rb.GetBitmapNamed(IDR_TAB_ALPHA_LEFT); tab_alpha.image_r = rb.GetBitmapNamed(IDR_TAB_ALPHA_RIGHT); tab_active.image_l = rb.GetBitmapNamed(IDR_TAB_ACTIVE_LEFT); tab_active.image_c = rb.GetBitmapNamed(IDR_TAB_ACTIVE_CENTER); tab_active.image_r = rb.GetBitmapNamed(IDR_TAB_ACTIVE_RIGHT); tab_active.l_width = tab_active.image_l->width(); tab_active.r_width = tab_active.image_r->width(); tab_inactive.image_l = rb.GetBitmapNamed(IDR_TAB_INACTIVE_LEFT); tab_inactive.image_c = rb.GetBitmapNamed(IDR_TAB_INACTIVE_CENTER); tab_inactive.image_r = rb.GetBitmapNamed(IDR_TAB_INACTIVE_RIGHT); tab_inactive.l_width = tab_inactive.image_l->width(); tab_inactive.r_width = tab_inactive.image_r->width(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ipolypolygoneditorcontroller.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-07-06 13:16:59 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDR_IPOLYPOLYGONEDITORCONTROLLER_HXX #define _SDR_IPOLYPOLYGONEDITORCONTROLLER_HXX #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif #ifndef _SVDEDTV_HXX #include <svx/svdedtv.hxx> #endif //************************************************************ // Defines //************************************************************ enum SdrPathSmoothKind {SDRPATHSMOOTH_DONTCARE, // nur fuer Statusabfrage SDRPATHSMOOTH_ANGULAR, // Eckig SDRPATHSMOOTH_ASYMMETRIC, // unsymmetrisch, normales Smooth SDRPATHSMOOTH_SYMMETRIC}; // symmetrisch enum SdrPathSegmentKind {SDRPATHSEGMENT_DONTCARE, // nur fuer Statusabfrage SDRPATHSEGMENT_LINE, // gerader Streckenabschnitt SDRPATHSEGMENT_CURVE, // Kurvenabschnitt (Bezier) SDRPATHSEGMENT_TOGGLE}; // nur fuer Set: Toggle enum SdrObjClosedKind {SDROBJCLOSED_DONTCARE, // nur fuer Statusabfrage SDROBJCLOSED_OPEN, // Objekte geoeffnet (Linie, Polyline, ...) SDROBJCLOSED_CLOSED, // Objekte geschlossen (Polygon, ...) SDROBJCLOSED_TOGGLE}; // nur fuer Set: Toggle (not implemented yet) class IPolyPolygonEditorController { public: virtual void DeleteMarkedPoints() = 0; virtual BOOL IsDeleteMarkedPointsPossible() const = 0; virtual void RipUpAtMarkedPoints() = 0; virtual bool IsRipUpAtMarkedPointsPossible() const = 0; virtual BOOL IsSetMarkedSegmentsKindPossible() const = 0; virtual SdrPathSegmentKind GetMarkedSegmentsKind() const = 0; virtual void SetMarkedSegmentsKind(SdrPathSegmentKind eKind) = 0; virtual BOOL IsSetMarkedPointsSmoothPossible() const = 0; virtual SdrPathSmoothKind GetMarkedPointsSmooth() const = 0; virtual void SetMarkedPointsSmooth(SdrPathSmoothKind eKind) = 0; virtual void CloseMarkedObjects(BOOL bToggle, BOOL bOpen ) = 0; virtual bool IsOpenCloseMarkedObjectsPossible() const = 0; virtual SdrObjClosedKind GetMarkedObjectsClosedState() const = 0; }; #endif //_SDR_IPOLYPOLYGONEDITORCONTROLLER_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.354); FILE MERGED 2008/04/01 12:46:42 thb 1.2.354.2: #i85898# Stripping all external header guards 2008/03/31 14:18:13 rt 1.2.354.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ipolypolygoneditorcontroller.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SDR_IPOLYPOLYGONEDITORCONTROLLER_HXX #define _SDR_IPOLYPOLYGONEDITORCONTROLLER_HXX #include "svx/svxdllapi.h" #include <svx/svdedtv.hxx> //************************************************************ // Defines //************************************************************ enum SdrPathSmoothKind {SDRPATHSMOOTH_DONTCARE, // nur fuer Statusabfrage SDRPATHSMOOTH_ANGULAR, // Eckig SDRPATHSMOOTH_ASYMMETRIC, // unsymmetrisch, normales Smooth SDRPATHSMOOTH_SYMMETRIC}; // symmetrisch enum SdrPathSegmentKind {SDRPATHSEGMENT_DONTCARE, // nur fuer Statusabfrage SDRPATHSEGMENT_LINE, // gerader Streckenabschnitt SDRPATHSEGMENT_CURVE, // Kurvenabschnitt (Bezier) SDRPATHSEGMENT_TOGGLE}; // nur fuer Set: Toggle enum SdrObjClosedKind {SDROBJCLOSED_DONTCARE, // nur fuer Statusabfrage SDROBJCLOSED_OPEN, // Objekte geoeffnet (Linie, Polyline, ...) SDROBJCLOSED_CLOSED, // Objekte geschlossen (Polygon, ...) SDROBJCLOSED_TOGGLE}; // nur fuer Set: Toggle (not implemented yet) class IPolyPolygonEditorController { public: virtual void DeleteMarkedPoints() = 0; virtual BOOL IsDeleteMarkedPointsPossible() const = 0; virtual void RipUpAtMarkedPoints() = 0; virtual bool IsRipUpAtMarkedPointsPossible() const = 0; virtual BOOL IsSetMarkedSegmentsKindPossible() const = 0; virtual SdrPathSegmentKind GetMarkedSegmentsKind() const = 0; virtual void SetMarkedSegmentsKind(SdrPathSegmentKind eKind) = 0; virtual BOOL IsSetMarkedPointsSmoothPossible() const = 0; virtual SdrPathSmoothKind GetMarkedPointsSmooth() const = 0; virtual void SetMarkedPointsSmooth(SdrPathSmoothKind eKind) = 0; virtual void CloseMarkedObjects(BOOL bToggle, BOOL bOpen ) = 0; virtual bool IsOpenCloseMarkedObjectsPossible() const = 0; virtual SdrObjClosedKind GetMarkedObjectsClosedState() const = 0; }; #endif //_SDR_IPOLYPOLYGONEDITORCONTROLLER_HXX <|endoftext|>
<commit_before>/* * File: main.cpp * Author: ben * * Created on September 19, 2012, 3:01 PM */ #include <cstdlib> #include <iostream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include "Config.h" #include "Simulation.h" #include "observables/SizeObservable.h" #include "observables/GridObservable.h" #include "observables/TimeSliceObservable.h" #include "moves/MoveFactory.h" #include "observables/VolumeProfileObservable.h" #include "observables/SpectralDimensionObservable.h" #include "observables/ShapeObservable.h" #include "observables/HausdorffObservable.h" #include "observables/ConnectivityObservable.h" #include "observables/AcceptanceRateObservable.h" #include "observables/TriangleRatioObservable.h" using namespace std; struct ConfigStruct { double alpha, deltaVolume; unsigned int N, T, numSweeps, sweepLength, volume, sizeFreq, gridFreq, timeFreq, volProfFreq, specDimFreq, shapeFreq, hausFreq, connFreq, accFreq, ratioFreq; std::string gridFile; }; /** * Build a basic configuration structure. */ ConfigStruct buildConfiguration() { const boost::property_tree::ptree& pt = Config::getInstance().getPropertyTree(); ConfigStruct config; config.N = pt.get<unsigned int>("general.N"); config.T = pt.get<unsigned int>("general.T"); config.alpha = pt.get<double>("general.alpha"); config.volume = pt.get<unsigned int>("general.volume"); config.deltaVolume = pt.get<double>("general.delta"); config.numSweeps = pt.get<unsigned int>("general.numSweeps"); config.sweepLength = pt.get<unsigned int>("general.sweepLength"); config.gridFile = pt.get("general.gridFile", std::string("")); /* Check for observables */ config.sizeFreq = pt.get("size.freq", 0); config.gridFreq = pt.get("grid.freq", 0); config.timeFreq = pt.get("time.freq", 0); config.volProfFreq = pt.get("vol.freq", 0); config.specDimFreq = pt.get("spec.freq", 0); config.shapeFreq = pt.get("shape.freq", 0); config.hausFreq = pt.get("haus.freq", 0); config.connFreq = pt.get("conn.freq", 0); config.accFreq = pt.get("acc.freq", 0); config.ratioFreq = pt.get("ratio.freq", 0); return config; } int main(int argc, char** argv) { const char* configFile = "config.ini"; if (argc >= 2) { configFile = argv[1]; } Config::getInstance().parseConfiguration(configFile); ConfigStruct config = buildConfiguration(); Simulation simulation; /* Create observables */ if (config.sizeFreq > 0) { SizeObservable* sizeObservable = new SizeObservable(config.sizeFreq, 0); simulation.addObservable(sizeObservable); } if (config.gridFreq > 0) { GridObservable* gridObservable = new GridObservable(simulation, config.gridFreq); simulation.addObservable(gridObservable); } if (config.timeFreq > 0) { TimeSliceObservable* timeSliceObservable = new TimeSliceObservable(config.timeFreq); simulation.addObservable(timeSliceObservable); if (config.volProfFreq > 0) { VolumeProfileObservable* volumeProfileObservable = new VolumeProfileObservable(config.volProfFreq, timeSliceObservable, &simulation); simulation.addObservable(volumeProfileObservable); } } if (config.specDimFreq > 0) { SpectralDimensionObservable* spectralDimensionObservable = new SpectralDimensionObservable(config.specDimFreq); simulation.addObservable(spectralDimensionObservable); } if (config.shapeFreq > 0) { ShapeObservable* shapeObservable = new ShapeObservable(config.shapeFreq); simulation.addObservable(shapeObservable); } if (config.hausFreq > 0) { HausdorffObservable* hausdorffObservable = new HausdorffObservable(&simulation, config.hausFreq); simulation.addObservable(hausdorffObservable); } if (config.connFreq > 0) { ConnectivityObservable* connectivityObservable = new ConnectivityObservable(config.connFreq); simulation.addObservable(connectivityObservable); } if (config.accFreq > 0) { AcceptanceRateObservable* acceptanceRateObservable = new AcceptanceRateObservable(config.accFreq, &simulation.getMoveFactory()); simulation.addObservable(acceptanceRateObservable); } if (config.ratioFreq > 0) { TriangleRatioObservable* triangleRatioObservable = new TriangleRatioObservable(config.accFreq, &simulation); simulation.addObservable(triangleRatioObservable); } if (config.gridFile.size() > 0) { simulation.readFromFile(config.gridFile.c_str()); } else { simulation.generateInitialTriangulation(config.N, config.T); } simulation.Metropolis(config.alpha, config.volume, config.deltaVolume, config.numSweeps, config.sweepLength); std::cout << "Simulation ended." << std::endl; return 0; }<commit_msg>Fixed error<commit_after>/* * File: main.cpp * Author: ben * * Created on September 19, 2012, 3:01 PM */ #include <cstdlib> #include <iostream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include "Config.h" #include "Simulation.h" #include "observables/SizeObservable.h" #include "observables/GridObservable.h" #include "observables/TimeSliceObservable.h" #include "moves/MoveFactory.h" #include "observables/VolumeProfileObservable.h" #include "observables/SpectralDimensionObservable.h" #include "observables/ShapeObservable.h" #include "observables/HausdorffObservable.h" #include "observables/ConnectivityObservable.h" #include "observables/AcceptanceRateObservable.h" #include "observables/TriangleRatioObservable.h" using namespace std; struct ConfigStruct { double alpha, deltaVolume; unsigned int N, T, numSweeps, sweepLength, volume, sizeFreq, gridFreq, timeFreq, volProfFreq, specDimFreq, shapeFreq, hausFreq, connFreq, accFreq, ratioFreq; std::string gridFile; }; /** * Build a basic configuration structure. */ ConfigStruct buildConfiguration() { const boost::property_tree::ptree& pt = Config::getInstance().getPropertyTree(); ConfigStruct config; config.N = pt.get<unsigned int>("general.N"); config.T = pt.get<unsigned int>("general.T"); config.alpha = pt.get<double>("general.alpha"); config.volume = pt.get<unsigned int>("general.volume"); config.deltaVolume = pt.get<double>("general.delta"); config.numSweeps = pt.get<unsigned int>("general.numSweeps"); config.sweepLength = pt.get<unsigned int>("general.sweepLength"); config.gridFile = pt.get("general.gridFile", std::string("")); /* Check for observables */ config.sizeFreq = pt.get("size.freq", 0); config.gridFreq = pt.get("grid.freq", 0); config.timeFreq = pt.get("time.freq", 0); config.volProfFreq = pt.get("vol.freq", 0); config.specDimFreq = pt.get("spec.freq", 0); config.shapeFreq = pt.get("shape.freq", 0); config.hausFreq = pt.get("haus.freq", 0); config.connFreq = pt.get("conn.freq", 0); config.accFreq = pt.get("acc.freq", 0); config.ratioFreq = pt.get("ratio.freq", 0); return config; } int main(int argc, char** argv) { const char* configFile = "config.ini"; if (argc >= 2) { configFile = argv[1]; } Config::getInstance().parseConfiguration(configFile); ConfigStruct config = buildConfiguration(); Simulation simulation; /* Create observables */ if (config.sizeFreq > 0) { SizeObservable* sizeObservable = new SizeObservable(config.sizeFreq, 0); simulation.addObservable(sizeObservable); } if (config.gridFreq > 0) { GridObservable* gridObservable = new GridObservable(simulation, config.gridFreq); simulation.addObservable(gridObservable); } if (config.timeFreq > 0) { TimeSliceObservable* timeSliceObservable = new TimeSliceObservable(config.timeFreq); simulation.addObservable(timeSliceObservable); if (config.volProfFreq > 0) { VolumeProfileObservable* volumeProfileObservable = new VolumeProfileObservable(config.volProfFreq, timeSliceObservable, &simulation); simulation.addObservable(volumeProfileObservable); } } if (config.specDimFreq > 0) { SpectralDimensionObservable* spectralDimensionObservable = new SpectralDimensionObservable(config.specDimFreq); simulation.addObservable(spectralDimensionObservable); } if (config.shapeFreq > 0) { ShapeObservable* shapeObservable = new ShapeObservable(config.shapeFreq); simulation.addObservable(shapeObservable); } if (config.hausFreq > 0) { HausdorffObservable* hausdorffObservable = new HausdorffObservable(&simulation, config.hausFreq); simulation.addObservable(hausdorffObservable); } if (config.connFreq > 0) { ConnectivityObservable* connectivityObservable = new ConnectivityObservable(config.connFreq); simulation.addObservable(connectivityObservable); } if (config.accFreq > 0) { AcceptanceRateObservable* acceptanceRateObservable = new AcceptanceRateObservable(config.accFreq, &simulation.getMoveFactory()); simulation.addObservable(acceptanceRateObservable); } if (config.ratioFreq > 0) { TriangleRatioObservable* triangleRatioObservable = new TriangleRatioObservable(config.ratioFreq, &simulation); simulation.addObservable(triangleRatioObservable); } if (config.gridFile.size() > 0) { simulation.readFromFile(config.gridFile.c_str()); } else { simulation.generateInitialTriangulation(config.N, config.T); } simulation.Metropolis(config.alpha, config.volume, config.deltaVolume, config.numSweeps, config.sweepLength); std::cout << "Simulation ended." << std::endl; return 0; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SpellDialogChildWindow.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:58:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVX_SPELL_DIALOG_CHILD_WINDOW_HXX #include <SpellDialogChildWindow.hxx> #endif #include "svxdlg.hxx" namespace svx { /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ SpellDialogChildWindow::SpellDialogChildWindow ( Window* _pParent, USHORT nId, SfxBindings* pBindings, SfxChildWinInfo* /*pInfo*/) : SfxChildWindow (_pParent, nId) { SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "SvxAbstractDialogFactory::Create() failed"); m_pAbstractSpellDialog = pFact->CreateSvxSpellDialog(_pParent, pBindings, this ); pWindow = m_pAbstractSpellDialog->GetWindow(); eChildAlignment = SFX_ALIGN_NOALIGNMENT; SetHideNotDelete (TRUE); } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ SpellDialogChildWindow::~SpellDialogChildWindow (void) { } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ SfxBindings& SpellDialogChildWindow::GetBindings (void) const { OSL_ASSERT (m_pAbstractSpellDialog != NULL); return m_pAbstractSpellDialog->GetBindings(); } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ void SpellDialogChildWindow::InvalidateSpellDialog() { OSL_ASSERT (m_pAbstractSpellDialog != NULL); if(m_pAbstractSpellDialog) m_pAbstractSpellDialog->Invalidate(); } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ bool SpellDialogChildWindow::HasAutoCorrection() { return false; } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ void SpellDialogChildWindow::AddAutoCorrection( const String& /*rOld*/, const String& /*rNew*/, LanguageType /*eLanguage*/) { DBG_ERROR("AutoCorrection should have been overloaded - if avalable") } } // end of namespace ::svx <commit_msg>INTEGRATION: CWS pchfix02 (1.4.116); FILE MERGED 2006/09/01 17:46:03 kaib 1.4.116.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SpellDialogChildWindow.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 04:08:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef SVX_SPELL_DIALOG_CHILD_WINDOW_HXX #include <SpellDialogChildWindow.hxx> #endif #include "svxdlg.hxx" namespace svx { /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ SpellDialogChildWindow::SpellDialogChildWindow ( Window* _pParent, USHORT nId, SfxBindings* pBindings, SfxChildWinInfo* /*pInfo*/) : SfxChildWindow (_pParent, nId) { SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "SvxAbstractDialogFactory::Create() failed"); m_pAbstractSpellDialog = pFact->CreateSvxSpellDialog(_pParent, pBindings, this ); pWindow = m_pAbstractSpellDialog->GetWindow(); eChildAlignment = SFX_ALIGN_NOALIGNMENT; SetHideNotDelete (TRUE); } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ SpellDialogChildWindow::~SpellDialogChildWindow (void) { } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ SfxBindings& SpellDialogChildWindow::GetBindings (void) const { OSL_ASSERT (m_pAbstractSpellDialog != NULL); return m_pAbstractSpellDialog->GetBindings(); } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ void SpellDialogChildWindow::InvalidateSpellDialog() { OSL_ASSERT (m_pAbstractSpellDialog != NULL); if(m_pAbstractSpellDialog) m_pAbstractSpellDialog->Invalidate(); } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ bool SpellDialogChildWindow::HasAutoCorrection() { return false; } /*------------------------------------------------------------------------- -----------------------------------------------------------------------*/ void SpellDialogChildWindow::AddAutoCorrection( const String& /*rOld*/, const String& /*rNew*/, LanguageType /*eLanguage*/) { DBG_ERROR("AutoCorrection should have been overloaded - if avalable") } } // end of namespace ::svx <|endoftext|>
<commit_before>#include "eigensolver/block_dense_matrix.h" using namespace fm; size_t long_dim = 60 * 1024 * 1024; size_t repeats = 1; void test_gemm(eigen::block_multi_vector::ptr mv) { bool in_mem = mv->get_block(0)->is_in_mem(); dense_matrix::ptr mat = dense_matrix::create_randu<double>(0, 1, mv->get_num_cols(), mv->get_block_size(), matrix_layout_t::L_COL, -1, true); detail::mem_col_matrix_store::const_ptr B = detail::mem_col_matrix_store::cast(mat->get_raw_store()); scalar_variable_impl<double> alpha(2); scalar_variable_impl<double> beta(0); struct timeval start, end; #if 0 eigen::block_multi_vector::ptr res0 = eigen::block_multi_vector::create( long_dim, mv->get_block_size(), mv->get_block_size(), get_scalar_type<double>(), true); res0->set_block(0, dense_matrix::create_const<double>(0, long_dim, mv->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); res0->set_multiply_blocks(1); gettimeofday(&start, NULL); res0 = res0->gemm(*mv, B, alpha, beta); assert(res0->get_num_blocks() == 1); dense_matrix::ptr res_mat0 = res0->get_block(0); res_mat0->materialize_self(); gettimeofday(&end, NULL); printf("agg materialization takes %.3f seconds\n", time_diff(start, end)); #endif for (size_t i = 0; i < repeats; i++) { eigen::block_multi_vector::ptr res1 = eigen::block_multi_vector::create( long_dim, mv->get_block_size(), mv->get_block_size(), get_scalar_type<double>(), true); res1->set_block(0, dense_matrix::create_const<double>(0, long_dim, mv->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); res1->set_multiply_blocks(4); gettimeofday(&start, NULL); res1 = res1->gemm(*mv, B, alpha, beta); assert(res1->get_num_blocks() == 1); dense_matrix::ptr res_mat1 = res1->get_block(0); res_mat1->materialize_self(); gettimeofday(&end, NULL); printf("hierarchical materialization takes %.3f seconds\n", time_diff(start, end)); } for (size_t i = 0; i < repeats; i++) { eigen::block_multi_vector::ptr res2 = eigen::block_multi_vector::create( long_dim, mv->get_block_size(), mv->get_block_size(), get_scalar_type<double>(), true); res2->set_block(0, dense_matrix::create_const<double>(0, long_dim, mv->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); res2->set_multiply_blocks(mv->get_num_blocks()); gettimeofday(&start, NULL); res2 = res2->gemm(*mv, B, alpha, beta); assert(res2->get_num_blocks() == 1); dense_matrix::ptr res_mat2 = res2->get_block(0); res_mat2->materialize_self(); gettimeofday(&end, NULL); printf("flat materialization takes %.3f seconds\n", time_diff(start, end)); } #if 0 dense_matrix::ptr diff = res_mat1->minus(*res_mat2); scalar_variable::ptr max_diff = diff->abs()->max(); scalar_variable::ptr max1 = res_mat1->max(); scalar_variable::ptr max2 = res_mat2->max(); printf("max diff: %g, max mat1: %g, max mat2: %g\n", *(double *) max_diff->get_raw(), *(double *) max1->get_raw(), *(double *) max2->get_raw()); #endif } void test_gemm(bool in_mem, size_t block_size, size_t min_num_blocks, size_t max_num_blocks) { std::vector<dense_matrix::ptr> mats(max_num_blocks); for (size_t i = 0; i < mats.size(); i++) mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim, block_size, matrix_layout_t::L_COL, -1, in_mem); for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks; num_blocks *= 2) { eigen::block_multi_vector::ptr mv = eigen::block_multi_vector::create( long_dim, num_blocks * block_size, block_size, get_scalar_type<double>(), in_mem); printf("gemm on block multi-vector (block size: %ld, #blocks: %ld)\n", mv->get_block_size(), mv->get_num_blocks()); for (size_t i = 0; i < mv->get_num_blocks(); i++) mv->set_block(i, mats[i]); test_gemm(mv); } } void test_MvTransMv(eigen::block_multi_vector::ptr mv1, eigen::block_multi_vector::ptr mv2) { struct timeval start, end; #if 0 mv1->set_multiply_blocks(1); gettimeofday(&start, NULL); fm::dense_matrix::ptr res1 = mv1->MvTransMv(*mv2); gettimeofday(&end, NULL); printf("MvTransMv (1 block) takes %.3f seconds\n", time_diff(start, end)); #endif mv1->set_multiply_blocks(4); for (size_t i = 0; i < repeats; i++) { gettimeofday(&start, NULL); fm::dense_matrix::ptr res2 = mv1->MvTransMv(*mv2); gettimeofday(&end, NULL); printf("MvTransMv (4 blocks) takes %.3f seconds\n", time_diff(start, end)); } mv1->set_multiply_blocks(mv1->get_num_blocks()); for (size_t i = 0; i < repeats; i++) { gettimeofday(&start, NULL); fm::dense_matrix::ptr res3 = mv1->MvTransMv(*mv2); gettimeofday(&end, NULL); printf("MvTransMv (all blocks) takes %.3f seconds\n", time_diff(start, end)); } #if 0 dense_matrix::ptr diff = res2->minus(*res3); scalar_variable::ptr max_diff = diff->abs()->max(); scalar_variable::ptr max1 = res2->max(); scalar_variable::ptr max2 = res3->max(); printf("max diff: %g, max mat1: %g, max mat2: %g\n", *(double *) max_diff->get_raw(), *(double *) max1->get_raw(), *(double *) max2->get_raw()); #endif } void test_MvTransMv(bool in_mem, size_t block_size, size_t min_num_blocks, size_t max_num_blocks) { std::vector<dense_matrix::ptr> mats(max_num_blocks); for (size_t i = 0; i < mats.size(); i++) mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim, block_size, matrix_layout_t::L_COL, -1, in_mem); eigen::block_multi_vector::ptr mv2 = eigen::block_multi_vector::create( long_dim, block_size, block_size, get_scalar_type<double>(), in_mem); mv2->set_block(0, dense_matrix::create_randu<double>(0, 1, long_dim, mv2->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); printf("MvTransMv on block multi-vector\n"); for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks; num_blocks *= 2) { eigen::block_multi_vector::ptr mv1 = eigen::block_multi_vector::create( long_dim, num_blocks * block_size, block_size, get_scalar_type<double>(), in_mem); for (size_t i = 0; i < mv1->get_num_blocks(); i++) mv1->set_block(i, mats[i]); test_MvTransMv(mv1, mv2); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "test conf_file\n"); exit(1); } std::string conf_file = argv[1]; config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); test_gemm(true, 4, 1, 128); test_gemm(true, 64, 1, 8); test_MvTransMv(true, 4, 1, 128); test_MvTransMv(true, 64, 1, 8); test_gemm(false, 4, 1, 128); test_gemm(false, 64, 1, 8); test_MvTransMv(false, 4, 1, 128); test_MvTransMv(false, 64, 1, 8); destroy_flash_matrix(); } <commit_msg>[Matrix]: caching some matrices in block MV multiply test.<commit_after>#include "eigensolver/block_dense_matrix.h" using namespace fm; size_t long_dim = 60 * 1024 * 1024; size_t repeats = 1; void test_gemm(eigen::block_multi_vector::ptr mv) { bool in_mem = mv->get_block(0)->is_in_mem(); dense_matrix::ptr mat = dense_matrix::create_randu<double>(0, 1, mv->get_num_cols(), mv->get_block_size(), matrix_layout_t::L_COL, -1, true); detail::mem_col_matrix_store::const_ptr B = detail::mem_col_matrix_store::cast(mat->get_raw_store()); scalar_variable_impl<double> alpha(2); scalar_variable_impl<double> beta(0); struct timeval start, end; #if 0 eigen::block_multi_vector::ptr res0 = eigen::block_multi_vector::create( long_dim, mv->get_block_size(), mv->get_block_size(), get_scalar_type<double>(), true); res0->set_block(0, dense_matrix::create_const<double>(0, long_dim, mv->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); res0->set_multiply_blocks(1); gettimeofday(&start, NULL); res0 = res0->gemm(*mv, B, alpha, beta); assert(res0->get_num_blocks() == 1); dense_matrix::ptr res_mat0 = res0->get_block(0); res_mat0->materialize_self(); gettimeofday(&end, NULL); printf("agg materialization takes %.3f seconds\n", time_diff(start, end)); #endif for (size_t i = 0; i < repeats; i++) { eigen::block_multi_vector::ptr res1 = eigen::block_multi_vector::create( long_dim, mv->get_block_size(), mv->get_block_size(), get_scalar_type<double>(), true); res1->set_block(0, dense_matrix::create_const<double>(0, long_dim, mv->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); res1->set_multiply_blocks(4); gettimeofday(&start, NULL); res1 = res1->gemm(*mv, B, alpha, beta); assert(res1->get_num_blocks() == 1); dense_matrix::ptr res_mat1 = res1->get_block(0); res_mat1->materialize_self(); gettimeofday(&end, NULL); printf("hierarchical materialization takes %.3f seconds\n", time_diff(start, end)); } for (size_t i = 0; i < repeats; i++) { eigen::block_multi_vector::ptr res2 = eigen::block_multi_vector::create( long_dim, mv->get_block_size(), mv->get_block_size(), get_scalar_type<double>(), true); res2->set_block(0, dense_matrix::create_const<double>(0, long_dim, mv->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); res2->set_multiply_blocks(mv->get_num_blocks()); gettimeofday(&start, NULL); res2 = res2->gemm(*mv, B, alpha, beta); assert(res2->get_num_blocks() == 1); dense_matrix::ptr res_mat2 = res2->get_block(0); res_mat2->materialize_self(); gettimeofday(&end, NULL); printf("flat materialization takes %.3f seconds\n", time_diff(start, end)); } #if 0 dense_matrix::ptr diff = res_mat1->minus(*res_mat2); scalar_variable::ptr max_diff = diff->abs()->max(); scalar_variable::ptr max1 = res_mat1->max(); scalar_variable::ptr max2 = res_mat2->max(); printf("max diff: %g, max mat1: %g, max mat2: %g\n", *(double *) max_diff->get_raw(), *(double *) max1->get_raw(), *(double *) max2->get_raw()); #endif } void test_gemm(bool in_mem, size_t block_size, size_t min_num_blocks, size_t max_num_blocks, size_t num_cached_blocks) { std::vector<dense_matrix::ptr> mats(max_num_blocks); for (size_t i = 0; i < mats.size(); i++) { if (i < num_cached_blocks) mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim, block_size, matrix_layout_t::L_COL, -1, true); else mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim, block_size, matrix_layout_t::L_COL, -1, in_mem); } for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks; num_blocks *= 2) { eigen::block_multi_vector::ptr mv = eigen::block_multi_vector::create( long_dim, num_blocks * block_size, block_size, get_scalar_type<double>(), in_mem); printf("gemm on block multi-vector (block size: %ld, #blocks: %ld)\n", mv->get_block_size(), mv->get_num_blocks()); for (size_t i = 0; i < mv->get_num_blocks(); i++) mv->set_block(i, mats[i]); test_gemm(mv); } } void test_MvTransMv(eigen::block_multi_vector::ptr mv1, eigen::block_multi_vector::ptr mv2) { struct timeval start, end; #if 0 mv1->set_multiply_blocks(1); gettimeofday(&start, NULL); fm::dense_matrix::ptr res1 = mv1->MvTransMv(*mv2); gettimeofday(&end, NULL); printf("MvTransMv (1 block) takes %.3f seconds\n", time_diff(start, end)); #endif mv1->set_multiply_blocks(4); for (size_t i = 0; i < repeats; i++) { gettimeofday(&start, NULL); fm::dense_matrix::ptr res2 = mv1->MvTransMv(*mv2); gettimeofday(&end, NULL); printf("MvTransMv (4 blocks) takes %.3f seconds\n", time_diff(start, end)); } mv1->set_multiply_blocks(mv1->get_num_blocks()); for (size_t i = 0; i < repeats; i++) { gettimeofday(&start, NULL); fm::dense_matrix::ptr res3 = mv1->MvTransMv(*mv2); gettimeofday(&end, NULL); printf("MvTransMv (all blocks) takes %.3f seconds\n", time_diff(start, end)); } #if 0 dense_matrix::ptr diff = res2->minus(*res3); scalar_variable::ptr max_diff = diff->abs()->max(); scalar_variable::ptr max1 = res2->max(); scalar_variable::ptr max2 = res3->max(); printf("max diff: %g, max mat1: %g, max mat2: %g\n", *(double *) max_diff->get_raw(), *(double *) max1->get_raw(), *(double *) max2->get_raw()); #endif } void test_MvTransMv(bool in_mem, size_t block_size, size_t min_num_blocks, size_t max_num_blocks, size_t num_cached_blocks) { std::vector<dense_matrix::ptr> mats(max_num_blocks); for (size_t i = 0; i < mats.size(); i++) { if (i < num_cached_blocks) mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim, block_size, matrix_layout_t::L_COL, -1, true); else mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim, block_size, matrix_layout_t::L_COL, -1, in_mem); } eigen::block_multi_vector::ptr mv2 = eigen::block_multi_vector::create( long_dim, block_size, block_size, get_scalar_type<double>(), in_mem); mv2->set_block(0, dense_matrix::create_randu<double>(0, 1, long_dim, mv2->get_block_size(), matrix_layout_t::L_COL, -1, in_mem)); for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks; num_blocks *= 2) { eigen::block_multi_vector::ptr mv1 = eigen::block_multi_vector::create( long_dim, num_blocks * block_size, block_size, get_scalar_type<double>(), in_mem); for (size_t i = 0; i < mv1->get_num_blocks(); i++) mv1->set_block(i, mats[i]); printf("MvTransMv on block MV (block size: %ld, #blocks: %ld)\n", block_size, mv1->get_num_blocks()); test_MvTransMv(mv1, mv2); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "test conf_file\n"); exit(1); } std::string conf_file = argv[1]; config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); test_gemm(true, 4, 1, 128, 0); test_gemm(true, 64, 1, 8, 0); test_MvTransMv(true, 4, 128, 128, 0); test_MvTransMv(true, 64, 1, 8, 0); test_gemm(false, 4, 8, 128, 4); test_gemm(false, 64, 1, 8, 0); test_MvTransMv(false, 4, 8, 128, 4); test_MvTransMv(false, 64, 1, 8, 0); destroy_flash_matrix(); } <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> #include <string> #include <array> #include <fstream> #include "tty_state.hpp" #include "pseudo_term.hpp" int main(int const, char ** const) try { sts::tty_state tty; sts::pseudo_term pt{ tty }; pt([] { char const *shell{ getenv("SHELL") }; if(!shell || *shell == '\0') { shell = "/bin/sh"; } execlp(shell, shell, nullptr); throw std::runtime_error{ "shell failed to run" }; }); /* Parent: relay data between terminal and pty master */ auto const log_fd = open("typescript", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if(log_fd == -1) { throw std::runtime_error{ "failed to open log file" }; } /* Place terminal in raw mode so that we can pass all terminal input to the pseudoterminal master untouched */ tty.enter_raw_mode(); std::array<char, 256> buf{}; ssize_t num_read{}; fd_set in_fds{}; int const master_fd{ pt.get_master() }; std::ofstream ofs{ "log" }; while(true) { FD_ZERO(&in_fds); FD_SET(STDIN_FILENO, &in_fds); FD_SET(master_fd, &in_fds); if(select(master_fd + 1, &in_fds, nullptr, nullptr, nullptr) == -1) { throw std::runtime_error{ "failed to select" }; } if(FD_ISSET(STDIN_FILENO, &in_fds)) /* stdin --> pty */ { num_read = read(STDIN_FILENO, buf.data(), buf.size()); if(num_read <= 0) { break; } for(size_t i{}; i < num_read; ++i) { if(buf[i] == 25) { ofs << "scroll up" << " "; } else if(buf[i] == 5) { ofs << "scroll down" << " "; } else { ofs << static_cast<int>(buf[i]) << " "; } } ofs << std::endl; if(write(master_fd, buf.data(), num_read) != num_read) { throw std::runtime_error{ "partial/failed write (master)" }; } } if(FD_ISSET(master_fd, &in_fds)) /* pty --> stdout + log */ { num_read = read(master_fd, buf.data(), buf.size()); if(num_read <= 0) { break; } if(write(STDOUT_FILENO, buf.data(), num_read) != num_read) { throw std::runtime_error{ "partial/failed write (stdout)" }; } if(write(log_fd, buf.data(), num_read) != num_read) { throw std::runtime_error{ "partial/failed write (log)" }; } } } } catch(std::exception const &e) { std::cout << "exception: " << e.what() << std::endl; } catch(...) { std::cout << "unknown error occurred" << std::endl; } <commit_msg>Toying with key input<commit_after>#include <iostream> #include <stdexcept> #include <string> #include <array> #include <fstream> #include "tty_state.hpp" #include "pseudo_term.hpp" int main(int const, char ** const) try { sts::tty_state tty; sts::pseudo_term pt{ tty }; pt([] { char const *shell{ getenv("SHELL") }; if(!shell || *shell == '\0') { shell = "/bin/sh"; } execlp(shell, shell, nullptr); throw std::runtime_error{ "shell failed to run" }; }); /* Parent: relay data between terminal and pty master */ auto const log_fd = open("typescript", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if(log_fd == -1) { throw std::runtime_error{ "failed to open log file" }; } /* Place terminal in raw mode so that we can pass all terminal input to the pseudoterminal master untouched */ tty.enter_raw_mode(); std::array<char, 256> buf{}; ssize_t num_read{}; fd_set in_fds{}; int const master_fd{ pt.get_master() }; std::ofstream ofs{ "log" }; while(true) { FD_ZERO(&in_fds); FD_SET(STDIN_FILENO, &in_fds); FD_SET(master_fd, &in_fds); if(select(master_fd + 1, &in_fds, nullptr, nullptr, nullptr) == -1) { throw std::runtime_error{ "failed to select" }; } if(FD_ISSET(STDIN_FILENO, &in_fds)) /* stdin --> pty */ { num_read = read(STDIN_FILENO, buf.data(), buf.size()); if(num_read <= 0) { break; } bool done{}; for(size_t i{}; i < num_read; ++i) { /* TODO: check num_read */ if(buf[i] == 25) { ofs << "(" << num_read << ") " << "scroll up" << " "; done = true; } else if(buf[i] == 5) { ofs << "(" << num_read << ") " << "scroll down" << " "; done = true; } else if(buf[i] == 11) { ofs << "(" << num_read << ") " << "clearing" << " "; //std::string const clear{ "printf '\\x1B[2J\\x1B[H'\n" }; //if(write(master_fd, clear.c_str(), clear.size()) != clear.size()) //{ throw std::runtime_error{ "unable to clear screen" }; } std::string const clear_out{ "\x1B[2J\x1B[H" }; if(write(STDOUT_FILENO, clear_out.c_str(), clear_out.size()) != clear_out.size()) { throw std::runtime_error{ "unable to clear screen" }; } num_read = 1; buf[0] = '\n'; } else { ofs << "(" << num_read << ") " << static_cast<int>(buf[i]) << " "; } } ofs << std::endl; if(done) { continue; } if(write(master_fd, buf.data(), num_read) != num_read) { throw std::runtime_error{ "partial/failed write (master)" }; } } if(FD_ISSET(master_fd, &in_fds)) /* pty --> stdout + log */ { num_read = read(master_fd, buf.data(), buf.size()); if(num_read <= 0) { break; } if(write(STDOUT_FILENO, buf.data(), num_read) != num_read) { throw std::runtime_error{ "partial/failed write (stdout)" }; } if(write(log_fd, buf.data(), num_read) != num_read) { throw std::runtime_error{ "partial/failed write (log)" }; } } } } catch(std::exception const &e) { std::cout << "exception: " << e.what() << std::endl; } catch(...) { std::cout << "unknown error occurred" << std::endl; } <|endoftext|>
<commit_before><commit_msg>fdo#79691: Fix ppt files embedded in .docx documents<commit_after><|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL Southwest Research Institute® BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ***************************************************************************** #include <swri_profiler_tools/partition_widget.h> #include <QPainter> #include <QVBoxLayout> #include <QToolTip> #include <QHelpEvent> #include <QMouseEvent> #include <QDebug> #include <swri_profiler_tools/util.h> #include <swri_profiler_tools/profile_database.h> #include <swri_profiler_tools/variant_animation.h> namespace swri_profiler_tools { static QColor colorFromString(const QString &name) { size_t name_hash = std::hash<std::string>{}(name.toStdString()); int h = (name_hash >> 0) % 255; int s = (name_hash >> 8) % 200 + 55; int v = (name_hash >> 16) % 200 + 55; return QColor::fromHsv(h, s, v); } PartitionWidget::PartitionWidget(QWidget *parent) : QWidget(parent), db_(NULL) { view_animator_ = new VariantAnimation(this); view_animator_->setEasingCurve(QEasingCurve::InOutCubic); QObject::connect(view_animator_, SIGNAL(valueChanged(const QVariant &)), this, SLOT(update())); } PartitionWidget::~PartitionWidget() { } void PartitionWidget::setDatabase(ProfileDatabase *db) { if (db_) { // note(exjohnson): we can implement this later if desired, but // currently no use case for it. qWarning("PartitionWidget: Cannot change the profile database."); return; } db_ = db; updateData(); QObject::connect(db_, SIGNAL(dataAdded(int)), this, SLOT(updateData())); QObject::connect(db_, SIGNAL(profileAdded(int)), this, SLOT(updateData())); QObject::connect(db_, SIGNAL(nodesAdded(int)), this, SLOT(updateData())); } void PartitionWidget::updateData() { if (!active_key_.isValid()) { return; } const Profile &profile = db_->profile(active_key_.profileKey()); Layout layout = layoutProfile(profile); QRectF data_rect = dataRect(layout); view_animator_->setEndValue(data_rect); current_layout_ = layout; update(); } void PartitionWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setPen(Qt::NoPen); painter.fillRect(0, 0, width(), height(), QColor(255, 255, 255)); if (current_layout_.empty()) { return; } QRectF data_rect = view_animator_->currentValue().toRectF(); QRectF win_rect(QPointF(0, 0), QPointF(width(), height())); win_from_data_ = getTransform(win_rect, data_rect); const Profile &profile = db_->profile(active_key_.profileKey()); renderLayout(painter, win_from_data_, current_layout_, profile); } QRectF PartitionWidget::dataRect(const Layout &layout) const { if (layout.empty()) { return QRectF(0.0, 0.0, 1.0, 1.0); } double right = layout.back().rect.right(); for (auto const &item : layout) { if (active_key_.nodeKey() == item.node_key && item.exclusive == false) { QRectF rect = item.rect; rect.setLeft(std::max(0.0, rect.left()-0.2)); rect.setRight(right); double margin = 0.05 * rect.height(); rect.setTop(std::max(0.0, rect.top() - margin)); rect.setBottom(std::min(1.0, rect.bottom() + margin)); return rect; } } qWarning("Active node key was not found in layout"); return QRectF(QPointF(0.0, 0.0), QPointF(right, 1.0)); } void PartitionWidget::setActiveNode(int profile_key, int node_key) { const DatabaseKey new_key(profile_key, node_key); if (new_key == active_key_) { return; } bool first = true; if (active_key_.isValid()) { first = false; } active_key_ = new_key; const Profile &profile = db_->profile(active_key_.profileKey()); Layout layout = layoutProfile(profile); QRectF data_rect = dataRect(layout); current_layout_ = layout; if (!first) { view_animator_->stop(); view_animator_->setStartValue(view_animator_->endValue()); view_animator_->setEndValue(data_rect); view_animator_->setDuration(500); view_animator_->start(); } else { view_animator_->setStartValue(data_rect); view_animator_->setEndValue(data_rect); } emit activeNodeChanged(profile_key, node_key); } PartitionWidget::Layout PartitionWidget::layoutProfile(const Profile &profile) { Layout layout; const ProfileNode &root_node = profile.rootNode(); if (!root_node.isValid()) { qWarning("Profile returned invalid root node."); return layout; } if (root_node.data().empty()) { return layout; } double time_scale = root_node.data().back().cumulative_inclusive_duration_ns; int column = 0; LayoutItem root_item; root_item.node_key = root_node.nodeKey(); root_item.exclusive = false; root_item.rect = QRectF(column, 0.0, 1, 1.0); layout.push_back(root_item); bool keep_going = root_node.hasChildren(); std::vector<LayoutItem> parents; std::vector<LayoutItem> children; parents.push_back(root_item); while (keep_going) { // We going to stop unless we see some children. keep_going = false; column++; double span_start = 0.0; for (auto const &parent_item : parents) { const ProfileNode &parent_node = profile.node(parent_item.node_key); // Add the carry-over exclusive item. { double height = parent_node.data().back().cumulative_exclusive_duration_ns/time_scale; LayoutItem item; item.node_key = parent_item.node_key; item.exclusive = true; item.rect = QRectF(column, span_start, 1, height); children.push_back(item); span_start = item.rect.bottom(); } // Don't add children for an exclusive item because they've already been added. if (parent_item.exclusive) { continue; } for (int child_key : parent_node.childKeys()) { const ProfileNode &child_node = profile.node(child_key); double height = child_node.data().back().cumulative_inclusive_duration_ns / time_scale; LayoutItem item; item.node_key = child_key; item.exclusive = false; item.rect = QRectF(column, span_start, 1, height); children.push_back(item); span_start = item.rect.bottom(); keep_going |= child_node.hasChildren(); } } layout.insert(layout.end(), children.begin(), children.end()); parents.swap(children); children.clear(); } return layout; } void PartitionWidget::renderLayout(QPainter &painter, const QTransform &win_from_data, const Layout &layout, const Profile &profile) { // Set painter to use a single-pixel black pen. painter.setPen(Qt::black); for (auto const &item : layout) { if (item.exclusive) { continue; } const ProfileNode &node = profile.node(item.node_key); QColor color = colorFromString(node.name()); QRectF data_rect = item.rect; data_rect.setRight(layout.size()); QRectF win_rect = win_from_data.mapRect(data_rect); QRect int_rect = roundRectF(win_rect); painter.setBrush(color); painter.drawRect(int_rect.adjusted(0,0,-1,-1)); } } QTransform PartitionWidget::getTransform(const QRectF &win_rect, const QRectF &data_rect) { double sx = win_rect.width() / data_rect.width(); double sy = win_rect.height() / data_rect.height(); double tx = win_rect.topLeft().x() - sx*data_rect.topLeft().x(); double ty = win_rect.topLeft().y() - sy*data_rect.topLeft().y(); QTransform win_from_data(sx, 0.0, 0.0, 0.0, sy, 0.0, tx, ty, 1.0); return win_from_data; } int PartitionWidget::itemAtPoint(const QPointF &point) const { for (size_t i = 0; i < current_layout_.size(); i++) { auto const &item = current_layout_[i]; if (item.rect.contains(point)) { return i; } } return -1; } bool PartitionWidget::event(QEvent *event) { if (event->type() == QEvent::ToolTip) { toolTipEvent(static_cast<QHelpEvent*>(event)); event->accept(); return true; } return QWidget::event(event); } void PartitionWidget::toolTipEvent(QHelpEvent *event) { QTransform data_from_win = win_from_data_.inverted(); int index = itemAtPoint(data_from_win.map(QPointF(event->pos()))); if (index < 0) { QToolTip::hideText(); return; } const Profile &profile = db_->profile(active_key_.profileKey()); const LayoutItem &item = current_layout_[index]; QString tool_tip; if (item.node_key == profile.rootKey()) { tool_tip = profile.name(); } else { tool_tip = profile.node(item.node_key).path(); if (item.exclusive) { tool_tip += " [exclusive]"; } } QRectF win_rect = win_from_data_.mapRect(item.rect); QRect int_rect = roundRectF(win_rect); QToolTip::showText(event->globalPos(), tool_tip, this, int_rect); } void PartitionWidget::mousePressEvent(QMouseEvent *event) { } void PartitionWidget::mouseDoubleClickEvent(QMouseEvent *event) { QTransform data_from_win = win_from_data_.inverted(); int index = itemAtPoint(data_from_win.map(event->posF())); if (index < 0) { return; } const LayoutItem &item = current_layout_[index]; setActiveNode(active_key_.profileKey(), item.node_key); } } // namespace swri_profiler_tools <commit_msg>Fixing some minor alignment issues in partition widget.<commit_after>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL Southwest Research Institute® BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ***************************************************************************** #include <swri_profiler_tools/partition_widget.h> #include <QPainter> #include <QVBoxLayout> #include <QToolTip> #include <QHelpEvent> #include <QMouseEvent> #include <QDebug> #include <swri_profiler_tools/util.h> #include <swri_profiler_tools/profile_database.h> #include <swri_profiler_tools/variant_animation.h> namespace swri_profiler_tools { static QColor colorFromString(const QString &name) { size_t name_hash = std::hash<std::string>{}(name.toStdString()); int h = (name_hash >> 0) % 255; int s = (name_hash >> 8) % 200 + 55; int v = (name_hash >> 16) % 200 + 55; return QColor::fromHsv(h, s, v); } PartitionWidget::PartitionWidget(QWidget *parent) : QWidget(parent), db_(NULL) { view_animator_ = new VariantAnimation(this); view_animator_->setEasingCurve(QEasingCurve::InOutCubic); QObject::connect(view_animator_, SIGNAL(valueChanged(const QVariant &)), this, SLOT(update())); } PartitionWidget::~PartitionWidget() { } void PartitionWidget::setDatabase(ProfileDatabase *db) { if (db_) { // note(exjohnson): we can implement this later if desired, but // currently no use case for it. qWarning("PartitionWidget: Cannot change the profile database."); return; } db_ = db; updateData(); QObject::connect(db_, SIGNAL(dataAdded(int)), this, SLOT(updateData())); QObject::connect(db_, SIGNAL(profileAdded(int)), this, SLOT(updateData())); QObject::connect(db_, SIGNAL(nodesAdded(int)), this, SLOT(updateData())); } void PartitionWidget::updateData() { if (!active_key_.isValid()) { return; } const Profile &profile = db_->profile(active_key_.profileKey()); Layout layout = layoutProfile(profile); QRectF data_rect = dataRect(layout); view_animator_->setEndValue(data_rect); current_layout_ = layout; update(); } void PartitionWidget::paintEvent(QPaintEvent *) { QPainter painter(this); if (current_layout_.empty()) { QRect win_rect(0,0,width(), height()); painter.setBrush(Qt::white); painter.drawRect(win_rect.adjusted(1,1,-1,-1)); return; } QRectF data_rect = view_animator_->currentValue().toRectF(); QRectF win_rect(QPointF(0, 0), QPointF(width()-1, height()-1)); win_rect = win_rect.adjusted(1,1,-1,-1); win_from_data_ = getTransform(win_rect, data_rect); const Profile &profile = db_->profile(active_key_.profileKey()); renderLayout(painter, win_from_data_, current_layout_, profile); } QRectF PartitionWidget::dataRect(const Layout &layout) const { if (layout.empty()) { return QRectF(0.0, 0.0, 1.0, 1.0); } double right = layout.back().rect.right(); for (auto const &item : layout) { if (active_key_.nodeKey() == item.node_key && item.exclusive == false) { QRectF rect = item.rect; rect.setLeft(std::max(0.0, rect.left()-0.2)); rect.setRight(right); double margin = 0.05 * rect.height(); rect.setTop(std::max(0.0, rect.top() - margin)); rect.setBottom(std::min(1.0, rect.bottom() + margin)); return rect; } } qWarning("Active node key was not found in layout"); return QRectF(QPointF(0.0, 0.0), QPointF(right, 1.0)); } void PartitionWidget::setActiveNode(int profile_key, int node_key) { const DatabaseKey new_key(profile_key, node_key); if (new_key == active_key_) { return; } bool first = true; if (active_key_.isValid()) { first = false; } active_key_ = new_key; const Profile &profile = db_->profile(active_key_.profileKey()); Layout layout = layoutProfile(profile); QRectF data_rect = dataRect(layout); current_layout_ = layout; if (!first) { view_animator_->stop(); view_animator_->setStartValue(view_animator_->endValue()); view_animator_->setEndValue(data_rect); view_animator_->setDuration(500); view_animator_->start(); } else { view_animator_->setStartValue(data_rect); view_animator_->setEndValue(data_rect); } emit activeNodeChanged(profile_key, node_key); } PartitionWidget::Layout PartitionWidget::layoutProfile(const Profile &profile) { Layout layout; const ProfileNode &root_node = profile.rootNode(); if (!root_node.isValid()) { qWarning("Profile returned invalid root node."); return layout; } if (root_node.data().empty()) { return layout; } double time_scale = root_node.data().back().cumulative_inclusive_duration_ns; int column = 0; LayoutItem root_item; root_item.node_key = root_node.nodeKey(); root_item.exclusive = false; root_item.rect = QRectF(column, 0.0, 1, 1.0); layout.push_back(root_item); bool keep_going = root_node.hasChildren(); std::vector<LayoutItem> parents; std::vector<LayoutItem> children; parents.push_back(root_item); while (keep_going) { // We going to stop unless we see some children. keep_going = false; column++; double span_start = 0.0; for (auto const &parent_item : parents) { const ProfileNode &parent_node = profile.node(parent_item.node_key); // Add the carry-over exclusive item. { double height = parent_node.data().back().cumulative_exclusive_duration_ns/time_scale; LayoutItem item; item.node_key = parent_item.node_key; item.exclusive = true; item.rect = QRectF(column, span_start, 1, height); children.push_back(item); span_start = item.rect.bottom(); } // Don't add children for an exclusive item because they've already been added. if (parent_item.exclusive) { continue; } for (int child_key : parent_node.childKeys()) { const ProfileNode &child_node = profile.node(child_key); double height = child_node.data().back().cumulative_inclusive_duration_ns / time_scale; LayoutItem item; item.node_key = child_key; item.exclusive = false; item.rect = QRectF(column, span_start, 1, height); children.push_back(item); span_start = item.rect.bottom(); keep_going |= child_node.hasChildren(); } } layout.insert(layout.end(), children.begin(), children.end()); parents.swap(children); children.clear(); } return layout; } void PartitionWidget::renderLayout(QPainter &painter, const QTransform &win_from_data, const Layout &layout, const Profile &profile) { // Set painter to use a single-pixel black pen. painter.setPen(Qt::black); double right = layout.back().rect.right(); for (auto const &item : layout) { if (item.exclusive) { continue; } const ProfileNode &node = profile.node(item.node_key); QColor color = colorFromString(node.name()); QRectF data_rect = item.rect; data_rect.setRight(right); QRectF win_rect = win_from_data.mapRect(data_rect); QRect int_rect = roundRectF(win_rect); painter.setBrush(color); painter.drawRect(int_rect.adjusted(0,0,-1,-1)); } } QTransform PartitionWidget::getTransform(const QRectF &win_rect, const QRectF &data_rect) { double sx = win_rect.width() / data_rect.width(); double sy = win_rect.height() / data_rect.height(); double tx = win_rect.topLeft().x() - sx*data_rect.topLeft().x(); double ty = win_rect.topLeft().y() - sy*data_rect.topLeft().y(); QTransform win_from_data(sx, 0.0, 0.0, 0.0, sy, 0.0, tx, ty, 1.0); return win_from_data; } int PartitionWidget::itemAtPoint(const QPointF &point) const { for (size_t i = 0; i < current_layout_.size(); i++) { auto const &item = current_layout_[i]; if (item.rect.contains(point)) { return i; } } return -1; } bool PartitionWidget::event(QEvent *event) { if (event->type() == QEvent::ToolTip) { toolTipEvent(static_cast<QHelpEvent*>(event)); event->accept(); return true; } return QWidget::event(event); } void PartitionWidget::toolTipEvent(QHelpEvent *event) { QTransform data_from_win = win_from_data_.inverted(); int index = itemAtPoint(data_from_win.map(QPointF(event->pos()))); if (index < 0) { QToolTip::hideText(); return; } const Profile &profile = db_->profile(active_key_.profileKey()); const LayoutItem &item = current_layout_[index]; QString tool_tip; if (item.node_key == profile.rootKey()) { tool_tip = profile.name(); } else { tool_tip = profile.node(item.node_key).path(); if (item.exclusive) { tool_tip += " [exclusive]"; } } QRectF win_rect = win_from_data_.mapRect(item.rect); QRect int_rect = roundRectF(win_rect); QToolTip::showText(event->globalPos(), tool_tip, this, int_rect); } void PartitionWidget::mousePressEvent(QMouseEvent *event) { } void PartitionWidget::mouseDoubleClickEvent(QMouseEvent *event) { QTransform data_from_win = win_from_data_.inverted(); int index = itemAtPoint(data_from_win.map(event->posF())); if (index < 0) { return; } const LayoutItem &item = current_layout_[index]; setActiveNode(active_key_.profileKey(), item.node_key); } } // namespace swri_profiler_tools <|endoftext|>
<commit_before><commit_msg>LocationBarView::PageActionImageView::LoadImageTask::Run() may pass a NULL image pointer through to OnImageLoaded; make sure that the pointer is not dereferenced in these cases.<commit_after><|endoftext|>
<commit_before>//Includes all the headers necessary to use the most common public pieces of the ROS system. #include <ros/ros.h> //Use image_transport for publishing and subscribing to images in ROS #include <image_transport/image_transport.h> //Use cv_bridge to convert between ROS and OpenCV Image formats #include <cv_bridge/cv_bridge.h> //Include some useful constants for image encoding. Refer to: http://www.ros.org/doc/api/sensor_msgs/html/namespacesensor__msgs_1_1image__encodings.html for more info. #include <sensor_msgs/image_encodings.h> //Include headers for OpenCV Image processing #include <opencv2/imgproc/imgproc.hpp> //Include headers for OpenCV GUI handling #include <opencv2/highgui/highgui.hpp> //Store all constants for image encodings in the enc namespace to be used later. namespace enc = sensor_msgs::image_encodings; //Declare a string with the name of the window that we will create using OpenCV where processed images will be displayed. static const char WINDOW[] = "Image Processed"; //Use method of ImageTransport to create image publisher image_transport::Publisher pub; //This function is called everytime a new image is published void imageCallback(const sensor_msgs::ImageConstPtr& original_image) { //Convert from the ROS image message to a CvImage suitable for working with OpenCV for processing cv_bridge::CvImagePtr cv_ptr; try { //Always copy, returning a mutable CvImage //OpenCV expects color images to use BGR channel order. cv_ptr = cv_bridge::toCvCopy(original_image, enc::BGR8); } catch (cv_bridge::Exception& e) { //if there is an error during conversion, display it ROS_ERROR("tutorialROSOpenCV::main.cpp::cv_bridge exception: %s", e.what()); return; } // The code below is from: http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html cv::Mat dst, cdst; cv::Canny(cv_ptr->image, dst, 50, 200, 3); cv::cvtColor(dst, cdst, CV_GRAY2BGR); std::vector<cv::Vec4i> lines; cv::HoughLinesP(dst, lines, 1, CV_PI/180, 80, 50, 10 ); for( size_t i = 0; i < lines.size(); i++ ) { cv::Vec4i l = lines[i]; line( cdst, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar(0,0,255), 3, CV_AA); printf("[%d,%d] [%d,%d]\n", l[0], l[1], l[2], l[3]); } cv::imshow("source", cv_ptr->image); cv::imshow("detected lines", cdst); //Invert Image //Go through all the rows // for(int i=0; i<cv_ptr->image.rows; i++) // { // //Go through all the columns // for(int j=0; j<cv_ptr->image.cols; j++) // { // //Go through all the channels (b, g, r) // for(int k=0; k<cv_ptr->image.channels(); k++) // { // //Invert the image by subtracting image data from 255 // cv_ptr->image.data[i*cv_ptr->image.rows*4+j*3 + k] = 255-cv_ptr->image.data[i*cv_ptr->image.rows*4+j*3 + k]; // } // } // } //Display the image using OpenCV //cv::imshow(WINDOW, cv_ptr->image); //Add some delay in miliseconds. The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active. cv::waitKey(3); /** * The publish() function is how you send messages. The parameter * is the message object. The type of this object must agree with the type * given as a template parameter to the advertise<>() call, as was done * in the constructor in main(). */ //Convert the CvImage to a ROS image message and publish it on the "camera/image_processed" topic. //pub.publish(cv_ptr->toImageMsg()); } /** * This tutorial demonstrates simple image conversion between ROS image message and OpenCV formats and image processing */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. Node names must be unique in a running system. * The name used here must be a base name, ie. it cannot have a / in it. * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "image_processor"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle nh; //Create an ImageTransport instance, initializing it with our NodeHandle. image_transport::ImageTransport it(nh); //OpenCV HighGUI call to create a display window on start-up. cv::namedWindow(WINDOW, CV_WINDOW_AUTOSIZE); /** * Subscribe to the "camera/image_raw" base topic. The actual ROS topic subscribed to depends on which transport is used. * In the default case, "raw" transport, the topic is in fact "camera/image_raw" with type sensor_msgs/Image. ROS will call * the "imageCallback" function whenever a new image arrives. The 2nd argument is the queue size. * subscribe() returns an image_transport::Subscriber object, that you must hold on to until you want to unsubscribe. * When the Subscriber object is destructed, it will automatically unsubscribe from the "camera/image_raw" base topic. */ image_transport::TransportHints hints("compressed", ros::TransportHints()); image_transport::Subscriber sub = it.subscribe("camera/image", 1, imageCallback, hints); //OpenCV HighGUI call to destroy a display window on shut-down. cv::destroyWindow(WINDOW); /** * The advertise() function is how you tell ROS that you want to * publish on a given topic name. This invokes a call to the ROS * master node, which keeps a registry of who is publishing and who * is subscribing. After this advertise() call is made, the master * node will notify anyone who is trying to subscribe to this topic name, * and they will in turn negotiate a peer-to-peer connection with this * node. advertise() returns a Publisher object which allows you to * publish messages on that topic through a call to publish(). Once * all copies of the returned Publisher object are destroyed, the topic * will be automatically unadvertised. * * The second parameter to advertise() is the size of the message queue * used for publishing messages. If messages are published more quickly * than we can send them, the number here specifies how many messages to * buffer up before throwing some away. */ //pub = it.advertise("usb_cam/image_processed", 1); /** * In this application all user callbacks will be called from within the ros::spin() call. * ros::spin() will not return until the node has been shutdown, either through a call * to ros::shutdown() or a Ctrl-C. */ ros::spin(); //ROS_INFO is the replacement for printf/cout. ROS_INFO("tutorialROSOpenCV::main.cpp::No error."); } <commit_msg>send twist msgs on cmd_vel<commit_after>//Includes all the headers necessary to use the most common public pieces of the ROS system. #include <ros/ros.h> //Use image_transport for publishing and subscribing to images in ROS #include <image_transport/image_transport.h> //Use cv_bridge to convert between ROS and OpenCV Image formats #include <cv_bridge/cv_bridge.h> //Include some useful constants for image encoding. Refer to: http://www.ros.org/doc/api/sensor_msgs/html/namespacesensor__msgs_1_1image__encodings.html for more info. #include <sensor_msgs/image_encodings.h> //Include headers for OpenCV Image processing #include <opencv2/imgproc/imgproc.hpp> //Include headers for OpenCV GUI handling #include <opencv2/highgui/highgui.hpp> #include <geometry_msgs/Twist.h> //Store all constants for image encodings in the enc namespace to be used later. namespace enc = sensor_msgs::image_encodings; //Declare a string with the name of the window that we will create using OpenCV where processed images will be displayed. static const char WINDOW[] = "Image Processed"; ros::Publisher pub; //This function is called everytime a new image is published void imageCallback(const sensor_msgs::ImageConstPtr& original_image) { //Convert from the ROS image message to a CvImage suitable for working with OpenCV for processing cv_bridge::CvImagePtr cv_ptr; try { //Always copy, returning a mutable CvImage //OpenCV expects color images to use BGR channel order. cv_ptr = cv_bridge::toCvCopy(original_image, enc::BGR8); } catch (cv_bridge::Exception& e) { //if there is an error during conversion, display it ROS_ERROR("tutorialROSOpenCV::main.cpp::cv_bridge exception: %s", e.what()); return; } // Rotate 90 deg CCW cv::transpose(cv_ptr->image, cv_ptr->image); cv::flip(cv_ptr->image, cv_ptr->image, 0); int width = cv_ptr->image.size().width; int height = cv_ptr->image.size().height; // The code below is from: http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html cv::Mat dst, cdst; cv::Canny(cv_ptr->image, dst, 50, 200, 3); cv::cvtColor(dst, cdst, CV_GRAY2BGR); std::vector<cv::Vec4i> lines; cv::HoughLinesP(dst, lines, 1, CV_PI/180, 20, 20, 5 ); long int sum = 0; float avg; for( size_t i = 0; i < lines.size(); i++ ) { cv::Vec4i l = lines[i]; line( cdst, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar(0,0,255), 3, CV_AA); sum += ((l[0] + l[2]) - width) / 2; } if (lines.size() > 0) { avg = (sum / (float)lines.size()) / (float)(width / 2); //ROS_INFO("angle = %f\n", avg); geometry_msgs::Twist msg; msg.linear.x = 1.0; msg.angular.x = avg; pub.publish(msg); } cv::imshow("source", cv_ptr->image); cv::imshow("detected lines", cdst); //Display the image using OpenCV //cv::imshow(WINDOW, cv_ptr->image); //Add some delay in miliseconds. The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active. cv::waitKey(3); } /** * This tutorial demonstrates simple image conversion between ROS image message and OpenCV formats and image processing */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. Node names must be unique in a running system. * The name used here must be a base name, ie. it cannot have a / in it. * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "image_processor"); ros::NodeHandle nh; pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1000); //Create an ImageTransport instance, initializing it with our NodeHandle. image_transport::ImageTransport it(nh); //OpenCV HighGUI call to create a display window on start-up. cv::namedWindow(WINDOW, CV_WINDOW_AUTOSIZE); image_transport::TransportHints hints("compressed", ros::TransportHints()); image_transport::Subscriber sub = it.subscribe("camera/image", 1, imageCallback, hints); //OpenCV HighGUI call to destroy a display window on shut-down. cv::destroyWindow(WINDOW); /** * In this application all user callbacks will be called from within the ros::spin() call. * ros::spin() will not return until the node has been shutdown, either through a call * to ros::shutdown() or a Ctrl-C. */ ros::spin(); //ROS_INFO is the replacement for printf/cout. ROS_INFO("tutorialROSOpenCV::main.cpp::No error."); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "Game.h" #include "MazeGeneratorType.h" #include "RenderType.h" extern "C" { #include <argp.h> const char* version = "mazegame 1.0"; static char doc[] = "Mazegame -- an interactive terminal-based maze written with ncurses"; static char args_doc[] = "WIDTH HEIGHT"; static struct argp_option options[] = { {"generator", 'g', "GENERATOR", 0, "Changes maze generation. Accepted values are \"DFS\" (hard) and \"PRIMS\" (easy)" }, {"color", 'c', 0, 0, "Forces color rendering (overrides --no-color if used after)"}, {"no-color", 'n', 0, 0, "Forces no color rendering (overrides --color if used after)"}, { 0 } }; static error_t parse_opt(int key, char *arg, struct argp_state *state); static struct argp argp = { options, parse_opt, args_doc, doc }; } struct Args { int width; int height; MazeGeneratorType generator; RenderType renderer; Args(int w, int h, MazeGeneratorType g, RenderType r) : width(w), height(h), generator(g), renderer(r) {} Args() : Args(-1, -1, MazeGeneratorType::PRIMS, RenderType::CONSOLE_RENDER_DEFAULT) {} bool valid() { return width > 0 && height > 0; } }; MazeGeneratorType getMGTypeFromName(char* arg); void handleArg(struct argp_state* state, char* arg, Args& a); int main(int argc, char* argv[]) { bool win; { Args a; argp_parse(&argp, argc, argv, 0, 0, &a); Game game(a.renderer, a.width, a.height, a.generator); game.run(); win = game.win(); } if (win) { std::cout << "You win!" << std::endl; } else { std::cout << "Quitter!" << std::endl; } Stats s = Stats::getInst(); std::cout << s; std::cout << "Elapsed time: " << s.getTime("endTime")() - s.getTime("startTime")() << "s" << std::endl; } static error_t parse_opt(int key, char* arg, struct argp_state* state) { Args& a = *((Args*)state->input); switch (key) { case 'g': a.generator = getMGTypeFromName(arg); if (a.generator == MazeGeneratorType::UNKNOWN) { argp_error(state, "unknown generator -- '%s'", arg); } break; case 'c': a.renderer = RenderType::CONSOLE_RENDER_COLOR; break; case 'n': a.renderer = RenderType::CONSOLE_RENDER_NO_COLOR; break; case ARGP_KEY_ARG: handleArg(state, arg, a); break; case ARGP_KEY_END: if (!a.valid()) argp_error(state, "too few arguments"); break; default: return ARGP_ERR_UNKNOWN; } return 0; } MazeGeneratorType getMGTypeFromName(char* arg) { std::string s(arg); for (int i = 0; i < s.size(); ++i) { s.at(i) = toupper(s.at(i)); } if (s == "PRIMS") { return MazeGeneratorType::PRIMS; } else if (s == "DFS") { return MazeGeneratorType::DFS; } else { return MazeGeneratorType::UNKNOWN; } } void handleArg(struct argp_state *state, char* arg, Args& a) { char* p = nullptr; //initialized to suppress warnings; the program exits before it's used w/o initialization if (a.width == -1) { a.width = strtol(arg, &p, 10); if (a.width <= 0) argp_error(state, "width must be greater than 0"); } else if (a.height == -1) { a.height = strtol(arg, &p, 10); if (a.height <= 0) argp_error(state, "height must be greater than 0"); } else { argp_error(state, "too many args"); } if (*p != 0) { argp_error(state, "invalid arg -- '%s'", arg); } } <commit_msg>Changed win message for cheaters<commit_after>#include <iostream> #include <string> #include "Game.h" #include "MazeGeneratorType.h" #include "RenderType.h" extern "C" { #include <argp.h> const char* version = "mazegame 1.0"; static char doc[] = "Mazegame -- an interactive terminal-based maze written with ncurses"; static char args_doc[] = "WIDTH HEIGHT"; static struct argp_option options[] = { {"generator", 'g', "GENERATOR", 0, "Changes maze generation. Accepted values are \"DFS\" (hard) and \"PRIMS\" (easy)" }, {"color", 'c', 0, 0, "Forces color rendering (overrides --no-color if used after)"}, {"no-color", 'n', 0, 0, "Forces no color rendering (overrides --color if used after)"}, { 0 } }; static error_t parse_opt(int key, char *arg, struct argp_state *state); static struct argp argp = { options, parse_opt, args_doc, doc }; } struct Args { int width; int height; MazeGeneratorType generator; RenderType renderer; Args(int w, int h, MazeGeneratorType g, RenderType r) : width(w), height(h), generator(g), renderer(r) {} Args() : Args(-1, -1, MazeGeneratorType::PRIMS, RenderType::CONSOLE_RENDER_DEFAULT) {} bool valid() { return width > 0 && height > 0; } }; MazeGeneratorType getMGTypeFromName(char* arg); void handleArg(struct argp_state* state, char* arg, Args& a); int main(int argc, char* argv[]) { Stats& s = Stats::getInst(); { Args a; argp_parse(&argp, argc, argv, 0, 0, &a); Game game(a.renderer, a.width, a.height, a.generator); game.run(); } if (s.getBool("win")) { std::cout << "You win!" << std::endl; if (s.getBool("cheated")) { std::cout << "But you cheated so it doesn't really count." << std::endl; } } else { std::cout << "Quitter!" << std::endl; } std::cout << s; std::cout << "Elapsed time: " << s.getTime("endTime")() - s.getTime("startTime")() << "s" << std::endl; } static error_t parse_opt(int key, char* arg, struct argp_state* state) { Args& a = *((Args*)state->input); switch (key) { case 'g': a.generator = getMGTypeFromName(arg); if (a.generator == MazeGeneratorType::UNKNOWN) { argp_error(state, "unknown generator -- '%s'", arg); } break; case 'c': a.renderer = RenderType::CONSOLE_RENDER_COLOR; break; case 'n': a.renderer = RenderType::CONSOLE_RENDER_NO_COLOR; break; case ARGP_KEY_ARG: handleArg(state, arg, a); break; case ARGP_KEY_END: if (!a.valid()) argp_error(state, "too few arguments"); break; default: return ARGP_ERR_UNKNOWN; } return 0; } MazeGeneratorType getMGTypeFromName(char* arg) { std::string s(arg); for (int i = 0; i < s.size(); ++i) { s.at(i) = toupper(s.at(i)); } if (s == "PRIMS") { return MazeGeneratorType::PRIMS; } else if (s == "DFS") { return MazeGeneratorType::DFS; } else { return MazeGeneratorType::UNKNOWN; } } void handleArg(struct argp_state *state, char* arg, Args& a) { char* p = nullptr; //initialized to suppress warnings; the program exits before it's used w/o initialization if (a.width == -1) { a.width = strtol(arg, &p, 10); if (a.width <= 0) argp_error(state, "width must be greater than 0"); } else if (a.height == -1) { a.height = strtol(arg, &p, 10); if (a.height <= 0) argp_error(state, "height must be greater than 0"); } else { argp_error(state, "too many args"); } if (*p != 0) { argp_error(state, "invalid arg -- '%s'", arg); } } <|endoftext|>
<commit_before>#include <chrono> #include <iostream> #include <vector> #include <armadillo> using std::chrono::high_resolution_clock; using std::chrono::duration; namespace { uint32_t num = 1; uint32_t fft_size = 48000; uint32_t conv_ir_size = 72000; //uint32_t conv_ir_size = 10; uint32_t conv_sig_size = 5760000; //uint32_t conv_sig_size = 48000; } duration<double> Convolution(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::fvec output (sig_size+ir_size-1); auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { for (uint32_t sample_cnt=0;sample_cnt<sig_size;++sample_cnt) { for (uint32_t ir_cnt=0;ir_cnt<ir_size;++ir_cnt) { output[sample_cnt] += sig[sample_cnt+ir_cnt] * ir[ir_cnt]; } } } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloConv(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::conv(sig, ir); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFftConv(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig) % arma::fft(ir,sig_size+ir_size-1)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFftPow2Conv(uint32_t ir_size, uint32_t sig_size) { uint32_t size = pow(2,ceil(log2(sig_size+ir_size-1))); arma::fvec sig {arma::randn<arma::fvec>(sig_size)}; arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig,size) % arma::fft(ir,size)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFft(uint32_t fft_size) { arma::fvec input {arma::randn<arma::fvec>(fft_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::fft(input); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloIFft(uint32_t fft_size) { arma::cx_fvec input {arma::randn<arma::cx_fvec>(fft_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(input); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } int main(int argc, char* argv[]) { auto arma_fft_time = ArmadilloFft(::fft_size); std::cout << "Armadillo FFT: " << arma_fft_time.count() << std::endl; auto arma_ifft_time = ArmadilloIFft(::fft_size); std::cout << "Armadillo iFFT: " << arma_ifft_time.count() << std::endl; auto arma_fft_pow2_conv_time = ArmadilloFftPow2Conv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo FFT-Pow2-convolution: " << arma_fft_pow2_conv_time.count() << std::endl; auto arma_fft_conv_time = ArmadilloFftConv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo FFT-convolution: " << arma_fft_conv_time.count() << std::endl; auto arma_conv_time = ArmadilloConv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo convolution: " << arma_conv_time.count() << std::endl; auto conv_time = Convolution(::conv_ir_size, ::conv_sig_size); std::cout << "convolution: " << conv_time.count() << std::endl; } <commit_msg>join FFT and iFFT<commit_after>#include <chrono> #include <iostream> #include <vector> #include <armadillo> using std::chrono::high_resolution_clock; using std::chrono::duration; namespace { uint32_t num = 1; uint32_t fft_size = 48000; uint32_t conv_ir_size = 72000; uint32_t conv_sig_size = 5760000; } duration<double> Convolution(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::fvec output (sig_size+ir_size-1); auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { for (uint32_t sample_cnt=0;sample_cnt<sig_size;++sample_cnt) { for (uint32_t ir_cnt=0;ir_cnt<ir_size;++ir_cnt) { output[sample_cnt] += sig[sample_cnt+ir_cnt] * ir[ir_cnt]; } } } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloConv(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::conv(sig, ir); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFftConv(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig) % arma::fft(ir,sig_size+ir_size-1)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFftPow2Conv(uint32_t ir_size, uint32_t sig_size) { uint32_t size = pow(2,ceil(log2(sig_size+ir_size-1))); arma::fvec sig {arma::randn<arma::fvec>(sig_size)}; arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig,size) % arma::fft(ir,size)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFft(uint32_t fft_size) { arma::fvec input {arma::randn<arma::fvec>(fft_size)}; arma::cx_fvec output_fd; arma::cx_fvec output_td; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output_fd = arma::fft(input); output_td = arma::ifft(output_fd); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output_td)); auto end = high_resolution_clock::now(); return end - begin; } int main(int argc, char* argv[]) { auto arma_fft_time = ArmadilloFft(::fft_size); std::cout << "Armadillo FFT: " << arma_fft_time.count() << std::endl; auto arma_fft_pow2_conv_time = ArmadilloFftPow2Conv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo FFT-Pow2-convolution: " << arma_fft_pow2_conv_time.count() << std::endl; auto arma_fft_conv_time = ArmadilloFftConv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo FFT-convolution: " << arma_fft_conv_time.count() << std::endl; auto arma_conv_time = ArmadilloConv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo convolution: " << arma_conv_time.count() << std::endl; auto conv_time = Convolution(::conv_ir_size, ::conv_sig_size); std::cout << "convolution: " << conv_time.count() << std::endl; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "TwitchBot.h" #include <pencode.h> struct botData { std::string name; std::string channel; std::string pass; }; botData readSettings(const std::string &appDir); int main() { botData bd; try { bd = readSettings(utils::getApplicationDirectory()); if (bd.name.empty()) { throw std::runtime_error("Could not extract name from settings.txt"); } if (bd.channel.empty()) { throw std::runtime_error("Could not extract channel from settings.txt"); } if (bd.pass.empty()) { throw std::runtime_error("Could not extract password from settings.txt"); } } catch (std::runtime_error &e) { std::cerr << e.what(); std::cin.get(); return 1; } TwitchBot bot(bd.name, bd.channel, bd.pass); if (bot.isConnected()) { bot.serverLoop(); } return 0; } botData readSettings(const std::string &appDir) { // open settings.cfg std::ifstream reader(appDir + "\\settings.txt"); if (!reader.is_open()) { throw std::runtime_error("Could not locate settings.txt"); } std::string line; uint8_t lineNum = 0; botData bd; while (std::getline(reader, line)) { lineNum++; // remove whitespace line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); // lines starting with * are comments if (utils::startsWith(line, "*")) { continue; } else { std::regex lineRegex("(name|channel|password):(.+?)"); std::smatch match; const std::string s = line; if (std::regex_match(s.begin(), s.end(), match, lineRegex)) { if (match[1].str() == "name") { bd.name = match[2]; } else if (match[1].str() == "channel") { if (!utils::startsWith(match[2].str(), "#")) { throw std::runtime_error("Channel name must start with #."); } bd.channel = match[2]; } else { if (!utils::startsWith(match[2].str(), "oauth:")) { throw std::runtime_error("Password must be a valid oauth token, starting with \"oauth:\"."); } bd.pass = match[2]; } } else { throw std::runtime_error("Syntax error on line " + std::to_string(lineNum) + " of settings.txt."); } } } reader.close(); return bd; }<commit_msg>Minor changes<commit_after>#include "stdafx.h" #include "TwitchBot.h" /* botData stores settings for a TwitchBot instance */ struct botData { std::string name; std::string channel; std::string pass; }; bool readSettings(const std::string &appDir, botData *bd, std::string &error); int main() { botData bd; std::string error; if (!readSettings(utils::getApplicationDirectory(), &bd, error)) { std::cerr << error << std::endl; std::cin.get(); return 1; } TwitchBot bot(bd.name, bd.channel, bd.pass); if (bot.isConnected()) { bot.serverLoop(); } return 0; } bool readSettings(const std::string &appDir, botData *bd, std::string &error) { // open settings.cfg std::ifstream reader(appDir + "\\settings.txt"); if (!reader.is_open()) { error = "Could not locate settings.txt"; return false; } std::string line; uint8_t lineNum = 0; while (std::getline(reader, line)) { lineNum++; // remove whitespace line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); // lines starting with * are comments if (utils::startsWith(line, "*")) { continue; } else { std::regex lineRegex("(name|channel|password):(.+?)"); std::smatch match; const std::string s = line; if (std::regex_match(s.begin(), s.end(), match, lineRegex)) { if (match[1].str() == "name") { bd->name = match[2]; } else if (match[1].str() == "channel") { if (!utils::startsWith(match[2].str(), "#")) { error = "Channel name must start with #."; } bd->channel = match[2]; } else { if (!utils::startsWith(match[2].str(), "oauth:")) { error = "Password must be a valid oauth token, starting with \"oauth:\"."; } bd->pass = match[2]; } } else { error = "Syntax error on line " + std::to_string(lineNum) + " of settings.txt."; } } if (!error.empty()) { return false; } } reader.close(); return true; }<|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <sstream> #include <cctype> #include <clocale> #include <string> #include <vector> #include <list> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <stack> #include <string.h> #include <netdb.h> #include <pwd.h> #include <sys/socket.h> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost::algorithm; //Virtual Base Class - Ammar class Base { public: Base(){}; //Function Inherited by each class - Ammar virtual bool evaluate() = 0; }; class Test{ private: int flagNum; public: // filetype found bool found; // format args Test(vector<string> argsTest){ if (argsTest[0] =="-e") { argsTest.erase(argsTest.begin()); flagNum =1; } else if (argsTest[0] =="-f") { argsTest.erase(argsTest.begin()); flagNum =2; } else if (argsTest[0] =="-d") { argsTest.erase(argsTest.begin()); flagNum =3; } else{ flagNum = 1; } vector<char *> charVec; charVec.push_back(const_cast<char *>(argsTest[0].c_str())); charVec.push_back(('\0')); char** charVec_two = &charVec[0]; struct stat statStruct; if(stat(const_cast<char *>(charVec[0]), &statStruct)<0){ // testing if file was located found = 1; } else{ if (flagNum == 1) { found = true; } else if(flagNum == 2) { (S_ISREG(statStruct.st_mode)) ? found = 1 : found = 0; } else if (flagNum == 3) { (S_ISDIR(statStruct.st_mode)) ? found = 1 : found = 0; } else { cout << "Error" << endl; } } } }; // Command Class that each command will inherit from - Ammar class Command : public Base { private: //Vector of commands - Ammar vector<string> commandVec; public: //Contructor to take in vector and set it to commands vectors Command(vector<string>s){ commandVec = s; } bool evaluate(){ //exit if cmd is "exit" if(commandVec[0] == "exit") { //Program stops if input is "exit" - Ammar exit(0); } //this chunk is to format the vector in the way we want it vector<char *> temp2; for(unsigned int i = 0; i < commandVec.size(); i++) { temp2.push_back(const_cast<char *>(commandVec[i].c_str())); } temp2.push_back('\0'); //'\0 is to make sure there is a null char in c-str' char** arrChar = &temp2[0]; //here we will use fork() so we can do multiple process at once int status; pid_t pid = fork(); if (pid < 0) { //to chck if fork failed perror("FAILED"); exit(1); } else if (pid == 0) { //if it reaches here, you can pass into execvp //execvp will do all the work for you execvp(const_cast<char *>(arrChar[0]), arrChar); //if it reaches here there is some error exit(127); // exit 127 "command not found" } else if(pid > 0){ //have to wait until child finishes // use wait pid or wait ???? waitpid(pid, &status, 0); wait(&status); if(wait(&status) != -1){ perror("ERROR: wait"); } if(WIFEXITED(status)){ if(WEXITSTATUS(status) == 0) { //program is succesful return true; } else { //this return is false, then the program failed but exiting was normal return false; } } else { //the program messed up and exited abnormally perror("EXIT: ABNORMAL CHILD"); return false; } } return false; } }; class Connectors : public Base { public: Connectors(){}; protected: bool leftCommand; //command b4 the connector Base* rightCommand; //command @ft3r the connect0r }; //will always attempt to run rightCommand class Semicolon : public Connectors { public: Semicolon(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate() { return rightCommand->evaluate(); } }; //will run the rightcommand if leftcommand succededs class And : public Connectors{ public: And(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate(){ if(leftCommand) return rightCommand->evaluate(); return false; } }; //will run the rightCommand if the LeftCommand fails class Or : public Connectors{ public: Or(bool l, Base* r){ leftCommand = l; rightCommand = r; } //Return if it evaluated or not bool evaluate(){ if(!leftCommand) return rightCommand->evaluate(); return false; } }; //This Function takes the user input and parses it returns us a vector of strings - Ammar vector<string> parser(string toSplit, const char* delimiters) { char* toTokenize = new char[toSplit.size() + 1]; strcpy(toTokenize, toSplit.c_str()); toTokenize[toSplit.size() + 1] = '\0'; char* cutThis; //begin parsing cutThis = strtok(toTokenize, delimiters); vector<string> returnThis; while (cutThis != NULL) { string currWord(cutThis); trim(currWord); returnThis.push_back(currWord); cutThis = strtok(NULL, delimiters); } return returnThis; } unsigned perEnds(string commandInput, int a){ stack<char> charStack; int i =a; charStack.push('f'); i++; for(int i=0; i < commandInput.size(); i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i) == ')'){ char open = charStack.top(); charStack.pop(); if(charStack.empty() && open =='f') { return i; } } } return i; } string parsePer(string commandInput){ stack<char> charStack; bool isBool = 0; do{ trim(commandInput); if(commandInput.find('(') !=0){ return commandInput; } else if(perEnds(commandInput, 0) == commandInput.size()-1){ commandInput.erase(0,1); commandInput.erase(commandInput.size()-1); if(perEnds(commandInput, 0)== commandInput.size()-1){ isBool = 1; } else{ return commandInput; } } else{ return commandInput; } } while(isBool == 1); return commandInput; } void perCheck(string commandInput){ stack<char> charStack; for(int i =0; i < commandInput.size();i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i)== ')'){ if(!charStack.empty()){ charStack.pop(); } else{ cout << "Error"; exit(0); } } } if(!charStack.empty()){ cout << "Error"; exit(0); } } class Chunks:public Base{ private: string commandInput; vector<bool> track; bool isNested; public: Chunks(string s){ commandInput =s; } bool evaluate() { trim(commandInput); commandInput = parsePer(commandInput); if(commandInput == ""){ return 1; } isNested = 0; for(int i =0;i<commandInput.size();i++){ if(commandInput.at(i)=='('){ isNested =1; } } if(isNested) { vector<string> VecConnect; vector<string> chunksVec; unsigned begin; unsigned end; string chuncksPush; for(int i =0;i < commandInput.size();){ if(commandInput.at(i)=='('){ begin =i; end = perEnds(commandInput, i); chuncksPush = commandInput.substr(begin,end -begin+1); chunksVec.push_back(chuncksPush); i += end - begin+1; } else if(commandInput.at(i)=='&'){ if(commandInput.at(i+1)=='&'){ VecConnect.push_back("&&"); } i+=2; } else if(commandInput.at(i)==';'){ VecConnect.push_back(";"); i++; } else if(commandInput.at(i)==' '){ i++; } else if(commandInput.at(i)=='|'){ if(commandInput.at(i+1)=='|'){ VecConnect.push_back("||"); } i+=2; } else{ begin =i; unsigned a; unsigned b; unsigned c; c = commandInput.find(";",i); a = commandInput.find("&&",i); b = commandInput.find("||",i); if(commandInput.find("&&", i) == string::npos&&commandInput.find("||",i) ==string::npos && commandInput.find(";",i)== string::npos){ end= commandInput.size(); } else{ if(a<b && a<c){ end = a-1; } else if(b< a && b<c){ end = b-1; } else if(c< a && c<b){ end = c-1; } } chuncksPush = commandInput.substr(begin,end-begin); i+= end - begin; chunksVec.push_back(chuncksPush); } } Base* firstChunck = new Chunks(chunksVec[0]); bool boolean = firstChunck->evaluate(); track.push_back(boolean); for(int j =0; j < VecConnect.size(); j++){ Base* nextChunk; if(VecConnect[j] == "&&"){ nextChunk = new And(boolean, new Chunks(chunksVec[j+1])); } else if(VecConnect[j] == "||"){ nextChunk = new Or(boolean, new Chunks(chunksVec[j+1])); } else if(VecConnect[j] == ";"){ nextChunk = new Semicolon(boolean, new Chunks(chunksVec[j+1])); } bool nextC = nextChunk->evaluate(); track.push_back(nextC); } for(int k=0; k< track.size();k++){ if(track.at(k)==1){ return 1; } } } else if(!isNested){ int ind_one; int ind_two; if(commandInput.find('[') != string::npos){ ind_one = commandInput.find('['); if(commandInput.find(']')){ ind_two = commandInput.find(']'); } else{ cout << "Not closed"<< endl; exit(0); } commandInput.erase(ind_one,1); commandInput.erase(ind_two-1,1); commandInput.insert(0, "test "); } vector<string> ConVec; for(unsigned l=0; l< commandInput.length();l++){ if(commandInput[l]=='&'){ if(commandInput[l+1]=='&'){ ConVec.push_back("&&"); } } else if(commandInput[l]=='|'){ if(commandInput[l+1]=='|'){ ConVec.push_back("||"); } } else if(commandInput[l]==';'){ ConVec.push_back(";"); } } vector<string> commands= parser(commandInput, "||&&;"); vector<string> begincommands = parser(commands.at(0), " "); Base* first = new Command(begincommands); bool g = first->evaluate(); track.push_back(g); for (unsigned i = 0; i < ConVec.size(); i ++) { Base* next; vector<string> args = parser(commands.at(i + 1), " "); if (ConVec.at(i) == "&&") { next = new And(g, new Command(args)); } else if (ConVec.at(i) == "||") { next = new Or(g, new Command(args)); } else if (ConVec.at(i) == ";") { next = new Semicolon(g, new Command(args)); } bool cNext = next->evaluate(); track.push_back(cNext); } for (unsigned int f = 0; f < track.size(); f++) { if (track[f] == 1) { return 1; } } return 0; } return 0; } }; int main () { string commandInput = ""; string formattedInput; vector<string> v; Base* theLine; while (true) { string login = getlogin(); char hostname[100]; gethostname(hostname, 100); cout << "[" << login << "@" << hostname << "] $ "; getline(cin, commandInput); trim(commandInput); theLine = new Line(commandInput); vector<string> parsedVector; if ((commandInput.find("(") != string::npos) && (commandInput.find(")") != string::npos)) { //there is precedence string command; for (unsigned int i = 0; i < commandInput.size(); ++i) { if (commandInput.at(i) == '&' && i != commandInput.size() - 1) { if (commandInput.at(i + 1) == '&') { parsedVector.push_back(command); command = ""; parsedVector.push_back("&&"); } } else if (commandInput.at(i) == '|' && i != commandInput.size() - 1) { if (commandInput.at(i + 1) == '|') { parsedVector.push_back(command); command = ""; parsedVector.push_back("||"); } } else if (commandInput.at(i) == ';') { parsedVector.push_back(command); command = ""; parsedVector.push_back(";"); } else { command += commandInput.at(i); } } printVec(parsedVector); vector<string> postfix; //infix2postfix(parsedVector, postfix); //printVec(postfix); } else { theLine->evaluate(); } } return 0; } <commit_msg>Update main.cpp<commit_after>#include <iostream> #include <algorithm> #include <sstream> #include <cctype> #include <clocale> #include <string> #include <vector> #include <list> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <stack> #include <string.h> #include <netdb.h> #include <pwd.h> #include <sys/socket.h> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost::algorithm; //Virtual Base Class - Ammar class Base { public: Base(){}; //Function Inherited by each class - Ammar virtual bool evaluate() = 0; }; class Test{ private: int flagNum; public: // filetype found bool found; // format args Test(vector<string> argsTest){ if (argsTest[0] =="-e") { argsTest.erase(argsTest.begin()); flagNum =1; } else if (argsTest[0] =="-f") { argsTest.erase(argsTest.begin()); flagNum =2; } else if (argsTest[0] =="-d") { argsTest.erase(argsTest.begin()); flagNum =3; } else{ flagNum = 1; } vector<char *> charVec; charVec.push_back(const_cast<char *>(argsTest[0].c_str())); charVec.push_back(('\0')); char** charVec_two = &charVec[0]; struct stat statStruct; if(stat(const_cast<char *>(charVec[0]), &statStruct)<0){ // testing if file was located found = 1; } else{ if (flagNum == 1) { found = true; } else if(flagNum == 2) { (S_ISREG(statStruct.st_mode)) ? found = 1 : found = 0; } else if (flagNum == 3) { (S_ISDIR(statStruct.st_mode)) ? found = 1 : found = 0; } else { cout << "Error" << endl; } } } }; // Command Class that each command will inherit from - Ammar class Command : public Base { private: //Vector of commands - Ammar vector<string> commandVec; public: //Contructor to take in vector and set it to commands vectors Command(vector<string>s){ commandVec = s; } bool evaluate(){ //exit if cmd is "exit" if(commandVec[0] == "exit") { //Program stops if input is "exit" - Ammar exit(0); } //this chunk is to format the vector in the way we want it vector<char *> temp2; for(unsigned int i = 0; i < commandVec.size(); i++) { temp2.push_back(const_cast<char *>(commandVec[i].c_str())); } temp2.push_back('\0'); //'\0 is to make sure there is a null char in c-str' char** arrChar = &temp2[0]; //here we will use fork() so we can do multiple process at once int status; pid_t pid = fork(); if (pid < 0) { //to chck if fork failed perror("FAILED"); exit(1); } else if (pid == 0) { //if it reaches here, you can pass into execvp //execvp will do all the work for you execvp(const_cast<char *>(arrChar[0]), arrChar); //if it reaches here there is some error exit(127); // exit 127 "command not found" } else if(pid > 0){ //have to wait until child finishes // use wait pid or wait ???? waitpid(pid, &status, 0); wait(&status); if(wait(&status) != -1){ perror("ERROR: wait"); } if(WIFEXITED(status)){ if(WEXITSTATUS(status) == 0) { //program is succesful return true; } else { //this return is false, then the program failed but exiting was normal return false; } } else { //the program messed up and exited abnormally perror("EXIT: ABNORMAL CHILD"); return false; } } return false; } }; class Connectors : public Base { public: Connectors(){}; protected: bool leftCommand; //command b4 the connector Base* rightCommand; //command @ft3r the connect0r }; //will always attempt to run rightCommand class Semicolon : public Connectors { public: Semicolon(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate() { return rightCommand->evaluate(); } }; //will run the rightcommand if leftcommand succededs class And : public Connectors{ public: And(bool l, Base* r){ leftCommand = l; rightCommand = r; } bool evaluate(){ if(leftCommand) return rightCommand->evaluate(); return false; } }; //will run the rightCommand if the LeftCommand fails class Or : public Connectors{ public: Or(bool l, Base* r){ leftCommand = l; rightCommand = r; } //Return if it evaluated or not bool evaluate(){ if(!leftCommand) return rightCommand->evaluate(); return false; } }; //This Function takes the user input and parses it returns us a vector of strings - Ammar vector<string> parser(string toSplit, const char* delimiters) { char* toTokenize = new char[toSplit.size() + 1]; strcpy(toTokenize, toSplit.c_str()); toTokenize[toSplit.size() + 1] = '\0'; char* cutThis; //begin parsing cutThis = strtok(toTokenize, delimiters); vector<string> returnThis; while (cutThis != NULL) { string currWord(cutThis); trim(currWord); returnThis.push_back(currWord); cutThis = strtok(NULL, delimiters); } return returnThis; } unsigned perEnds(string commandInput, int a){ stack<char> charStack; int i =a; charStack.push('f'); i++; for(int i=0; i < commandInput.size(); i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i) == ')'){ char open = charStack.top(); charStack.pop(); if(charStack.empty() && open =='f') { return i; } } } return i; } string parsePer(string commandInput){ stack<char> charStack; bool isBool = 0; do{ trim(commandInput); if(commandInput.find('(') !=0){ return commandInput; } else if(perEnds(commandInput, 0) == commandInput.size()-1){ commandInput.erase(0,1); commandInput.erase(commandInput.size()-1); if(perEnds(commandInput, 0)== commandInput.size()-1){ isBool = 1; } else{ return commandInput; } } else{ return commandInput; } } while(isBool == 1); return commandInput; } void perCheck(string commandInput){ stack<char> charStack; for(int i =0; i < commandInput.size();i++) { if(commandInput.at(i)== '('){ charStack.push('('); } else if(commandInput.at(i)== ')'){ if(!charStack.empty()){ charStack.pop(); } else{ cout << "Error"; exit(0); } } } if(!charStack.empty()){ cout << "Error"; exit(0); } } class Chunks:public Base{ private: string commandInput; vector<bool> track; bool isNested; public: Chunks(string s){ commandInput =s; } bool evaluate() { trim(commandInput); commandInput = parsePer(commandInput); if(commandInput == ""){ return 1; } isNested = 0; for(int i =0;i<commandInput.size();i++){ if(commandInput.at(i)=='('){ isNested =1; } } if(isNested) { vector<string> VecConnect; vector<string> chunksVec; unsigned begin; unsigned end; string chuncksPush; for(int i =0;i < commandInput.size();){ if(commandInput.at(i)=='('){ begin =i; end = perEnds(commandInput, i); chuncksPush = commandInput.substr(begin,end -begin+1); chunksVec.push_back(chuncksPush); i += end - begin+1; } else if(commandInput.at(i)=='&'){ if(commandInput.at(i+1)=='&'){ VecConnect.push_back("&&"); } i+=2; } else if(commandInput.at(i)==';'){ VecConnect.push_back(";"); i++; } else if(commandInput.at(i)==' '){ i++; } else if(commandInput.at(i)=='|'){ if(commandInput.at(i+1)=='|'){ VecConnect.push_back("||"); } i+=2; } else{ begin =i; unsigned a; unsigned b; unsigned c; c = commandInput.find(";",i); a = commandInput.find("&&",i); b = commandInput.find("||",i); if(commandInput.find("&&", i) == string::npos&&commandInput.find("||",i) ==string::npos && commandInput.find(";",i)== string::npos){ end= commandInput.size(); } else{ if(a<b && a<c){ end = a-1; } else if(b< a && b<c){ end = b-1; } else if(c< a && c<b){ end = c-1; } } chuncksPush = commandInput.substr(begin,end-begin); i+= end - begin; chunksVec.push_back(chuncksPush); } } Base* firstChunck = new Chunks(chunksVec[0]); bool boolean = firstChunck->evaluate(); track.push_back(boolean); for(int j =0; j < VecConnect.size(); j++){ Base* nextChunk; if(VecConnect[j] == "&&"){ nextChunk = new And(boolean, new Chunks(chunksVec[j+1])); } else if(VecConnect[j] == "||"){ nextChunk = new Or(boolean, new Chunks(chunksVec[j+1])); } else if(VecConnect[j] == ";"){ nextChunk = new Semicolon(boolean, new Chunks(chunksVec[j+1])); } bool nextC = nextChunk->evaluate(); track.push_back(nextC); } for(int k=0; k< track.size();k++){ if(track.at(k)==1){ return 1; } } } else if(!isNested){ int ind_one; int ind_two; if(commandInput.find('[') != string::npos){ ind_one = commandInput.find('['); if(commandInput.find(']')){ ind_two = commandInput.find(']'); } else{ cout << "Not closed"<< endl; exit(0); } commandInput.erase(ind_one,1); commandInput.erase(ind_two-1,1); commandInput.insert(0, "test "); } vector<string> ConVec; for(unsigned l=0; l< commandInput.length();l++){ if(commandInput[l]=='&'){ if(commandInput[l+1]=='&'){ ConVec.push_back("&&"); } } else if(commandInput[l]=='|'){ if(commandInput[l+1]=='|'){ ConVec.push_back("||"); } } else if(commandInput[l]==';'){ ConVec.push_back(";"); } } vector<string> commands= parser(commandInput, "||&&;"); vector<string> begincommands = parser(commands.at(0), " "); Base* first = new Command(begincommands); bool g = first->evaluate(); track.push_back(g); for (unsigned i = 0; i < ConVec.size(); i ++) { Base* next; vector<string> args = parser(commands.at(i + 1), " "); if (ConVec.at(i) == "&&") { next = new And(g, new Command(args)); } else if (ConVec.at(i) == "||") { next = new Or(g, new Command(args)); } else if (ConVec.at(i) == ";") { next = new Semicolon(g, new Command(args)); } bool cNext = next->evaluate(); track.push_back(cNext); } for (unsigned int f = 0; f < track.size(); f++) { if (track[f] == 1) { return 1; } } return 0; } return 0; } }; int main () { //take user input string commandInput = ""; while (true) { //Keep checking until exit is found //this is the extra credit part string login = getlogin(); char hostname[100]; gethostname(hostname, 100); //display login and host name and waits for user input cout << "[" << login << "@" << hostname << "] $ "; getline(cin, commandInput); // Gets rid of leading and ending uneeded space - Ammar trim(commandInput); bool blank = false; if(commandInput == ""){ blank = true; } while(blank == false){ string inputCommand = commandInput.substr(0, commandInput.find('#', 1)); Base* line = new Chunks(inputCommand); line->evaluate(); blank = true; //this means done with this command and wants next one } } return 0; } <|endoftext|>
<commit_before>#include <mount.hpp> #include <algorithm> #include <iostream> #include <iterator> #include <fstream> #include <vector> #include <string> #include <kdbinternal.h> using namespace std; using namespace kdb; std::string MountCommand::root = "system/elektra/mountpoints"; MountCommand::MountCommand() {} KeySet MountCommand::addPlugins(std::string name, std::string which) { KeySet ret; ret.append (*Key (root + "/" + name + "/" + which + "plugins", KEY_COMMENT, "List of plugins to use", KEY_END)); cout << "Now you have to provide some " << which << " plugins which should be used for that backend" << endl; for (int i=0; i<10; ++i) { cout << "Enter the " << i << " plugin to use." << endl; cout << "Write \".\" as name in a single line if you are finished" << endl; cout << "Name of the " << which << " plugin: "; std::string pluginName; cin >> pluginName; if (pluginName == ".") break; cout << "Enter a path to a file in the filesystem: "; std::string path; cin >> path; std::ofstream f(path.c_str()); if (!f.is_open()) cerr << "Warning, could not open that file" << endl; KeySet testConfig(1, *Key( "system/path", KEY_VALUE, path.c_str(), KEY_COMMENT, "Test config for loading a plugin.", KEY_END), KS_END); ckdb::Plugin *plugin = ckdb::pluginOpen(pluginName.c_str(), testConfig.dup()); if (plugin && which == "get") { if (!plugin->kdbGet) { cout << "get symbol missing" << endl; plugin = 0; } } if (plugin && which == "set") { if (!plugin->kdbSet) { cout << "set symbol missing" << endl; plugin = 0; } } ckdb::pluginClose(plugin); if (!plugin) { cout << "Was not able to load such a plugin!" << endl; cout << "or it had no " << which << " symbol exported (see above)" << endl; cout << "Do you want to (P)roceed with next plugin?" << endl; cout << "Do you want to (R)etry?" << endl; cout << "Do you want to (F)inish entering plugins?" << endl; cout << "Or do you want to (A)bort?" << endl; string answer; cin >> answer; if (answer == "P" || answer == "Proceed" || answer == "(P)roceed" || answer == "p") { continue; } else if (answer == "R" || answer == "Retry" || answer == "(R)etry" || answer == "r") { --i; continue; } else if (answer == "F" || answer == "Finish" || answer == "(F)inish" || answer == "f") { break; } else throw 3; } std::ostringstream pluginNumber; pluginNumber << i; ret.append (*Key (root + "/" + name + "/" + which + std::string("plugins/#") + pluginNumber.str() + pluginName, KEY_COMMENT, "A plugin", KEY_END)); ret.append (*Key (root + "/" + name + "/" + which + std::string("plugins/#") + pluginNumber.str() + pluginName + "/config", KEY_COMMENT, "The configuration for the specific plugin.\n" "All keys below that directory will be passed to plugin.\n" "These keys have backend specific meaning.\n" "See documentation http://www.libelektra.org for which keys must or can be set.\n" "Here the most important keys should be preloaded.", KEY_END)); ret.append (*Key (root + "/" + name + "/" + which + "plugins/#" + pluginNumber.str() + pluginName + "/config/path", KEY_VALUE, path.c_str(), KEY_COMMENT, "The path where the config file is located." "This item is often used by backends using configuration in a filesystem" "to know there relative location of the keys to fetch or write.", KEY_END)); } return ret; } int MountCommand::execute(int , char** ) { cout << "Welcome to interactive mounting" << endl; cout << "Please provide a unique name." << endl; KeySet conf; try { kdb.get(conf, Key(root, KEY_END)); } catch (KDBException const& e) { cout << "Could not get configuration" << endl; cout << "Seems like this is your first mount" << endl; } std::vector <std::string> names; conf.rewind(); Key cur; try { cur = conf.lookup(Key(root, KEY_END)); } catch (KeySetNotFound const& e) { cout << "Did not find the root key, will add them" << endl; cout << "Note that nothing will be written out" << endl; cout << "until you say y at the very end of the mounting process" << endl; conf.append ( *Key(root, KEY_COMMENT, "Below are the mountpoints.", KEY_END)); conf.rewind(); } while (cur = conf.next()) { if (Key(root, KEY_END).isDirectBelow(cur)) { cout << "adding " << cur.getName() << endl; names.push_back(cur.getBaseName()); } else cout << "not adding " << cur.getName() << endl; } cout << "Already used are: "; std::copy (names.begin(), names.end(), ostream_iterator<std::string>(cout, " ")); std::string name; std::cout << endl << "Name: "; cin >> name; if (std::find(names.begin(), names.end(), name) != names.end()) { cerr << "Name already used, will abort" << endl; return 2; } conf.append ( *Key(name, KEY_COMMENT, "This is a mounted backend.", KEY_END)); conf.append ( *Key( root + "/" + name, KEY_DIR, KEY_VALUE, "", KEY_COMMENT, "This is a mounted backend, see subkeys for more information", KEY_END)); cout << "Please use / for the root backend" << endl; cout << "Enter the mountpoint: "; std::string mp; cin >> mp; if (mp == "/") { conf.append ( *Key( root + "/" + name + "/mountpoint", KEY_VALUE, "", KEY_COMMENT, "The mountpoint says the location where the backend should be mounted.\n" "It must be a valid, canonical elektra path. There are no ., .. or multiple slashes allowed.\n" "You are not allowed to mount inside system/elektra.", KEY_END)); } else { if (!Key (mp, KEY_END)) { cerr << "This was not a valid key name" << endl; cerr << "Examples: system/hosts or user/sw/app" << endl; return 3; } conf.append ( *Key( root + "/" + name + "/mountpoint", KEY_VALUE, mp.c_str(), KEY_COMMENT, "The mountpoint says the location where the backend should be mounted.\n" "It must be a valid, canonical elektra path. There are no ., .. or multiple slashes allowed.\n" "You are not allowed to mount inside system/elektra.", KEY_END)); } conf.append(addPlugins(name, "set")); conf.append(addPlugins(name, "get")); cout << "Enter a path to a file in the filesystem (for all plugins): "; std::string path; cin >> path; std::ofstream f(path.c_str()); if (!f.is_open()) cerr << "Warning, could not open that file" << endl; conf.append ( *Key( root + "/" + name + "/config", KEY_VALUE, "", KEY_COMMENT, "This is a configuration for a backend, see subkeys for more information", KEY_END)); conf.append ( *Key( root + "/" + name + "/config/path", KEY_VALUE, path.c_str(), KEY_COMMENT, "The path for this backend. Note that plugins can override that with more specific configuration.", KEY_END)); cout << "Ready to mount with following configuration:" << endl; cout << "Name: " << name << endl; cout << "Mountpoint: " << mp << endl; cout << "Path: " << path << endl; cout << "The configuration which will be set is:" << endl; conf.rewind(); while (Key k = conf.next()) { cout << k.getName() << " " << k.getString() << endl; } cout << "Are you sure you want to do that (y/N): "; std::string answer; cin >> answer; if (answer != "y") { cerr << "Aborted by user request" << endl; return 4; } kdb.set(conf, Key(root, KEY_END)); return 0; } MountCommand::~MountCommand() {} <commit_msg>kdb mount more robust<commit_after>#include <mount.hpp> #include <algorithm> #include <iostream> #include <iterator> #include <fstream> #include <vector> #include <string> #include <kdbinternal.h> using namespace std; using namespace kdb; std::string MountCommand::root = "system/elektra/mountpoints"; MountCommand::MountCommand() {} KeySet MountCommand::addPlugins(std::string name, std::string which) { KeySet ret; ret.append (*Key (root + "/" + name + "/" + which + "plugins", KEY_COMMENT, "List of plugins to use", KEY_END)); cout << "Now you have to provide some " << which << " plugins which should be used for that backend" << endl; for (int i=0; i<10; ++i) { cout << "Enter the " << i << " plugin to use." << endl; cout << "Write \".\" as name in a single line if you are finished" << endl; cout << "Name of the " << which << " plugin: "; std::string pluginName; cin >> pluginName; if (pluginName == ".") break; cout << "Enter a path to a file in the filesystem: "; std::string path; cin >> path; std::ofstream f(path.c_str()); if (!f.is_open()) cerr << "Warning, could not open that file" << endl; KeySet testConfig(1, *Key( "system/path", KEY_VALUE, path.c_str(), KEY_COMMENT, "Test config for loading a plugin.", KEY_END), KS_END); ckdb::Plugin *plugin = ckdb::pluginOpen(pluginName.c_str(), testConfig.dup()); if (plugin && which == "get") { if (!plugin->kdbGet) { cout << "get symbol missing" << endl; plugin = 0; } } if (plugin && which == "set") { if (!plugin->kdbSet) { cout << "set symbol missing" << endl; plugin = 0; } } ckdb::pluginClose(plugin); if (!plugin) { cout << "Was not able to load such a plugin!" << endl; cout << "or it had no " << which << " symbol exported (see above)" << endl; cout << "Do you want to (P)roceed with next plugin?" << endl; cout << "Do you want to (R)etry?" << endl; cout << "Do you want to (F)inish entering plugins?" << endl; cout << "Or do you want to (A)bort?" << endl; string answer; cin >> answer; if (answer == "P" || answer == "Proceed" || answer == "(P)roceed" || answer == "p") { continue; } else if (answer == "R" || answer == "Retry" || answer == "(R)etry" || answer == "r") { --i; continue; } else if (answer == "F" || answer == "Finish" || answer == "(F)inish" || answer == "f") { break; } else throw 3; } std::ostringstream pluginNumber; pluginNumber << i; ret.append (*Key (root + "/" + name + "/" + which + std::string("plugins/#") + pluginNumber.str() + pluginName, KEY_COMMENT, "A plugin", KEY_END)); ret.append (*Key (root + "/" + name + "/" + which + std::string("plugins/#") + pluginNumber.str() + pluginName + "/config", KEY_COMMENT, "The configuration for the specific plugin.\n" "All keys below that directory will be passed to plugin.\n" "These keys have backend specific meaning.\n" "See documentation http://www.libelektra.org for which keys must or can be set.\n" "Here the most important keys should be preloaded.", KEY_END)); ret.append (*Key (root + "/" + name + "/" + which + "plugins/#" + pluginNumber.str() + pluginName + "/config/path", KEY_VALUE, path.c_str(), KEY_COMMENT, "The path where the config file is located." "This item is often used by backends using configuration in a filesystem" "to know there relative location of the keys to fetch or write.", KEY_END)); } return ret; } int MountCommand::execute(int , char** ) { cout << "Welcome to interactive mounting" << endl; cout << "Please provide a unique name." << endl; KeySet conf; try { kdb.get(conf, Key(root, KEY_END)); } catch (KDBException const& e) { cout << "Could not get configuration" << endl; cout << "Seems like this is your first mount" << endl; } conf.rewind(); Key cur; try { cur = conf.lookup(Key(root, KEY_END)); } catch (KeySetNotFound const& e) { cout << "Did not find the root key, will add it" << endl; cout << "Note that nothing will be written out" << endl; cout << "until you say y at the very end of the mounting process" << endl; conf.append ( *Key(root, KEY_COMMENT, "Below are the mountpoints.", KEY_END)); conf.rewind(); } std::vector <std::string> names; while (cur = conf.next()) { if (Key(root, KEY_END).isDirectBelow(cur)) { names.push_back(cur.getBaseName()); } } cout << "Already used are: "; std::copy (names.begin(), names.end(), ostream_iterator<std::string>(cout, " ")); cout << endl; std::string name; std::cout << "Name: "; cin >> name; if (std::find(names.begin(), names.end(), name) != names.end()) { cerr << "Name already used, will abort" << endl; return 2; } cout << endl; conf.append ( *Key( root + "/" + name, KEY_DIR, KEY_VALUE, "", KEY_COMMENT, "This is a mounted backend, see subkeys for more information", KEY_END)); std::vector <std::string> mountpoints; KeySet ksMountpoints; conf.rewind(); while (cur = conf.next()) { if (cur.getBaseName() == "mountpoint") { if (cur.getString() == "") { mountpoints.push_back("/"); } else { try { conf.lookup(Key(cur.getString(), KEY_END)); } catch (KeySetNotFound const& e) { cout << "Did not find the mountpoint " << cur.getString() << ", will add it" << endl; // Hack: currently the mountpoints need to exist, so that they can be found ksMountpoints.append ( *Key(cur.getString(), KEY_COMMENT, "This is a mountpoint", KEY_META, "mountpoint", "", KEY_END)); } mountpoints.push_back(cur.getString()); } }; } conf.append(ksMountpoints); cout << "Already used are: "; std::copy (mountpoints.begin(), mountpoints.end(), ostream_iterator<std::string>(cout, " ")); cout << endl; cout << "Please use / for the root backend" << endl; cout << "Enter the mountpoint: "; std::string mp; cin >> mp; if (std::find(mountpoints.begin(), mountpoints.end(), name) != mountpoints.end()) { cerr << "Mountpoint already used, will abort" << endl; return 2; } if (mp == "/") { conf.append ( *Key( root + "/" + name + "/mountpoint", KEY_VALUE, "", KEY_COMMENT, "The mountpoint says the location where the backend should be mounted.\n" "It must be a valid, canonical elektra path. There are no ., .. or multiple slashes allowed.\n" "You are not allowed to mount inside system/elektra.", KEY_END)); } else { if (!Key (mp, KEY_END)) { cerr << "This was not a valid key name" << endl; cerr << "Examples: system/hosts or user/sw/app" << endl; return 3; } // Hack: currently the mountpoints need to exist, so that they can be found conf.append ( *Key(mp, KEY_COMMENT, "This is a mounted backend.", KEY_META, "mountpoint", "", KEY_END)); conf.append ( *Key( root + "/" + name + "/mountpoint", KEY_VALUE, mp.c_str(), KEY_COMMENT, "The mountpoint says the location where the backend should be mounted.\n" "It must be a valid, canonical elektra path. There are no ., .. or multiple slashes allowed.\n" "You are not allowed to mount inside system/elektra.", KEY_END)); } cout << endl; conf.append(addPlugins(name, "set")); conf.append(addPlugins(name, "get")); cout << "Enter a path to a file in the filesystem (for all plugins): "; std::string path; cin >> path; std::ofstream f(path.c_str()); if (!f.is_open()) cerr << "Warning, could not open that file" << endl; conf.append ( *Key( root + "/" + name + "/config", KEY_VALUE, "", KEY_COMMENT, "This is a configuration for a backend, see subkeys for more information", KEY_END)); conf.append ( *Key( root + "/" + name + "/config/path", KEY_VALUE, path.c_str(), KEY_COMMENT, "The path for this backend. Note that plugins can override that with more specific configuration.", KEY_END)); cout << "Ready to mount with following configuration:" << endl; cout << "Name: " << name << endl; cout << "Mountpoint: " << mp << endl; cout << "Path: " << path << endl; cout << "The configuration which will be set is:" << endl; conf.rewind(); while (Key k = conf.next()) { cout << k.getName() << " " << k.getString() << endl; } cout << "Are you sure you want to do that (y/N): "; std::string answer; cin >> answer; if (answer != "y") { cerr << "Aborted by user request" << endl; return 4; } kdb.set(conf, Key(root, KEY_END)); return 0; } MountCommand::~MountCommand() {} <|endoftext|>
<commit_before>#include "other.hpp" int main() { Test::hello(); return 0; } <commit_msg>A little fix<commit_after>int main() { return 0; } <|endoftext|>
<commit_before>// This program is free software licenced under MIT Licence. You can // find a copy of this licence in LICENCE.txt in the top directory of // source code. // // C++ #include <iostream> #include <exception> // Project #include "Bot.h" int main() { std::cout.sync_with_stdio(false); #ifndef STARTERBOT_DEBUG try { #endif Bot b; b.play(); #ifndef STARTERBOT_DEBUG } catch (std::exception& ex) { std::cerr << "Exception:" << ex.what() << std::endl; return 1; } #endif return 0; } <commit_msg>Do not hide static method ffs<commit_after>// This program is free software licenced under MIT Licence. You can // find a copy of this licence in LICENCE.txt in the top directory of // source code. // // C++ #include <iostream> #include <exception> // Project #include "Bot.h" int main() { std::ios_base::sync_with_stdio(false); #ifndef STARTERBOT_DEBUG try { #endif Bot b; b.play(); #ifndef STARTERBOT_DEBUG } catch (std::exception& ex) { std::cerr << "Exception:" << ex.what() << std::endl; return 1; } #endif return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <list> #include <time.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <errno.h> #include "util.hpp" #include "table.hpp" #include "naive.hpp" //#include "dxr.hpp" #include "basicTrie.hpp" #include "pcTrie.hpp" #define CHALLENGE_VERSION 1 using namespace std; struct challenge_header { uint32_t version; uint32_t num_entries; uint32_t reserved_1; uint32_t reserved_2; }; struct challenge_entry { uint32_t addr; uint32_t next_hop; }; void print_usage(string name){ cout << "Usage: " << name << endl; cout << "\t --algo <name>\t\t\t\t valid: Naive, BasicTrie, PCTrie (default: BasicTrie)" << endl; cout << "\t --dump-fib <rib>" << endl; cout << "\t --dump-challenge <fib> <challenge>" << endl; cout << "\t --run-challenge <fib> <challenge>" << endl; cout << "\t --convert-challenge <old> <new>" << endl; }; void dump_challenge(Table& table, string filename){ #define NUM_ENTRIES 10000000 ofstream challenge_file (filename, ios::out | ios::binary); struct challenge_header header; header.version = CHALLENGE_VERSION; header.num_entries = NUM_ENTRIES; header.reserved_1 = 0; header.reserved_2 = 0; challenge_file.write((char*) &header, sizeof(challenge_header)); BasicTrie lpm(table); for(int i=0; i<NUM_ENTRIES; i++){ challenge_entry entry; entry.addr = random(); entry.next_hop = lpm.route(entry.addr); challenge_file.write((char*) &entry, sizeof(challenge_entry)); } challenge_file.close(); }; template <typename LPM> void run_challenge(Table& table, string challenge_filename){ // read the challenge file int fd = open(challenge_filename.c_str(), 0); challenge_header header; int ret = read(fd, &header, sizeof(challenge_header)); if(ret != sizeof(challenge_header)){ cerr << "Error while reader challenge_header!" << endl; return; } if(header.version != CHALLENGE_VERSION){ cerr << "challenge version is not supported!" << endl; return; } char* mmap_base = (char*) mmap( NULL, header.num_entries * sizeof(challenge_entry) + sizeof(challenge_header), PROT_READ, MAP_PRIVATE, fd, 0); if(mmap_base == MAP_FAILED){ cerr << "mmap failed! errno: " << errno << endl; return; } challenge_entry* entries = (challenge_entry*) (mmap_base + sizeof(challenge_header)); int failed = 0; int success = 0; LPM lpm(table); clock_t start = clock(); for(unsigned int i=0; i<header.num_entries; i++){ uint32_t res = lpm.route(entries[i].addr); if(unlikely(res != entries[i].next_hop)){ cout << "Failed IP: " << ip_to_str(entries[i].addr) << endl; cout << "Expected : " << ip_to_str(entries[i].next_hop) << endl; cout << "Got : " << ip_to_str(res) << endl << endl; failed++; } else { success++; } } clock_t end = clock(); float seconds = (1.0*(end-start)) / CLOCKS_PER_SEC; cerr << "Lookups took " << seconds << " seconds" << endl; cerr << "Rate: " << ((success + failed) / seconds) / 1000000 << " Mlps" << endl; cout << "Successful lookups: " << success << endl; cout << "Failed lookups: " << failed << endl; }; void convert_challenge(string old_file, string new_file){ // read the challenge file list<pair<uint32_t, uint32_t>> challenge; ifstream dump(old_file); regex regex("^(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)$"); while(1) { bool finished = false; string line; if(dump.eof()){ finished = true; } else { getline(dump, line); } if(dump.eof()){ finished = true; } if(finished){ break; } smatch m; uint32_t addr, next_hop; struct in_addr in_addr; regex_match(line, m, regex); inet_aton(m[1].str().c_str(), &in_addr); addr = ntohl(in_addr.s_addr); inet_aton(m[2].str().c_str(), &in_addr); next_hop = ntohl(in_addr.s_addr); challenge.push_back({addr, next_hop}); } ofstream challenge_file (new_file, ios::out | ios::binary); struct challenge_header header; header.version = CHALLENGE_VERSION; header.num_entries = challenge.size(); header.reserved_1 = 0; header.reserved_2 = 0; challenge_file.write((char*) &header, sizeof(challenge_header)); for(auto& e : challenge){ challenge_entry entry; entry.addr = e.first; entry.next_hop = e.second; challenge_file.write((char*) &entry, sizeof(challenge_entry)); } challenge_file.close(); } int main(int argc, char** argv){ string challenge_filename = ""; enum {INVALID_MODE, DUMP_FIB, DUMP_CHALLENGE, RUN_CHALLENGE, CONVERT_CHALLENGE} mode = INVALID_MODE; enum {INVALID_ALGO, NAIVE, BASICTRIE, PCTRIE} algo = INVALID_ALGO; if(argc < 3){ print_usage(string(argv[0])); return 0; } int cmd_pos = 1; string filename; while(cmd_pos < argc){ if(strcmp(argv[cmd_pos], "--algo") == 0){ if(strcmp(argv[cmd_pos+1], "Naive") == 0) algo = NAIVE; else if (strcmp(argv[cmd_pos+1], "BasicTrie") == 0) algo = BASICTRIE; else if (strcmp(argv[cmd_pos+1], "PCTrie") == 0) algo = PCTRIE; cmd_pos += 2; } else if(strcmp(argv[cmd_pos], "--dump-fib") == 0){ mode = DUMP_FIB; filename = argv[cmd_pos+1]; cmd_pos += 2; } else if(strcmp(argv[cmd_pos], "--dump-challenge") == 0){ mode = DUMP_CHALLENGE; filename = argv[cmd_pos+1]; challenge_filename = string(argv[cmd_pos+2]); cmd_pos += 3; } else if(strcmp(argv[cmd_pos], "--run-challenge") == 0){ mode = RUN_CHALLENGE; filename = argv[cmd_pos+1]; challenge_filename = string(argv[cmd_pos+2]); cmd_pos += 3; } else if(strcmp(argv[cmd_pos], "--convert-challenge") == 0){ mode = CONVERT_CHALLENGE; filename = argv[cmd_pos+1]; challenge_filename = string(argv[cmd_pos+2]); cmd_pos += 3; } else { print_usage(string(argv[0])); return 0; } } Table table(filename); switch(mode){ case DUMP_FIB: table.aggregate(); table.print_table(); break; case DUMP_CHALLENGE: dump_challenge(table, challenge_filename); break; case RUN_CHALLENGE: switch(algo){ case NAIVE: run_challenge<Naive>(table, challenge_filename); break; case BASICTRIE: run_challenge<BasicTrie>(table, challenge_filename); break; case PCTRIE: run_challenge<PCTrie>(table, challenge_filename); break; default: run_challenge<BasicTrie>(table, challenge_filename); break; } break; case CONVERT_CHALLENGE: convert_challenge(filename, challenge_filename); break; default: print_usage(string(argv[0])); break; } return 0; } <commit_msg>populate challenge map + repeat challenge 10 times<commit_after>#include <iostream> #include <fstream> #include <list> #include <time.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <errno.h> #include "util.hpp" #include "table.hpp" #include "naive.hpp" //#include "dxr.hpp" #include "basicTrie.hpp" #include "pcTrie.hpp" #define CHALLENGE_VERSION 1 using namespace std; struct challenge_header { uint32_t version; uint32_t num_entries; uint32_t reserved_1; uint32_t reserved_2; }; struct challenge_entry { uint32_t addr; uint32_t next_hop; }; void print_usage(string name){ cout << "Usage: " << name << endl; cout << "\t --algo <name>\t\t\t\t valid: Naive, BasicTrie, PCTrie (default: BasicTrie)" << endl; cout << "\t --dump-fib <rib>" << endl; cout << "\t --dump-challenge <fib> <challenge>" << endl; cout << "\t --run-challenge <fib> <challenge>" << endl; cout << "\t --convert-challenge <old> <new>" << endl; }; void dump_challenge(Table& table, string filename){ #define NUM_ENTRIES 10000000 ofstream challenge_file (filename, ios::out | ios::binary); struct challenge_header header; header.version = CHALLENGE_VERSION; header.num_entries = NUM_ENTRIES; header.reserved_1 = 0; header.reserved_2 = 0; challenge_file.write((char*) &header, sizeof(challenge_header)); BasicTrie lpm(table); for(int i=0; i<NUM_ENTRIES; i++){ challenge_entry entry; entry.addr = random(); entry.next_hop = lpm.route(entry.addr); challenge_file.write((char*) &entry, sizeof(challenge_entry)); } challenge_file.close(); }; template <typename LPM> void run_challenge(Table& table, string challenge_filename){ // read the challenge file int fd = open(challenge_filename.c_str(), 0); challenge_header header; int ret = read(fd, &header, sizeof(challenge_header)); if(ret != sizeof(challenge_header)){ cerr << "Error while reader challenge_header!" << endl; return; } if(header.version != CHALLENGE_VERSION){ cerr << "challenge version is not supported!" << endl; return; } char* mmap_base = (char*) mmap( NULL, header.num_entries * sizeof(challenge_entry) + sizeof(challenge_header), PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0); if(mmap_base == MAP_FAILED){ cerr << "mmap failed! errno: " << errno << endl; return; } challenge_entry* entries = (challenge_entry*) (mmap_base + sizeof(challenge_header)); int failed = 0; int success = 0; LPM lpm(table); clock_t start = clock(); for(int reps=0; reps<10; reps++){ for(unsigned int i=0; i<header.num_entries; i++){ uint32_t res = lpm.route(entries[i].addr); if(unlikely(res != entries[i].next_hop)){ cout << "Failed IP: " << ip_to_str(entries[i].addr) << endl; cout << "Expected : " << ip_to_str(entries[i].next_hop) << endl; cout << "Got : " << ip_to_str(res) << endl << endl; failed++; } else { success++; } } } clock_t end = clock(); float seconds = (1.0*(end-start)) / CLOCKS_PER_SEC; cerr << "Lookups took " << seconds << " seconds" << endl; cerr << "Rate: " << ((success + failed) / seconds) / 1000000 << " Mlps" << endl; cout << "Successful lookups: " << success << endl; cout << "Failed lookups: " << failed << endl; }; void convert_challenge(string old_file, string new_file){ // read the challenge file list<pair<uint32_t, uint32_t>> challenge; ifstream dump(old_file); regex regex("^(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)$"); while(1) { bool finished = false; string line; if(dump.eof()){ finished = true; } else { getline(dump, line); } if(dump.eof()){ finished = true; } if(finished){ break; } smatch m; uint32_t addr, next_hop; struct in_addr in_addr; regex_match(line, m, regex); inet_aton(m[1].str().c_str(), &in_addr); addr = ntohl(in_addr.s_addr); inet_aton(m[2].str().c_str(), &in_addr); next_hop = ntohl(in_addr.s_addr); challenge.push_back({addr, next_hop}); } ofstream challenge_file (new_file, ios::out | ios::binary); struct challenge_header header; header.version = CHALLENGE_VERSION; header.num_entries = challenge.size(); header.reserved_1 = 0; header.reserved_2 = 0; challenge_file.write((char*) &header, sizeof(challenge_header)); for(auto& e : challenge){ challenge_entry entry; entry.addr = e.first; entry.next_hop = e.second; challenge_file.write((char*) &entry, sizeof(challenge_entry)); } challenge_file.close(); } int main(int argc, char** argv){ string challenge_filename = ""; enum {INVALID_MODE, DUMP_FIB, DUMP_CHALLENGE, RUN_CHALLENGE, CONVERT_CHALLENGE} mode = INVALID_MODE; enum {INVALID_ALGO, NAIVE, BASICTRIE, PCTRIE} algo = INVALID_ALGO; if(argc < 3){ print_usage(string(argv[0])); return 0; } int cmd_pos = 1; string filename; while(cmd_pos < argc){ if(strcmp(argv[cmd_pos], "--algo") == 0){ if(strcmp(argv[cmd_pos+1], "Naive") == 0) algo = NAIVE; else if (strcmp(argv[cmd_pos+1], "BasicTrie") == 0) algo = BASICTRIE; else if (strcmp(argv[cmd_pos+1], "PCTrie") == 0) algo = PCTRIE; cmd_pos += 2; } else if(strcmp(argv[cmd_pos], "--dump-fib") == 0){ mode = DUMP_FIB; filename = argv[cmd_pos+1]; cmd_pos += 2; } else if(strcmp(argv[cmd_pos], "--dump-challenge") == 0){ mode = DUMP_CHALLENGE; filename = argv[cmd_pos+1]; challenge_filename = string(argv[cmd_pos+2]); cmd_pos += 3; } else if(strcmp(argv[cmd_pos], "--run-challenge") == 0){ mode = RUN_CHALLENGE; filename = argv[cmd_pos+1]; challenge_filename = string(argv[cmd_pos+2]); cmd_pos += 3; } else if(strcmp(argv[cmd_pos], "--convert-challenge") == 0){ mode = CONVERT_CHALLENGE; filename = argv[cmd_pos+1]; challenge_filename = string(argv[cmd_pos+2]); cmd_pos += 3; } else { print_usage(string(argv[0])); return 0; } } Table table(filename); switch(mode){ case DUMP_FIB: table.aggregate(); table.print_table(); break; case DUMP_CHALLENGE: dump_challenge(table, challenge_filename); break; case RUN_CHALLENGE: switch(algo){ case NAIVE: run_challenge<Naive>(table, challenge_filename); break; case BASICTRIE: run_challenge<BasicTrie>(table, challenge_filename); break; case PCTRIE: run_challenge<PCTrie>(table, challenge_filename); break; default: run_challenge<BasicTrie>(table, challenge_filename); break; } break; case CONVERT_CHALLENGE: convert_challenge(filename, challenge_filename); break; default: print_usage(string(argv[0])); break; } return 0; } <|endoftext|>
<commit_before>#include <common.h> #include <Parser.h> #include <Tokenizer.h> #include <TextLoader.h> #include <PatternMatch.h> #include <Configuration.h> #include <ErrorProcessor.h> #include <PatternsFileProcessor.h> using namespace Lspl; using namespace Lspl::Text; using namespace Lspl::Parser; using namespace Lspl::Pattern; using namespace Lspl::Configuration; int main( int argc, const char* argv[] ) { try { if( argc != 4 ) { cerr << "Usage: lspl2 CONFIGURATION PATTERNS TEXT" << endl; return 1; } CConfigurationPtr conf = LoadConfigurationFromFile( argv[1], cerr, cout ); if( !static_cast<bool>( conf ) ) { return 1; } for( TAttribute a = 0; a < conf->Attributes().Size(); a++ ) { if( conf->Attributes()[a].Consistent ) { CAnnotation::SetArgreementBegin( a ); break; } } CErrorProcessor errorProcessor; CPatternsBuilder patternsBuilder( conf, errorProcessor ); patternsBuilder.Read( argv[2] ); patternsBuilder.Check(); if( errorProcessor.HasAnyErrors() ) { errorProcessor.PrintErrors( cerr, argv[2] ); return 1; } const CPatterns patterns = patternsBuilder.Save(); patterns.Print( cout ); argv[3] = "_text1.json"; CWords words; LoadText( patterns, argv[3], words ); CText text( move( words ) ); for( TReference ref = 0; ref < patterns.Size(); ref++ ) { const CPattern& pattern = patterns.Pattern( ref ); cout << pattern.Name() << endl; CStates states; { CPatternBuildContext buildContext( patterns ); CPatternVariants variants; pattern.Build( buildContext, variants, 12 ); variants.Print( patterns, cout ); states = move( variants.Build( patterns ) ); } { CMatchContext matchContext( text, states ); for( TWordIndex wi = 0; wi < text.Length(); wi++ ) { matchContext.Match( wi ); } } cout << endl; } } catch( exception& e ) { cerr << e.what() << endl; return 1; } catch( ... ) { cerr << "unknown error!"; return 1; } return 0; } <commit_msg>remove debug code<commit_after>#include <common.h> #include <Parser.h> #include <Tokenizer.h> #include <TextLoader.h> #include <PatternMatch.h> #include <Configuration.h> #include <ErrorProcessor.h> #include <PatternsFileProcessor.h> using namespace Lspl; using namespace Lspl::Text; using namespace Lspl::Parser; using namespace Lspl::Pattern; using namespace Lspl::Configuration; int main( int argc, const char* argv[] ) { try { if( argc != 4 ) { cerr << "Usage: lspl2 CONFIGURATION PATTERNS TEXT" << endl; return 1; } CConfigurationPtr conf = LoadConfigurationFromFile( argv[1], cerr, cout ); if( !static_cast<bool>( conf ) ) { return 1; } for( TAttribute a = 0; a < conf->Attributes().Size(); a++ ) { if( conf->Attributes()[a].Consistent ) { CAnnotation::SetArgreementBegin( a ); break; } } CErrorProcessor errorProcessor; CPatternsBuilder patternsBuilder( conf, errorProcessor ); patternsBuilder.Read( argv[2] ); patternsBuilder.Check(); if( errorProcessor.HasAnyErrors() ) { errorProcessor.PrintErrors( cerr, argv[2] ); return 1; } const CPatterns patterns = patternsBuilder.Save(); patterns.Print( cout ); CWords words; LoadText( patterns, argv[3], words ); CText text( move( words ) ); for( TReference ref = 0; ref < patterns.Size(); ref++ ) { const CPattern& pattern = patterns.Pattern( ref ); cout << pattern.Name() << endl; CStates states; { CPatternBuildContext buildContext( patterns ); CPatternVariants variants; pattern.Build( buildContext, variants, 12 ); variants.Print( patterns, cout ); states = move( variants.Build( patterns ) ); } { CMatchContext matchContext( text, states ); for( TWordIndex wi = 0; wi < text.Length(); wi++ ) { matchContext.Match( wi ); } } cout << endl; } } catch( exception& e ) { cerr << e.what() << endl; return 1; } catch( ... ) { cerr << "unknown error!"; return 1; } return 0; } <|endoftext|>
<commit_before>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> //#include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> */ #ifndef EFU_CURLEASY_H #include "curleasy.h" #endif #if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H) #include "win_error_string.hpp" #endif const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { #ifdef _WIN32 unsigned file_start = path.find_last_of("/\\"); if (file_start == std::string::npos) { return; } if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr)) { WinErrorString wes; if (wes.code() != ERROR_ALREADY_EXISTS) { throw std::ios_base::failure("sdf" + wes.str()); } } #else auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } #endif } // TODO #ifdef CPP11_ENUM_CLASS #define ENUM_CLASS enum class #else #define ENUM_CLASS enum #endif class Target { public: ENUM_CLASS Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() const { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() const { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() const { std::ofstream ofs(name(), std::ios::binary); if (ofs.good()) { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.progressbar(true); curl.perform(); ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ios::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8 * 1024; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), static_cast<size_t>(is.gcount())); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); #ifdef CPP11_FOR_EACH for (const unsigned char c : result) #else std::for_each(std::begin(result), std::end(result), [&calcsum](const unsigned char c) #endif { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } #ifndef CPP11_FOR_EACH ); #endif return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = static_cast<char>(tolower(c)); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: // TODO: assignment, copy operator explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); //TODO try { curl.perform(); } catch (CurlEasyException &e) { std::cout << e.what() << std::endl; } std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); // TODO #ifdef CPP11_ENUM_CLASS if (status == Target::Status::Nonexistent) #else if (status == Target::Nonexistent) #endif { new_targets.push_back(std::move(t)); } // TODO #ifdef CPP11_ENUM_CLASS else if (status == Target::Status::Outdated) #else else if (status == Target::Outdated) #endif { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : new_targets) #else std::for_each(new_targets.cbegin(), new_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : old_targets) #else std::for_each(old_targets.cbegin(), old_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG #ifdef CPP11_FOR_EACH for (auto &t : new_targets) #else std::for_each(new_targets.cbegin(), new_targets.cend(), [](const Target &t) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); std::for_each(old_targets.cbegin(), old_targets.cend(), [](const Target &t) #else for (auto &t : old_targets) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); #endif #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } try { l.stat_targets(); } catch (std::exception &e) { std::cerr << e.what() << std::endl; } return 0; } <commit_msg>Give better error when failing to create directory.<commit_after>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> //#include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> */ #ifndef EFU_CURLEASY_H #include "curleasy.h" #endif #if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H) #include "win_error_string.hpp" #endif const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { #ifdef _WIN32 unsigned file_start = path.find_last_of("/\\"); if (file_start == std::string::npos) { return; } if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr)) { WinErrorString wes; if (wes.code() != ERROR_ALREADY_EXISTS) { throw std::ios_base::failure("Failed creating " + path + ": " + wes.str()); } } #else auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } #endif } // TODO #ifdef CPP11_ENUM_CLASS #define ENUM_CLASS enum class #else #define ENUM_CLASS enum #endif class Target { public: ENUM_CLASS Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() const { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() const { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() const { std::ofstream ofs(name(), std::ios::binary); if (ofs.good()) { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.progressbar(true); curl.perform(); ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ios::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8 * 1024; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), static_cast<size_t>(is.gcount())); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); #ifdef CPP11_FOR_EACH for (const unsigned char c : result) #else std::for_each(std::begin(result), std::end(result), [&calcsum](const unsigned char c) #endif { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } #ifndef CPP11_FOR_EACH ); #endif return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = static_cast<char>(tolower(c)); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: // TODO: assignment, copy operator explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); //TODO try { curl.perform(); } catch (CurlEasyException &e) { std::cout << e.what() << std::endl; } std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); // TODO #ifdef CPP11_ENUM_CLASS if (status == Target::Status::Nonexistent) #else if (status == Target::Nonexistent) #endif { new_targets.push_back(std::move(t)); } // TODO #ifdef CPP11_ENUM_CLASS else if (status == Target::Status::Outdated) #else else if (status == Target::Outdated) #endif { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : new_targets) #else std::for_each(new_targets.cbegin(), new_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; #ifdef CPP11_FOR_EACH for (auto &t : old_targets) #else std::for_each(old_targets.cbegin(), old_targets.cend(), [](const Target &t) #endif { std::cout << "- " << t.name() << std::endl; } #ifndef CPP11_FOR_EACH ); #endif } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG #ifdef CPP11_FOR_EACH for (auto &t : new_targets) #else std::for_each(new_targets.cbegin(), new_targets.cend(), [](const Target &t) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); std::for_each(old_targets.cbegin(), old_targets.cend(), [](const Target &t) #else for (auto &t : old_targets) #endif { t.fetch(); } #ifndef CPP11_FOR_EACH ); #endif #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } try { l.stat_targets(); } catch (std::exception &e) { std::cerr << e.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "serial.h" #include "bled112client.h" #include "gattclient.h" #include "bleapi.h" #include "myohw.h" #include <unistd.h> #include <netinet/in.h> #include <cinttypes> #include <iostream> #include <iomanip> #include <type_traits> void print_address(uint8_t *address) { std::ios state(NULL); state.copyfmt(std::cout); for (int i = 0; i < 6; i++) { std::cout << std::hex << std::setw(2) << (int)address[i]; if (i != 5) { std::cout << ":"; } } std::cout << std::endl; std::cout.copyfmt(state); } int main() { Serial serial("/dev/ttyACM0", 115200); Bled112Client dev(serial); GattClient cl(dev); // Connect to device cl.connect(GattClient::Address{{0x73, 0x83, 0x1b, 0x61, 0xb3, 0xe2}}); // Read firmware version auto version = unpack<myohw_fw_version_t>(cl.readAttribute(0x17)); std::cout << version.major << "." << version.minor << "." << version.patch << "." << version.hardware_rev << std::endl; // Vibrate cl.writeAttribute(0x19, Buffer{0x03, 0x01, 0x02}); // Read name auto name = cl.readAttribute(0x3); for (auto x : name) { std::cout << x; } std::cout << std::endl; // Read EMG, doesn't work // cl.writeAttribute(0x19, Buffer{0x1, 0x3, 0x2, 0x0, 0x0}); // cl.writeAttribute(0x2b, Buffer{0x1, 0x0}); // cl.writeAttribute(0x2e, Buffer{0x1, 0x0}); // cl.writeAttribute(0x31, Buffer{0x1, 0x0}); // cl.writeAttribute(0x34, Buffer{0x1, 0x0}); // Read EMG data (Legacy mode) cl.writeAttribute(0x19, Buffer{0x1, 0x3, 0x1, 0x0, 0x0}); cl.writeAttribute(0x28, Buffer{0x1, 0x0}); struct PACKED Packet { std::uint16_t sample[8]; std::uint8_t moving; }; auto cb = [&](const std::uint16_t, const Buffer &data) { auto values = unpack<Packet>(data); for (int i = 0; i < 8; i++) { std::cout << static_cast<int>(values.sample[i]); if (i != 7) { std::cout << ", "; } } std::cout << std::endl; }; while (true) { cl.readAttribute(cb); } } <commit_msg>Read EMG using the new interface at a glorious rate of 200 Hz<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "serial.h" #include "bled112client.h" #include "gattclient.h" #include "bleapi.h" #include "myohw.h" #include <unistd.h> #include <netinet/in.h> #include <cinttypes> #include <iostream> #include <iomanip> #include <type_traits> void print_address(uint8_t *address) { std::ios state(NULL); state.copyfmt(std::cout); for (int i = 0; i < 6; i++) { std::cout << std::hex << std::setw(2) << (int)address[i]; if (i != 5) { std::cout << ":"; } } std::cout << std::endl; std::cout.copyfmt(state); } int main() { Serial serial("/dev/ttyACM0", 115200); Bled112Client dev(serial); GattClient cl(dev); // Connect to device cl.connect(GattClient::Address{{0x73, 0x83, 0x1b, 0x61, 0xb3, 0xe2}}); // Read firmware version auto version = unpack<myohw_fw_version_t>(cl.readAttribute(0x17)); std::cout << version.major << "." << version.minor << "." << version.patch << "." << version.hardware_rev << std::endl; // Vibrate cl.writeAttribute(0x19, Buffer{0x03, 0x01, 0x02}); // Read name auto name = cl.readAttribute(0x3); for (auto x : name) { std::cout << x; } std::cout << std::endl; // Read EMG cl.writeAttribute(0x19, Buffer{0x1, 0x3, 0x2, 0x0, 0x0}); cl.writeAttribute(0x2c, Buffer{0x1, 0x0}); cl.writeAttribute(0x2f, Buffer{0x1, 0x0}); cl.writeAttribute(0x32, Buffer{0x1, 0x0}); cl.writeAttribute(0x35, Buffer{0x1, 0x0}); // Read EMG data (Legacy mode) //cl.writeAttribute(0x19, Buffer{0x1, 0x3, 0x1, 0x0, 0x0}); //cl.writeAttribute(0x28, Buffer{0x1, 0x0}); auto cb = [&](const std::uint16_t, const Buffer &data) { auto values = unpack<myohw_emg_data_t>(data); for (int i = 0; i < 8; i++) { std::cout << static_cast<int>(values.sample1[i]); if (i != 7) { std::cout << ", "; } } for (int i = 0; i < 8; i++) { std::cout << static_cast<int>(values.sample2[i]); if (i != 7) { std::cout << ", "; } } std::cout << std::endl; }; while (true) { cl.readAttribute(cb); } } <|endoftext|>
<commit_before>// // TMGas.cpp // jdemon // // Created by Mark Larus on 3/22/13. // Copyright (c) 2013 Kenyon College. All rights reserved. // #include "TMGas.h" #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <boost/iterator/filter_iterator.hpp> #include <boost/functional.hpp> #include <map> #include <numeric> #include <bitset> #include <functional> #include "Utilities.h" using namespace TMGas; #pragma mark -- Grid Initialization -- Grid::Grid(int dim) : CATools::Grid<Cell>(dim),oddBlocks(_oddBlocks), evenBlocks(_evenBlocks) { _oddBlocks.reserve(size()); _evenBlocks.reserve(size()); std::insert_iterator<BlockList> oddOutputIterator = std::inserter(_oddBlocks,_oddBlocks.begin()); std::insert_iterator<BlockList> evenOutputIterator = std::inserter(_evenBlocks,_evenBlocks.begin()); std::multimap<Cell *, Block *> cellsToBlocks; for (int column = 0; column < getDimension(); ++column) { for (int row = 0; row < getDimension(); ++row ) { if (row % 2 == column % 2) { if (row % 2) { const CATools::Coordinate currentCellCoord(column,row,getDimension()); *oddOutputIterator = Block(cellsFromCoordinates<CATools::Coordinate::CNeighbors, 4>(currentCellCoord.twoByTwoFromTopLeftCoordinate())); } else { CATools::Coordinate currentCoord(column,row,getDimension()); *evenOutputIterator = Block(cellsFromCoordinates<CATools::Coordinate::CNeighbors, 4>(currentCoord.twoByTwoFromTopLeftCoordinate())); } } } } } #pragma mark -- Block Operations -- Block::Block(const boost::array<Cell *, 4>& array) { std::copy(array.begin(), array.end(), begin()); } bool Block::isAbove(const TMGas::Block &above) const { return !isBelow(above); } bool Block::isBelow(const TMGas::Block &below) const { return this->topLeft() == below.bottomRight() || this->topLeft() == below.bottomLeft() || this->topRight() == below.bottomLeft() || this->topRight() == below.bottomRight(); } bool Block::isLeft(const TMGas::Block &other) const { // This is a stub so that tests will fail. return this->bottomRight() == other.topLeft() || this->bottomRight() == other.bottomLeft() || this->topRight() == other.bottomLeft() || this->topRight() == other.bottomRight(); } bool Block::isRight(const TMGas::Block &other) const { return !isLeft(other); } const BlockState Block::currentState() const { return BlockState(*this); } #pragma mark -- BlockState Operations -- BlockState::BlockState(const boost::array<Cell *,4> &cells) { std::transform(cells.begin(), cells.end(), begin(), Cell::ValueTransformer()); } void BlockState::setValuesClockwise(bool topLeft, bool topRight, bool bottomLeft, bool bottomRight) { at(0) = topLeft; at(1) = bottomLeft; at(2) = topRight; at(3) = bottomRight; } BlockState::BlockState(const StateIdentifier &state) { for (int k = 0; k!=size(); ++k) { size_t offset = size() - k - 1; at(k) = (state >> offset) & 1; } } BlockState::BlockState(bool topLeft,bool topRight,bool bottomLeft,bool bottomRight) { setValuesClockwise(topLeft, topRight, bottomLeft, bottomRight); } void BlockState::update(const TMGas::Block &block) const { for (int k = 0; k!=size(); ++k) { block[k]->setValue(at(k)); } } class AppendBit { public: char operator()(const char &init, const bool& next) const { return (init<<1) + (next ? 1 : 0); } }; StateIdentifier BlockState::getStateIdentifier() const { StateIdentifier id = std::accumulate(begin(), end(), 0, AppendBit()); return id; } BlockState BlockState::operator!() const { BlockState invertedState; std::transform(begin(), end(), invertedState.begin(), std::logical_not<bool>()); return invertedState; } bool BlockState::isDiagonal() const { TMGas::BlockState primaryDiagonal(true,false, false,true); TMGas::BlockState secondaryDiagonal(false,true, true,false); return *this==primaryDiagonal || *this == secondaryDiagonal; } #pragma mark -- Evolution Rule -- const BlockState EvolutionRule::operator[](const BlockState &block) const { return table.at(block); } void EvolutionRule::operator()(const Block &block) const { BlockState newState = table.at(block.currentState()); newState.update(block); } DefaultEvolutionRule::DefaultEvolutionRule() { BlockState start; BlockState end; start.setValuesClockwise(true, false, false, false); end.setValuesClockwise(false, true, false, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false,true, false,false); end.setValuesClockwise(false, false, false, true); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false, false, false, true); end.setValuesClockwise(false, false, true, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false,false, true,false); end.setValuesClockwise(true, false, false, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false, false, false, false); end = start; table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false, true, true, false); end = start; table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(true, false, true, false); end.setValuesClockwise(true, true, false, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(true, true, false, false); end.setValuesClockwise(false, true, false, true); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); } #pragma mark -- Reservoir -- Reservoir::Reservoir(DemonBase::Constants c, int dimension,Randomness::GSLDelegate &delegate) : DemonBase::Reservoir(c), cells(dimension), randomness(delegate), interactionCell(cells[dimension/2]) { initializeGridWithOccupationProbability(cells, c.getEpsilon()/2, delegate); using namespace boost; typedef std::binder1st< std::not_equal_to<Cell *> > CellFilter; CellFilter filter = std::bind1st(std::not_equal_to<Cell *>(),&interactionCell); BOOST_AUTO(begin, make_filter_iterator(filter, cells.begin())); BOOST_AUTO(end, make_filter_iterator(filter, cells.end())); cellsExcludingInteractionCell.insert(cellsExcludingInteractionCell.begin(), begin, end); } void Reservoir::reset() { initializeGridWithOccupationProbability(cells, constants.getEpsilon()/2, randomness); currentState = DemonBase::randomState(); } Reservoir::InteractionResult Reservoir::interactWithBit(int bit) { const int stepCount = 2; InteractionResult result; currentState = currentState->stateForBit(bit); for (int k = 0; k != stepCount; ++k) { gridStep(); wheelStep(result); } return result; } void Reservoir::wheelStep(Reservoir::InteractionResult &result) { std::pair<bool, bool> bits = hashBits(); InteractionStateMachine::InputType input(currentState,interactionCell.getValue(),bits.first,bits.second); InteractionStateMachine::OutputType output = machine(input); currentState = output.get<0>(); result.work -= interactionCell.getValue() - output.get<1>(); interactionCell.setValue(output.get<1>()); result.bit = currentState->bit; } class EvolutionRuleRef { // For some reason, uses for_each directly on the rule causes the member to be optimized out. // instead, a new rule is instantiated at every call to grid step // --expensive! Adding an extra level of indirection satisfies the compiler's need to delete deallocate something at the end of that function and ensures that only one rule gets created. EvolutionRule &rule; public: EvolutionRuleRef(EvolutionRule &_rule) : rule(_rule) { } void operator()(const Block &block) const { rule(block); } }; void Reservoir::gridStep() { EvolutionRuleRef evolver(rule); std::for_each(cells.evenBlocks.begin(), cells.evenBlocks.end(), evolver); std::for_each(cells.oddBlocks.begin(), cells.oddBlocks.end(), evolver); } std::pair<bool, bool> Reservoir::hashBits() { using namespace boost; Cell::ValueTransformer transformer; BOOST_AUTO(begin, make_transform_iterator(cellsExcludingInteractionCell.begin(), transformer)); BOOST_AUTO(end, make_transform_iterator(cellsExcludingInteractionCell.end(), transformer)); std::size_t hash = hash_range(begin, end); bool first = hash & 1; bool second = (hash >> 1) & 1; return std::make_pair(first,second); } std::size_t TMGas::hash_value(const TMGas::BlockState& input) { boost::hash<TMGas::StateIdentifier> hasher; return hasher(input.getStateIdentifier()); } std::size_t TMGas::hash_value(InteractionStateMachine::InputType const& input) { std::size_t hash = 0; boost::hash_combine(hash, input.get<0>()); boost::hash_combine(hash, input.get<1>()); boost::hash_combine(hash, input.get<2>()); boost::hash_combine(hash, input.get<3>()); return hash; } std::size_t TMGas::hash_value(InteractionStateMachine::OutputType const& input) { std::size_t hash = 0; boost::hash_combine(hash, input.get<0>()); boost::hash_combine(hash, input.get<1>()); return hash; } bool TMGas::InteractionStateMachine::InputType::operator==(const TMGas::InteractionStateMachine::InputType &other) const { return (get<0>() == other.get<0>()) && (get<1>() == other.get<1>()) && (get<2>() == other.get<2>()) && (get<3>() == other.get<3>()); } bool TMGas::InteractionStateMachine::OutputType::operator==(const TMGas::InteractionStateMachine::OutputType &other) const { return (get<0>() == other.get<0>()) && (get<1>() == other.get<1>()); } TMGas::InteractionStateMachine::InputType::InputType(DemonBase::SystemState *wheel, bool boltzmann, bool hash1, bool hash2) : boost::tuple<DemonBase::SystemState *, bool, bool, bool>(boost::make_tuple(wheel,boltzmann,hash1,hash2)) { } TMGas::InteractionStateMachine::OutputType::OutputType(DemonBase::SystemState *wheel, bool boltzmann) : boost::tuple<DemonBase::SystemState *, bool>(boost::make_tuple(wheel,boltzmann)) { } boost::unordered_set<InteractionStateMachine::InputType> InteractionStateMachine::possibleInputs() const { using namespace DemonBase; boost::unordered_set<InputType> inputs; #define HighAndLowInputs(XX,hash1,hash2) \ inputs.insert(InputType(&State##XX,hash1,hash2,0));\ inputs.insert(InputType(&State##XX,hash1,hash2,1)); #define AllStatesFor(XX) \ HighAndLowInputs(XX,0,0);\ HighAndLowInputs(XX,0,1);\ HighAndLowInputs(XX,1,0);\ HighAndLowInputs(XX,1,1); AllStatesFor(A1); AllStatesFor(B1); AllStatesFor(C1); AllStatesFor(A0); AllStatesFor(B0); AllStatesFor(C0); return inputs; } DefaultInteractionMachine::DefaultInteractionMachine() { using namespace DemonBase; using namespace boost; #define CommuteRule(XX,a,b,c,YY) \ table[InputType(&State##XX,a,b,c)]=OutputType(&State##YY,a);\ table[InputType(&State##YY,a,b,c)]=OutputType(&State##XX,a); #define HighAndLowRule(XX,hash1,hash2,YY) \ CommuteRule(XX,1,hash1,hash2,YY) \ CommuteRule(XX,0,hash1,hash2,YY) #define FixedPoints(XX) \ HighAndLowRule(XX,0,0,XX) \ HighAndLowRule(XX,0,1,XX) \ HighAndLowRule(XX,1,0,XX) \ HighAndLowRule(XX,1,1,XX) FixedPoints(A1); FixedPoints(B1); FixedPoints(C1); FixedPoints(A0); FixedPoints(B0); FixedPoints(C0); // High States: //C1 <-> B1 HighAndLowRule(C1,0, 1,B1); //B1 <-> A1 HighAndLowRule(B1, 0, 0, A1); // A1 -> C0 table[InputType(&StateA1,0,1,0)] = OutputType(&StateC0,1); table[InputType(&StateA1,0,1,1)] = OutputType(&StateC0,1); // Low states: // C0 -> A1 table[InputType(&StateC0,1,1,1)] = OutputType(&StateA1,0); table[InputType(&StateC0,1,1,0)] = OutputType(&StateA1,0); // A0 <-> B0 HighAndLowRule(C0, 0, 0, B0); // B0 <-> C0 HighAndLowRule(B0, 0, 1, A0); #undef CommuteRule #undef HighAndLowRule #undef FixedPoints } <commit_msg>Calculate the work once, at the end of the interaction with the bit.<commit_after>// // TMGas.cpp // jdemon // // Created by Mark Larus on 3/22/13. // Copyright (c) 2013 Kenyon College. All rights reserved. // #include "TMGas.h" #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <boost/iterator/filter_iterator.hpp> #include <boost/functional.hpp> #include <map> #include <numeric> #include <bitset> #include <functional> #include "Utilities.h" using namespace TMGas; #pragma mark -- Grid Initialization -- Grid::Grid(int dim) : CATools::Grid<Cell>(dim),oddBlocks(_oddBlocks), evenBlocks(_evenBlocks) { _oddBlocks.reserve(size()); _evenBlocks.reserve(size()); std::insert_iterator<BlockList> oddOutputIterator = std::inserter(_oddBlocks,_oddBlocks.begin()); std::insert_iterator<BlockList> evenOutputIterator = std::inserter(_evenBlocks,_evenBlocks.begin()); std::multimap<Cell *, Block *> cellsToBlocks; for (int column = 0; column < getDimension(); ++column) { for (int row = 0; row < getDimension(); ++row ) { if (row % 2 == column % 2) { if (row % 2) { const CATools::Coordinate currentCellCoord(column,row,getDimension()); *oddOutputIterator = Block(cellsFromCoordinates<CATools::Coordinate::CNeighbors, 4>(currentCellCoord.twoByTwoFromTopLeftCoordinate())); } else { CATools::Coordinate currentCoord(column,row,getDimension()); *evenOutputIterator = Block(cellsFromCoordinates<CATools::Coordinate::CNeighbors, 4>(currentCoord.twoByTwoFromTopLeftCoordinate())); } } } } } #pragma mark -- Block Operations -- Block::Block(const boost::array<Cell *, 4>& array) { std::copy(array.begin(), array.end(), begin()); } bool Block::isAbove(const TMGas::Block &above) const { return !isBelow(above); } bool Block::isBelow(const TMGas::Block &below) const { return this->topLeft() == below.bottomRight() || this->topLeft() == below.bottomLeft() || this->topRight() == below.bottomLeft() || this->topRight() == below.bottomRight(); } bool Block::isLeft(const TMGas::Block &other) const { // This is a stub so that tests will fail. return this->bottomRight() == other.topLeft() || this->bottomRight() == other.bottomLeft() || this->topRight() == other.bottomLeft() || this->topRight() == other.bottomRight(); } bool Block::isRight(const TMGas::Block &other) const { return !isLeft(other); } const BlockState Block::currentState() const { return BlockState(*this); } #pragma mark -- BlockState Operations -- BlockState::BlockState(const boost::array<Cell *,4> &cells) { std::transform(cells.begin(), cells.end(), begin(), Cell::ValueTransformer()); } void BlockState::setValuesClockwise(bool topLeft, bool topRight, bool bottomLeft, bool bottomRight) { at(0) = topLeft; at(1) = bottomLeft; at(2) = topRight; at(3) = bottomRight; } BlockState::BlockState(const StateIdentifier &state) { for (int k = 0; k!=size(); ++k) { size_t offset = size() - k - 1; at(k) = (state >> offset) & 1; } } BlockState::BlockState(bool topLeft,bool topRight,bool bottomLeft,bool bottomRight) { setValuesClockwise(topLeft, topRight, bottomLeft, bottomRight); } void BlockState::update(const TMGas::Block &block) const { for (int k = 0; k!=size(); ++k) { block[k]->setValue(at(k)); } } class AppendBit { public: char operator()(const char &init, const bool& next) const { return (init<<1) + (next ? 1 : 0); } }; StateIdentifier BlockState::getStateIdentifier() const { StateIdentifier id = std::accumulate(begin(), end(), 0, AppendBit()); return id; } BlockState BlockState::operator!() const { BlockState invertedState; std::transform(begin(), end(), invertedState.begin(), std::logical_not<bool>()); return invertedState; } bool BlockState::isDiagonal() const { TMGas::BlockState primaryDiagonal(true,false, false,true); TMGas::BlockState secondaryDiagonal(false,true, true,false); return *this==primaryDiagonal || *this == secondaryDiagonal; } #pragma mark -- Evolution Rule -- const BlockState EvolutionRule::operator[](const BlockState &block) const { return table.at(block); } void EvolutionRule::operator()(const Block &block) const { BlockState newState = table.at(block.currentState()); newState.update(block); } DefaultEvolutionRule::DefaultEvolutionRule() { BlockState start; BlockState end; start.setValuesClockwise(true, false, false, false); end.setValuesClockwise(false, true, false, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false,true, false,false); end.setValuesClockwise(false, false, false, true); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false, false, false, true); end.setValuesClockwise(false, false, true, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false,false, true,false); end.setValuesClockwise(true, false, false, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false, false, false, false); end = start; table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(false, true, true, false); end = start; table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(true, false, true, false); end.setValuesClockwise(true, true, false, false); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); start.setValuesClockwise(true, true, false, false); end.setValuesClockwise(false, true, false, true); table[start.getStateIdentifier()]=end.getStateIdentifier(); table[(!start).getStateIdentifier()]=(!end).getStateIdentifier(); } #pragma mark -- Reservoir -- Reservoir::Reservoir(DemonBase::Constants c, int dimension,Randomness::GSLDelegate &delegate) : DemonBase::Reservoir(c), cells(dimension), randomness(delegate), interactionCell(cells[dimension/2]) { initializeGridWithOccupationProbability(cells, c.getEpsilon()/2, delegate); using namespace boost; typedef std::binder1st< std::not_equal_to<Cell *> > CellFilter; CellFilter filter = std::bind1st(std::not_equal_to<Cell *>(),&interactionCell); BOOST_AUTO(begin, make_filter_iterator(filter, cells.begin())); BOOST_AUTO(end, make_filter_iterator(filter, cells.end())); cellsExcludingInteractionCell.insert(cellsExcludingInteractionCell.begin(), begin, end); } void Reservoir::reset() { initializeGridWithOccupationProbability(cells, constants.getEpsilon()/2, randomness); currentState = DemonBase::randomState(); } Reservoir::InteractionResult Reservoir::interactWithBit(int bit) { const int stepCount = 2; InteractionResult result; currentState = currentState->stateForBit(bit); for (int k = 0; k != stepCount; ++k) { gridStep(); wheelStep(result); } result.bit = currentState->bit; result.work = currentState->bit - bit; return result; } void Reservoir::wheelStep(Reservoir::InteractionResult &result) { std::pair<bool, bool> bits = hashBits(); InteractionStateMachine::InputType input(currentState,interactionCell.getValue(),bits.first,bits.second); InteractionStateMachine::OutputType output = machine(input); currentState = output.get<0>(); interactionCell.setValue(output.get<1>()); } class EvolutionRuleRef { // For some reason, uses for_each directly on the rule causes the member to be optimized out. // instead, a new rule is instantiated at every call to grid step // --expensive! Adding an extra level of indirection satisfies the compiler's need to delete deallocate something at the end of that function and ensures that only one rule gets created. EvolutionRule &rule; public: EvolutionRuleRef(EvolutionRule &_rule) : rule(_rule) { } void operator()(const Block &block) const { rule(block); } }; void Reservoir::gridStep() { EvolutionRuleRef evolver(rule); std::for_each(cells.evenBlocks.begin(), cells.evenBlocks.end(), evolver); std::for_each(cells.oddBlocks.begin(), cells.oddBlocks.end(), evolver); } std::pair<bool, bool> Reservoir::hashBits() { using namespace boost; Cell::ValueTransformer transformer; BOOST_AUTO(begin, make_transform_iterator(cellsExcludingInteractionCell.begin(), transformer)); BOOST_AUTO(end, make_transform_iterator(cellsExcludingInteractionCell.end(), transformer)); std::size_t hash = hash_range(begin, end); bool first = hash & 1; bool second = (hash >> 1) & 1; return std::make_pair(first,second); } std::size_t TMGas::hash_value(const TMGas::BlockState& input) { boost::hash<TMGas::StateIdentifier> hasher; return hasher(input.getStateIdentifier()); } std::size_t TMGas::hash_value(InteractionStateMachine::InputType const& input) { std::size_t hash = 0; boost::hash_combine(hash, input.get<0>()); boost::hash_combine(hash, input.get<1>()); boost::hash_combine(hash, input.get<2>()); boost::hash_combine(hash, input.get<3>()); return hash; } std::size_t TMGas::hash_value(InteractionStateMachine::OutputType const& input) { std::size_t hash = 0; boost::hash_combine(hash, input.get<0>()); boost::hash_combine(hash, input.get<1>()); return hash; } bool TMGas::InteractionStateMachine::InputType::operator==(const TMGas::InteractionStateMachine::InputType &other) const { return (get<0>() == other.get<0>()) && (get<1>() == other.get<1>()) && (get<2>() == other.get<2>()) && (get<3>() == other.get<3>()); } bool TMGas::InteractionStateMachine::OutputType::operator==(const TMGas::InteractionStateMachine::OutputType &other) const { return (get<0>() == other.get<0>()) && (get<1>() == other.get<1>()); } TMGas::InteractionStateMachine::InputType::InputType(DemonBase::SystemState *wheel, bool boltzmann, bool hash1, bool hash2) : boost::tuple<DemonBase::SystemState *, bool, bool, bool>(boost::make_tuple(wheel,boltzmann,hash1,hash2)) { } TMGas::InteractionStateMachine::OutputType::OutputType(DemonBase::SystemState *wheel, bool boltzmann) : boost::tuple<DemonBase::SystemState *, bool>(boost::make_tuple(wheel,boltzmann)) { } boost::unordered_set<InteractionStateMachine::InputType> InteractionStateMachine::possibleInputs() const { using namespace DemonBase; boost::unordered_set<InputType> inputs; #define HighAndLowInputs(XX,hash1,hash2) \ inputs.insert(InputType(&State##XX,hash1,hash2,0));\ inputs.insert(InputType(&State##XX,hash1,hash2,1)); #define AllStatesFor(XX) \ HighAndLowInputs(XX,0,0);\ HighAndLowInputs(XX,0,1);\ HighAndLowInputs(XX,1,0);\ HighAndLowInputs(XX,1,1); AllStatesFor(A1); AllStatesFor(B1); AllStatesFor(C1); AllStatesFor(A0); AllStatesFor(B0); AllStatesFor(C0); return inputs; } DefaultInteractionMachine::DefaultInteractionMachine() { using namespace DemonBase; using namespace boost; #define CommuteRule(XX,a,b,c,YY) \ table[InputType(&State##XX,a,b,c)]=OutputType(&State##YY,a);\ table[InputType(&State##YY,a,b,c)]=OutputType(&State##XX,a); #define HighAndLowRule(XX,hash1,hash2,YY) \ CommuteRule(XX,1,hash1,hash2,YY) \ CommuteRule(XX,0,hash1,hash2,YY) #define FixedPoints(XX) \ HighAndLowRule(XX,0,0,XX) \ HighAndLowRule(XX,0,1,XX) \ HighAndLowRule(XX,1,0,XX) \ HighAndLowRule(XX,1,1,XX) FixedPoints(A1); FixedPoints(B1); FixedPoints(C1); FixedPoints(A0); FixedPoints(B0); FixedPoints(C0); // High States: //C1 <-> B1 HighAndLowRule(C1,0, 1,B1); //B1 <-> A1 HighAndLowRule(B1, 0, 0, A1); // A1 -> C0 table[InputType(&StateA1,0,1,0)] = OutputType(&StateC0,1); table[InputType(&StateA1,0,1,1)] = OutputType(&StateC0,1); // Low states: // C0 -> A1 table[InputType(&StateC0,1,1,1)] = OutputType(&StateA1,0); table[InputType(&StateC0,1,1,0)] = OutputType(&StateA1,0); // A0 <-> B0 HighAndLowRule(C0, 0, 0, B0); // B0 <-> C0 HighAndLowRule(B0, 0, 1, A0); #undef CommuteRule #undef HighAndLowRule #undef FixedPoints } <|endoftext|>
<commit_before>#include <stdexcept> #include <iostream> #include <cmath> #include <boost/lexical_cast.hpp> #include <boost/timer/timer.hpp> #include "HorizontalDiffusionSA.h" #include "Definitions.h" #include "Options.h" #include <mpi.h> #include "IJKSize.h" #ifdef __CUDA_BACKEND__ #include "cuda_profiler_api.h" #endif void readOptions(int argc, char** argv) { Options::setCommandLineParameters(argc, argv); const int& rank = Options::get<int>("rank"); if (rank == 0) { std::cout << "StandaloneStencilsCUDA\n\n"; std::cout << "usage: StandaloneStencilsCUDA [--ie isize] [--je jsize] [--ke ksize] \\\n" << " [--sync] [--nocomm] [--nocomp] \\\n" << " [--nh nhaloupdates] [-n nrepetitions] [--inorder]\n" << std::endl; } MPI_Barrier(MPI_COMM_WORLD); Options::parse("isize", "--ie", 128); Options::parse("jsize", "--je", 128); Options::parse("ksize", "--ke", 60); Options::parse("sync", "--sync", false); Options::parse("nocomm", "--nocomm", false); Options::parse("nocomp", "--nocomp", false); Options::parse("nhaloupdates", "--nh", 2); Options::parse("nrep", "-n", cNumBenchmarkRepetitions); Options::parse("inorder", "--inorder", false); std::cout << "\n"; } void setupDevice() { const int& rank = Options::get<int>("rank"); #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); if(!env_p) { std::cout << "SLURM_PROCID not set" << std::endl; exit (EXIT_FAILURE); } const char* local_rank = std::getenv("MV2_COMM_WORLD_LOCAL_RANK"); if (local_rank) { std::cout << "Rank: " << std::to_string(rank) << ", MV2_COMM_WORLD_LOCAL_RANK: " << local_rank << std::endl; } #elif OPENMPI const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); if(!env_p) { std::cout << "OMPI_COMM_WORLD_RANK not set" << std::endl; exit (EXIT_FAILURE); } #else const char* env_p = "0"; #endif const char* visible_devices = std::getenv("CUDA_VISIBLE_DEVICES"); if (visible_devices) { std::cout << "Rank: " << std::to_string(rank) << ", CUDA_VISIBLE_DEVICES: " << visible_devices << std::endl; } int numGPU; cudaError_t error = cudaGetDeviceCount(&numGPU); if(error) { std::cout << "CUDA ERROR: No device found " << std::endl; exit(EXIT_FAILURE); } error = cudaSetDevice(atoi(env_p)%numGPU); if(error) { std::cout << "CUDA ERROR: Could not set device " << std::to_string(atoi(env_p)%numGPU) << std::endl; exit(EXIT_FAILURE); } } void init_mpi(int argc, char** argv) { MPI_Init(&argc, &argv); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); Options::set("rank", rank); } int main(int argc, char** argv) { init_mpi(argc, argv); readOptions(argc, argv); setupDevice(); IJKSize domain(Options::get<int>("isize"), Options::get<int>("jsize"), Options::get<int>("ksize")); auto repository = std::shared_ptr<Repository>(new Repository(domain)); const int& rank = Options::get<int>("rank"); if (Options::get<int>("rank") == 0) { std::cout << "CONFIGURATION " << std::endl; std::cout << "====================================" << std::endl; std::cout << "Domain : [" << domain.isize << "," << domain.jsize << "," << domain.ksize << "]" << std::endl; std::cout << "Sync? : " << Options::get<bool>("sync") << std::endl; std::cout << "NoComm? : " << Options::get<bool>("nocomm") << std::endl; std::cout << "NoComp? : " << Options::get<bool>("nocomp") << std::endl; std::cout << "Number Halo Exchanges : " << Options::get<int>("nhaloupdates") << std::endl; std::cout << "Number benchmark repetitions : " << Options::get<int>("nrep") << std::endl; std::cout << "In Order halo exchanges? : " << Options::get<bool>("inorder") << std::endl; } MPI_Barrier(MPI_COMM_WORLD); int deviceId; if( cudaGetDevice(&deviceId) != cudaSuccess) { std::cerr << cudaGetErrorString(cudaGetLastError()) << std::endl; } std::cout << "Rank: "<< std::to_string(rank) << " Device ID: " << std::to_string(deviceId) << std::endl; MPI_Barrier(MPI_COMM_WORLD); #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); std::cout << "SLURM_PROCID :" << env_p << std::endl; std::cout << "Compiled for mvapich2" << std::endl; #elif OPENMPI const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); std::cout << "OMPI_COMM_WORLD_RANK :" << env_p<< std::endl; std::cout << "Compiled for openmpi" << std::endl; #else // Default proc const char* env_p = "0"; #endif boost::timer::cpu_timer cpu_timer; // Generate a horizontal diffusion operator HorizontalDiffusionSA horizontalDiffusionSA(repository); cudaDeviceSynchronize(); #ifdef __CUDA_BACKEND__ cudaProfilerStart(); #endif bool sync = Options::get<bool>("sync"); bool nocomm = Options::get<bool>("nocomm"); bool inOrder = Options::get<bool>("inorder"); bool nocomp = Options::get<bool>("nocomp"); int nHaloUpdates = Options::get<int>("nhaloupdates"); int nRep = Options::get<int>("nrep"); cpu_timer.start(); // Benchmark! for(int i=0; i < nRep; ++i) { int numGPU; cudaGetDeviceCount(&numGPU); // flush cache between calls to horizontal diffusion stencil if(i!=0 && !sync && !nocomm && !inOrder) { for(int c=0; c < nHaloUpdates ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } if(!nocomp) { horizontalDiffusionSA.Apply(); } if(inOrder) { for(int c=0; c < nHaloUpdates; ++c) { if(!nocomm){ if(!sync) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } repository->swap(); if(!nocomp) horizontalDiffusionSA.Apply(); if(!nocomm){ if(!sync) horizontalDiffusionSA.WaitHalos(c); } } } else { for(int c=0; c < nHaloUpdates ; ++c) { if(!nocomm){ if(!sync) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } repository->swap(); if(!nocomp) horizontalDiffusionSA.Apply(); } } } if(!nocomm && !sync && !inOrder){ for(int c=0; c < nHaloUpdates ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } cudaDeviceSynchronize(); #ifdef __CUDA_BACKEND__ cudaProfilerStop(); #endif cpu_timer.stop(); boost::timer::cpu_times elapsed = cpu_timer.elapsed(); double total_time = ((double) elapsed.wall)/1000000000.0; int num_ranks; MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); int rank_id; MPI_Comm_rank(MPI_COMM_WORLD, &rank_id); std::vector<double> total_time_g(num_ranks); MPI_Gather(&total_time, 1, MPI_DOUBLE, &(total_time_g[0]), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(rank_id==0) { double avg = 0.0; double rms = 0.0; for(int i=0; i < num_ranks; ++i) { avg += total_time_g[i]; } avg /= (double)num_ranks; for(int i=0; i < num_ranks; ++i) { rms += (total_time_g[i]-avg)*(total_time_g[i]-avg); } rms /= (double)num_ranks; rms = std::sqrt(rms); std::cout <<"ELAPSED TIME : " << avg << " +- + " << rms << std::endl; } MPI_Finalize(); } <commit_msg>Print MPI Rank and selected device<commit_after>#include <stdexcept> #include <iostream> #include <cmath> #include <boost/lexical_cast.hpp> #include <boost/timer/timer.hpp> #include "HorizontalDiffusionSA.h" #include "Definitions.h" #include "Options.h" #include <mpi.h> #include "IJKSize.h" #ifdef __CUDA_BACKEND__ #include "cuda_profiler_api.h" #endif void readOptions(int argc, char** argv) { Options::setCommandLineParameters(argc, argv); const int& rank = Options::get<int>("rank"); if (rank == 0) { std::cout << "StandaloneStencilsCUDA\n\n"; std::cout << "usage: StandaloneStencilsCUDA [--ie isize] [--je jsize] [--ke ksize] \\\n" << " [--sync] [--nocomm] [--nocomp] \\\n" << " [--nh nhaloupdates] [-n nrepetitions] [--inorder]\n" << std::endl; } MPI_Barrier(MPI_COMM_WORLD); Options::parse("isize", "--ie", 128); Options::parse("jsize", "--je", 128); Options::parse("ksize", "--ke", 60); Options::parse("sync", "--sync", false); Options::parse("nocomm", "--nocomm", false); Options::parse("nocomp", "--nocomp", false); Options::parse("nhaloupdates", "--nh", 2); Options::parse("nrep", "-n", cNumBenchmarkRepetitions); Options::parse("inorder", "--inorder", false); std::cout << "\n"; } void setupDevice() { const int& rank = Options::get<int>("rank"); #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); if(!env_p) { std::cout << "SLURM_PROCID not set" << std::endl; exit (EXIT_FAILURE); } const char* local_rank = std::getenv("MV2_COMM_WORLD_LOCAL_RANK"); if (local_rank) { std::cout << "Rank: " << std::to_string(rank) << ", MV2_COMM_WORLD_LOCAL_RANK: " << local_rank << std::endl; } #elif OPENMPI const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); if(!env_p) { std::cout << "OMPI_COMM_WORLD_RANK not set" << std::endl; exit (EXIT_FAILURE); } #else const char* env_p = "0"; #endif const char* visible_devices = std::getenv("CUDA_VISIBLE_DEVICES"); if (visible_devices) { std::cout << "Rank: " << std::to_string(rank) << ", CUDA_VISIBLE_DEVICES: " << visible_devices << std::endl; } int numGPU; cudaError_t error = cudaGetDeviceCount(&numGPU); if(error) { std::cout << "CUDA ERROR: No device found " << std::endl; exit(EXIT_FAILURE); } error = cudaSetDevice(atoi(env_p)%numGPU); if(error) { std::cout << "CUDA ERROR: Could not set device " << std::to_string(atoi(env_p)%numGPU) << std::endl; exit(EXIT_FAILURE); } int device; error = cudaGetDevice(&device); if(error) { std::cout << "CUDA ERROR: Could not get configured device." << std::endl; exit(EXIT_FAILURE); } std::cout << "Rank: " << std::to_string(rank) << ", Device: " << std::to_string(device) << std::endl; } void init_mpi(int argc, char** argv) { MPI_Init(&argc, &argv); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); Options::set("rank", rank); } int main(int argc, char** argv) { init_mpi(argc, argv); readOptions(argc, argv); setupDevice(); IJKSize domain(Options::get<int>("isize"), Options::get<int>("jsize"), Options::get<int>("ksize")); auto repository = std::shared_ptr<Repository>(new Repository(domain)); const int& rank = Options::get<int>("rank"); if (Options::get<int>("rank") == 0) { std::cout << "CONFIGURATION " << std::endl; std::cout << "====================================" << std::endl; std::cout << "Domain : [" << domain.isize << "," << domain.jsize << "," << domain.ksize << "]" << std::endl; std::cout << "Sync? : " << Options::get<bool>("sync") << std::endl; std::cout << "NoComm? : " << Options::get<bool>("nocomm") << std::endl; std::cout << "NoComp? : " << Options::get<bool>("nocomp") << std::endl; std::cout << "Number Halo Exchanges : " << Options::get<int>("nhaloupdates") << std::endl; std::cout << "Number benchmark repetitions : " << Options::get<int>("nrep") << std::endl; std::cout << "In Order halo exchanges? : " << Options::get<bool>("inorder") << std::endl; } MPI_Barrier(MPI_COMM_WORLD); int deviceId; if( cudaGetDevice(&deviceId) != cudaSuccess) { std::cerr << cudaGetErrorString(cudaGetLastError()) << std::endl; } std::cout << "Rank: "<< std::to_string(rank) << " Device ID: " << std::to_string(deviceId) << std::endl; MPI_Barrier(MPI_COMM_WORLD); #ifdef MVAPICH2 const char* env_p = std::getenv("SLURM_PROCID"); std::cout << "SLURM_PROCID :" << env_p << std::endl; std::cout << "Compiled for mvapich2" << std::endl; #elif OPENMPI const char* env_p = std::getenv("OMPI_COMM_WORLD_RANK"); std::cout << "OMPI_COMM_WORLD_RANK :" << env_p<< std::endl; std::cout << "Compiled for openmpi" << std::endl; #else // Default proc const char* env_p = "0"; #endif boost::timer::cpu_timer cpu_timer; // Generate a horizontal diffusion operator HorizontalDiffusionSA horizontalDiffusionSA(repository); cudaDeviceSynchronize(); #ifdef __CUDA_BACKEND__ cudaProfilerStart(); #endif bool sync = Options::get<bool>("sync"); bool nocomm = Options::get<bool>("nocomm"); bool inOrder = Options::get<bool>("inorder"); bool nocomp = Options::get<bool>("nocomp"); int nHaloUpdates = Options::get<int>("nhaloupdates"); int nRep = Options::get<int>("nrep"); cpu_timer.start(); // Benchmark! for(int i=0; i < nRep; ++i) { int numGPU; cudaGetDeviceCount(&numGPU); // flush cache between calls to horizontal diffusion stencil if(i!=0 && !sync && !nocomm && !inOrder) { for(int c=0; c < nHaloUpdates ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } if(!nocomp) { horizontalDiffusionSA.Apply(); } if(inOrder) { for(int c=0; c < nHaloUpdates; ++c) { if(!nocomm){ if(!sync) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } repository->swap(); if(!nocomp) horizontalDiffusionSA.Apply(); if(!nocomm){ if(!sync) horizontalDiffusionSA.WaitHalos(c); } } } else { for(int c=0; c < nHaloUpdates ; ++c) { if(!nocomm){ if(!sync) horizontalDiffusionSA.StartHalos(c); else horizontalDiffusionSA.ApplyHalos(c); } repository->swap(); if(!nocomp) horizontalDiffusionSA.Apply(); } } } if(!nocomm && !sync && !inOrder){ for(int c=0; c < nHaloUpdates ; ++c) { horizontalDiffusionSA.WaitHalos(c); } } cudaDeviceSynchronize(); #ifdef __CUDA_BACKEND__ cudaProfilerStop(); #endif cpu_timer.stop(); boost::timer::cpu_times elapsed = cpu_timer.elapsed(); double total_time = ((double) elapsed.wall)/1000000000.0; int num_ranks; MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); int rank_id; MPI_Comm_rank(MPI_COMM_WORLD, &rank_id); std::vector<double> total_time_g(num_ranks); MPI_Gather(&total_time, 1, MPI_DOUBLE, &(total_time_g[0]), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(rank_id==0) { double avg = 0.0; double rms = 0.0; for(int i=0; i < num_ranks; ++i) { avg += total_time_g[i]; } avg /= (double)num_ranks; for(int i=0; i < num_ranks; ++i) { rms += (total_time_g[i]-avg)*(total_time_g[i]-avg); } rms /= (double)num_ranks; rms = std::sqrt(rms); std::cout <<"ELAPSED TIME : " << avg << " +- + " << rms << std::endl; } MPI_Finalize(); } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Richard Martin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Richard Martin nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RICHARD MARTIN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "BookReader.hpp" #include "MainWindow.hpp" #include "Pages.hpp" #include <gtkmm/application.h> #include <gtkmm/window.h> using namespace Glib; using namespace Gtk; HeaderBar * header_bar; Pages pages; int main(int argc, char* argv[]) { Paginator::load(pages, string("book2")); RefPtr<Application> app = Application::create(argc, argv, "org.rmarti.dnd"); MainWindow window; return app->run(window); }<commit_msg>Updating application ID<commit_after>/* Copyright (c) 2014, Richard Martin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Richard Martin nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RICHARD MARTIN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "BookReader.hpp" #include "MainWindow.hpp" #include "Pages.hpp" #include <gtkmm/application.h> #include <gtkmm/window.h> using namespace Glib; using namespace Gtk; HeaderBar * header_bar; Pages pages; int main(int argc, char* argv[]) { Paginator::load(pages, string("book")); RefPtr<Application> app = Application::create(argc, argv, "org.rmarti.reader"); MainWindow window; return app->run(window); }<|endoftext|>
<commit_before>#include <memory> #include <SDL2/SDL.h> #include <GL/glew.h> #include <SDL2/SDL_opengl.h> #include <GL/glu.h> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <easylogging++.h> #include "b2draw/DebugDraw.h" #include "dukdemo/render/Context.h" #include "dukdemo/render/util.h" #include "dukdemo/util/deleters.h" constexpr int screenWidth{640}; constexpr int screenHeight{480}; constexpr float worldTimeStep{1.0f / 60.0f}; constexpr unsigned velocityIterations{8}; constexpr unsigned positionIterations{3}; constexpr char const* const pPositionAttribName = "position"; constexpr char const* const pColourAttribName = "colour"; INITIALIZE_EASYLOGGINGPP using duk_context_ptr = std::unique_ptr<duk_context, dukdemo::util::DukContextDeleter>; using sdl_window_ptr = std::unique_ptr<SDL_Window, dukdemo::util::SDLWindowDeleter>; using gl_context_ptr = std::unique_ptr<void, dukdemo::util::GLContextDeleter>; void run(int argc, char const* const argv[]) { dukdemo::render::Context renderContext{"Dukdemo"}; dukdemo::render::checkGLErrors("Render context created"); auto const programID = dukdemo::render::createProgram(); // Set up scene for rendering. glClearColor(0.0f, 0.0f, 0.0f, 1.0f); b2draw::DebugDraw debugDraw{ programID, pPositionAttribName, pColourAttribName }; debugDraw.SetFlags(0xff); b2Vec2 const gravity{0.0f, -9.8f}; b2World world{gravity}; world.SetDebugDraw(&debugDraw); { b2BodyDef bodyDef; bodyDef.type = b2_staticBody; bodyDef.position.Set(0.0f, -4.0f); auto const pGroundBody = world.CreateBody(&bodyDef); b2PolygonShape box; box.SetAsBox(-30.0f, 1.0f); pGroundBody->CreateFixture(&box, 0.0f /* Density. */); } { b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(0.0f, 4.0f); auto const pDynamicBody = world.CreateBody(&bodyDef); b2PolygonShape box; box.SetAsBox(1.0f, 1.0f); b2FixtureDef fixtureDef; fixtureDef.shape = &box; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; pDynamicBody->CreateFixture(&fixtureDef); } constexpr float fieldOfView{45.0f}; auto const projMat = glm::perspective( fieldOfView, 4.0f / 3.0f, 0.1f, 100.0f ); constexpr glm::vec3 eye{0.0f, 0.0f, 40.0f}; constexpr glm::vec3 focus{0.0f, 0.0f, 0.0f}; constexpr glm::vec3 up{0.0f, 1.0f, 0.0f}; auto const viewMat = glm::lookAt(eye, focus, up); glm::mat4 const modelMat{1.0f}; auto const mvpMat{projMat * viewMat * modelMat}; auto const pMvpMatStart{&mvpMat[0][0]}; auto const mvpAttribLoc{glGetUniformLocation(programID, "MVP")}; if (mvpAttribLoc < 0) { throw std::runtime_error{"Unable to locate uniform 'MVP'"}; } auto const update = [&debugDraw, &world] { world.Step(worldTimeStep, velocityIterations, positionIterations); debugDraw.Clear(); world.DrawDebugData(); debugDraw.BufferData(); }; auto const render = [ &debugDraw, programID, pSDLWindow = renderContext.window(), mvpAttribLoc, pMvpMatStart ] { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniformMatrix4fv(mvpAttribLoc, 1, GL_FALSE, pMvpMatStart); debugDraw.Render(); }; renderContext.setOnRender(render); // Ensure no GL errors. dukdemo::render::checkGLErrors("Ready to render"); update(); renderContext.render(); renderContext.render(); // TODO: Why is this second render required? SDL_Event event; bool userQuit{false}; while (not userQuit) { while (SDL_PollEvent(&event) != 0) { switch (event.type) { case SDL_QUIT: userQuit = true; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: userQuit = true; break; case SDLK_s: update(); renderContext.render(); break; default: break; } break; default: break; } } } renderContext.reset(); } int main(int argc, char const* const argv[]) { try { run(argc, argv); } catch (std::exception const& err) { LOG(ERROR) << err.what(); return 1; } return 0; } <commit_msg>Add basic b2BodyDef example<commit_after>#include <memory> #include <SDL2/SDL.h> #include <GL/glew.h> #include <SDL2/SDL_opengl.h> #include <GL/glu.h> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <easylogging++.h> #include <duktape.h> #include "b2draw/DebugDraw.h" #include "dukdemo/util/deleters.h" #include "dukdemo/render/Context.h" #include "dukdemo/render/util.h" #include "dukdemo/scripting/physics.h" constexpr int screenWidth{640}; constexpr int screenHeight{480}; constexpr float worldTimeStep{1.0f / 60.0f}; constexpr unsigned velocityIterations{8}; constexpr unsigned positionIterations{3}; constexpr char const* const pPositionAttribName = "position"; constexpr char const* const pColourAttribName = "colour"; INITIALIZE_EASYLOGGINGPP using duk_context_ptr = std::unique_ptr<duk_context, dukdemo::util::DukContextDeleter>; using sdl_window_ptr = std::unique_ptr<SDL_Window, dukdemo::util::SDLWindowDeleter>; using gl_context_ptr = std::unique_ptr<void, dukdemo::util::GLContextDeleter>; duk_ret_t jsFunc(duk_context* pContext) { duk_push_int(pContext, 123); return 1; } void addBody(duk_context* pContext) { // Stack: [bodyDef]. assert(duk_get_top(pContext) == 1 && "Invalid args"); b2BodyDef def; } void runScripts() { // Create Duktape heap and context. duk_context_ptr pContext{duk_create_heap_default()}; if (!pContext) { throw std::runtime_error{"Failed to create duktype context"}; } constexpr const char* const pJSON = R"JSON({ "type": 1, "position": [1, 2], "angularVelocity": 1.2345, "bullet": true })JSON"; duk_push_string(pContext.get(), pJSON); duk_json_decode(pContext.get(), -1); b2BodyDef bodyDef; dukdemo::scripting::setBodyDef(pContext.get(), -1, &bodyDef); } void runSimulation() { dukdemo::render::Context renderContext{"Dukdemo"}; dukdemo::render::checkGLErrors("Render context created"); auto const programID = dukdemo::render::createProgram(); // Set up scene for rendering. glClearColor(0.0f, 0.0f, 0.0f, 1.0f); b2draw::DebugDraw debugDraw{ programID, pPositionAttribName, pColourAttribName }; debugDraw.SetFlags(0xff); b2Vec2 const gravity{0.0f, -9.8f}; b2World world{gravity}; world.SetDebugDraw(&debugDraw); { b2BodyDef bodyDef; bodyDef.type = b2_staticBody; bodyDef.position.Set(0.0f, -4.0f); auto const pGroundBody = world.CreateBody(&bodyDef); b2PolygonShape box; box.SetAsBox(-30.0f, 1.0f); pGroundBody->CreateFixture(&box, 0.0f /* Density. */); } { b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(0.0f, 4.0f); auto const pDynamicBody = world.CreateBody(&bodyDef); b2PolygonShape box; box.SetAsBox(1.0f, 1.0f); b2FixtureDef fixtureDef; fixtureDef.shape = &box; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; pDynamicBody->CreateFixture(&fixtureDef); } constexpr float fieldOfView{45.0f}; auto const projMat = glm::perspective( fieldOfView, 4.0f / 3.0f, 0.1f, 100.0f ); constexpr glm::vec3 eye{0.0f, 0.0f, 40.0f}; constexpr glm::vec3 focus{0.0f, 0.0f, 0.0f}; constexpr glm::vec3 up{0.0f, 1.0f, 0.0f}; auto const viewMat = glm::lookAt(eye, focus, up); glm::mat4 const modelMat{1.0f}; auto const mvpMat{projMat * viewMat * modelMat}; auto const pMvpMatStart{&mvpMat[0][0]}; auto const mvpAttribLoc{glGetUniformLocation(programID, "MVP")}; if (mvpAttribLoc < 0) { throw std::runtime_error{"Unable to locate uniform 'MVP'"}; } auto const update = [&debugDraw, &world] { world.Step(worldTimeStep, velocityIterations, positionIterations); debugDraw.Clear(); world.DrawDebugData(); debugDraw.BufferData(); }; auto const render = [ &debugDraw, programID, pSDLWindow = renderContext.window(), mvpAttribLoc, pMvpMatStart ] { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniformMatrix4fv(mvpAttribLoc, 1, GL_FALSE, pMvpMatStart); debugDraw.Render(); }; renderContext.setOnRender(render); // Ensure no GL errors. dukdemo::render::checkGLErrors("Ready to render"); update(); renderContext.render(); renderContext.render(); // TODO: Why is this second render required? SDL_Event event; bool userQuit{false}; while (not userQuit) { while (SDL_PollEvent(&event) != 0) { switch (event.type) { case SDL_QUIT: userQuit = true; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: userQuit = true; break; case SDLK_s: update(); renderContext.render(); break; default: break; } break; default: break; } } } renderContext.reset(); } int main(int argc, char const* const argv[]) { #ifdef NDEBUG try { runSimulation(); } catch (std::exception const& err) { LOG(ERROR) << err.what(); return 1; } #else // Run without intercepting exceptions so we get a stack trace. runSimulation(); #endif return 0; } <|endoftext|>
<commit_before>/* * PartsBasedDetectorOnVideo * * * Huge chunks of code shamelessly taken from Hilton Bristow's demo for * PartsBasedDetector. * * Software License Agreement (BSD License) * * Copyright (c) 2013, Chili lab, EPFL. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Chili, EPFL nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * File: main.h * Author: Mirko Raca <name.lastname@epfl.ch> * Created: November 5, 2013 */ #include <glog/logging.h> #include <boost/filesystem.hpp> #include <time.h> #include <stdio.h> #include <fstream> #include <ncurses.h> #include <opencv2/highgui/highgui.hpp> #include <PartsBasedDetector.hpp> #include <Candidate.hpp> #include <FileStorageModel.hpp> #define WITH_MATLABIO #ifdef WITH_MATLABIO #include <MatlabIOModel.hpp> #endif #include "outputFormat.h" #include "mirrorUtils.h" using namespace cv; using namespace std; #define OUTPUT_FILENAME_FORMAT "facedetect_frame%06d.txt" #define DEFAULT_NMS_THRESHOLD 0.3f #define DEFAULT_MIRRORING true #define DEFAULT_RESUME false void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder); void updateDisplay(int _frame, float _perc, double _time); int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); DLOG(INFO) << "Execution started"; if (argc < 4) { printf("Usage: PartsBasedDetectorOnVideo model_file video_file output_folder [-r] [nmsThreshold]\n"); exit(-1); } // process variables boost::scoped_ptr<Model> model; float nmsThreshold = DEFAULT_NMS_THRESHOLD; bool optMirroring = DEFAULT_MIRRORING; bool optResume = DEFAULT_RESUME; if( argc >= 5 ){ if(strcmp(argv[4], "-r") == 0){ optResume = true; DLOG(INFO) << "Resume flag: ON"; } } if( argc >= 6 ){ nmsThreshold = atof(argv[5]); } // determine the type of model to read string ext = boost::filesystem::path(argv[1]).extension().string(); if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) { model.reset(new FileStorageModel); } #ifdef WITH_MATLABIO else if (ext.compare(".mat") == 0) { model.reset(new MatlabIOModel); } #endif else { printf("Unsupported model format: %s\n", ext.c_str()); LOG(FATAL) << "Unsupported model format: " << ext.c_str(); exit(-2); } bool ok = model->deserialize(argv[1]); if (!ok) { printf("Error deserializing file\n"); LOG(FATAL) << "Error deserializing file."; exit(-3); } // check output folder string outputFilePattern = (string) argv[3]; if( outputFilePattern[outputFilePattern.length()-1] != '/' ){ outputFilePattern.append("/"); } outputFilePattern.append(OUTPUT_FILENAME_FORMAT); // create the PartsBasedDetector and distribute the model parameters Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable PartsBasedDetector<float> pbd; pbd.distributeModel(*model); // load video sequence VideoCapture videoSrc((string)argv[2]); if( !videoSrc.isOpened() ){ printf("Could not read video file\n"); LOG(FATAL) << "Could not read video file: " << argv[2]; endwin(); exit(-4); } double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT); double frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); DLOG(INFO) << "Frame count: " << frameCount; DLOG(INFO) << "Start frame no: " << frameNo; // DEBUG // frameCount = 100; // display initialzation setupDisplay(argv[1], argv[2], argv[3]); // main loop DLOG(INFO) << "main loop"; vectorCandidate candidates; Mat curFrameIm; char outputFilenameBuffer[1024]; clock_t timeElapsed = clock(); while(frameNo < frameCount){ DLOG(INFO) << "FrameNo " << frameNo; updateDisplay(frameNo, ((float)frameNo/(float)frameCount*100.0f), (double) ( clock() - timeElapsed )/CLOCKS_PER_SEC ); timeElapsed = clock(); candidates.clear(); frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); videoSrc >> curFrameIm; sprintf(outputFilenameBuffer, outputFilePattern.c_str(), (int) frameNo); if( optResume ){ if(boost::filesystem::exists(outputFilenameBuffer)) continue; } pbd.detect(curFrameIm, depth, candidates); #ifndef NDEBUG gOutputFormat = FT_BBOX_BRIEF; #endif DLOG(INFO) << "Found original: " << candidates; if(optMirroring){ vectorCandidate mirroredCandidates; flip(curFrameIm, curFrameIm, 1); // flip around y-axis pbd.detect(curFrameIm, depth, mirroredCandidates); DLOG(INFO) << "Found flipped: " << mirroredCandidates; flipHorizontaly(mirroredCandidates, curFrameIm.size); DLOG(INFO) << "After flipping: " << mirroredCandidates; candidates.insert(candidates.end(), mirroredCandidates.begin(), mirroredCandidates.end()); } Candidate::nonMaximaSuppression(curFrameIm, candidates, nmsThreshold); DLOG(INFO) << "Final all detections" << candidates; // output ofstream outFile(outputFilenameBuffer); #ifndef NDEBUG gOutputFormat = FT_FULL_OUTPUT; #endif outFile << candidates; // cleanup outFile.close(); if(!curFrameIm.empty()) curFrameIm.release(); } // cleanup DLOG(INFO) << "Cleanup part"; videoSrc.release(); DLOG(INFO) << "Execution finished"; endwin(); return 0; } void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder){ initscr(); cbreak(); noecho(); int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later attron(A_BOLD); mvprintw(1, cols/2-19, "[[ PartsBasedDetector (onVideo) v1.0 ]]"); attroff(A_BOLD); mvprintw(3, 3, "Model file: "); mvprintw(3, 25, boost::filesystem::path(_model).filename().c_str()); mvprintw(4, 3, "Input video file: "); mvprintw(4, 25, boost::filesystem::path(_inputVideo).filename().c_str()); mvprintw(5, 3, "Output folder: "); mvprintw(5, 25, boost::filesystem::path(_outputFolder).leaf().c_str()); refresh(); } void updateDisplay(int _frame, float _perc, double _time){ // update display with information int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later float runnerStep = 100.0f/((float)cols-40); move(10, 5); addch('['); attron(A_BOLD); float runner; int change = 0; for(runner = 0; runner < _perc; runner+=runnerStep ){ switch( change % 4 ){ case 0: addch('.'); break; case 1: addch('o'); break; case 2: addch('O'); break; case 3: addch('o'); break; } change++; } for(;runner < 100.0f; runner += runnerStep) addch(' '); attroff(A_BOLD); printw("] %.2f% [Frame #%d]", _perc, _frame); move(11, cols/2 - 3); printw("TPF: %.2f sec", _time); refresh(); } <commit_msg>Skipping the mirroring thing due to better models<commit_after>/* * PartsBasedDetectorOnVideo * * * Huge chunks of code shamelessly taken from Hilton Bristow's demo for * PartsBasedDetector. * * Software License Agreement (BSD License) * * Copyright (c) 2013, Chili lab, EPFL. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Chili, EPFL nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * File: main.h * Author: Mirko Raca <name.lastname@epfl.ch> * Created: November 5, 2013 */ #include <glog/logging.h> #include <boost/filesystem.hpp> #include <time.h> #include <stdio.h> #include <fstream> #include <ncurses.h> #include <opencv2/highgui/highgui.hpp> #include <PartsBasedDetector.hpp> #include <Candidate.hpp> #include <FileStorageModel.hpp> #define WITH_MATLABIO #ifdef WITH_MATLABIO #include <MatlabIOModel.hpp> #endif #include "outputFormat.h" #include "mirrorUtils.h" using namespace cv; using namespace std; #define OUTPUT_FILENAME_FORMAT "facedetect_frame%06d.txt" #define DEFAULT_NMS_THRESHOLD 0.3f #define DEFAULT_MIRRORING false #define DEFAULT_RESUME false void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder); void updateDisplay(int _frame, float _perc, double _time); int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); DLOG(INFO) << "Execution started"; if (argc < 4) { printf("Usage: PartsBasedDetectorOnVideo model_file video_file output_folder [-r] [nmsThreshold]\n"); exit(-1); } // process variables boost::scoped_ptr<Model> model; float nmsThreshold = DEFAULT_NMS_THRESHOLD; bool optMirroring = DEFAULT_MIRRORING; bool optResume = DEFAULT_RESUME; if( argc >= 5 ){ if(strcmp(argv[4], "-r") == 0){ optResume = true; DLOG(INFO) << "Resume flag: ON"; } } if( argc >= 6 ){ nmsThreshold = atof(argv[5]); } // determine the type of model to read string ext = boost::filesystem::path(argv[1]).extension().string(); if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) { model.reset(new FileStorageModel); } #ifdef WITH_MATLABIO else if (ext.compare(".mat") == 0) { model.reset(new MatlabIOModel); } #endif else { printf("Unsupported model format: %s\n", ext.c_str()); LOG(FATAL) << "Unsupported model format: " << ext.c_str(); exit(-2); } bool ok = model->deserialize(argv[1]); if (!ok) { printf("Error deserializing file\n"); LOG(FATAL) << "Error deserializing file."; exit(-3); } // check output folder string outputFilePattern = (string) argv[3]; if( outputFilePattern[outputFilePattern.length()-1] != '/' ){ outputFilePattern.append("/"); } outputFilePattern.append(OUTPUT_FILENAME_FORMAT); // create the PartsBasedDetector and distribute the model parameters Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable PartsBasedDetector<float> pbd; pbd.distributeModel(*model); // load video sequence VideoCapture videoSrc((string)argv[2]); if( !videoSrc.isOpened() ){ printf("Could not read video file\n"); LOG(FATAL) << "Could not read video file: " << argv[2]; endwin(); exit(-4); } double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT); double frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); DLOG(INFO) << "Frame count: " << frameCount; DLOG(INFO) << "Start frame no: " << frameNo; // DEBUG // frameCount = 100; // display initialzation setupDisplay(argv[1], argv[2], argv[3]); // main loop DLOG(INFO) << "main loop"; vectorCandidate candidates; Mat curFrameIm; char outputFilenameBuffer[1024]; clock_t timeElapsed = clock(); while(frameNo < frameCount){ DLOG(INFO) << "FrameNo " << frameNo; updateDisplay(frameNo, ((float)frameNo/(float)frameCount*100.0f), (double) ( clock() - timeElapsed )/CLOCKS_PER_SEC ); timeElapsed = clock(); candidates.clear(); frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); videoSrc >> curFrameIm; sprintf(outputFilenameBuffer, outputFilePattern.c_str(), (int) frameNo); if( optResume ){ if(boost::filesystem::exists(outputFilenameBuffer)) continue; } pbd.detect(curFrameIm, depth, candidates); #ifndef NDEBUG gOutputFormat = FT_BBOX_BRIEF; #endif DLOG(INFO) << "Found original: " << candidates; if(optMirroring){ vectorCandidate mirroredCandidates; flip(curFrameIm, curFrameIm, 1); // flip around y-axis pbd.detect(curFrameIm, depth, mirroredCandidates); DLOG(INFO) << "Found flipped: " << mirroredCandidates; flipHorizontaly(mirroredCandidates, curFrameIm.size); DLOG(INFO) << "After flipping: " << mirroredCandidates; candidates.insert(candidates.end(), mirroredCandidates.begin(), mirroredCandidates.end()); } Candidate::nonMaximaSuppression(curFrameIm, candidates, nmsThreshold); DLOG(INFO) << "Final all detections" << candidates; // output ofstream outFile(outputFilenameBuffer); #ifndef NDEBUG gOutputFormat = FT_FULL_OUTPUT; #endif outFile << candidates; // cleanup outFile.close(); if(!curFrameIm.empty()) curFrameIm.release(); } // cleanup DLOG(INFO) << "Cleanup part"; videoSrc.release(); DLOG(INFO) << "Execution finished"; endwin(); return 0; } void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder){ initscr(); cbreak(); noecho(); int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later attron(A_BOLD); mvprintw(1, cols/2-19, "[[ PartsBasedDetector (onVideo) v1.0 ]]"); attroff(A_BOLD); mvprintw(3, 3, "Model file: "); mvprintw(3, 25, boost::filesystem::path(_model).filename().c_str()); mvprintw(4, 3, "Input video file: "); mvprintw(4, 25, boost::filesystem::path(_inputVideo).filename().c_str()); mvprintw(5, 3, "Output folder: "); mvprintw(5, 25, boost::filesystem::path(_outputFolder).leaf().c_str()); refresh(); } void updateDisplay(int _frame, float _perc, double _time){ // update display with information int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later float runnerStep = 100.0f/((float)cols-40); move(10, 5); addch('['); attron(A_BOLD); float runner; int change = 0; for(runner = 0; runner < _perc; runner+=runnerStep ){ switch( change % 4 ){ case 0: addch('.'); break; case 1: addch('o'); break; case 2: addch('O'); break; case 3: addch('o'); break; } change++; } for(;runner < 100.0f; runner += runnerStep) addch(' '); attroff(A_BOLD); printw("] %.2f% [Frame #%d]", _perc, _frame); move(11, cols/2 - 3); printw("TPF: %.2f sec", _time); refresh(); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> using namespace std; int N = 256; //const char *FName="/home/semen/monkey/Cut.txt"; const char *FName="/etc/passwd"; void ReadFile() { cout<<endl<<"ReadFile: "; char S[N]={""}; ifstream in1(FName); while (!in1.eof()) { in1.getline(S,N); cout<<S<<endl; } in1.close(); } int main() { ReadFile(); return 0; } <commit_msg>add alternative reading from file<commit_after>#include <iostream> #include <fstream> // # For Alternative Read #include <iterator> #include <algorithm> #include <ios> using namespace std; int N = 256; //const char *FName="/home/semen/monkey/Cut.txt"; const char *FName="/etc/passwd"; void AltReadFile() { std::ifstream f(FName); std::copy( std::istream_iterator<char>(f >> std::noskipws), std::istream_iterator<char>(), std::ostream_iterator<char>( std::cout ) ); } void ReadFile() { cout<<endl<<"ReadFile: "; char S[N]={""}; ifstream in1(FName); while (!in1.eof()) { in1.getline(S,N); cout<<S<<endl; } in1.close(); } int main() { //AltReadFile(); ReadFile(); return 0; } <|endoftext|>
<commit_before>#include "image.h" #include "body.h" #include "font.h" #include "units.h" #include "linkedlist.h" #include <fstream> #include <pngwriter.h> using namespace std; //pngwriter png; Image::Image(string filename, int w, int h, double _scale) { fileName = filename; width = w; height = h; scale = _scale; png = pngwriter(width, height, 0, filename.c_str()); } void Image::Draw(int x, int y, int r, int g, int b) { double redValue = ((double)r / 255.0); double greenValue = ((double)g / 255.0); double blueValue = ((double)b / 255.0); png.plot(x, y, redValue, greenValue, blueValue); } void Image::DrawLine(int x1, int y1, int x2, int y2, int r, int g, int b) { double redValue = ((double)r / 255.0); double greenValue = ((double)g / 255.0); double blueValue = ((double)b / 255.0); png.line(x1, height - y1, x2, height - y2, redValue, greenValue, blueValue); } int Image::Scale(double coordinate, double scale) { int position = (int)(coordinate / AU * scale); return position; } void Image::DrawBody(double x, double y, double radius, int r, int g, int b) { int xScaled = (width / 2) + Scale(x, scale); int yScaled = (height / 2) + Scale(y, scale); int radiusScaled = Scale(radius, scale); bool xValid = xScaled < width && xScaled >= 0; bool yValid = yScaled < height && yScaled >= 0; if (xValid && yValid) { double redValue = ((double)r / 255.0); double greenValue = ((double)g / 255.0); double blueValue = ((double)b / 255.0); if (radiusScaled == 0) { Draw(xScaled, yScaled, r, g, b); } else { png.filledcircle(xScaled, yScaled, radiusScaled, redValue, greenValue, blueValue); } //Draw(xScaled, yScaled, r, g, b); } } void Image::DrawAllBodies(int bodyCount, List bodyList, int r, int g, int b) { Body * body = bodyList.GetHead(); while (body != NULL) { DrawBody(body->GetX(), body->GetY(), body->GetRadius(), r, g, b); body = body->next; } } void Image::DrawTextArray(int textArray [5][5], int xStart, int yStart, int r, int g, int b) { for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { if (textArray[y][x] == 0) { png.plot(x + xStart, height - (y + yStart), 0.0, 0.0, 0.0); } else { png.plot(x + xStart, height - (y + yStart), ((double)r / 255.0), ((double)g / 255.0), ((double)b / 255.0)); } } } } void Image::DrawText(string text, int x, int y, int r, int g, int b) { for (size_t i = 0; i < text.length(); i++) { int c = (int)i; // Handle Alphabet if (tolower(text[c]) >= 97 && tolower(text[c]) <= 122) { int index = tolower(text[c]) - 97; DrawTextArray(fontAlphabet[index], x, y, r, g, b); } // Handle Numbers else if (tolower(text[c]) >= 48 && tolower(text[c]) <= 57) { int index = tolower(text[c]) - 48; DrawTextArray(fontNumbers[index], x, y, r, g, b); } // Handle Punctuation else { switch (text[c]) { case '.': DrawTextArray(fontPERIOD, x, y, r, g, b); break; case ':': DrawTextArray(fontCOLON, x, y, r, g, b); break; case '-': DrawTextArray(fontHYPHEN, x, y, r, g, b); break; case '/': DrawTextArray(fontSLASH, x, y, r, g, b); break; default: break; } } x += fontWidth + kerning; } } void Image::DrawScale(double scale, int x, int y, int r, int g, int b) { if (scale >= 3.0) { // Long enough to a line DrawLine(x, y, x + scale, y, r, g, b); Draw(x, height - y + 1, r, g, b); Draw(x + scale, height - y + 1, r, g, b); DrawText("1 AU", x + scale + 5, y - 2, r, g, b); } else { // Not long enough - just write a message string scaleText = "SCALE: " + to_string(scale) + " PX/AU"; DrawText(scaleText.c_str(), x, y - 2, r, g, b); } } void Image::Save() { png.close(); } <commit_msg>Scale line now scales with screen if too long<commit_after>#include "image.h" #include "body.h" #include "font.h" #include "units.h" #include "linkedlist.h" #include <fstream> #include <pngwriter.h> using namespace std; //pngwriter png; Image::Image(string filename, int w, int h, double _scale) { fileName = filename; width = w; height = h; scale = _scale; png = pngwriter(width, height, 0, filename.c_str()); } void Image::Draw(int x, int y, int r, int g, int b) { double redValue = ((double)r / 255.0); double greenValue = ((double)g / 255.0); double blueValue = ((double)b / 255.0); png.plot(x, y, redValue, greenValue, blueValue); } void Image::DrawLine(int x1, int y1, int x2, int y2, int r, int g, int b) { double redValue = ((double)r / 255.0); double greenValue = ((double)g / 255.0); double blueValue = ((double)b / 255.0); png.line(x1, height - y1, x2, height - y2, redValue, greenValue, blueValue); } int Image::Scale(double coordinate, double scale) { int position = (int)(coordinate / AU * scale); return position; } void Image::DrawBody(double x, double y, double radius, int r, int g, int b) { int xScaled = (width / 2) + Scale(x, scale); int yScaled = (height / 2) + Scale(y, scale); int radiusScaled = Scale(radius, scale); bool xValid = xScaled < width && xScaled >= 0; bool yValid = yScaled < height && yScaled >= 0; if (xValid && yValid) { double redValue = ((double)r / 255.0); double greenValue = ((double)g / 255.0); double blueValue = ((double)b / 255.0); if (radiusScaled == 0) { Draw(xScaled, yScaled, r, g, b); } else { png.filledcircle(xScaled, yScaled, radiusScaled, redValue, greenValue, blueValue); } //Draw(xScaled, yScaled, r, g, b); } } void Image::DrawAllBodies(int bodyCount, List bodyList, int r, int g, int b) { Body * body = bodyList.GetHead(); while (body != NULL) { DrawBody(body->GetX(), body->GetY(), body->GetRadius(), r, g, b); body = body->next; } } void Image::DrawTextArray(int textArray [5][5], int xStart, int yStart, int r, int g, int b) { for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { if (textArray[y][x] == 0) { png.plot(x + xStart, height - (y + yStart), 0.0, 0.0, 0.0); } else { png.plot(x + xStart, height - (y + yStart), ((double)r / 255.0), ((double)g / 255.0), ((double)b / 255.0)); } } } } void Image::DrawText(string text, int x, int y, int r, int g, int b) { for (size_t i = 0; i < text.length(); i++) { int c = (int)i; // Handle Alphabet if (tolower(text[c]) >= 97 && tolower(text[c]) <= 122) { int index = tolower(text[c]) - 97; DrawTextArray(fontAlphabet[index], x, y, r, g, b); } // Handle Numbers else if (tolower(text[c]) >= 48 && tolower(text[c]) <= 57) { int index = tolower(text[c]) - 48; DrawTextArray(fontNumbers[index], x, y, r, g, b); } // Handle Punctuation else { switch (text[c]) { case '.': DrawTextArray(fontPERIOD, x, y, r, g, b); break; case ':': DrawTextArray(fontCOLON, x, y, r, g, b); break; case '-': DrawTextArray(fontHYPHEN, x, y, r, g, b); break; case '/': DrawTextArray(fontSLASH, x, y, r, g, b); break; default: break; } } x += fontWidth + kerning; } } void Image::DrawScale(double scale, int x, int y, int r, int g, int b) { if (scale >= 3.0) { // Long enough to a line double distanceOfScale = 1.0; string scaleString = "1 AU"; // Check if line + text will fit on screen while (x + scale + 5 * scaleString.length() >= width) { scale /= 10; distanceOfScale /= 10; scaleString = to_string(distanceOfScale) + " AU"; } // Remove trailing zeroes (aesthetic) string scaleDistance = to_string(distanceOfScale); int i = scaleDistance.length() - 1; int lastNotZero; while (i >= 0) { if (scaleDistance[i] != '0') { lastNotZero = i; break; } i--; } if (scaleDistance[lastNotZero] == '.') lastNotZero++; scaleString = scaleDistance.substr(0, lastNotZero + 1) + "AU"; DrawLine(x, y, x + scale, y, r, g, b); Draw(x, height - y + 1, r, g, b); Draw(x + scale, height - y + 1, r, g, b); DrawText(scaleString.c_str(), x + scale + 5, y - 2, r, g, b); } else { // Not long enough - just write a message string scaleText = "SCALE: " + to_string(scale) + " PX/AU"; DrawText(scaleText.c_str(), x, y - 2, r, g, b); } } void Image::Save() { png.close(); } <|endoftext|>
<commit_before>#include "Base.h" #include "BiosRom.h" #include "Cartridge.h" #include "Cpu.h" #include "Debugger.h" #include "EngineClient.h" #include "MemoryBus.h" #include "MemoryMap.h" #include "Platform.h" #include "Ram.h" #include "SDLEngine.h" #include "UnmappedMemoryDevice.h" #include "Via.h" #include <memory> #include <random> class Vectrexy final : public IEngineClient { private: bool Init(int argc, char** argv) override { std::string rom = argc == 2 ? argv[1] : ""; m_cpu.Init(m_memoryBus); m_via.Init(m_memoryBus); m_ram.Init(m_memoryBus); m_biosRom.Init(m_memoryBus); m_unmapped.Init(m_memoryBus); m_cartridge.Init(m_memoryBus); m_debugger.Init(m_memoryBus, m_cpu, m_via); // Some games rely on initial random state of memory (e.g. Mine Storm) const unsigned int seed = std::random_device{}(); m_ram.Randomize(seed); m_biosRom.LoadBiosRom("bios_rom.bin"); if (!rom.empty()) m_cartridge.LoadRom(rom.c_str()); m_cpu.Reset(); return true; } bool Update(double deltaTime, const Input& input) override { if (!m_debugger.Update(deltaTime, input)) return false; return true; } void Render(double deltaTime, Display& display) override { m_elapsed += deltaTime; //@HACK: clear lines and screen at approximately 50hz if (m_elapsed >= (1.0 / 50.0)) { m_elapsed = 0; display.Clear(); for (const auto& line : m_via.m_lines) { display.DrawLine(line.p0.x, line.p0.y, line.p1.x, line.p1.y); } m_via.m_lines.clear(); } #define DRAW_LINES_EVERY_RENDER 0 /* Useful for debugging vector drawing */ #if DRAW_LINES_EVERY_RENDER for (const auto& line : m_via.m_lines) { display.DrawLine(line.p0.x, line.p0.y, line.p1.x, line.p1.y); } #endif } void Shutdown() override {} MemoryBus m_memoryBus; Cpu m_cpu; Via m_via; Ram m_ram; BiosRom m_biosRom; UnmappedMemoryDevice m_unmapped; Cartridge m_cartridge; Debugger m_debugger; double m_elapsed = 0; }; int main(int argc, char** argv) { auto client = std::make_unique<Vectrexy>(); auto engine = std::make_unique<SDLEngine>(); engine->RegisterClient(*client); bool result = engine->Run(argc, argv); return result ? 0 : -1; } <commit_msg>Enable DRAW_LINES_EVERY_RENDER by default as it's generally useful during development<commit_after>#include "Base.h" #include "BiosRom.h" #include "Cartridge.h" #include "Cpu.h" #include "Debugger.h" #include "EngineClient.h" #include "MemoryBus.h" #include "MemoryMap.h" #include "Platform.h" #include "Ram.h" #include "SDLEngine.h" #include "UnmappedMemoryDevice.h" #include "Via.h" #include <memory> #include <random> class Vectrexy final : public IEngineClient { private: bool Init(int argc, char** argv) override { std::string rom = argc == 2 ? argv[1] : ""; m_cpu.Init(m_memoryBus); m_via.Init(m_memoryBus); m_ram.Init(m_memoryBus); m_biosRom.Init(m_memoryBus); m_unmapped.Init(m_memoryBus); m_cartridge.Init(m_memoryBus); m_debugger.Init(m_memoryBus, m_cpu, m_via); // Some games rely on initial random state of memory (e.g. Mine Storm) const unsigned int seed = std::random_device{}(); m_ram.Randomize(seed); m_biosRom.LoadBiosRom("bios_rom.bin"); if (!rom.empty()) m_cartridge.LoadRom(rom.c_str()); m_cpu.Reset(); return true; } bool Update(double deltaTime, const Input& input) override { if (!m_debugger.Update(deltaTime, input)) return false; return true; } void Render(double deltaTime, Display& display) override { m_elapsed += deltaTime; //@HACK: clear lines and screen at approximately 50hz if (m_elapsed >= (1.0 / 50.0)) { m_elapsed = 0; display.Clear(); for (const auto& line : m_via.m_lines) { display.DrawLine(line.p0.x, line.p0.y, line.p1.x, line.p1.y); } m_via.m_lines.clear(); } #define DRAW_LINES_EVERY_RENDER 1 /* Useful for debugging vector drawing */ #if DRAW_LINES_EVERY_RENDER for (const auto& line : m_via.m_lines) { display.DrawLine(line.p0.x, line.p0.y, line.p1.x, line.p1.y); } #endif } void Shutdown() override {} MemoryBus m_memoryBus; Cpu m_cpu; Via m_via; Ram m_ram; BiosRom m_biosRom; UnmappedMemoryDevice m_unmapped; Cartridge m_cartridge; Debugger m_debugger; double m_elapsed = 0; }; int main(int argc, char** argv) { auto client = std::make_unique<Vectrexy>(); auto engine = std::make_unique<SDLEngine>(); engine->RegisterClient(*client); bool result = engine->Run(argc, argv); return result ? 0 : -1; } <|endoftext|>
<commit_before>#include <unistd.h> #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <string> #include <iostream> #include <cstdlib> using namespace std; #define DELIMS " \r\t\n\"" #define MAX 1024 void piping(char in[],int count,int cmdnum) { unsigned pos=0; int pipefd[2]; int fd; char *str=NULL; char leftPart[MAX]; char rightPart[MAX]; for(unsigned i=0;in[i]!='|';++i) { leftPart[i]=in[i]; ++pos; } ++pos; for(unsigned i=0;in[i]!='\0';++i) { rightPart[i]=in[pos]; ++pos; } if(cmdnum!=count) { fd=pipe(pipefd); if(fd==-1) { perror("pipe"); exit(1); } } int id=fork(); if(id==0)//in child process { for(int u=0;u<2;++u) { str=strtok(leftPart,DELIMS); char* argv[MAX]; argv[0]=new char[50]; strcpy(argv[0],str); str=strtok(NULL,DELIMS); unsigned int i=0; while(str!=NULL)//tokenize and set arguments for execvp { argv[i+1]=new char[50]; strcpy(argv[i+1],str); str=strtok(NULL,DELIMS); ++i; } argv[i+1]='\0';//add null terminating character if(cmdnum==0) { if(close(1)==-1) perror("close"); if(dup(fd)==-1) perror("dup"); } else { if(close(0)==-1) perror("close"); if(dup(fd)==-1) perror("dup"); } ++cmdnum; for(unsigned o=0;rightPart[o]!='\0';++o) leftPart[o]=rightPart[o]; int pid =execvp(argv[0],argv); if(pid==-1) {//exit if execvp failed perror("execvp"); exit(1); } } } else if (id==-1) { perror("fork"); exit(1); } else { for(int u=0;u<2;++u) { if(wait(NULL)==-1) { perror("wait"); exit(1); } } } } int main() { char line[MAX]; //line is used for input char *cmd=NULL; //cmd is used for the parsed string, first parse is the cmd char user[256]; char host[256]; bool hasQuote=false; int pipeCnt=0; bool hasPipe=false; int log=getlogin_r(user,sizeof(user)-1); //login int hos=gethostname(host,sizeof(host)-1); //hostname if(log!=0) perror("getlogin"); if(hos!=0) perror("gethostname"); while(1) { //print out prompt and wait for user input cout<<user<<"@"<<host<< "$ "; fgets(line, MAX, stdin); //check for quote or comment and set null terminating accordingly for(unsigned j=0;j<MAX;++j) { if(line[j]=='\"') hasQuote=true; if(!hasQuote&&line[j]=='#') line[j]='\0'; if(line[j]=='|'||line[j]=='<'||line[j]=='>') { hasPipe=true; ++pipeCnt; } } if(hasPipe) { piping(line,pipeCnt,0); hasPipe=false; } //parse line for first cmd and see if it is exit cmd=strtok(line, DELIMS); if(strcmp(cmd,"exit")==0) exit(0); //if not exit attempt to execute cmd else { int id=fork(); if(id==0)//in child process { char* argv[MAX]; argv[0]=new char[50]; strcpy(argv[0],cmd); cmd=strtok(NULL,DELIMS); unsigned int i=0; while(cmd!=NULL) //tokenize and set arguments for execvp { argv[i+1]=new char[50]; strcpy(argv[i+1],cmd); cmd=strtok(NULL,DELIMS); ++i; } argv[i+1]='\0'; //add null terminating character int pid =execvp(argv[0],argv); if(pid==-1) //exit if execvp failed perror("execvp"); exit(1); } else if(id==-1) //exit if fork failed { perror("fork"); exit(1); } else //in parent process wait(NULL); } } return 0; } <commit_msg>first commit finished cd and ^C must change execvp to execv<commit_after>#include <unistd.h> #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <string> #include <iostream> #include <cstdlib> using namespace std; #define DELIMS " \r\t\n\"" #define MAX 1024 void piping(char in[],int count,int cmdnum) { unsigned pos=0; int pipefd[2]; int fd; char *str=NULL; char leftPart[MAX]; char rightPart[MAX]; for(unsigned i=0;in[i]!='|';++i) { leftPart[i]=in[i]; ++pos; } ++pos; for(unsigned i=0;in[i]!='\0';++i) { rightPart[i]=in[pos]; ++pos; } if(cmdnum!=count) { fd=pipe(pipefd); if(fd==-1) { perror("pipe"); exit(1); } } int id=fork(); if(id==0)//in child process { for(int u=0;u<2;++u) { str=strtok(leftPart,DELIMS); char* argv[MAX]; argv[0]=new char[50]; strcpy(argv[0],str); str=strtok(NULL,DELIMS); unsigned int i=0; while(str!=NULL)//tokenize and set arguments for execvp { argv[i+1]=new char[50]; strcpy(argv[i+1],str); str=strtok(NULL,DELIMS); ++i; } argv[i+1]='\0';//add null terminating character if(cmdnum==0) { if(close(1)==-1) perror("close"); if(dup(fd)==-1) perror("dup"); } else { if(close(0)==-1) perror("close"); } ++cmdnum; for(unsigned o=0;rightPart[o]!='\0';++o) leftPart[o]=rightPart[o]; if(leftPart[0]!='|') piping(leftPart,count,cmdnum); int pid =execvp(argv[0],argv); if(pid==-1) {//exit if execvp failed perror("execvp"); exit(1); } } } else if (id==-1) { perror("fork"); exit(1); } else { for(int u=0;u<2;++u) { if(wait(NULL)==-1) { perror("wait"); exit(1); } } } } void sig_handler(int signum) { if(signum==SIGINT) { signal(SIGINT,SIG_IGN); if(errno==-1) perror("perror"); } return; } int main() { char line[MAX]; //line is used for input char *cmd=NULL; //cmd is used for the parsed string, first parse is the cmd char user[256]; char host[256]; bool hasQuote=false; int pipeCnt=0; bool hasPipe=false; int log=getlogin_r(user,sizeof(user)-1); //login int hos=gethostname(host,sizeof(host)-1); //hostname if(log!=0) perror("getlogin"); if(hos!=0) perror("gethostname"); signal(SIGINT,sig_handler); if(errno==-1) perror("signal"); while(1) { begin: //print out prompt and wait for user input char *wd=get_current_dir_name(); if(errno==-1) perror("getenv"); cout<<endl; cout<<wd<<endl; cout<<user<<"@"<<host<< "$ "; fgets(line, MAX, stdin); //check for quote or comment and set null terminating accordingly for(unsigned j=0;j<MAX;++j) { if(line[j]=='\"') hasQuote=true; if(!hasQuote&&line[j]=='#') line[j]='\0'; if(line[j]=='|'||line[j]=='<'||line[j]=='>') { hasPipe=true; ++pipeCnt; } } if(line[0]=='\n' || line[0]=='\0') goto begin; if(hasPipe); { // piping(line,pipeCnt,0); // hasPipe=false; } //parse line for first cmd and see if it is exit cmd=strtok(line, DELIMS); if(strcmp(cmd,"exit")==0) exit(0); if(strcmp(cmd,"cd")==0) { cmd=strtok(NULL,DELIMS); chdir(cmd); if(errno==-1) perror("cd"); goto begin; } //if not exit attempt to execute cmd else { int id=fork(); if(id==0)//in child process { char* argv[MAX]; argv[0]=new char[50]; strcpy(argv[0],cmd); cmd=strtok(NULL,DELIMS); unsigned int i=0; while(cmd!=NULL) //tokenize and set arguments for execvp { argv[i+1]=new char[50]; strcpy(argv[i+1],cmd); cmd=strtok(NULL,DELIMS); ++i; } argv[i+1]='\0'; //add null terminating character int pid =execvp(argv[0],argv); if(pid==-1) //exit if execvp failed perror("execvp"); exit(1); } else if(id==-1) //exit if fork failed { perror("fork"); exit(1); } else //in parent process wait(NULL); if(errno==-1) perror("wait"); } } return 0; } <|endoftext|>
<commit_before>#include "serialutil.h" #include "usbutil.h" #include "ethernetutil.h" #include "listener.h" #include "signals.h" #include "log.h" #include <stdlib.h> #define VERSION_CONTROL_COMMAND 0x80 #define RESET_CONTROL_COMMAND 0x81 // USB #define DATA_IN_ENDPOINT 1 #define DATA_OUT_ENDPOINT 2 extern void reset(); extern void setup(); extern void loop(); const char* VERSION = "2.0"; SerialDevice SERIAL_DEVICE; EthernetDevice ETHERNET_DEVICE; UsbDevice USB_DEVICE = { DATA_IN_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES, DATA_OUT_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES}; Listener listener = {&USB_DEVICE, #ifndef NO_UART &SERIAL_DEVICE, #else NULL, #endif // NO_UART #ifndef NO_ETHERNET &ETHERNET_DEVICE #endif // NO_ETHERNET }; int main(void) { #ifdef __PIC32__ init(); #endif // __PIC32__ initializeLogging(); initializeUsb(listener.usb); initializeSerial(listener.serial); initializeEthernet(listener.ethernet); debug("Initializing as a CAN "); #ifdef TRANSMITTER debug("transmitter\r\n"); #else #ifdef CAN_EMULATOR debug("emulator\r\n"); #else debug("translator\r\n"); #endif // TRANSMITTER #endif setup(); for (;;) { loop(); processListenerQueues(&listener); } return 0; } #ifdef __cplusplus extern "C" { #endif bool handleControlRequest(uint8_t request) { switch(request) { case VERSION_CONTROL_COMMAND: { char* combinedVersion = (char*)malloc(strlen(VERSION) + strlen(getMessageSet()) + 4); sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet()); debug("Version: %s\r\n", combinedVersion); sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion)); free(combinedVersion); return true; } case RESET_CONTROL_COMMAND: debug("Resetting...\r\n"); reset(); return true; default: return false; } } #ifdef __cplusplus } #endif <commit_msg>Use message set in initialize logging instead of hard coded strings.<commit_after>#include "serialutil.h" #include "usbutil.h" #include "ethernetutil.h" #include "listener.h" #include "signals.h" #include "log.h" #include <stdlib.h> #define VERSION_CONTROL_COMMAND 0x80 #define RESET_CONTROL_COMMAND 0x81 // USB #define DATA_IN_ENDPOINT 1 #define DATA_OUT_ENDPOINT 2 extern void reset(); extern void setup(); extern void loop(); const char* VERSION = "2.0"; SerialDevice SERIAL_DEVICE; EthernetDevice ETHERNET_DEVICE; UsbDevice USB_DEVICE = { DATA_IN_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES, DATA_OUT_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES}; Listener listener = {&USB_DEVICE, #ifndef NO_UART &SERIAL_DEVICE, #else NULL, #endif // NO_UART #ifndef NO_ETHERNET &ETHERNET_DEVICE #endif // NO_ETHERNET }; int main(void) { #ifdef __PIC32__ init(); #endif // __PIC32__ initializeLogging(); initializeUsb(listener.usb); initializeSerial(listener.serial); initializeEthernet(listener.ethernet); debug("Initializing as %s\r\n", getMessageSet()); setup(); for (;;) { loop(); processListenerQueues(&listener); } return 0; } #ifdef __cplusplus extern "C" { #endif bool handleControlRequest(uint8_t request) { switch(request) { case VERSION_CONTROL_COMMAND: { char* combinedVersion = (char*)malloc(strlen(VERSION) + strlen(getMessageSet()) + 4); sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet()); debug("Version: %s\r\n", combinedVersion); sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion)); free(combinedVersion); return true; } case RESET_CONTROL_COMMAND: debug("Resetting...\r\n"); reset(); return true; default: return false; } } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Andreas Pohl * Licensed under MIT (see COPYING) * * Author: Andreas Pohl */ #include "log.h" #include "options.h" #include "server.h" #include "server_impl.h" void sig_handler(petrel::server& s, const petrel::bs::error_code& ec, int signal_number) { if (!ec) { set_log_tag("main"); log_info("Received signal " << signal_number); s.impl()->stop(); } } int main(int argc, const char** argv) { // Parse command line if (!petrel::options::parse(argc, argv)) { return 1; } if (petrel::options::opts.count("help")) { std::cout << "petrel version: petrel/" << PETREL_VERSION << std::endl << "Usage: " << argv[0] << " <options>" << std::endl << petrel::options::desc << std::endl; return 0; } if (petrel::options::opts.count("version")) { std::cout << "petrel version: petrel/" << PETREL_VERSION << std::endl; return 0; } if (petrel::options::opts.count("test")) { std::cout << "Config OK" << std::endl; return 0; } petrel::log::init(petrel::options::opts.count("log.syslog"), petrel::options::opts["log.level"].as<int>()); try { petrel::server s; petrel::ba::io_service iosvc; petrel::ba::signal_set signals(iosvc, SIGINT, SIGTERM); signals.async_wait(std::bind(sig_handler, std::ref(s), std::placeholders::_1, std::placeholders::_2)); s.impl()->init(); s.impl()->start(); iosvc.run(); // wait for a signal to stop s.impl()->join(); } catch (std::exception& e) { set_log_tag("main"); log_emerg(e.what()); return 1; } return 0; } <commit_msg>Added google profiler support<commit_after>/* * Copyright (c) 2016 Andreas Pohl * Licensed under MIT (see COPYING) * * Author: Andreas Pohl */ #include "log.h" #include "options.h" #include "server.h" #include "server_impl.h" #ifndef PETREL_VERSION #define PETREL_VERSION 0 #endif #ifdef GOOGLE_PROFILER #include <gperftools/profiler.h> #endif void sig_handler(petrel::server& s, const petrel::bs::error_code& ec, int signal_number) { if (!ec) { set_log_tag("main"); log_info("Received signal " << signal_number); s.impl()->stop(); } } int main(int argc, const char** argv) { // Parse command line if (!petrel::options::parse(argc, argv)) { return 1; } if (petrel::options::opts.count("help")) { std::cout << "petrel version: petrel/" << PETREL_VERSION << std::endl << "Usage: " << argv[0] << " <options>" << std::endl << petrel::options::desc << std::endl; return 0; } if (petrel::options::opts.count("version")) { std::cout << "petrel version: petrel/" << PETREL_VERSION << std::endl; return 0; } if (petrel::options::opts.count("test")) { std::cout << "Config OK" << std::endl; return 0; } petrel::log::init(petrel::options::opts.count("log.syslog"), petrel::options::opts["log.level"].as<int>()); #ifdef GOOGLE_PROFILER ProfilerStart("petrel.prof"); #endif try { petrel::server s; petrel::ba::io_service iosvc; petrel::ba::signal_set signals(iosvc, SIGINT, SIGTERM); signals.async_wait(std::bind(sig_handler, std::ref(s), std::placeholders::_1, std::placeholders::_2)); s.impl()->init(); s.impl()->start(); iosvc.run(); // wait for a signal to stop s.impl()->join(); } catch (std::exception& e) { set_log_tag("main"); log_emerg(e.what()); return 1; } #ifdef GOOGLE_PROFILER ProfilerStop(); #endif return 0; } <|endoftext|>
<commit_before> #ifndef __LIBPYTHON_HPP__ #define __LIBPYTHON_HPP__ #include <string> #define _PYTHON_API_VERSION 1013 #if _WIN32 || _WIN64 #if _WIN64 typedef __int64 Py_ssize_t; #else typedef int Py_ssize_t; #endif #else typedef long Py_ssize_t; #endif typedef struct _object PyObject; #define METH_VARARGS 0x0001 #define METH_KEYWORDS 0x0002 typedef PyObject *(*_PyCFunction)(PyObject *, PyObject *); struct _PyMethodDef { const char *ml_name; /* The name of the built-in function/method */ _PyCFunction ml_meth; /* The C function that implements it */ int ml_flags; /* Combination of METH_xxx flags, which mostly describe the args expected by the C func */ const char *ml_doc; /* The __doc__ attribute, or NULL */ }; typedef struct _PyMethodDef _PyMethodDef; extern void (*_Py_Initialize)(); extern PyObject* (*_Py_InitModule4)(const char *name, _PyMethodDef *methods, const char *doc, PyObject *self, int apiver); extern void (*_Py_IncRef)(PyObject *); extern void (*_Py_DecRef)(PyObject *); extern PyObject* (*__PyObject_Str)(PyObject *); extern PyObject* (*_PyObject_Dir)(PyObject *); extern PyObject* (*_PyObject_GetAttrString)(PyObject*, const char *); extern int (*_PyObject_HasAttrString)(PyObject*, const char *); extern Py_ssize_t (*_PyTuple_Size)(PyObject *); extern PyObject* (*_PyTuple_GetItem)(PyObject *, Py_ssize_t); extern PyObject* (*_PyList_New)(Py_ssize_t size); extern Py_ssize_t (*_PyList_Size)(PyObject *); extern PyObject* (*_PyList_GetItem)(PyObject *, Py_ssize_t); extern int (*_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *); extern int (*_PyString_AsStringAndSize)( register PyObject *obj, /* string or Unicode object */ register char **s, /* pointer to buffer variable */ register Py_ssize_t *len /* pointer to length variable or NULL (only possible for 0-terminated strings) */ ); extern PyObject* (*_PyString_FromString)(const char *); extern PyObject* (*_PyString_FromStringAndSize)(const char *, Py_ssize_t); extern void (*_PyErr_Fetch)(PyObject **, PyObject **, PyObject **); extern PyObject* (*_PyErr_Occurred)(void); extern void (*_PyErr_NormalizeException)(PyObject**, PyObject**, PyObject**); extern int (*_PyCallable_Check)(PyObject *); extern PyObject* (*_PyModule_GetDict)(PyObject *); extern PyObject* (*_PyImport_AddModule)(const char *); extern PyObject* (*_PyRun_StringFlags)(const char *, int, PyObject*, PyObject*, void*); extern int (*_PyRun_SimpleFileExFlags)(FILE *, const char *, int, void *); extern PyObject* (*_PyObject_GetIter)(PyObject *); extern PyObject* (*_PyIter_Next)(PyObject *); extern void (*_PySys_SetArgv)(int, char **); typedef void (*_PyCapsule_Destructor)(PyObject *); extern PyObject* (*_PyCapsule_New)(void *pointer, const char *name, _PyCapsule_Destructor destructor); extern void* (*_PyCapsule_GetPointer)(PyObject *capsule, const char *name); class LibPython { public: LibPython() : pLib_(NULL) {} bool load(const std::string& libPath, bool python3, std::string* pError); bool unload(std::string* pError); private: LibPython(const LibPython&); void* pLib_; }; #endif <commit_msg>import more declarations<commit_after> #ifndef __LIBPYTHON_HPP__ #define __LIBPYTHON_HPP__ #include <string> #define _PYTHON_API_VERSION 1013 #if _WIN32 || _WIN64 #if _WIN64 typedef __int64 Py_ssize_t; #else typedef int Py_ssize_t; #endif #else typedef long Py_ssize_t; #endif typedef struct _object PyObject; #define METH_VARARGS 0x0001 #define METH_KEYWORDS 0x0002 #define __PyObject_HEAD_EXTRA #define __PyObject_EXTRA_INIT /* PyObject_HEAD defines the initial segment of every PyObject. */ #define _PyObject_HEAD \ __PyObject_HEAD_EXTRA \ Py_ssize_t ob_refcnt; \ struct __typeobject *ob_type; #define _PyObject_VAR_HEAD \ _PyObject_HEAD \ Py_ssize_t ob_size; /* Number of items in variable part */ typedef struct __typeobject { _PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "<module>.<name>" */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ } _PyTypeObject; typedef struct __object { _PyObject_HEAD } _PyObject; typedef struct { _PyObject_VAR_HEAD } _PyVarObject; typedef _PyObject *(*_PyCFunction)(PyObject *, PyObject *); struct _PyMethodDef { // Is the same for Python 3.4 and 2.7 const char *ml_name; /* The name of the built-in function/method */ _PyCFunction ml_meth; /* The C function that implements it */ int ml_flags; /* Combination of METH_xxx flags, which mostly describe the args expected by the C func */ const char *ml_doc; /* The __doc__ attribute, or NULL */ }; typedef struct _PyMethodDef _PyMethodDef; // For Python 3 we need different initialization macros #define _PyObject_HEAD3 _PyObject ob_base; #define _PyObject_HEAD_INIT(type) \ { __PyObject_EXTRA_INIT \ 1, type }, #define _PyModuleDef_HEAD_INIT { \ _PyObject_HEAD_INIT(NULL) \ NULL, /* m_init */ \ 0, /* m_index */ \ NULL, /* m_copy */ \ } typedef int (*_inquiry)(PyObject *); typedef int (*_visitproc)(PyObject *, void *); typedef int (*_traverseproc)(PyObject *, _visitproc, void *); typedef void (*_freefunc)(void *); typedef struct _PyModuleDef_Base { _PyObject_HEAD3 _PyObject* (*m_init)(void); Py_ssize_t m_index; _PyObject* m_copy; } _PyModuleDef_Base; typedef struct _PyModuleDef{ _PyModuleDef_Base m_base; const char* m_name; const char* m_doc; Py_ssize_t m_size; _PyMethodDef *m_methods; _inquiry m_reload; _traverseproc m_traverse; _inquiry m_clear; _freefunc m_free; } _PyModuleDef; extern void (*_Py_Initialize)(); extern PyObject* (*_Py_InitModule4)(const char *name, _PyMethodDef *methods, const char *doc, PyObject *self, int apiver); extern void (*_Py_IncRef)(PyObject *); extern void (*_Py_DecRef)(PyObject *); extern PyObject* (*__PyObject_Str)(PyObject *); extern PyObject* (*_PyObject_Dir)(PyObject *); extern PyObject* (*_PyObject_GetAttrString)(PyObject*, const char *); extern int (*_PyObject_HasAttrString)(PyObject*, const char *); extern Py_ssize_t (*_PyTuple_Size)(PyObject *); extern PyObject* (*_PyTuple_GetItem)(PyObject *, Py_ssize_t); extern PyObject* (*_PyList_New)(Py_ssize_t size); extern Py_ssize_t (*_PyList_Size)(PyObject *); extern PyObject* (*_PyList_GetItem)(PyObject *, Py_ssize_t); extern int (*_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *); extern int (*_PyString_AsStringAndSize)( register PyObject *obj, /* string or Unicode object */ register char **s, /* pointer to buffer variable */ register Py_ssize_t *len /* pointer to length variable or NULL (only possible for 0-terminated strings) */ ); extern PyObject* (*_PyString_FromString)(const char *); extern PyObject* (*_PyString_FromStringAndSize)(const char *, Py_ssize_t); extern void (*_PyErr_Fetch)(PyObject **, PyObject **, PyObject **); extern PyObject* (*_PyErr_Occurred)(void); extern void (*_PyErr_NormalizeException)(PyObject**, PyObject**, PyObject**); extern int (*_PyCallable_Check)(PyObject *); extern PyObject* (*_PyModule_GetDict)(PyObject *); extern PyObject* (*_PyImport_AddModule)(const char *); extern PyObject* (*_PyRun_StringFlags)(const char *, int, PyObject*, PyObject*, void*); extern int (*_PyRun_SimpleFileExFlags)(FILE *, const char *, int, void *); extern PyObject* (*_PyObject_GetIter)(PyObject *); extern PyObject* (*_PyIter_Next)(PyObject *); extern void (*_PySys_SetArgv)(int, char **); typedef void (*_PyCapsule_Destructor)(PyObject *); extern PyObject* (*_PyCapsule_New)(void *pointer, const char *name, _PyCapsule_Destructor destructor); extern void* (*_PyCapsule_GetPointer)(PyObject *capsule, const char *name); class LibPython { public: LibPython() : pLib_(NULL) {} bool load(const std::string& libPath, bool python3, std::string* pError); bool unload(std::string* pError); private: LibPython(const LibPython&); void* pLib_; }; #endif <|endoftext|>
<commit_before>#include <sys/errno.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <common/buffer.h> #include <common/endian.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/socket.h> struct socket_address { union address_union { struct sockaddr sockaddr_; struct sockaddr_in inet_; struct sockaddr_in6 inet6_; struct sockaddr_un unix_; operator std::string (void) const { /* XXX getnameinfo(3); */ char address[256]; /* XXX*/ const char *p; std::ostringstream str; switch (sockaddr_.sa_family) { case AF_INET: p = ::inet_ntop(inet_.sin_family, &inet_.sin_addr, address, sizeof address); ASSERT(p != NULL); str << '[' << address << ']' << ':' << ntohs(inet_.sin_port); break; case AF_INET6: p = ::inet_ntop(inet6_.sin6_family, &inet6_.sin6_addr, address, sizeof address); ASSERT(p != NULL); str << '[' << address << ']' << ':' << ntohs(inet6_.sin6_port); break; default: return ("<unsupported-address-family>"); } return (str.str()); } } addr_; size_t addrlen_; socket_address(void) : addr_(), addrlen_(0) { memset(&addr_, 0, sizeof addr_); } bool operator() (int domain, int socktype, int protocol, const std::string& str) { switch (domain) { case AF_UNSPEC: case AF_INET6: case AF_INET: { std::string::size_type pos = str.find(']'); if (pos == std::string::npos) return (false); if (pos < 3 || str[0] != '[' || str[pos + 1] != ':') return (false); std::string name(str, 1, pos - 1); std::string service(str, pos + 2); struct addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = domain; hints.ai_socktype = socktype; hints.ai_protocol = protocol; /* * Mac OS X ~Snow Leopard~ cannot handle a service name * of "0" where older Mac OS X could. Don't know if * that is because it's not in services(5) or due to * some attempt at input validation. So work around it * here, sigh. */ const char *servptr; if (service == "" || service == "0") servptr = NULL; else servptr = service.c_str(); struct addrinfo *ai; int rv = getaddrinfo(name.c_str(), servptr, &hints, &ai); if (rv != 0) { ERROR("/socket/address") << "Could not look up " << str << ": " << gai_strerror(rv); return (false); } /* * Just use the first one. * XXX Will we ever get one in the wrong family? Is the hint mandatory? */ memcpy(&addr_.sockaddr_, ai->ai_addr, ai->ai_addrlen); addrlen_ = ai->ai_addrlen; freeaddrinfo(ai); break; } case AF_UNIX: addr_.unix_.sun_family = domain; strncpy(addr_.unix_.sun_path, str.c_str(), sizeof addr_.unix_.sun_path); addrlen_ = sizeof addr_.unix_; #if !defined(__linux__) && !defined(__sun__) addr_.unix_.sun_len = addrlen_; #endif break; default: ERROR("/socket/address") << "Addresss family not supported: " << domain; return (false); } return (true); } }; Socket::Socket(int fd, int domain, int socktype, int protocol) : FileDescriptor(fd), log_("/socket"), domain_(domain), socktype_(socktype), protocol_(protocol), accept_action_(NULL), accept_callback_(NULL), connect_callback_(NULL), connect_action_(NULL) { ASSERT(fd_ != -1); } Socket::~Socket() { ASSERT(accept_action_ == NULL); ASSERT(accept_callback_ == NULL); ASSERT(connect_callback_ == NULL); ASSERT(connect_action_ == NULL); } Action * Socket::accept(EventCallback *cb) { ASSERT(accept_action_ == NULL); ASSERT(accept_callback_ == NULL); accept_callback_ = cb; accept_action_ = accept_schedule(); return (cancellation(this, &Socket::accept_cancel)); } bool Socket::bind(const std::string& name) { socket_address addr; if (!addr(domain_, socktype_, protocol_, name)) { ERROR(log_) << "Invalid name for bind: " << name; return (false); } int rv = ::bind(fd_, &addr.addr_.sockaddr_, addr.addrlen_); if (rv == -1) return (false); return (true); } Action * Socket::connect(const std::string& name, EventCallback *cb) { ASSERT(connect_callback_ == NULL); ASSERT(connect_action_ == NULL); socket_address addr; if (!addr(domain_, socktype_, protocol_, name)) { ERROR(log_) << "Invalid name for connect: " << name; cb->event(Event(Event::Error, EINVAL)); return (EventSystem::instance()->schedule(cb)); } /* * TODO * * If the address we are connecting to is the address of another * Socket, set up some sort of zero-copy IO between them. This is * easy enough if we do it right here. Trying to do it at the file * descriptor level seems to be really hard since there's a lot of * races possible there. This way, we're still at the point of the * connection set up. * * We may want to allow the connection to complete so that calls to * getsockname(2) and getpeername(2) do what you'd expect. We may * still want to poll on the file descriptors even, to make it * possible to use tcpdrop, etc., to reset the connections. I guess * the thing to do is poll if there's no input ready. */ int rv = ::connect(fd_, &addr.addr_.sockaddr_, addr.addrlen_); switch (rv) { case 0: cb->event(Event(Event::Done, 0)); connect_action_ = EventSystem::instance()->schedule(cb); break; case -1: switch (errno) { case EINPROGRESS: connect_callback_ = cb; connect_action_ = connect_schedule(); break; default: cb->event(Event(Event::Error, errno)); connect_action_ = EventSystem::instance()->schedule(cb); break; } break; default: HALT(log_) << "Connect returned unexpected value: " << rv; } return (cancellation(this, &Socket::connect_cancel)); } bool Socket::listen(int backlog) { int rv = ::listen(fd_, backlog); if (rv == -1) return (false); return (true); } std::string Socket::getpeername(void) const { socket_address::address_union un; socklen_t len; int rv; len = sizeof un; rv = ::getpeername(fd_, &un.sockaddr_, &len); if (rv == -1) return ("<unknown>"); /* XXX Check len. */ return ((std::string)un); } std::string Socket::getsockname(void) const { socket_address::address_union un; socklen_t len; int rv; len = sizeof un; rv = ::getsockname(fd_, &un.sockaddr_, &len); if (rv == -1) return ("<unknown>"); /* XXX Check len. */ return ((std::string)un); } void Socket::accept_callback(Event e) { accept_action_->cancel(); accept_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::EOS: case Event::Error: accept_callback_->event(Event(Event::Error, e.error_)); accept_action_ = EventSystem::instance()->schedule(accept_callback_); accept_callback_ = NULL; return; default: HALT(log_) << "Unexpected event: " << e; } int s = ::accept(fd_, NULL, NULL); if (s == -1) { switch (errno) { case EAGAIN: accept_action_ = accept_schedule(); return; default: accept_callback_->event(Event(Event::Error, errno)); accept_action_ = EventSystem::instance()->schedule(accept_callback_); accept_callback_ = NULL; return; } } Socket *child = new Socket(s, domain_, socktype_, protocol_); accept_callback_->event(Event(Event::Done, 0, (void *)child)); Action *a = EventSystem::instance()->schedule(accept_callback_); accept_action_ = a; accept_callback_ = NULL; } void Socket::accept_cancel(void) { ASSERT(accept_action_ != NULL); accept_action_->cancel(); accept_action_ = NULL; if (accept_callback_ != NULL) { delete accept_callback_; accept_callback_ = NULL; } } Action * Socket::accept_schedule(void) { EventCallback *cb = callback(this, &Socket::accept_callback); Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb); return (a); } void Socket::connect_callback(Event e) { connect_action_->cancel(); connect_action_ = NULL; switch (e.type_) { case Event::Done: connect_callback_->event(Event(Event::Done, 0)); break; case Event::EOS: case Event::Error: connect_callback_->event(Event(Event::Error, e.error_)); break; default: HALT(log_) << "Unexpected event: " << e; } Action *a = EventSystem::instance()->schedule(connect_callback_); connect_action_ = a; connect_callback_ = NULL; } void Socket::connect_cancel(void) { ASSERT(connect_action_ != NULL); connect_action_->cancel(); connect_action_ = NULL; if (connect_callback_ != NULL) { delete connect_callback_; connect_callback_ = NULL; } } Action * Socket::connect_schedule(void) { EventCallback *cb = callback(this, &Socket::connect_callback); Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb); return (a); } Socket * Socket::create(SocketAddressFamily family, SocketType type, const std::string& protocol, const std::string& hint) { int typenum; switch (type) { case SocketTypeStream: typenum = SOCK_STREAM; break; case SocketTypeDatagram: typenum = SOCK_DGRAM; break; default: ERROR("/socket") << "Unsupported socket type."; return (NULL); } int protonum; if (protocol == "") { protonum = 0; } else { struct protoent *proto = getprotobyname(protocol.c_str()); if (proto == NULL) { ERROR("/socket") << "Invalid protocol: " << protocol; return (NULL); } protonum = proto->p_proto; } int domainnum; switch (family) { case SocketAddressFamilyIP: if (hint == "") { ERROR("/socket") << "Must specify hint address for IP sockets or specify IPv4 or IPv6 explicitly."; return (NULL); } else { socket_address addr; if (!addr(AF_UNSPEC, typenum, protonum, hint)) { ERROR("/socket") << "Invalid hint: " << hint; return (NULL); } /* XXX Just make socket_address::operator() smarter about AF_UNSPEC? */ switch (addr.addr_.sockaddr_.sa_family) { case AF_INET: domainnum = AF_INET; break; case AF_INET6: domainnum = AF_INET6; break; default: ERROR("/socket") << "Unsupported address family for hint: " << hint; return (NULL); } break; } case SocketAddressFamilyIPv4: domainnum = AF_INET; break; case SocketAddressFamilyIPv6: domainnum = AF_INET6; break; case SocketAddressFamilyUnix: domainnum = AF_UNIX; break; default: ERROR("/socket") << "Unsupported address family."; return (NULL); } int s = ::socket(domainnum, typenum, protonum); if (s == -1) { /* * If we were trying to create an IPv6 socket for a request that * did not specify IPv4 vs. IPv6 and the system claims that the * protocol is not supported, try explicitly creating an IPv4 * socket. */ if (errno == EPROTONOSUPPORT && domainnum == AF_INET6 && family == SocketAddressFamilyIP) { DEBUG("/socket") << "IPv6 socket create failed; trying IPv4."; return (Socket::create(SocketAddressFamilyIPv4, type, protocol, hint)); } ERROR("/socket") << "Could not create socket: " << strerror(errno); return (NULL); } return (new Socket(s, domainnum, typenum, protonum)); } <commit_msg>Hide IPv6 support if even AF_INET6 is undefined!<commit_after>#include <sys/errno.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <common/buffer.h> #include <common/endian.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/socket.h> /* * XXX Presently using AF_INET6 as the test for what is supported, but that is * wrong in many, many ways. */ struct socket_address { union address_union { struct sockaddr sockaddr_; struct sockaddr_in inet_; #if defined(AF_INET6) struct sockaddr_in6 inet6_; #endif struct sockaddr_un unix_; operator std::string (void) const { /* XXX getnameinfo(3); */ char address[256]; /* XXX*/ const char *p; std::ostringstream str; switch (sockaddr_.sa_family) { case AF_INET: p = ::inet_ntop(inet_.sin_family, &inet_.sin_addr, address, sizeof address); ASSERT(p != NULL); str << '[' << address << ']' << ':' << ntohs(inet_.sin_port); break; #if defined(AF_INET6) case AF_INET6: p = ::inet_ntop(inet6_.sin6_family, &inet6_.sin6_addr, address, sizeof address); ASSERT(p != NULL); str << '[' << address << ']' << ':' << ntohs(inet6_.sin6_port); break; #endif default: return ("<unsupported-address-family>"); } return (str.str()); } } addr_; size_t addrlen_; socket_address(void) : addr_(), addrlen_(0) { memset(&addr_, 0, sizeof addr_); } bool operator() (int domain, int socktype, int protocol, const std::string& str) { switch (domain) { #if defined(AF_INET6) case AF_UNSPEC: case AF_INET6: #endif case AF_INET: { std::string::size_type pos = str.find(']'); if (pos == std::string::npos) return (false); if (pos < 3 || str[0] != '[' || str[pos + 1] != ':') return (false); std::string name(str, 1, pos - 1); std::string service(str, pos + 2); struct addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = domain; hints.ai_socktype = socktype; hints.ai_protocol = protocol; /* * Mac OS X ~Snow Leopard~ cannot handle a service name * of "0" where older Mac OS X could. Don't know if * that is because it's not in services(5) or due to * some attempt at input validation. So work around it * here, sigh. */ const char *servptr; if (service == "" || service == "0") servptr = NULL; else servptr = service.c_str(); struct addrinfo *ai; int rv = getaddrinfo(name.c_str(), servptr, &hints, &ai); if (rv != 0) { ERROR("/socket/address") << "Could not look up " << str << ": " << gai_strerror(rv); return (false); } /* * Just use the first one. * XXX Will we ever get one in the wrong family? Is the hint mandatory? */ memcpy(&addr_.sockaddr_, ai->ai_addr, ai->ai_addrlen); addrlen_ = ai->ai_addrlen; freeaddrinfo(ai); break; } case AF_UNIX: addr_.unix_.sun_family = domain; strncpy(addr_.unix_.sun_path, str.c_str(), sizeof addr_.unix_.sun_path); addrlen_ = sizeof addr_.unix_; #if !defined(__linux__) && !defined(__sun__) && !defined(__OPENNT) addr_.unix_.sun_len = addrlen_; #endif break; default: ERROR("/socket/address") << "Addresss family not supported: " << domain; return (false); } return (true); } }; Socket::Socket(int fd, int domain, int socktype, int protocol) : FileDescriptor(fd), log_("/socket"), domain_(domain), socktype_(socktype), protocol_(protocol), accept_action_(NULL), accept_callback_(NULL), connect_callback_(NULL), connect_action_(NULL) { ASSERT(fd_ != -1); } Socket::~Socket() { ASSERT(accept_action_ == NULL); ASSERT(accept_callback_ == NULL); ASSERT(connect_callback_ == NULL); ASSERT(connect_action_ == NULL); } Action * Socket::accept(EventCallback *cb) { ASSERT(accept_action_ == NULL); ASSERT(accept_callback_ == NULL); accept_callback_ = cb; accept_action_ = accept_schedule(); return (cancellation(this, &Socket::accept_cancel)); } bool Socket::bind(const std::string& name) { socket_address addr; if (!addr(domain_, socktype_, protocol_, name)) { ERROR(log_) << "Invalid name for bind: " << name; return (false); } int rv = ::bind(fd_, &addr.addr_.sockaddr_, addr.addrlen_); if (rv == -1) return (false); return (true); } Action * Socket::connect(const std::string& name, EventCallback *cb) { ASSERT(connect_callback_ == NULL); ASSERT(connect_action_ == NULL); socket_address addr; if (!addr(domain_, socktype_, protocol_, name)) { ERROR(log_) << "Invalid name for connect: " << name; cb->event(Event(Event::Error, EINVAL)); return (EventSystem::instance()->schedule(cb)); } /* * TODO * * If the address we are connecting to is the address of another * Socket, set up some sort of zero-copy IO between them. This is * easy enough if we do it right here. Trying to do it at the file * descriptor level seems to be really hard since there's a lot of * races possible there. This way, we're still at the point of the * connection set up. * * We may want to allow the connection to complete so that calls to * getsockname(2) and getpeername(2) do what you'd expect. We may * still want to poll on the file descriptors even, to make it * possible to use tcpdrop, etc., to reset the connections. I guess * the thing to do is poll if there's no input ready. */ int rv = ::connect(fd_, &addr.addr_.sockaddr_, addr.addrlen_); switch (rv) { case 0: cb->event(Event(Event::Done, 0)); connect_action_ = EventSystem::instance()->schedule(cb); break; case -1: switch (errno) { case EINPROGRESS: connect_callback_ = cb; connect_action_ = connect_schedule(); break; default: cb->event(Event(Event::Error, errno)); connect_action_ = EventSystem::instance()->schedule(cb); break; } break; default: HALT(log_) << "Connect returned unexpected value: " << rv; } return (cancellation(this, &Socket::connect_cancel)); } bool Socket::listen(int backlog) { int rv = ::listen(fd_, backlog); if (rv == -1) return (false); return (true); } std::string Socket::getpeername(void) const { socket_address::address_union un; socklen_t len; int rv; len = sizeof un; rv = ::getpeername(fd_, &un.sockaddr_, &len); if (rv == -1) return ("<unknown>"); /* XXX Check len. */ return ((std::string)un); } std::string Socket::getsockname(void) const { socket_address::address_union un; socklen_t len; int rv; len = sizeof un; rv = ::getsockname(fd_, &un.sockaddr_, &len); if (rv == -1) return ("<unknown>"); /* XXX Check len. */ return ((std::string)un); } void Socket::accept_callback(Event e) { accept_action_->cancel(); accept_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::EOS: case Event::Error: accept_callback_->event(Event(Event::Error, e.error_)); accept_action_ = EventSystem::instance()->schedule(accept_callback_); accept_callback_ = NULL; return; default: HALT(log_) << "Unexpected event: " << e; } int s = ::accept(fd_, NULL, NULL); if (s == -1) { switch (errno) { case EAGAIN: accept_action_ = accept_schedule(); return; default: accept_callback_->event(Event(Event::Error, errno)); accept_action_ = EventSystem::instance()->schedule(accept_callback_); accept_callback_ = NULL; return; } } Socket *child = new Socket(s, domain_, socktype_, protocol_); accept_callback_->event(Event(Event::Done, 0, (void *)child)); Action *a = EventSystem::instance()->schedule(accept_callback_); accept_action_ = a; accept_callback_ = NULL; } void Socket::accept_cancel(void) { ASSERT(accept_action_ != NULL); accept_action_->cancel(); accept_action_ = NULL; if (accept_callback_ != NULL) { delete accept_callback_; accept_callback_ = NULL; } } Action * Socket::accept_schedule(void) { EventCallback *cb = callback(this, &Socket::accept_callback); Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb); return (a); } void Socket::connect_callback(Event e) { connect_action_->cancel(); connect_action_ = NULL; switch (e.type_) { case Event::Done: connect_callback_->event(Event(Event::Done, 0)); break; case Event::EOS: case Event::Error: connect_callback_->event(Event(Event::Error, e.error_)); break; default: HALT(log_) << "Unexpected event: " << e; } Action *a = EventSystem::instance()->schedule(connect_callback_); connect_action_ = a; connect_callback_ = NULL; } void Socket::connect_cancel(void) { ASSERT(connect_action_ != NULL); connect_action_->cancel(); connect_action_ = NULL; if (connect_callback_ != NULL) { delete connect_callback_; connect_callback_ = NULL; } } Action * Socket::connect_schedule(void) { EventCallback *cb = callback(this, &Socket::connect_callback); Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb); return (a); } Socket * Socket::create(SocketAddressFamily family, SocketType type, const std::string& protocol, const std::string& hint) { int typenum; switch (type) { case SocketTypeStream: typenum = SOCK_STREAM; break; case SocketTypeDatagram: typenum = SOCK_DGRAM; break; default: ERROR("/socket") << "Unsupported socket type."; return (NULL); } int protonum; if (protocol == "") { protonum = 0; } else { struct protoent *proto = getprotobyname(protocol.c_str()); if (proto == NULL) { ERROR("/socket") << "Invalid protocol: " << protocol; return (NULL); } protonum = proto->p_proto; } int domainnum; switch (family) { case SocketAddressFamilyIP: #if defined(AF_INET6) if (hint == "") { ERROR("/socket") << "Must specify hint address for IP sockets or specify IPv4 or IPv6 explicitly."; return (NULL); } else { socket_address addr; if (!addr(AF_UNSPEC, typenum, protonum, hint)) { ERROR("/socket") << "Invalid hint: " << hint; return (NULL); } /* XXX Just make socket_address::operator() smarter about AF_UNSPEC? */ switch (addr.addr_.sockaddr_.sa_family) { case AF_INET: domainnum = AF_INET; break; case AF_INET6: domainnum = AF_INET6; break; default: ERROR("/socket") << "Unsupported address family for hint: " << hint; return (NULL); } break; } #else (void)hint; domainnum = AF_INET; break; #endif case SocketAddressFamilyIPv4: domainnum = AF_INET; break; #if defined(AF_INET6) case SocketAddressFamilyIPv6: domainnum = AF_INET6; break; #endif case SocketAddressFamilyUnix: domainnum = AF_UNIX; break; default: ERROR("/socket") << "Unsupported address family."; return (NULL); } int s = ::socket(domainnum, typenum, protonum); if (s == -1) { #if defined(AF_INET6) /* * If we were trying to create an IPv6 socket for a request that * did not specify IPv4 vs. IPv6 and the system claims that the * protocol is not supported, try explicitly creating an IPv4 * socket. */ if (errno == EPROTONOSUPPORT && domainnum == AF_INET6 && family == SocketAddressFamilyIP) { DEBUG("/socket") << "IPv6 socket create failed; trying IPv4."; return (Socket::create(SocketAddressFamilyIPv4, type, protocol, hint)); } #endif ERROR("/socket") << "Could not create socket: " << strerror(errno); return (NULL); } return (new Socket(s, domainnum, typenum, protonum)); } <|endoftext|>
<commit_before>/* * PartsBasedDetectorOnVideo * * * Huge chunks of code shamelessly taken from Hilton Bristow's demo for * PartsBasedDetector. * * Software License Agreement (BSD License) * * Copyright (c) 2013, Chili lab, EPFL. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Chili, EPFL nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * File: main.h * Author: Mirko Raca <name.lastname@epfl.ch> * Created: November 5, 2013 */ #include "globalIncludes.h" #include <boost/filesystem.hpp> #include <time.h> #include <stdio.h> #include <fstream> #include <ncurses.h> #include <opencv2/highgui/highgui.hpp> #include <PartsBasedDetector.hpp> #include <Candidate.hpp> #include <FileStorageModel.hpp> #define WITH_MATLABIO #ifdef WITH_MATLABIO #include <MatlabIOModel.hpp> #endif #include "outputFormat.h" #include "mirrorUtils.h" using namespace cv; using namespace std; #define OUTPUT_FILENAME_FORMAT "facedetect_frame%06d.txt" #define DEFAULT_NMS_THRESHOLD 0.3f #define DEFAULT_MIRRORING false #define DEFAULT_RESUME false void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder); void updateDisplay(int _frame, float _perc, double _time); int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); DLOG(INFO) << "Execution started"; if (argc < 4) { printf("Usage: PartsBasedDetectorOnVideo model_file video_file output_folder [-r] [nmsThreshold]\n"); exit(-1); } // process variables boost::scoped_ptr<Model> model; float nmsThreshold = DEFAULT_NMS_THRESHOLD; bool optMirroring = DEFAULT_MIRRORING; bool optResume = DEFAULT_RESUME; if( argc >= 5 ){ if(strcmp(argv[4], "-r") == 0){ optResume = true; DLOG(INFO) << "Resume flag: ON"; } } if( argc >= 6 ){ nmsThreshold = atof(argv[5]); } // determine the type of model to read string ext = boost::filesystem::path(argv[1]).extension().string(); if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) { model.reset(new FileStorageModel); } #ifdef WITH_MATLABIO else if (ext.compare(".mat") == 0) { model.reset(new MatlabIOModel); } #endif else { printf("Unsupported model format: %s\n", ext.c_str()); LOG(FATAL) << "Unsupported model format: " << ext.c_str(); exit(-2); } bool ok = model->deserialize(argv[1]); if (!ok) { printf("Error deserializing file\n"); LOG(FATAL) << "Error deserializing file."; exit(-3); } // check output folder string outputFilePattern = (string) argv[3]; if( outputFilePattern[outputFilePattern.length()-1] != '/' ){ outputFilePattern.append("/"); } outputFilePattern.append(OUTPUT_FILENAME_FORMAT); // create the PartsBasedDetector and distribute the model parameters Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable PartsBasedDetector<float> pbd; pbd.distributeModel(*model); // load video sequence VideoCapture videoSrc((string)argv[2]); if( !videoSrc.isOpened() ){ printf("Could not read video file\n"); LOG(FATAL) << "Could not read video file: " << argv[2]; endwin(); exit(-4); } double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT); double frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); DLOG(INFO) << "Frame count: " << frameCount; DLOG(INFO) << "Start frame no: " << frameNo; // DEBUG // frameCount = 100; // display initialzation setupDisplay(argv[1], argv[2], argv[3]); // main loop DLOG(INFO) << "main loop"; vectorCandidate candidates; Mat curFrameIm; char outputFilenameBuffer[1024]; clock_t timeElapsed = clock(); while(frameNo < frameCount){ DLOG(INFO) << "FrameNo " << frameNo; updateDisplay(frameNo, ((float)frameNo/(float)frameCount*100.0f), (double) ( clock() - timeElapsed )/CLOCKS_PER_SEC ); timeElapsed = clock(); candidates.clear(); frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); videoSrc >> curFrameIm; sprintf(outputFilenameBuffer, outputFilePattern.c_str(), (int) frameNo); if( optResume ){ if(boost::filesystem::exists(outputFilenameBuffer)) continue; } pbd.detect(curFrameIm, depth, candidates); #ifndef NDEBUG gOutputFormat = FT_BBOX_BRIEF; #endif DLOG(INFO) << "Found original: " << candidates; if(optMirroring){ vectorCandidate mirroredCandidates; flip(curFrameIm, curFrameIm, 1); // flip around y-axis pbd.detect(curFrameIm, depth, mirroredCandidates); DLOG(INFO) << "Found flipped: " << mirroredCandidates; flipHorizontaly(mirroredCandidates, curFrameIm.size); DLOG(INFO) << "After flipping: " << mirroredCandidates; candidates.insert(candidates.end(), mirroredCandidates.begin(), mirroredCandidates.end()); } Candidate::nonMaximaSuppression(curFrameIm, candidates, nmsThreshold); DLOG(INFO) << "Final all detections" << candidates; // output ofstream outFile(outputFilenameBuffer); #ifndef NDEBUG gOutputFormat = FT_FULL_OUTPUT; #endif outFile << candidates; // cleanup outFile.close(); if(!curFrameIm.empty()) curFrameIm.release(); } // cleanup DLOG(INFO) << "Cleanup part"; videoSrc.release(); DLOG(INFO) << "Execution finished"; endwin(); return 0; } void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder){ initscr(); cbreak(); noecho(); int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later attron(A_BOLD); mvprintw(1, cols/2-19, "[[ PartsBasedDetector (onVideo) v1.0 ]]"); attroff(A_BOLD); mvprintw(3, 3, "Model file: "); mvprintw(3, 25, boost::filesystem::path(_model).filename().c_str()); mvprintw(4, 3, "Input video file: "); mvprintw(4, 25, boost::filesystem::path(_inputVideo).filename().c_str()); mvprintw(5, 3, "Output folder: "); mvprintw(5, 25, boost::filesystem::path(_outputFolder).leaf().c_str()); refresh(); } void updateDisplay(int _frame, float _perc, double _time){ // update display with information int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later float runnerStep = 100.0f/((float)cols-40); move(10, 5); addch('['); attron(A_BOLD); float runner; int change = 0; for(runner = 0; runner < _perc; runner+=runnerStep ){ switch( change % 4 ){ case 0: addch('.'); break; case 1: addch('o'); break; case 2: addch('O'); break; case 3: addch('o'); break; } change++; } for(;runner < 100.0f; runner += runnerStep) addch(' '); attroff(A_BOLD); printw("] %.2f% [Frame #%d]", _perc, _frame); move(11, cols/2 - 3); printw("TPF: %.2f sec", _time); refresh(); } <commit_msg>Implementation in place, not debugged<commit_after>/* * PartsBasedDetectorOnVideo * * * Huge chunks of code shamelessly taken from Hilton Bristow's demo for * PartsBasedDetector. * * Software License Agreement (BSD License) * * Copyright (c) 2013, Chili lab, EPFL. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Chili, EPFL nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * File: main.h * Author: Mirko Raca <name.lastname@epfl.ch> * Created: November 5, 2013 */ #include "globalIncludes.h" #include <boost/filesystem.hpp> #include <time.h> #include <stdio.h> #include <fstream> #include <ncurses.h> #include <vector> #include <opencv2/highgui/highgui.hpp> #include <PartsBasedDetector.hpp> #include <Candidate.hpp> #include <FileStorageModel.hpp> #include "filters/GenericFilter.h" #include "filters/FilterSize.h" #define WITH_MATLABIO #ifdef WITH_MATLABIO #include <MatlabIOModel.hpp> #endif #include "outputFormat.h" #include "mirrorUtils.h" using namespace cv; using namespace std; #define OUTPUT_FILENAME_FORMAT "facedetect_frame%06d.txt" #define DEFAULT_NMS_THRESHOLD 0.3f #define DEFAULT_MIRRORING false #define DEFAULT_RESUME false void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder); void updateDisplay(int _frame, float _perc, double _time); int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); DLOG(INFO) << "Execution started"; if (argc < 4) { printf("Usage: PartsBasedDetectorOnVideo model_file video_file output_folder [-r] [nmsThreshold]\n"); exit(-1); } // process variables boost::scoped_ptr<Model> model; float nmsThreshold = DEFAULT_NMS_THRESHOLD; bool optMirroring = DEFAULT_MIRRORING; bool optResume = DEFAULT_RESUME; if( argc >= 5 ){ if(strcmp(argv[4], "-r") == 0){ optResume = true; DLOG(INFO) << "Resume flag: ON"; } } if( argc >= 6 ){ nmsThreshold = atof(argv[5]); } // determine the type of model to read string ext = boost::filesystem::path(argv[1]).extension().string(); if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) { model.reset(new FileStorageModel); } #ifdef WITH_MATLABIO else if (ext.compare(".mat") == 0) { model.reset(new MatlabIOModel); } #endif else { printf("Unsupported model format: %s\n", ext.c_str()); LOG(FATAL) << "Unsupported model format: " << ext.c_str(); exit(-2); } bool ok = model->deserialize(argv[1]); if (!ok) { printf("Error deserializing file\n"); LOG(FATAL) << "Error deserializing file."; exit(-3); } // check output folder string outputFilePattern = (string) argv[3]; if( outputFilePattern[outputFilePattern.length()-1] != '/' ){ outputFilePattern.append("/"); } outputFilePattern.append(OUTPUT_FILENAME_FORMAT); // create the PartsBasedDetector and distribute the model parameters Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable PartsBasedDetector<float> pbd; pbd.distributeModel(*model); std::vector<GenericFilter*> postFilters; postFilters.push_back(new FilterSize(Size2f(140,140))); // TODO: exclude the hard-coding for a parameter // load video sequence VideoCapture videoSrc((string)argv[2]); if( !videoSrc.isOpened() ){ printf("Could not read video file\n"); LOG(FATAL) << "Could not read video file: " << argv[2]; endwin(); exit(-4); } double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT); double frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); DLOG(INFO) << "Frame count: " << frameCount; DLOG(INFO) << "Start frame no: " << frameNo; // DEBUG // frameCount = 100; // display initialzation setupDisplay(argv[1], argv[2], argv[3]); // main loop DLOG(INFO) << "main loop"; vectorCandidate candidates; Mat curFrameIm; char outputFilenameBuffer[1024]; clock_t timeElapsed = clock(); while(frameNo < frameCount){ DLOG(INFO) << "FrameNo " << frameNo; updateDisplay(frameNo, ((float)frameNo/(float)frameCount*100.0f), (double) ( clock() - timeElapsed )/CLOCKS_PER_SEC ); timeElapsed = clock(); candidates.clear(); frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES); videoSrc >> curFrameIm; sprintf(outputFilenameBuffer, outputFilePattern.c_str(), (int) frameNo); if( optResume ){ if(boost::filesystem::exists(outputFilenameBuffer)) continue; } pbd.detect(curFrameIm, depth, candidates); #ifndef NDEBUG gOutputFormat = FT_BBOX_BRIEF; #endif DLOG(INFO) << "Found original: " << candidates; if(optMirroring){ vectorCandidate mirroredCandidates; flip(curFrameIm, curFrameIm, 1); // flip around y-axis pbd.detect(curFrameIm, depth, mirroredCandidates); DLOG(INFO) << "Found flipped: " << mirroredCandidates; flipHorizontaly(mirroredCandidates, curFrameIm.size); DLOG(INFO) << "After flipping: " << mirroredCandidates; candidates.insert(candidates.end(), mirroredCandidates.begin(), mirroredCandidates.end()); } for( GenericFilter*& curFilter : postFilters) curFilter->process(candidates); // note: this can be a post-filter as well Candidate::nonMaximaSuppression(curFrameIm, candidates, nmsThreshold); DLOG(INFO) << "Final all detections" << candidates; // output ofstream outFile(outputFilenameBuffer); #ifndef NDEBUG gOutputFormat = FT_FULL_OUTPUT; #endif outFile << candidates; // cleanup outFile.close(); if(!curFrameIm.empty()) curFrameIm.release(); } // cleanup DLOG(INFO) << "Cleanup part"; videoSrc.release(); DLOG(INFO) << "Execution finished"; endwin(); return 0; } void setupDisplay(char* _model, char* _inputVideo, char* _outputFolder){ initscr(); cbreak(); noecho(); int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later attron(A_BOLD); mvprintw(1, cols/2-19, "[[ PartsBasedDetector (onVideo) v1.0 ]]"); attroff(A_BOLD); mvprintw(3, 3, "Model file: "); mvprintw(3, 25, boost::filesystem::path(_model).filename().c_str()); mvprintw(4, 3, "Input video file: "); mvprintw(4, 25, boost::filesystem::path(_inputVideo).filename().c_str()); mvprintw(5, 3, "Output folder: "); mvprintw(5, 25, boost::filesystem::path(_outputFolder).leaf().c_str()); refresh(); } void updateDisplay(int _frame, float _perc, double _time){ // update display with information int rows, cols; getmaxyx(stdscr, rows, cols); // will use it later float runnerStep = 100.0f/((float)cols-40); move(10, 5); addch('['); attron(A_BOLD); float runner; int change = 0; for(runner = 0; runner < _perc; runner+=runnerStep ){ switch( change % 4 ){ case 0: addch('.'); break; case 1: addch('o'); break; case 2: addch('O'); break; case 3: addch('o'); break; } change++; } for(;runner < 100.0f; runner += runnerStep) addch(' '); attroff(A_BOLD); printw("] %.2f% [Frame #%d]", _perc, _frame); move(11, cols/2 - 3); printw("TPF: %.2f sec", _time); refresh(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include <future> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/mesh_chunk.h" #include "gfx/idriver_ui_adapter.h" #include "gfx/support/load_wavefront.h" #include "gfx/support/mesh_conversion.h" #include "gfx/support/generate_aabb.h" #include "gfx/support/write_data_to_mesh.h" #include "gfx/support/texture_load.h" #include "gfx/support/software_texture.h" #include "gfx/support/unproject.h" #include "gfx/immediate_renderer.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "ui/pie_menu.h" #include "strat/map.h" #include "strat/wall.h" #include "strat/water.h" #include "strat/terrain.h" #include "strat/player_state.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } struct Glfw_User_Data { game::gfx::IDriver& driver; game::gfx::Camera& camera; game::ui::Element& root_hud; game::ui::Mouse_State& mouse_state; }; void mouse_button_callback(GLFWwindow* window, int glfw_button, int action,int) { using game::Vec; using game::ui::Mouse_State; auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& mouse_state = user_ptr.mouse_state; bool down = (action == GLFW_PRESS); using namespace game::ui; Mouse_Button button; switch(glfw_button) { case GLFW_MOUSE_BUTTON_LEFT: { button = Mouse_Button_Left; break; } case GLFW_MOUSE_BUTTON_RIGHT: { button = Mouse_Button_Right; break; } case GLFW_MOUSE_BUTTON_MIDDLE: { button = Mouse_Button_Middle; break; } } if(down) mouse_state.buttons |= button; else mouse_state.buttons &= ~button; } void mouse_motion_callback(GLFWwindow* window, double x, double y) { using game::ui::Mouse_State; auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& mouse_state = user_ptr.mouse_state; mouse_state.position.x = x; mouse_state.position.y = y; } void scroll_callback(GLFWwindow* window, double, double deltay) { using game::ui::Mouse_State; auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& mouse_state = user_ptr.mouse_state; mouse_state.scroll_delta = deltay; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } void error_callback(int error, const char* description) { game::log_d("GLFW Error: % (Code = %)", description, error); } void resize_callback(GLFWwindow* window, int width, int height) { // Change OpenGL viewport glViewport(0, 0, width, height); auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& idriver = user_ptr.driver; // Inform the driver of this change idriver.window_extents({width,height}); // Change the camera aspect ratio user_ptr.camera.perspective.aspect = width / (float) height; // Perhaps relayout the hud here? user_ptr.root_hud.layout(game::Vec<int>{width, height}); } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Error callback glfwSetErrorCallback(error_callback); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); // Set GLFW callbacks glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, mouse_motion_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetWindowSizeCallback(window, resize_callback); // UI Controller ui::Simple_Controller controller; { // Make an OpenGL driver. // Don't rely on any window resolution. Query it again. // After this, we'll query the driver for the real size. int window_width, window_height; glfwGetWindowSize(window, &window_width, &window_height); gfx::gl::Driver driver{Vec<int>{window_width, window_height}}; // Load our default shader. auto default_shader = driver.make_shader_repr(); default_shader->load_vertex_part("shader/basic/v"); default_shader->load_fragment_part("shader/basic/f"); default_shader->set_projection_name("proj"); default_shader->set_view_name("view"); default_shader->set_model_name("model"); default_shader->set_sampler_name("tex"); default_shader->set_diffuse_name("dif"); driver.use_shader(*default_shader); default_shader->set_sampler(0); // Load our textures. auto grass_tex = driver.make_texture_repr(); load_png("tex/grass.png", *grass_tex); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap Maybe_Owned<Mesh> terrain = driver.make_mesh_repr(); auto terrain_heightmap = strat::make_heightmap_from_image(terrain_image); auto terrain_data = make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01); auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f)); gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain); gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain)); gfx::format_mesh_buffers(*terrain); terrain->set_primitive_type(Primitive_Type::Triangle); // Map + structures. Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr(); strat::Game_State game_state{&driver, gfx::make_isometric_camera(driver), strat::Map{{1000, 1000}}}; // <-- Map size for now strat::Player_State player_state{game_state}; auto structures = strat::load_structures("structure/structures.json", ref_mo(structure_mesh), driver); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); hud->find_child_r("build_house")->on_step_mouse( ui::On_Release_Handler{[&](auto const& ms) { player_state.switch_state<strat::Building_State>(structures[0]); }}); hud->find_child_r("build_gvn_build")->on_step_mouse( ui::On_Release_Handler{[&](auto const& ms) { player_state.switch_state<strat::Building_State>(structures[1]); }}); hud->find_child_r("build_wall")->on_step_mouse( ui::On_Release_Handler{[&](auto const& ms) { strat::Wall_Type type{1, structures[2].aabb().width}; player_state.switch_state<strat::Wall_Building_State>(type); }}); hud->layout(driver.window_extents()); auto cur_mouse = ui::Mouse_State{}; // TODO: Put the camera somewhere else / Otherwise clean up the distinction // and usage of Glfw_User_Data, Game_State and Player_State. auto glfw_user_data = Glfw_User_Data{driver,game_state.cam, *hud, cur_mouse}; glfwSetWindowUserPointer(window, &glfw_user_data); while(!glfwWindowShouldClose(window)) { ++fps; // Reset the scroll delta cur_mouse.scroll_delta = 0.0; // Update the mouse state. glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, game_state.cam); driver.bind_texture(*grass_tex, 0); default_shader->set_diffuse(colors::white); default_shader->set_model(terrain_model); // Render the terrain before we calculate the depth of the mouse position. terrain->draw_elements(0, terrain_data.mesh.elements.size()); // These functions are bound to get the depth from the framebuffer. Make // sure the depth value is only based on the terrain. { if(!controller.step(hud, cur_mouse)) { player_state.step_mouse(cur_mouse); } // Handle zoom gfx::apply_zoom(game_state.cam, cur_mouse.scroll_delta, cur_mouse.position, driver); } // Render any structures. // Maybe the mouse? // We only want to be able to pan the terrain for now. That's why we need // to do this before any structure rendering. //auto mouse_world = gfx::unproject_screen(driver, game_state.cam, //glm::mat4(1.0f), //mouse_state.position); //player_state.handle_mouse(Vec<float>{mouse_world.x, mouse_world.z}); //if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS && //player_state.type == strat::Player_State_Type::Nothing) //{ //glfwSetWindowShouldClose(window, true); //} auto& pending_st = game_state.map.pending_structure; if(pending_st) { render_structure_instance(driver, pending_st.value()); } // Render all the other structures. for(auto const& st : game_state.map.structures) { // TODO: Find/store correct y somehow? render_structure_instance(driver, st); } // Render walls if(game_state.map.pending_wall) { // Render the structure at the pending wall point. render_structure(driver,structures[2],game_state.map.pending_wall->pos); } for(auto const& wall : game_state.map.walls) { render_wall(driver, wall, structures[2]); } //ir.render(cam); { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <commit_msg>Change indentation of map decl in main<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include <future> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/mesh_chunk.h" #include "gfx/idriver_ui_adapter.h" #include "gfx/support/load_wavefront.h" #include "gfx/support/mesh_conversion.h" #include "gfx/support/generate_aabb.h" #include "gfx/support/write_data_to_mesh.h" #include "gfx/support/texture_load.h" #include "gfx/support/software_texture.h" #include "gfx/support/unproject.h" #include "gfx/immediate_renderer.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "ui/pie_menu.h" #include "strat/map.h" #include "strat/wall.h" #include "strat/water.h" #include "strat/terrain.h" #include "strat/player_state.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } struct Glfw_User_Data { game::gfx::IDriver& driver; game::gfx::Camera& camera; game::ui::Element& root_hud; game::ui::Mouse_State& mouse_state; }; void mouse_button_callback(GLFWwindow* window, int glfw_button, int action,int) { using game::Vec; using game::ui::Mouse_State; auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& mouse_state = user_ptr.mouse_state; bool down = (action == GLFW_PRESS); using namespace game::ui; Mouse_Button button; switch(glfw_button) { case GLFW_MOUSE_BUTTON_LEFT: { button = Mouse_Button_Left; break; } case GLFW_MOUSE_BUTTON_RIGHT: { button = Mouse_Button_Right; break; } case GLFW_MOUSE_BUTTON_MIDDLE: { button = Mouse_Button_Middle; break; } } if(down) mouse_state.buttons |= button; else mouse_state.buttons &= ~button; } void mouse_motion_callback(GLFWwindow* window, double x, double y) { using game::ui::Mouse_State; auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& mouse_state = user_ptr.mouse_state; mouse_state.position.x = x; mouse_state.position.y = y; } void scroll_callback(GLFWwindow* window, double, double deltay) { using game::ui::Mouse_State; auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& mouse_state = user_ptr.mouse_state; mouse_state.scroll_delta = deltay; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } void error_callback(int error, const char* description) { game::log_d("GLFW Error: % (Code = %)", description, error); } void resize_callback(GLFWwindow* window, int width, int height) { // Change OpenGL viewport glViewport(0, 0, width, height); auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window); auto& idriver = user_ptr.driver; // Inform the driver of this change idriver.window_extents({width,height}); // Change the camera aspect ratio user_ptr.camera.perspective.aspect = width / (float) height; // Perhaps relayout the hud here? user_ptr.root_hud.layout(game::Vec<int>{width, height}); } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Error callback glfwSetErrorCallback(error_callback); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); // Set GLFW callbacks glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, mouse_motion_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetWindowSizeCallback(window, resize_callback); // UI Controller ui::Simple_Controller controller; { // Make an OpenGL driver. // Don't rely on any window resolution. Query it again. // After this, we'll query the driver for the real size. int window_width, window_height; glfwGetWindowSize(window, &window_width, &window_height); gfx::gl::Driver driver{Vec<int>{window_width, window_height}}; // Load our default shader. auto default_shader = driver.make_shader_repr(); default_shader->load_vertex_part("shader/basic/v"); default_shader->load_fragment_part("shader/basic/f"); default_shader->set_projection_name("proj"); default_shader->set_view_name("view"); default_shader->set_model_name("model"); default_shader->set_sampler_name("tex"); default_shader->set_diffuse_name("dif"); driver.use_shader(*default_shader); default_shader->set_sampler(0); // Load our textures. auto grass_tex = driver.make_texture_repr(); load_png("tex/grass.png", *grass_tex); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap Maybe_Owned<Mesh> terrain = driver.make_mesh_repr(); auto terrain_heightmap = strat::make_heightmap_from_image(terrain_image); auto terrain_data = make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01); auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f)); gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain); gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain)); gfx::format_mesh_buffers(*terrain); terrain->set_primitive_type(Primitive_Type::Triangle); // Map + structures. Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr(); strat::Game_State game_state{&driver, gfx::make_isometric_camera(driver), strat::Map{{1000, 1000}}}; // <-Map size for now strat::Player_State player_state{game_state}; auto structures = strat::load_structures("structure/structures.json", ref_mo(structure_mesh), driver); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); hud->find_child_r("build_house")->on_step_mouse( ui::On_Release_Handler{[&](auto const& ms) { player_state.switch_state<strat::Building_State>(structures[0]); }}); hud->find_child_r("build_gvn_build")->on_step_mouse( ui::On_Release_Handler{[&](auto const& ms) { player_state.switch_state<strat::Building_State>(structures[1]); }}); hud->find_child_r("build_wall")->on_step_mouse( ui::On_Release_Handler{[&](auto const& ms) { strat::Wall_Type type{1, structures[2].aabb().width}; player_state.switch_state<strat::Wall_Building_State>(type); }}); hud->layout(driver.window_extents()); auto cur_mouse = ui::Mouse_State{}; // TODO: Put the camera somewhere else / Otherwise clean up the distinction // and usage of Glfw_User_Data, Game_State and Player_State. auto glfw_user_data = Glfw_User_Data{driver,game_state.cam, *hud, cur_mouse}; glfwSetWindowUserPointer(window, &glfw_user_data); while(!glfwWindowShouldClose(window)) { ++fps; // Reset the scroll delta cur_mouse.scroll_delta = 0.0; // Update the mouse state. glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, game_state.cam); driver.bind_texture(*grass_tex, 0); default_shader->set_diffuse(colors::white); default_shader->set_model(terrain_model); // Render the terrain before we calculate the depth of the mouse position. terrain->draw_elements(0, terrain_data.mesh.elements.size()); // These functions are bound to get the depth from the framebuffer. Make // sure the depth value is only based on the terrain. { if(!controller.step(hud, cur_mouse)) { player_state.step_mouse(cur_mouse); } // Handle zoom gfx::apply_zoom(game_state.cam, cur_mouse.scroll_delta, cur_mouse.position, driver); } // Render any structures. // Maybe the mouse? // We only want to be able to pan the terrain for now. That's why we need // to do this before any structure rendering. //auto mouse_world = gfx::unproject_screen(driver, game_state.cam, //glm::mat4(1.0f), //mouse_state.position); //player_state.handle_mouse(Vec<float>{mouse_world.x, mouse_world.z}); //if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS && //player_state.type == strat::Player_State_Type::Nothing) //{ //glfwSetWindowShouldClose(window, true); //} auto& pending_st = game_state.map.pending_structure; if(pending_st) { render_structure_instance(driver, pending_st.value()); } // Render all the other structures. for(auto const& st : game_state.map.structures) { // TODO: Find/store correct y somehow? render_structure_instance(driver, st); } // Render walls if(game_state.map.pending_wall) { // Render the structure at the pending wall point. render_structure(driver,structures[2],game_state.map.pending_wall->pos); } for(auto const& wall : game_state.map.walls) { render_wall(driver, wall, structures[2]); } //ir.render(cam); { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cctype> #include <cstring> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <vector> #include <string> #include <iostream> #include "functions.h" int main(int argc, char** argv) { std::string prompt; getPrompt(prompt); bool quit = false; // print welcome message and prompt printf("Welcome to rshell!\n"); while (!quit) { // holds a single command and its arguments Command_t cmd; // holds multiple commands std::vector<Command_t> cmds; // hold a raw line of input std::string line; // print prompt and get a line of text (done in condition) printf("%s", prompt.c_str()); preProcessLine(line); int mode = GETWORD; unsigned begin = 0; // prepare cmd cmd.connector = NONE; // syntax error flag bool se = false; // starts with a connector? I don't think so if (line.size() > 0 && isConn(line[0]) && line[0] != ';') { se = true; } else if (line.size() > 0 && (isRedir(line[0]) || isdigit(line[0]))) { mode = GETREDIR; } // handle the input for(unsigned i = 0; i < line.size() && !se; ++i) { bool con = isConn(line[i]); // bool dig = isdigit(line[i]); bool redir = isRedir(line[i]); bool space = isspace(line[i]); // if we're getting a word and there's a whitespace or connector here if (mode == GETWORD && (space || con || redir)) { // only happens for blank lines: if (i == 0 && con) break; if (redir) { mode = GETREDIR; continue; } // chunk the last term and throw it into the vector addArg(cmd, line, begin, i); if (space) { mode = TRIMSPACE; } else { // if (con) { handleCon(cmds, cmd, line, mode, begin, i, se); } } else if (mode == TRIMSPACE && !space) { if (con && cmd.args.empty() && line[i] != ';') { se = true; } else if (con) { handleCon(cmds, cmd, line, mode, begin, i, se); } else if (redir) { begin = i; mode = GETREDIR; } else { begin = i; mode = GETWORD; } } else if (mode == HANDLESEMI && line[i] != ';') { if (isConn(line[i])) { se = true; } else if (isspace(line[i])) { mode = TRIMSPACE; } else { // it's a word begin = i; mode = GETWORD; } } else if (mode == GETREDIR && line[i] == '"') { mode = GETSTRING; } else if (mode == GETREDIR && space) { handleRedir(cmds, cmd, line, mode, begin, i, se); mode = TRIMSPACE; } else if (mode == GETSTRING && line[i] == '"') { mode = ENDQUOTE; } else if (mode == ENDQUOTE) { if (space) { handleRedir(cmds, cmd, line, mode, begin, i, se); mode = TRIMSPACE; } else { se = true; continue; } } } // if the last command has a continuation connector, syntax error if (cmds.size() > 0 && (cmds[cmds.size()-1].connector == AND || cmds[cmds.size()-1].connector == OR || cmds[cmds.size()-1].connector == PIPE)) { se = true; } if (mode == GETSTRING) se = true; // if there was a syntax error if (se) { printf("Syntax error\n"); continue; } // now to execute all the commands for(unsigned i = 0; i < cmds.size(); ++i) { int exitStatus = 0; char* arg = cmds[i].args[0]; if (strcmp(arg, "exit") == 0) { quit = true; break; } char** argv = new char*[cmds[i].args.size()+1]; for(unsigned j = 0; j < cmds[i].args.size(); ++j) { argv[j] = cmds[i].args[j]; } argv[cmds[i].args.size()] = 0; // arg and argv are now prepared pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // child process if (execvp(arg, argv) == -1) { // if there's a return value, there was a problem // -1 indicates a problem, specifically perror(arg); delete[] argv; exit(1); } } else { // parent process if (waitpid(pid, &exitStatus, 0) == -1) { perror("waitpid"); exit(1); } } if (!exitStatus) { // all is good (0) while (i < cmds.size() && cmds[i].connector == OR) { ++i; } } else { // last command failed while (i < cmds.size() && cmds[i].connector == AND) { ++i; } } } // deallocate allocated memory for(unsigned i = 0; i < cmds.size(); ++i) { for(unsigned j = 0; j < cmds[i].args.size(); ++j) { delete[] cmds[i].args[j]; } } } printf("Goodbye!\n"); return 0; } <commit_msg>added detailed debugging code<commit_after>#include <cstdio> #include <cstdlib> #include <cctype> #include <cstring> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <vector> #include <string> #include <iostream> #include "functions.h" int main(int argc, char** argv) { std::string prompt; getPrompt(prompt); bool quit = false; // print welcome message and prompt printf("Welcome to rshell!\n"); while (!quit) { // holds a single command and its arguments Command_t cmd; // holds multiple commands std::vector<Command_t> cmds; // hold a raw line of input std::string line; // print prompt and get a line of text (done in condition) printf("%s", prompt.c_str()); preProcessLine(line); int mode = GETWORD; unsigned begin = 0; // prepare cmd cmd.connector = NONE; // syntax error flag bool se = false; // starts with a connector? I don't think so if (line.size() > 0 && isConn(line[0]) && line[0] != ';') { se = true; } else if (line.size() > 0 && (isRedir(line[0]) || isdigit(line[0]))) { mode = GETREDIR; } // handle the input for(unsigned i = 0; i < line.size() && !se; ++i) { bool con = isConn(line[i]); // bool dig = isdigit(line[i]); bool redir = isRedir(line[i]); bool space = isspace(line[i]); // if we're getting a word and there's a whitespace or connector here if (mode == GETWORD && (space || con || redir)) { // only happens for blank lines: if (i == 0 && con) break; if (redir) { mode = GETREDIR; continue; } // chunk the last term and throw it into the vector addArg(cmd, line, begin, i); if (space) { mode = TRIMSPACE; } else { // if (con) { handleCon(cmds, cmd, line, mode, begin, i, se); } } else if (mode == TRIMSPACE && !space) { if (con && cmd.args.empty() && line[i] != ';') { se = true; } else if (con) { handleCon(cmds, cmd, line, mode, begin, i, se); } else if (redir) { begin = i; mode = GETREDIR; } else { begin = i; mode = GETWORD; } } else if (mode == HANDLESEMI && line[i] != ';') { if (isConn(line[i])) { se = true; } else if (isspace(line[i])) { mode = TRIMSPACE; } else { // it's a word begin = i; mode = GETWORD; } } else if (mode == GETREDIR && line[i] == '"') { mode = GETSTRING; } else if (mode == GETREDIR && space) { handleRedir(cmds, cmd, line, mode, begin, i, se); mode = TRIMSPACE; } else if (mode == GETSTRING && line[i] == '"') { mode = ENDQUOTE; } else if (mode == ENDQUOTE) { if (space) { handleRedir(cmds, cmd, line, mode, begin, i, se); mode = TRIMSPACE; } else { se = true; continue; } } } // if the last command has a continuation connector, syntax error if (cmds.size() > 0 && (cmds[cmds.size()-1].connector == AND || cmds[cmds.size()-1].connector == OR || cmds[cmds.size()-1].connector == PIPE)) { se = true; } if (mode == GETSTRING) se = true; // if there was a syntax error if (se) { printf("Syntax error\n"); continue; } /* for(unsigned i = 0; i < cmds.size(); ++i) { for(unsigned j = 0; j < cmds[i].args.size(); ++j) { printf("cmd %d arg %d: \"%s\"\n", i, j, cmds[i].args[j]); } if (cmds[i].connector == NONE) printf("connector: NONE\n"); else if (cmds[i].connector == AND) printf("connector: AND\n"); else if (cmds[i].connector == OR) printf("connector: OR\n"); else if (cmds[i].connector == SEMI) printf("connector: SEMI\n"); else if (cmds[i].connector == PIPE) printf("connector: PIPE\n"); printf("file descriptor modifications:\n"); for(unsigned j = 0; j < cmds[i].fdChanges.size(); ++j) { if (cmds[i].fdChanges[j].type == INPUT) { printf("change fd %d to ", (cmds[i].fdChanges[j].orig == DEFAULT) ? 0 : cmds[i].fdChanges[j].orig); if (cmds[i].fdChanges[j].moveTo == UNDEFINED) printf("UNDEFINED\n"); else if (cmds[i].fdChanges[j].moveTo == FROMSTR) printf("FROMSTR (\"%s\")\n", cmds[i].fdChanges[j].s.c_str()); else printf("Some other fd (%d)\n", cmds[i].fdChanges[j].moveTo); } if (cmds[i].fdChanges[j].type == OUTPUT) { printf("change fd %d to ", (cmds[i].fdChanges[j].orig == DEFAULT) ? 1 : cmds[i].fdChanges[j].orig); if (cmds[i].fdChanges[j].moveTo == UNDEFINED) printf("UNDEFINED\n"); else printf("Some other fd (%d)\n", cmds[i].fdChanges[j].moveTo); } } } */ // now to execute all the commands for(unsigned i = 0; i < cmds.size(); ++i) { int exitStatus = 0; char* arg = cmds[i].args[0]; if (strcmp(arg, "exit") == 0) { quit = true; break; } char** argv = new char*[cmds[i].args.size()+1]; for(unsigned j = 0; j < cmds[i].args.size(); ++j) { argv[j] = cmds[i].args[j]; } argv[cmds[i].args.size()] = 0; // arg and argv are now prepared pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // child process if (execvp(arg, argv) == -1) { // if there's a return value, there was a problem // -1 indicates a problem, specifically perror(arg); delete[] argv; exit(1); } } else { // parent process if (waitpid(pid, &exitStatus, 0) == -1) { perror("waitpid"); exit(1); } } if (!exitStatus) { // all is good (0) while (i < cmds.size() && cmds[i].connector == OR) { ++i; } } else { // last command failed while (i < cmds.size() && cmds[i].connector == AND) { ++i; } } } // deallocate allocated memory for(unsigned i = 0; i < cmds.size(); ++i) { for(unsigned j = 0; j < cmds[i].args.size(); ++j) { delete[] cmds[i].args[j]; } } } printf("Goodbye!\n"); return 0; } <|endoftext|>
<commit_before>#include "camera/perspective.h" #include "engine/cosine_debugger.h" #include "geom/rect.h" #include "geom/vector.h" #include "geom/point.h" #include "image/image.h" #include "node/group/simple.h" #include "node/solid/sphere.h" #include "node/solid/infinite_plane.h" #include "renderer/settings.h" #include "renderer/serial/serial.h" #include "renderer/parallel/parallel.h" #include "supersampling/random.h" #include "trajectory/bspline.h" #include "world/world.h" #include <iostream> #include <sstream> #include <cmath> #include <thread> using namespace Svit; int main (void) { Settings settings; settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.max_thread_count = std::thread::hardware_concurrency(); settings.tile_size = Vector2i(100, 100); settings.max_sample_count = 4; settings.adaptive_sample_step = 2; SimpleGroup scene; InfinitePlane infinite_plane(Point3(0.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)); scene.add(infinite_plane); Sphere* spheres[100]; int i = 0; for (float x = -3.0; x < 3.0; x += 0.5) for (float z = 0.0; z < 6.0; z += 0.5) { spheres[i] = new Sphere(Point3(x, 0.5, z), (float)(rand() % 15)/100.0); scene.add(*spheres[i]); i++; } PerspectiveCamera camera( Point3(0.0, 0.75, -2.0), Vector3(0.0, 0.0, 1.0), Vector3(0.0, 1.0, 0.0), settings.whole_area.get_aspect_ratio(), M_PI/2.0); World world; world.scene = &scene; world.camera = &camera; CosineDebuggerEngine engine; ParallelRenderer renderer; //SerialRenderer renderer; RandomSuperSampling super_sampling(true); BSplineTrajectory trajectory(true); trajectory.add_point(Point3(0.0f, 0.0f, 0.0f)); trajectory.add_point(Point3(-3.0f, 3.0f, 3.0f)); trajectory.add_point(Point3(0.0f, 6.0f, 6.0f)); trajectory.add_point(Point3(3.0f, 3.0f, 3.0f)); unsigned int FPS = 25; float animation_length = 10.0; unsigned int frame_count = FPS * (int)(animation_length); for (int frame = 0; frame < frame_count; frame++) { camera.position = trajectory.evaluate(4.0f / (float)frame_count * (float)frame) + Vector3(0.0, -0.25, -3.0); camera.look_at(Point3(0.0, 0.0, 3.0)); camera.position.dump("position"); camera.forward.dump("forward"); camera.up.dump("up"); Image image = renderer.render(world, settings, engine, super_sampling); std::ostringstream ss; ss << std::setw(3) << std::setfill('0') << frame; std::string frame_string(ss.str()); image.write(std::string("output") + frame_string + std::string(".png")); std::cout << "Frame " << frame << "/" << frame_count << " done." << std::endl; } return 0; } <commit_msg>Testing curve derivation<commit_after>#include "camera/perspective.h" #include "engine/cosine_debugger.h" #include "geom/rect.h" #include "geom/vector.h" #include "geom/point.h" #include "image/image.h" #include "node/group/simple.h" #include "node/solid/sphere.h" #include "node/solid/infinite_plane.h" #include "renderer/settings.h" #include "renderer/serial/serial.h" #include "renderer/parallel/parallel.h" #include "supersampling/random.h" #include "trajectory/bspline.h" #include "world/world.h" #include <iostream> #include <sstream> #include <cmath> #include <thread> using namespace Svit; int main (void) { Settings settings; settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.max_thread_count = std::thread::hardware_concurrency(); settings.tile_size = Vector2i(100, 100); settings.max_sample_count = 4; settings.adaptive_sample_step = 2; SimpleGroup scene; InfinitePlane infinite_plane(Point3(0.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)); scene.add(infinite_plane); Sphere* spheres[100]; int i = 0; for (float x = -3.0; x < 3.0; x += 0.5) for (float z = 0.0; z < 6.0; z += 0.5) { spheres[i] = new Sphere(Point3(x, 0.5, z), (float)(rand() % 15)/100.0); scene.add(*spheres[i]); i++; } PerspectiveCamera camera( Point3(0.0, 0.75, -2.0), Vector3(0.0, 0.0, 1.0), Vector3(0.0, 1.0, 0.0), settings.whole_area.get_aspect_ratio(), M_PI/2.0); World world; world.scene = &scene; world.camera = &camera; CosineDebuggerEngine engine; ParallelRenderer renderer; //SerialRenderer renderer; RandomSuperSampling super_sampling(true); BSplineTrajectory trajectory(true); trajectory.add_point(Point3(0.0f, 0.0f, 0.0f)); trajectory.add_point(Point3(-3.0f, 3.0f, 3.0f)); trajectory.add_point(Point3(0.0f, 6.0f, 6.0f)); trajectory.add_point(Point3(3.0f, 3.0f, 3.0f)); unsigned int FPS = 25; float animation_length = 10.0; unsigned int frame_count = FPS * (int)(animation_length); for (int frame = 0; frame < frame_count; frame++) { camera.position = trajectory.evaluate(4.0f / (float)frame_count * (float)frame) + Vector3(0.0, -0.25, -3.0); camera.look_at(Point3(0.0, 0.0, 3.0)); Point3 now = trajectory.evaluate(4.0f / (float)frame_count * (float)frame) + Vector3(0.0, -0.25, -3.0); Point3 next = trajectory.evaluate(4.0f / (float)frame_count * (((float)frame) + 0.0001f)) + Vector3(0.0, -0.25, -3.0); Vector3 left = ~(next - now); camera.up = left & camera.forward; camera.position.dump("position"); camera.forward.dump("forward"); camera.up.dump("up"); Image image = renderer.render(world, settings, engine, super_sampling); std::ostringstream ss; ss << std::setw(3) << std::setfill('0') << frame; std::string frame_string(ss.str()); image.write(std::string("output") + frame_string + std::string(".png")); std::cout << "Frame " << frame << "/" << frame_count << " done." << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include "simplefluid.h" #include "tinycl.h" int main(int argc, char **argv){ tcl::Context context(tcl::DEVICE::GPU, false, false); cl::Program program = context.loadProgram("../res/simple_fluid.cl"); //Test computation of the negative divergence of the velocity field cl::Kernel velocityDivergence(program, "velocity_divergence"); //Velocity fields for a 2x2 MAC grid //For these velocity fields we expect //0,0: 2 //1,0: 0 //0,1: 0 //1,1: 4 float vxField[] = { 1, 0, -1, 2, 0, -2 }; float vyField[] = { 1, -1, 0, 0, 2, -2 }; cl::Buffer vxBuf = context.buffer(tcl::MEM::READ_ONLY, 6 * sizeof(float), vxField); cl::Buffer vyBuf = context.buffer(tcl::MEM::READ_ONLY, 6 * sizeof(float), vyField); //Output for the negative divergence at each cell cl::Buffer negDiv = context.buffer(tcl::MEM::WRITE_ONLY, 4 * sizeof(float), nullptr); velocityDivergence.setArg(0, vxBuf); velocityDivergence.setArg(1, vyBuf); velocityDivergence.setArg(2, negDiv); context.runNDKernel(velocityDivergence, cl::NDRange(2, 2), cl::NullRange, cl::NullRange, false); float result[4] = {0}; context.readData(negDiv, 4 * sizeof(float), result, 0, true); for (int i = 0; i < 4; ++i){ std::cout << "Divergence at " << i % 2 << "," << i / 2 << " = " << result[i] << "\n"; } std::cout << std::endl; return 0; } <commit_msg>Adding a test for subtracting pressure from v_x<commit_after>#include <iostream> #include <iomanip> #include "simplefluid.h" #include "tinycl.h" //Test the velocity divergence kernel void testVelocityDivergence(); //Test the pressure subtraction to update the velocity field void testSubtractPressureX(); void testSubtractPressureY(); int main(int argc, char **argv){ testSubtractPressureX(); return 0; } void testVelocityDivergence(){ tcl::Context context(tcl::DEVICE::GPU, false, false); cl::Program program = context.loadProgram("../res/simple_fluid.cl"); //Test computation of the negative divergence of the velocity field cl::Kernel velocityDivergence(program, "velocity_divergence"); //Velocity fields for a 2x2 MAC grid //For these velocity fields we expect //0,0: 2 //1,0: 0 //0,1: 0 //1,1: 4 float vxField[] = { 1, 0, -1, 2, 0, -2 }; float vyField[] = { 1, -1, 0, 0, 2, -2 }; cl::Buffer vxBuf = context.buffer(tcl::MEM::READ_ONLY, 6 * sizeof(float), vxField); cl::Buffer vyBuf = context.buffer(tcl::MEM::READ_ONLY, 6 * sizeof(float), vyField); //Output for the negative divergence at each cell cl::Buffer negDiv = context.buffer(tcl::MEM::WRITE_ONLY, 4 * sizeof(float), nullptr); velocityDivergence.setArg(0, vxBuf); velocityDivergence.setArg(1, vyBuf); velocityDivergence.setArg(2, negDiv); context.runNDKernel(velocityDivergence, cl::NDRange(2, 2), cl::NullRange, cl::NullRange, false); float result[4] = {0}; context.readData(negDiv, 4 * sizeof(float), result, 0, true); for (int i = 0; i < 4; ++i){ std::cout << "Divergence at " << i % 2 << "," << i / 2 << " = " << result[i] << "\n"; } std::cout << std::endl; } void testSubtractPressureX(){ tcl::Context context(tcl::DEVICE::GPU, false, false); cl::Program program = context.loadProgram("../res/simple_fluid.cl"); cl::Kernel subPressX(program, "subtract_pressure_x"); float vxField[] = { 0, 0, 0, 0, 0, 0 }; float pressure[] = { 1, 0, 2, 0 }; //Just use 1 to make it easier to test float rho = 1.f, dt = 1.f; cl::Buffer vxBuff = context.buffer(tcl::MEM::READ_WRITE, 6 * sizeof(float), vxField); cl::Buffer pressBuff = context.buffer(tcl::MEM::READ_ONLY, 4 * sizeof(float), pressure); subPressX.setArg(0, rho); subPressX.setArg(1, dt); subPressX.setArg(2, vxBuff); subPressX.setArg(3, pressBuff); context.runNDKernel(subPressX, cl::NDRange(3, 2), cl::NullRange, cl::NullRange, false); context.readData(vxBuff, 6 * sizeof(float), vxField, 0, true); std::cout << "New velocity_x field:\n"; for (int i = 0; i < 6; ++i){ if (i != 0 && i % 3 == 0){ std::cout << "\n"; } std::cout << vxField[i] << " "; } std::cout << std::endl; } void testSubtractPressureY(){ } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <sstream> #include "Tokenizer.h" #include "Parser.h" #include "Writer.h" #include "Stylesheet.h" #include "IOException.h" using namespace std; /** * /main Interpreter * */ void usage () { cout << " cat infile.txt | Interpreter > output.txt" << endl; } void processInput(istream* in){ Tokenizer* tokenizer = new Tokenizer(in); Parser* parser = new Parser(tokenizer); Writer *w = new Writer(&cout); try{ Stylesheet* s = parser->parseStylesheet(); w->writeStylesheet(s); cout << endl; delete s; } catch(ParseException* e) { cerr << "Line " << tokenizer->getLineNumber() << ", Collumn " << tokenizer->getPosition() << " Parse Error: " << e->what() << endl; } delete tokenizer; delete parser; delete w; } int main(int argc, char * argv[]){ string helpstr("-h"); if (argc > 1 && helpstr.compare(argv[1]) == 0) { usage(); return 0; } try { if(argc <= 1){ processInput(&cin); } else { for (int i=1; i < argc; i++){ ifstream* file = new ifstream(argv[i]); if (file->fail() || file->bad()) throw new IOException("Error opening file"); processInput(file); file->close(); delete file; } } } catch (IOException* e) { ostringstream stream1(ostringstream::out); cerr << " Error: " << e->what() << endl; } return 0; } <commit_msg>Updated the references to the Tokenizer, Parser and Writer.<commit_after>#include <iostream> #include <fstream> #include <string> #include <sstream> #include "CssTokenizer.h" #include "CssParser.h" #include "CssWriter.h" #include "Stylesheet.h" #include "IOException.h" using namespace std; /** * /main Interpreter * */ void usage () { cout << " cat infile.txt | Interpreter > output.txt" << endl; } void processInput(istream* in){ CssTokenizer* tokenizer = new CssTokenizer(in); CssParser* parser = new CssParser(tokenizer); CssWriter *w = new CssWriter(&cout); try{ Stylesheet* s = parser->parseStylesheet(); w->writeStylesheet(s); cout << endl; delete s; } catch(ParseException* e) { cerr << "Line " << tokenizer->getLineNumber() << ", Collumn " << tokenizer->getPosition() << " Parse Error: " << e->what() << endl; } delete tokenizer; delete parser; delete w; } int main(int argc, char * argv[]){ string helpstr("-h"); if (argc > 1 && helpstr.compare(argv[1]) == 0) { usage(); return 0; } try { if(argc <= 1){ processInput(&cin); } else { for (int i=1; i < argc; i++){ ifstream* file = new ifstream(argv[i]); if (file->fail() || file->bad()) throw new IOException("Error opening file"); processInput(file); file->close(); delete file; } } } catch (IOException* e) { ostringstream stream1(ostringstream::out); cerr << " Error: " << e->what() << endl; } return 0; } <|endoftext|>
<commit_before>/* * flex_shoebox.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <boost/unordered_map.hpp> #include <boost_adaptbx/std_pair_conversion.h> #include <cmath> #include <scitbx/array_family/boost_python/flex_wrapper.h> #include <scitbx/array_family/ref_reductions.h> #include <scitbx/array_family/boost_python/ref_pickle_double_buffered.h> #include <scitbx/array_family/boost_python/flex_pickle_double_buffered.h> #include <dials/model/data/partial_shoebox.h> #include <dials/model/data/shoebox.h> #include <dials/config.h> namespace dials { namespace af { namespace boost_python { using namespace boost::python; using namespace scitbx::af::boost_python; using af::int2; using af::int6; using af::small; using dials::model::PartialShoebox; using dials::model::Shoebox; /** * Check if the arrays are consistent */ static shared<bool> is_consistent(const const_ref<PartialShoebox> &a) { shared<bool> result(a.size(), af::init_functor_null<bool>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].is_consistent(); } return result; } /** * Get the bounding boxes */ static shared<int6> bounding_boxes(const const_ref<PartialShoebox> &a) { shared<int6> result(a.size(), af::init_functor_null<int6>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].bbox; } return result; } /** * Get the panel numbers */ static shared<std::size_t> panels(const const_ref<PartialShoebox> &a) { shared<std::size_t> result(a.size(), af::init_functor_null<std::size_t>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].panel; } return result; } /** * Get the zranges */ static shared<int2> zranges(const const_ref<PartialShoebox> &a) { shared<int2> result(a.size(), af::init_functor_null<int2>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].zrange; } return result; } /** * Struct for sorting shoeboxes */ struct CompareMinZ { const_ref<PartialShoebox> x_; CompareMinZ(const const_ref<PartialShoebox> &x) : x_(x) {} bool operator()(int a, int b) const { return x_[a].zrange[0] < x_[b].zrange[0]; } }; /** * Try to merge the partial shoeboxes */ PartialShoebox merge(const const_ref<PartialShoebox> &a, int2 srange) { // Sort the array by minimum z DIALS_ASSERT(a.size() > 0); DIALS_ASSERT(srange[1] > srange[0]); shared<int> index(a.size()); for (std::size_t i = 0; i < index.size(); ++i) index[i] = i; std::sort(index.begin(), index.end(), CompareMinZ(a)); // Get the bbox and panel int6 bbox = a[0].bbox; std::size_t panel = a[0].panel; // Loop through and check ranges are valid and within the bbox range DIALS_ASSERT(a[index[0]].is_consistent()); DIALS_ASSERT(a[index[0]].zrange[0] == std::max(bbox[4], srange[0])); for (std::size_t i = 1; i < index.size(); ++i) { DIALS_ASSERT(a[index[i]].is_consistent()); DIALS_ASSERT(a[index[i]].bbox.all_eq(bbox)); DIALS_ASSERT(a[index[i]].panel == panel); int2 z0 = a[index[i-1]].zrange; int2 z1 = a[index[i]].zrange; DIALS_ASSERT(z1[0] == z0[1]); } DIALS_ASSERT(a[index.back()].zrange[1] <= std::min(bbox[5], srange[1])); // Copy all the data PartialShoebox shoebox(panel, bbox, int2(bbox[4], bbox[5])); shoebox.allocate(); std::size_t xysize = shoebox.xsize() * shoebox.ysize(); for (std::size_t i = 0; i < a.size(); ++i) { std::size_t offset = (a[i].zrange[0] - bbox[4]) * xysize; for (std::size_t j = 0; j < a[i].data.size(); ++j) { shoebox.data[offset + j] = a[i].data[j]; } } // Return the new shoebox return shoebox; } /** * Merge all shoeboxes and return indices and shoeboxes */ std::pair< af::shared<std::size_t>, af::shared<PartialShoebox> > merge_all(const const_ref<PartialShoebox> &shoeboxes, const const_ref<std::size_t> &indices, int2 srange) { // Some useful typedefs typedef boost::unordered_map<std::size_t, af::shared<PartialShoebox> > map_type; typedef typename map_type::iterator iterator; // Construct a map of the shoeboxes to merge DIALS_ASSERT(indices.size() == shoeboxes.size()); map_type tomerge(indices.size()); for (std::size_t i = 0; i < indices.size(); ++i) { tomerge[indices[i]].push_back(shoeboxes[i]); } // Merge all the shoeboxes af::shared<std::size_t> cindices; af::shared<PartialShoebox> cshoeboxes; for (iterator it = tomerge.begin(); it != tomerge.end(); ++it) { cindices.push_back(it->first); cshoeboxes.push_back(merge(it->second.const_ref(), srange)); } return std::make_pair(cindices, cshoeboxes); } /** * A class to convert the shoebox class to a string for pickling */ struct partial_shoebox_to_string : pickle_double_buffered::to_string { using pickle_double_buffered::to_string::operator<<; /** Initialise with the version for checking */ partial_shoebox_to_string() { unsigned int version = 1; *this << version; } /** Convert a single shoebox instance to string */ partial_shoebox_to_string& operator<<(const PartialShoebox &val) { *this << val.panel << val.bbox[0] << val.bbox[1] << val.bbox[2] << val.bbox[3] << val.bbox[4] << val.bbox[5] << val.zrange[0] << val.zrange[1]; profile_to_string(val.data); return *this; } /** Convert a profile to string */ template <typename ProfileType> void profile_to_string(const ProfileType &p) { *this << p.accessor().size(); for (std::size_t i = 0; i < p.accessor().size(); ++i) { *this << p.accessor()[i]; } for (std::size_t i = 0; i < p.size(); ++i) { *this << p[i]; } } }; /** * A class to convert a string to a shoebox for unpickling */ struct partial_shoebox_from_string : pickle_double_buffered::from_string { using pickle_double_buffered::from_string::operator>>; /** Initialise the class with the string. Get the version and check */ partial_shoebox_from_string(const char* str_ptr) : pickle_double_buffered::from_string(str_ptr) { *this >> version; DIALS_ASSERT(version == 1); } /** Get a single shoebox instance from a string */ partial_shoebox_from_string& operator>>(PartialShoebox &val) { *this >> val.panel >> val.bbox[0] >> val.bbox[1] >> val.bbox[2] >> val.bbox[3] >> val.bbox[4] >> val.bbox[5] >> val.zrange[0] >> val.zrange[1]; val.data = profile_from_string< versa<int, c_grid<3> > >(); return *this; } /** Get a profile from a string */ template <typename ProfileType> ProfileType profile_from_string() { typename ProfileType::accessor_type accessor; typename ProfileType::size_type n_dim; *this >> n_dim; DIALS_ASSERT(n_dim == accessor.size()); for (std::size_t i = 0; i < n_dim; ++i) { *this >> accessor[i]; } ProfileType p = ProfileType(accessor); for (std::size_t i = 0; i < p.size(); ++i) { *this >> p[i]; } return p; } unsigned int version; }; scitbx::af::boost_python::flex_wrapper< PartialShoebox, return_internal_reference<> >::class_f_t flex_partial_shoebox_wrapper(const char *name) { return scitbx::af::boost_python::flex_wrapper < PartialShoebox, return_internal_reference<> >::plain(name) .def("is_consistent", &is_consistent) .def("panels", &panels) .def("bounding_boxes", &bounding_boxes) .def("zranges", &zranges) .def("merge", &merge) .def("merge_all", &merge_all) .def_pickle(flex_pickle_double_buffered<PartialShoebox, partial_shoebox_to_string, partial_shoebox_from_string>()); } void export_flex_partial_shoebox() { flex_partial_shoebox_wrapper("partial_shoebox"); boost_adaptbx::std_pair_conversions::to_and_from_tuple< af::shared<std::size_t>, af::shared<PartialShoebox> >(); } }}} // namespace dials::af::boost_python <commit_msg>Removed typename outside template.<commit_after>/* * flex_shoebox.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <boost/unordered_map.hpp> #include <boost_adaptbx/std_pair_conversion.h> #include <cmath> #include <scitbx/array_family/boost_python/flex_wrapper.h> #include <scitbx/array_family/ref_reductions.h> #include <scitbx/array_family/boost_python/ref_pickle_double_buffered.h> #include <scitbx/array_family/boost_python/flex_pickle_double_buffered.h> #include <dials/model/data/partial_shoebox.h> #include <dials/model/data/shoebox.h> #include <dials/config.h> namespace dials { namespace af { namespace boost_python { using namespace boost::python; using namespace scitbx::af::boost_python; using af::int2; using af::int6; using af::small; using dials::model::PartialShoebox; using dials::model::Shoebox; /** * Check if the arrays are consistent */ static shared<bool> is_consistent(const const_ref<PartialShoebox> &a) { shared<bool> result(a.size(), af::init_functor_null<bool>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].is_consistent(); } return result; } /** * Get the bounding boxes */ static shared<int6> bounding_boxes(const const_ref<PartialShoebox> &a) { shared<int6> result(a.size(), af::init_functor_null<int6>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].bbox; } return result; } /** * Get the panel numbers */ static shared<std::size_t> panels(const const_ref<PartialShoebox> &a) { shared<std::size_t> result(a.size(), af::init_functor_null<std::size_t>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].panel; } return result; } /** * Get the zranges */ static shared<int2> zranges(const const_ref<PartialShoebox> &a) { shared<int2> result(a.size(), af::init_functor_null<int2>()); for (std::size_t i = 0; i < a.size(); ++i) { result[i] = a[i].zrange; } return result; } /** * Struct for sorting shoeboxes */ struct CompareMinZ { const_ref<PartialShoebox> x_; CompareMinZ(const const_ref<PartialShoebox> &x) : x_(x) {} bool operator()(int a, int b) const { return x_[a].zrange[0] < x_[b].zrange[0]; } }; /** * Try to merge the partial shoeboxes */ PartialShoebox merge(const const_ref<PartialShoebox> &a, int2 srange) { // Sort the array by minimum z DIALS_ASSERT(a.size() > 0); DIALS_ASSERT(srange[1] > srange[0]); shared<int> index(a.size()); for (std::size_t i = 0; i < index.size(); ++i) index[i] = i; std::sort(index.begin(), index.end(), CompareMinZ(a)); // Get the bbox and panel int6 bbox = a[0].bbox; std::size_t panel = a[0].panel; // Loop through and check ranges are valid and within the bbox range DIALS_ASSERT(a[index[0]].is_consistent()); DIALS_ASSERT(a[index[0]].zrange[0] == std::max(bbox[4], srange[0])); for (std::size_t i = 1; i < index.size(); ++i) { DIALS_ASSERT(a[index[i]].is_consistent()); DIALS_ASSERT(a[index[i]].bbox.all_eq(bbox)); DIALS_ASSERT(a[index[i]].panel == panel); int2 z0 = a[index[i-1]].zrange; int2 z1 = a[index[i]].zrange; DIALS_ASSERT(z1[0] == z0[1]); } DIALS_ASSERT(a[index.back()].zrange[1] <= std::min(bbox[5], srange[1])); // Copy all the data PartialShoebox shoebox(panel, bbox, int2(bbox[4], bbox[5])); shoebox.allocate(); std::size_t xysize = shoebox.xsize() * shoebox.ysize(); for (std::size_t i = 0; i < a.size(); ++i) { std::size_t offset = (a[i].zrange[0] - bbox[4]) * xysize; for (std::size_t j = 0; j < a[i].data.size(); ++j) { shoebox.data[offset + j] = a[i].data[j]; } } // Return the new shoebox return shoebox; } /** * Merge all shoeboxes and return indices and shoeboxes */ std::pair< af::shared<std::size_t>, af::shared<PartialShoebox> > merge_all(const const_ref<PartialShoebox> &shoeboxes, const const_ref<std::size_t> &indices, int2 srange) { // Some useful typedefs typedef boost::unordered_map<std::size_t, af::shared<PartialShoebox> > map_type; typedef map_type::iterator iterator; // Construct a map of the shoeboxes to merge DIALS_ASSERT(indices.size() == shoeboxes.size()); map_type tomerge(indices.size()); for (std::size_t i = 0; i < indices.size(); ++i) { tomerge[indices[i]].push_back(shoeboxes[i]); } // Merge all the shoeboxes af::shared<std::size_t> cindices; af::shared<PartialShoebox> cshoeboxes; for (iterator it = tomerge.begin(); it != tomerge.end(); ++it) { cindices.push_back(it->first); cshoeboxes.push_back(merge(it->second.const_ref(), srange)); } return std::make_pair(cindices, cshoeboxes); } /** * A class to convert the shoebox class to a string for pickling */ struct partial_shoebox_to_string : pickle_double_buffered::to_string { using pickle_double_buffered::to_string::operator<<; /** Initialise with the version for checking */ partial_shoebox_to_string() { unsigned int version = 1; *this << version; } /** Convert a single shoebox instance to string */ partial_shoebox_to_string& operator<<(const PartialShoebox &val) { *this << val.panel << val.bbox[0] << val.bbox[1] << val.bbox[2] << val.bbox[3] << val.bbox[4] << val.bbox[5] << val.zrange[0] << val.zrange[1]; profile_to_string(val.data); return *this; } /** Convert a profile to string */ template <typename ProfileType> void profile_to_string(const ProfileType &p) { *this << p.accessor().size(); for (std::size_t i = 0; i < p.accessor().size(); ++i) { *this << p.accessor()[i]; } for (std::size_t i = 0; i < p.size(); ++i) { *this << p[i]; } } }; /** * A class to convert a string to a shoebox for unpickling */ struct partial_shoebox_from_string : pickle_double_buffered::from_string { using pickle_double_buffered::from_string::operator>>; /** Initialise the class with the string. Get the version and check */ partial_shoebox_from_string(const char* str_ptr) : pickle_double_buffered::from_string(str_ptr) { *this >> version; DIALS_ASSERT(version == 1); } /** Get a single shoebox instance from a string */ partial_shoebox_from_string& operator>>(PartialShoebox &val) { *this >> val.panel >> val.bbox[0] >> val.bbox[1] >> val.bbox[2] >> val.bbox[3] >> val.bbox[4] >> val.bbox[5] >> val.zrange[0] >> val.zrange[1]; val.data = profile_from_string< versa<int, c_grid<3> > >(); return *this; } /** Get a profile from a string */ template <typename ProfileType> ProfileType profile_from_string() { typename ProfileType::accessor_type accessor; typename ProfileType::size_type n_dim; *this >> n_dim; DIALS_ASSERT(n_dim == accessor.size()); for (std::size_t i = 0; i < n_dim; ++i) { *this >> accessor[i]; } ProfileType p = ProfileType(accessor); for (std::size_t i = 0; i < p.size(); ++i) { *this >> p[i]; } return p; } unsigned int version; }; scitbx::af::boost_python::flex_wrapper< PartialShoebox, return_internal_reference<> >::class_f_t flex_partial_shoebox_wrapper(const char *name) { return scitbx::af::boost_python::flex_wrapper < PartialShoebox, return_internal_reference<> >::plain(name) .def("is_consistent", &is_consistent) .def("panels", &panels) .def("bounding_boxes", &bounding_boxes) .def("zranges", &zranges) .def("merge", &merge) .def("merge_all", &merge_all) .def_pickle(flex_pickle_double_buffered<PartialShoebox, partial_shoebox_to_string, partial_shoebox_from_string>()); } void export_flex_partial_shoebox() { flex_partial_shoebox_wrapper("partial_shoebox"); boost_adaptbx::std_pair_conversions::to_and_from_tuple< af::shared<std::size_t>, af::shared<PartialShoebox> >(); } }}} // namespace dials::af::boost_python <|endoftext|>
<commit_before>#include "filehandler.h" /** * @brief FileHandler::FileHandler * Initilize filehandler and set * default value for workspace */ FileHandler::FileHandler() { this->project_id = 0; // zero out counter ids this->file_id = 0; this->dir_id = 0; this->last_error = false; #ifdef _WIN32 this->work_space = create_directory("C:/"); #elif __APPLE__ this->work_space = create_directory("/Applications/"); #elif __unix__ this->work_space = create_directory("~/"); #endif //ID id = add_file("ViAn_config.txt"); Will be used to store current workspace and other run-to-run coonstans } /** * @todo save workspace to file * @brief FileHandler::set_workspace * @param new_work_space * Change default work_space, ie where project files are saved. */ void FileHandler::set_work_space(std::string new_work_space){ //this->work_space = new_work_space; //save_workspace(); } /** * @brief FileHandler::get_work_space * @return default work_space */ QDir FileHandler::get_work_space() { return this->get_dir(this->work_space); } /** * @brief FileHandler::create_project * creates project and associated files. * @param std::string name * @return Project* created project */ Project* FileHandler::create_project(QString proj_name, std::string dir_path){ Project* proj = new Project(this->project_id, proj_name.toStdString()); ID root_dir; if(dir_path != "") //Directory name provided root_dir = create_directory(QString::fromStdString(dir_path)); else if(dir_path != "" && proj->dir == -1) // No directory name provided, project has no directory. root_dir = this->work_space; // Default save location to workspace else if(dir_path == "" && proj->dir != -1) // No Directory provided and project previosuly saved root_dir = proj->dir; // Use present save location else root_dir = this->work_space; proj->dir = create_directory(get_dir(root_dir).absoluteFilePath(QString::fromStdString(proj->name))); add_project(proj); // Add project to file sytstem save_project(proj); // Save project file return proj; } /** * @brief FileHandler::create_directory * @param dir_path * @return id * Creates a directory and all directories needed for that directory, ie * "C:/THIS/IS/A/PATH/" will create THIS, IS, A and PATH directories if these do not exist. */ ID FileHandler::create_directory(QString dir_path){ QDir dir (QDir::root()); last_error = !dir.mkpath(dir_path); if(!last_error){ qWarning("Could not create directory %s",dir_path.toStdString().c_str()); } dir.setPath(dir_path); ID id = this->add_dir(dir); return id; } /** * @brief FileHandler::delete_directory * @param id * @return bool, success. * Deletes a given directory */ bool FileHandler::delete_directory(ID id){ QDir temp = this->get_dir(id); this->dir_map_lock.lock(); // Order important, locked in getter if(temp.rmdir(temp.absolutePath())){ this->dir_map.erase(id); this->dir_map_lock.unlock(); return true; } this->dir_map_lock.unlock(); return false; } /** * @brief FileHandler::save_project * @param id * Save projects, exposed interface. * Here for simplicity of call as well as hiding save format. */ void FileHandler::save_project(ID id){ Project* proj = get_project(id); this->save_project(proj, proj->dir, FileHandler::SaveFormat::Json); // get project and save it } /** * @brief FileHandler::save_project * @param proj * Exposed interface, added for simplicity of call when * project pointer is still available */ void FileHandler::save_project(Project* proj){ this->save_project(proj, proj->dir, FileHandler::SaveFormat::Json); } /** * @brief FileHandler::save_project * @param proj * @param dir_path * @param save_format * @return Saves a Json file to provided directory */ bool FileHandler::save_project(Project* proj, ID dir_id, FileHandler::SaveFormat save_format){ QDir dir = get_dir(dir_id); std::string file_path = dir.absoluteFilePath(QString::fromStdString(proj->name)).toStdString(); QFile save_file(save_format == Json ? QString::fromStdString(file_path + ".json") : QString::fromStdString(file_path + ".dat")); if(!save_file.open(QIODevice::WriteOnly)){ return false; } QJsonObject json_proj; proj->write(json_proj); QJsonDocument save_doc(json_proj); save_file.write(save_format == Json ? save_doc.toJson() : save_doc.toBinaryData()); return true; } /** * @brief FileHandler::load_project * @param full_project_path * @return loaded Project * Public load function * Used for simplicity of call and * for hiding save format. */ Project* FileHandler::load_project(std::string full_project_path){ return load_project(full_project_path, Json); // Decide format internally, here for flexibility } /** * @brief FileHandler::load_project * @param full_project_path * @param save_format * @return loaded Project * Loads project from json file and returns it */ Project* FileHandler::load_project(std::string full_path, FileHandler::SaveFormat save_form){ QFile load_file(save_form == Json ? QString::fromStdString(full_path) : QString::fromStdString(full_path)); if (!load_file.open(QIODevice::ReadOnly)) { qWarning("Couldn't open save file."); return nullptr; } QByteArray save_data = load_file.readAll(); QJsonDocument load_doc(save_form == Json ? QJsonDocument::fromJson(save_data) : QJsonDocument::fromBinaryData(save_data)); Project* proj = new Project(); proj->saved = true; proj->read(load_doc.object()); proj->id = add_project(proj); proj->dir = add_dir(QDir(QString::fromStdString(full_path.substr(0, full_path.find_last_of("/"))))); return proj; } /** * @brief FileHandler::delete_project * @param proj_id * @return Deletes project entirely * Deletes project and frees allocated memory. */ bool FileHandler::delete_project(ID proj_id){ Project* temp = get_project(proj_id); this->proj_map_lock.lock(); QFile file(get_dir(temp->dir).absoluteFilePath(QString::fromStdString(temp->name + ".json"))); if(this->projects.erase(proj_id)){ file.remove(); delete_directory(temp->dir); delete temp; this->proj_map_lock.unlock(); return true; } this->proj_map_lock.unlock(); return false; } /** * @todo make threadsafe * @brief FileHandler::add_video * @param Project*,string file_path * Add a video file_path to a given project. * Creates Video object which is accessed further by returned id. */ ID FileHandler::add_video(Project* proj, std::string file_path){ Video* v = new Video(file_path); return proj->add_video(v); // video id set in proj->add_video } /** * @brief FileHandler::remove_video_from_project * @param proj_id * @param vid_id * Removes video from project according to given ids. */ void FileHandler::remove_video_from_project(ID proj_id, ID vid_id){ Project* proj = this->get_project(proj_id); // get Project object from id proj->remove_video(vid_id); // Remove ´the video from project } /** * @brief FileHandler::create_file * @param std::string file name, ID directory id * create a file by given name in already existing * application tracked directory. * Note that the file is not actually created * in the file system until the file is written to. */ ID FileHandler::create_file(QString file_name, QDir dir){ return this->add_file(dir.absoluteFilePath(file_name)); // File created } /** * @brief FileHandler::delete_file * delete application tracked file * @param ID file id */ bool FileHandler::delete_file(ID id){ QFile file(this->get_file(id)); file.remove(); return this->file_map.erase(id); } /** * @todo make threadsafe * @brief FileHandler::write_file * Write given text to an application tracked file * @param ID file id, std::string text * @return void * Write given text with OPTION opt, supported OPTIONs are append and overwrite. */ void FileHandler::write_file(ID id, QString text, WRITE_OPTION opt){ QFile file; file.setFileName(this->get_file(id)); switch(opt){ case OVERWRITE: if(!file.open(QIODevice::ReadWrite | QIODevice::QIODevice::Truncate |QIODevice::Text))return; // Empty file break; case APPEND: if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append)) return; // File can not be written break; default: if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)) return; // File can not be written break; } QTextStream out(&file); out << text; file.close(); } /** * @brief FileHandler::read_file * @param ID file id, std::string text * @return voi * Read given lenght of lines to buffer from application * tracked file. OBS! If number of lines exceeds lines in file, * reads to end of file (EOF) */ void FileHandler::read_file(ID id, QString& buf, int lines_to_read){ QFile file (this->get_file(id)); if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){ qWarning("File %s could not be read", file.fileName().toStdString().c_str()); return; // File can not be read } QTextStream in(&file); QString line; while(lines_to_read-- && !in.atEnd()){ line = in.readLine(); buf.append(line); }; file.close(); } /** * @brief FileHandler::get_project * @param ID project id * @return Project* * Gets project by ID, locks in doing so. */ Project* FileHandler::get_project(ID id){ this->proj_map_lock.lock(); Project* p = this->projects.at(id); this->proj_map_lock.unlock(); return p; } /** * @brief FileHandler::get_file * Getter * @param ID project file id * @return std::string file_path * Get file by ID, locks in doing so. */ QString FileHandler::get_file(ID id){ this->file_map_lock.lock(); QString file = this->file_map.at(id); this->file_map_lock.unlock(); return file; } /** * @brief FileHandler::get_dir * @param ID directory id * @return directory path * Gets directory by id, locks in doing so. */ QDir FileHandler::get_dir(ID id){ this->dir_map_lock.lock(); QDir dir = this->dir_map.at(id); this->dir_map_lock.unlock(); return dir; } /** * @brief FileHandler::add_project * @param proj * Adds project to map. */ ID FileHandler::add_project(Project* proj){ add_project(this->project_id, proj); return this->project_id++; } /** * @brief FileHandler::add_project * @param std::pari<<ID, Project*> pair * @return void * Adds project to projects, locks in doing so. */ void FileHandler::add_project(ID id, Project* proj){ std::pair<ID,Project*> pair = std::make_pair(id,proj); this->proj_map_lock.lock(); this->projects.insert(pair); this->proj_map_lock.unlock(); } /** * @brief FileHandler::add_file * @param std::string file_path * @return unique file identifier * Adds file to filesystem. */ ID FileHandler::add_file(QString file){ add_file(this->file_id, file); return this->file_id++; } /** * @brief FileHandler::add_file * @param id * @param file_path * Adds file to file_map, locks in doing so. */ void FileHandler::add_file(ID id ,QString file){ std::pair<ID,QString> pair = std::make_pair(id, file); this->file_map_lock.lock(); this->file_map.insert(pair); this->file_map_lock.unlock(); } /** * @brief FileHandler::add_dir * @param std::string dir_path * @return unique directory identifier * Adds directory to directories, locks in doing so. */ ID FileHandler::add_dir(QDir dir){ add_dir(this->dir_id, dir); return this->dir_id++; } /** * @brief FileHandler::add_dir * @param dir * Inserts directory by id in directories. */ void FileHandler::add_dir(ID dir_id, QDir dir){ std::pair<ID,QDir> pair = std::make_pair(this->dir_id, dir); this->dir_map_lock.lock(); this->dir_map.insert(pair); this->dir_map_lock.unlock(); } /** * @brief FileHandler::proj_equals * @param proj * @param proj2 * @return true if project contents are the same */ bool FileHandler::proj_equals(Project& proj, Project& proj2){ bool video_equals = std::equal(proj.videos.begin(), proj.videos.end(), proj2.videos.begin(), [](const std::pair<ID,Video*> v, const std::pair<ID,Video*> v2){return *(v.second) == *(v2.second);}); // lambda function comparing using video== // by dereferencing pointers in vector return proj.name == proj2.name && video_equals; } <commit_msg>oops, double negation<commit_after>#include "filehandler.h" /** * @brief FileHandler::FileHandler * Initilize filehandler and set * default value for workspace */ FileHandler::FileHandler() { this->project_id = 0; // zero out counter ids this->file_id = 0; this->dir_id = 0; this->last_error = false; #ifdef _WIN32 this->work_space = create_directory("C:/"); #elif __APPLE__ this->work_space = create_directory("/Applications/"); #elif __unix__ this->work_space = create_directory("~/"); #endif //ID id = add_file("ViAn_config.txt"); Will be used to store current workspace and other run-to-run coonstans } /** * @todo save workspace to file * @brief FileHandler::set_workspace * @param new_work_space * Change default work_space, ie where project files are saved. */ void FileHandler::set_work_space(std::string new_work_space){ //this->work_space = new_work_space; //save_workspace(); } /** * @brief FileHandler::get_work_space * @return default work_space */ QDir FileHandler::get_work_space() { return this->get_dir(this->work_space); } /** * @brief FileHandler::create_project * creates project and associated files. * @param std::string name * @return Project* created project */ Project* FileHandler::create_project(QString proj_name, std::string dir_path){ Project* proj = new Project(this->project_id, proj_name.toStdString()); ID root_dir; if(dir_path != "") //Directory name provided root_dir = create_directory(QString::fromStdString(dir_path)); else if(dir_path != "" && proj->dir == -1) // No directory name provided, project has no directory. root_dir = this->work_space; // Default save location to workspace else if(dir_path == "" && proj->dir != -1) // No Directory provided and project previosuly saved root_dir = proj->dir; // Use present save location else root_dir = this->work_space; proj->dir = create_directory(get_dir(root_dir).absoluteFilePath(QString::fromStdString(proj->name))); add_project(proj); // Add project to file sytstem save_project(proj); // Save project file return proj; } /** * @brief FileHandler::create_directory * @param dir_path * @return id * Creates a directory and all directories needed for that directory, ie * "C:/THIS/IS/A/PATH/" will create THIS, IS, A and PATH directories if these do not exist. */ ID FileHandler::create_directory(QString dir_path){ QDir dir (QDir::root()); last_error = !dir.mkpath(dir_path); if(last_error){ qWarning("Could not create directory %s",dir_path.toStdString().c_str()); } dir.setPath(dir_path); ID id = this->add_dir(dir); return id; } /** * @brief FileHandler::delete_directory * @param id * @return bool, success. * Deletes a given directory */ bool FileHandler::delete_directory(ID id){ QDir temp = this->get_dir(id); this->dir_map_lock.lock(); // Order important, locked in getter if(temp.rmdir(temp.absolutePath())){ this->dir_map.erase(id); this->dir_map_lock.unlock(); return true; } this->dir_map_lock.unlock(); return false; } /** * @brief FileHandler::save_project * @param id * Save projects, exposed interface. * Here for simplicity of call as well as hiding save format. */ void FileHandler::save_project(ID id){ Project* proj = get_project(id); this->save_project(proj, proj->dir, FileHandler::SaveFormat::Json); // get project and save it } /** * @brief FileHandler::save_project * @param proj * Exposed interface, added for simplicity of call when * project pointer is still available */ void FileHandler::save_project(Project* proj){ this->save_project(proj, proj->dir, FileHandler::SaveFormat::Json); } /** * @brief FileHandler::save_project * @param proj * @param dir_path * @param save_format * @return Saves a Json file to provided directory */ bool FileHandler::save_project(Project* proj, ID dir_id, FileHandler::SaveFormat save_format){ QDir dir = get_dir(dir_id); std::string file_path = dir.absoluteFilePath(QString::fromStdString(proj->name)).toStdString(); QFile save_file(save_format == Json ? QString::fromStdString(file_path + ".json") : QString::fromStdString(file_path + ".dat")); if(!save_file.open(QIODevice::WriteOnly)){ return false; } QJsonObject json_proj; proj->write(json_proj); QJsonDocument save_doc(json_proj); save_file.write(save_format == Json ? save_doc.toJson() : save_doc.toBinaryData()); return true; } /** * @brief FileHandler::load_project * @param full_project_path * @return loaded Project * Public load function * Used for simplicity of call and * for hiding save format. */ Project* FileHandler::load_project(std::string full_project_path){ return load_project(full_project_path, Json); // Decide format internally, here for flexibility } /** * @brief FileHandler::load_project * @param full_project_path * @param save_format * @return loaded Project * Loads project from json file and returns it */ Project* FileHandler::load_project(std::string full_path, FileHandler::SaveFormat save_form){ QFile load_file(save_form == Json ? QString::fromStdString(full_path) : QString::fromStdString(full_path)); if (!load_file.open(QIODevice::ReadOnly)) { qWarning("Couldn't open save file."); return nullptr; } QByteArray save_data = load_file.readAll(); QJsonDocument load_doc(save_form == Json ? QJsonDocument::fromJson(save_data) : QJsonDocument::fromBinaryData(save_data)); Project* proj = new Project(); proj->saved = true; proj->read(load_doc.object()); proj->id = add_project(proj); proj->dir = add_dir(QDir(QString::fromStdString(full_path.substr(0, full_path.find_last_of("/"))))); return proj; } /** * @brief FileHandler::delete_project * @param proj_id * @return Deletes project entirely * Deletes project and frees allocated memory. */ bool FileHandler::delete_project(ID proj_id){ Project* temp = get_project(proj_id); this->proj_map_lock.lock(); QFile file(get_dir(temp->dir).absoluteFilePath(QString::fromStdString(temp->name + ".json"))); if(this->projects.erase(proj_id)){ file.remove(); delete_directory(temp->dir); delete temp; this->proj_map_lock.unlock(); return true; } this->proj_map_lock.unlock(); return false; } /** * @todo make threadsafe * @brief FileHandler::add_video * @param Project*,string file_path * Add a video file_path to a given project. * Creates Video object which is accessed further by returned id. */ ID FileHandler::add_video(Project* proj, std::string file_path){ Video* v = new Video(file_path); return proj->add_video(v); // video id set in proj->add_video } /** * @brief FileHandler::remove_video_from_project * @param proj_id * @param vid_id * Removes video from project according to given ids. */ void FileHandler::remove_video_from_project(ID proj_id, ID vid_id){ Project* proj = this->get_project(proj_id); // get Project object from id proj->remove_video(vid_id); // Remove ´the video from project } /** * @brief FileHandler::create_file * @param std::string file name, ID directory id * create a file by given name in already existing * application tracked directory. * Note that the file is not actually created * in the file system until the file is written to. */ ID FileHandler::create_file(QString file_name, QDir dir){ return this->add_file(dir.absoluteFilePath(file_name)); // File created } /** * @brief FileHandler::delete_file * delete application tracked file * @param ID file id */ bool FileHandler::delete_file(ID id){ QFile file(this->get_file(id)); file.remove(); return this->file_map.erase(id); } /** * @todo make threadsafe * @brief FileHandler::write_file * Write given text to an application tracked file * @param ID file id, std::string text * @return void * Write given text with OPTION opt, supported OPTIONs are append and overwrite. */ void FileHandler::write_file(ID id, QString text, WRITE_OPTION opt){ QFile file; file.setFileName(this->get_file(id)); switch(opt){ case OVERWRITE: if(!file.open(QIODevice::ReadWrite | QIODevice::QIODevice::Truncate |QIODevice::Text))return; // Empty file break; case APPEND: if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append)) return; // File can not be written break; default: if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)) return; // File can not be written break; } QTextStream out(&file); out << text; file.close(); } /** * @brief FileHandler::read_file * @param ID file id, std::string text * @return voi * Read given lenght of lines to buffer from application * tracked file. OBS! If number of lines exceeds lines in file, * reads to end of file (EOF) */ void FileHandler::read_file(ID id, QString& buf, int lines_to_read){ QFile file (this->get_file(id)); if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){ qWarning("File %s could not be read", file.fileName().toStdString().c_str()); return; // File can not be read } QTextStream in(&file); QString line; while(lines_to_read-- && !in.atEnd()){ line = in.readLine(); buf.append(line); }; file.close(); } /** * @brief FileHandler::get_project * @param ID project id * @return Project* * Gets project by ID, locks in doing so. */ Project* FileHandler::get_project(ID id){ this->proj_map_lock.lock(); Project* p = this->projects.at(id); this->proj_map_lock.unlock(); return p; } /** * @brief FileHandler::get_file * Getter * @param ID project file id * @return std::string file_path * Get file by ID, locks in doing so. */ QString FileHandler::get_file(ID id){ this->file_map_lock.lock(); QString file = this->file_map.at(id); this->file_map_lock.unlock(); return file; } /** * @brief FileHandler::get_dir * @param ID directory id * @return directory path * Gets directory by id, locks in doing so. */ QDir FileHandler::get_dir(ID id){ this->dir_map_lock.lock(); QDir dir = this->dir_map.at(id); this->dir_map_lock.unlock(); return dir; } /** * @brief FileHandler::add_project * @param proj * Adds project to map. */ ID FileHandler::add_project(Project* proj){ add_project(this->project_id, proj); return this->project_id++; } /** * @brief FileHandler::add_project * @param std::pari<<ID, Project*> pair * @return void * Adds project to projects, locks in doing so. */ void FileHandler::add_project(ID id, Project* proj){ std::pair<ID,Project*> pair = std::make_pair(id,proj); this->proj_map_lock.lock(); this->projects.insert(pair); this->proj_map_lock.unlock(); } /** * @brief FileHandler::add_file * @param std::string file_path * @return unique file identifier * Adds file to filesystem. */ ID FileHandler::add_file(QString file){ add_file(this->file_id, file); return this->file_id++; } /** * @brief FileHandler::add_file * @param id * @param file_path * Adds file to file_map, locks in doing so. */ void FileHandler::add_file(ID id ,QString file){ std::pair<ID,QString> pair = std::make_pair(id, file); this->file_map_lock.lock(); this->file_map.insert(pair); this->file_map_lock.unlock(); } /** * @brief FileHandler::add_dir * @param std::string dir_path * @return unique directory identifier * Adds directory to directories, locks in doing so. */ ID FileHandler::add_dir(QDir dir){ add_dir(this->dir_id, dir); return this->dir_id++; } /** * @brief FileHandler::add_dir * @param dir * Inserts directory by id in directories. */ void FileHandler::add_dir(ID dir_id, QDir dir){ std::pair<ID,QDir> pair = std::make_pair(this->dir_id, dir); this->dir_map_lock.lock(); this->dir_map.insert(pair); this->dir_map_lock.unlock(); } /** * @brief FileHandler::proj_equals * @param proj * @param proj2 * @return true if project contents are the same */ bool FileHandler::proj_equals(Project& proj, Project& proj2){ bool video_equals = std::equal(proj.videos.begin(), proj.videos.end(), proj2.videos.begin(), [](const std::pair<ID,Video*> v, const std::pair<ID,Video*> v2){return *(v.second) == *(v2.second);}); // lambda function comparing using video== // by dereferencing pointers in vector return proj.name == proj2.name && video_equals; } <|endoftext|>