text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2014 Author: Jeff Weisberg <jaw @ solvemedia.com> Created: 2014-Mar-21 16:04 (EDT) Function: the running task pipeline */ #define CURRENT_SUBSYSTEM 't' #include "defs.h" #include "diag.h" #include "config.h" #include "misc.h" #include "network.h" #include "pipeline.h" #include "mrmagoo.pb.h" #include "std_reply.pb.h" #include <sys/types.h> #include <poll.h> #include <sys/socket.h> #include <signal.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/wait.h> #include <libgen.h> // RSN - config #define CATPROG "/usr/bin/cat" #define GZCATPROG "/usr/bin/gzcat" #define SORTPROG "/usr/bin/sort" static int spawn(const char *, const ACPMRMTaskCreate *, int, int, int, int, bool); static char sort_tmp[256]; void pipeline_init(void){ // create a tmp directory for sort snprintf(sort_tmp, sizeof(sort_tmp), "%s/mrtmp/sort", config->basedir.c_str()); int e = mkdir( sort_tmp, 0777 ); chmod( sort_tmp, 0777 ); if( e && errno != EEXIST ){ PROBLEM("cannot create tmp dir: %s: %s", sort_tmp, strerror(errno)); sort_tmp[0] = 0; } } Pipeline::~Pipeline(){ _cleanup(); } void Pipeline::_cleanup(void){ // remove tmpfile if( ! _tmpfile.empty() ) unlink( _tmpfile.c_str() ); } void Pipeline::abort(void){ DEBUG("abort"); _cleanup(); if( _pid ) kill( _pid, 9 ); } bool Pipeline::still_producing(void){ // is the input pipeline still running? int ev; int w = ::waitpid( _inpid, &ev, WNOHANG ); return (w == _inpid) ? 0 : 1; } int Pipeline::waitpid(void){ int w, exitval; for(int t=0; t<10; t++){ w = ::waitpid( _pid, &exitval, WNOHANG ); if( w == _pid ){ // finished DEBUG("wait value %d", exitval); _cleanup(); return exitval; } // not done yet? wait a bit, maybe kill it if( t > 7 ) kill( _pid, 3 ); sleep(1); } // kill 9 abort(); ::waitpid( _pid, &exitval, 0 ); DEBUG("wait again value %d", exitval); return exitval; } static void _fail(const char *msg){ // uh oh! BUG("%s: %s", msg, strerror(errno)); exit(-1); } static int set_nbio(int fd){ fcntl(fd, F_SETFL, O_NDELAY); return fd; } // create one of: // map: // cat files | prog // gzcat files | prog // reduce: // sort files | prog // gzcat files | sort | prog Pipeline::Pipeline(const ACPMRMTaskCreate *g, int* outfds){ // save job src in tmp file _tmpfile = config->basedir; _tmpfile.append("/mrtmp/bin"); mkdirp( _tmpfile.c_str(), 0777 ); _tmpfile.append("/p"); unique( &_tmpfile ); DEBUG("tmpfile: %s", _tmpfile.c_str()); int tfd = open( _tmpfile.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0755 ); if( tfd < 0 ) _fail("open failed"); const string *jobsrc = & g->jobsrc(); write( tfd, jobsrc->c_str(), jobsrc->size() ); close(tfd); // [read write] int pprogin[2]; // pipe into prog int pprogout[2]; // std out from prog int pprogerr[2]; // std err from prog int pprogdat[2]; // data from prog int pinterm[2]; // intermediate pipe, if needed int unusedfd = pprogerr[1]; // tie unneeded fds to stderr // set up pipes for the end-user program DEBUG("creating pipes"); if( pipe(pprogin) ) _fail( "pipe failed"); if( pipe(pprogout) ) _fail( "pipe failed"); if( pipe(pprogerr) ) _fail( "pipe failed"); if( pipe(pprogdat) ) _fail( "pipe failed"); // attach these (non-blockingly) back to task.cc:run_task_prog() outfds[0] = set_nbio( pprogout[0] ); outfds[1] = set_nbio( pprogerr[0] ); outfds[2] = set_nbio( pprogdat[0] ); // spawn the end-user program _pid = spawn( _tmpfile.c_str(), 0, pprogin[0], pprogout[1], pprogerr[1], pprogdat[1], 0 ); DEBUG("spawn job prog: %d", _pid); // what do we need to run? // XXX - currently, all files are assumed to be compressed. // should be configurable. const char *e1=0, *e2=0; if( !g->phase().compare("map") ){ // gzcat files e1 = GZCATPROG; pinterm[1] = pprogin[1]; }else{ // gzcat files | sort e1 = GZCATPROG; e2 = SORTPROG; if( pipe(pinterm) ) _fail( "pipe failed"); } // intermediate? if( e2 ){ int p2 = spawn( e2, 0, pinterm[0], pprogin[1], pprogerr[1], unusedfd, sort_tmp[0] ); DEBUG("spawn %s: %d", e2, p2); _inpid = p2; } // initial prog (with files) // QQQ - stdin? int p1 = spawn( e1, g, unusedfd, pinterm[1], pprogerr[1], 0, 0 ); DEBUG("spawn %s %d", e1, p1); if( !e2 ) _inpid = p1; // close the far ends of the pipes close(pprogin[0]); close(pprogin[1]); close(pprogout[1]); close(pprogerr[1]); close(pprogdat[1]); if( e2 ){ close(pinterm[0]); close(pinterm[1]); } } static int spawn(const char *prog, const ACPMRMTaskCreate *g, int fin, int fout, int ferr, int fdat, bool issort){ // fork // wire up fds // exec int pid = fork(); if( pid == -1 ) _fail("fork failed"); // parent => done if( pid ) return pid; // child // rewire fds dup2( fin, 0 ); dup2( fout, 1 ); dup2( ferr, 2 ); dup2( fdat, 3 ); for(int i=4; i<256; i++) close(i); // build argv int argc = g ? g->infile_size() : 0; if( issort ) argc += 2; const char * argv[argc + 2]; argv[0] = (char*)prog; if( issort ){ argv[1] = "-T"; argv[2] = sort_tmp; }else if( g ){ for(int i=0; i<argc; i++){ argv[i+1] = g->infile(i).c_str(); } } argv[argc+1] = 0; // make sure we are not running as root setregid(65535, 65535); setreuid(65535, 65535); signal( SIGPIPE, SIG_DFL ); execv(prog, (char**)argv); VERBOSE("exec failed %s: %s", prog, strerror(errno)); _fail("exec failed"); } <commit_msg>make sure intermediate dir exists<commit_after>/* Copyright (c) 2014 Author: Jeff Weisberg <jaw @ solvemedia.com> Created: 2014-Mar-21 16:04 (EDT) Function: the running task pipeline */ #define CURRENT_SUBSYSTEM 't' #include "defs.h" #include "diag.h" #include "config.h" #include "misc.h" #include "network.h" #include "pipeline.h" #include "mrmagoo.pb.h" #include "std_reply.pb.h" #include <sys/types.h> #include <poll.h> #include <sys/socket.h> #include <signal.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/wait.h> #include <libgen.h> // RSN - config #define CATPROG "/usr/bin/cat" #define GZCATPROG "/usr/bin/gzcat" #define SORTPROG "/usr/bin/sort" static int spawn(const char *, const ACPMRMTaskCreate *, int, int, int, int, bool); static char sort_tmp[256]; void pipeline_init(void){ // create a tmp directory for sort snprintf(sort_tmp, sizeof(sort_tmp), "%s/mrtmp", config->basedir.c_str()); int e = mkdir( sort_tmp, 0777 ); chmod( sort_tmp, 0777 ); snprintf(sort_tmp, sizeof(sort_tmp), "%s/mrtmp/sort", config->basedir.c_str()); e = mkdir( sort_tmp, 0777 ); chmod( sort_tmp, 0777 ); if( e && errno != EEXIST ){ PROBLEM("cannot create tmp dir: %s: %s", sort_tmp, strerror(errno)); sort_tmp[0] = 0; } } Pipeline::~Pipeline(){ _cleanup(); } void Pipeline::_cleanup(void){ // remove tmpfile if( ! _tmpfile.empty() ) unlink( _tmpfile.c_str() ); } void Pipeline::abort(void){ DEBUG("abort"); _cleanup(); if( _pid ) kill( _pid, 9 ); } bool Pipeline::still_producing(void){ // is the input pipeline still running? int ev; int w = ::waitpid( _inpid, &ev, WNOHANG ); return (w == _inpid) ? 0 : 1; } int Pipeline::waitpid(void){ int w, exitval; for(int t=0; t<10; t++){ w = ::waitpid( _pid, &exitval, WNOHANG ); if( w == _pid ){ // finished DEBUG("wait value %d", exitval); _cleanup(); return exitval; } // not done yet? wait a bit, maybe kill it if( t > 7 ) kill( _pid, 3 ); sleep(1); } // kill 9 abort(); ::waitpid( _pid, &exitval, 0 ); DEBUG("wait again value %d", exitval); return exitval; } static void _fail(const char *msg){ // uh oh! BUG("%s: %s", msg, strerror(errno)); exit(-1); } static int set_nbio(int fd){ fcntl(fd, F_SETFL, O_NDELAY); return fd; } // create one of: // map: // cat files | prog // gzcat files | prog // reduce: // sort files | prog // gzcat files | sort | prog Pipeline::Pipeline(const ACPMRMTaskCreate *g, int* outfds){ // save job src in tmp file _tmpfile = config->basedir; _tmpfile.append("/mrtmp/bin"); mkdirp( _tmpfile.c_str(), 0777 ); _tmpfile.append("/p"); unique( &_tmpfile ); DEBUG("tmpfile: %s", _tmpfile.c_str()); int tfd = open( _tmpfile.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0755 ); if( tfd < 0 ) _fail("open failed"); const string *jobsrc = & g->jobsrc(); write( tfd, jobsrc->c_str(), jobsrc->size() ); close(tfd); // [read write] int pprogin[2]; // pipe into prog int pprogout[2]; // std out from prog int pprogerr[2]; // std err from prog int pprogdat[2]; // data from prog int pinterm[2]; // intermediate pipe, if needed int unusedfd = pprogerr[1]; // tie unneeded fds to stderr // set up pipes for the end-user program DEBUG("creating pipes"); if( pipe(pprogin) ) _fail( "pipe failed"); if( pipe(pprogout) ) _fail( "pipe failed"); if( pipe(pprogerr) ) _fail( "pipe failed"); if( pipe(pprogdat) ) _fail( "pipe failed"); // attach these (non-blockingly) back to task.cc:run_task_prog() outfds[0] = set_nbio( pprogout[0] ); outfds[1] = set_nbio( pprogerr[0] ); outfds[2] = set_nbio( pprogdat[0] ); // spawn the end-user program _pid = spawn( _tmpfile.c_str(), 0, pprogin[0], pprogout[1], pprogerr[1], pprogdat[1], 0 ); DEBUG("spawn job prog: %d", _pid); // what do we need to run? // XXX - currently, all files are assumed to be compressed. // should be configurable. const char *e1=0, *e2=0; if( !g->phase().compare("map") ){ // gzcat files e1 = GZCATPROG; pinterm[1] = pprogin[1]; }else{ // gzcat files | sort e1 = GZCATPROG; e2 = SORTPROG; if( pipe(pinterm) ) _fail( "pipe failed"); } // intermediate? if( e2 ){ int p2 = spawn( e2, 0, pinterm[0], pprogin[1], pprogerr[1], unusedfd, sort_tmp[0] ); DEBUG("spawn %s: %d", e2, p2); _inpid = p2; } // initial prog (with files) // QQQ - stdin? int p1 = spawn( e1, g, unusedfd, pinterm[1], pprogerr[1], 0, 0 ); DEBUG("spawn %s %d", e1, p1); if( !e2 ) _inpid = p1; // close the far ends of the pipes close(pprogin[0]); close(pprogin[1]); close(pprogout[1]); close(pprogerr[1]); close(pprogdat[1]); if( e2 ){ close(pinterm[0]); close(pinterm[1]); } } static int spawn(const char *prog, const ACPMRMTaskCreate *g, int fin, int fout, int ferr, int fdat, bool issort){ // fork // wire up fds // exec int pid = fork(); if( pid == -1 ) _fail("fork failed"); // parent => done if( pid ) return pid; // child // rewire fds dup2( fin, 0 ); dup2( fout, 1 ); dup2( ferr, 2 ); dup2( fdat, 3 ); for(int i=4; i<256; i++) close(i); // build argv int argc = g ? g->infile_size() : 0; if( issort ) argc += 2; const char * argv[argc + 2]; argv[0] = (char*)prog; if( issort ){ argv[1] = "-T"; argv[2] = sort_tmp; }else if( g ){ for(int i=0; i<argc; i++){ argv[i+1] = g->infile(i).c_str(); } } argv[argc+1] = 0; // make sure we are not running as root setregid(65535, 65535); setreuid(65535, 65535); signal( SIGPIPE, SIG_DFL ); execv(prog, (char**)argv); VERBOSE("exec failed %s: %s", prog, strerror(errno)); _fail("exec failed"); } <|endoftext|>
<commit_before>/** * @file arm.cpp * @brief Purpose: Contains methods to arm class' management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include <assert.h> #include "../include/arm.hpp" #include "../include/platform.hpp" #include "../engine/include/log.hpp" using namespace mindscape; /** * @brief Arm constructor * * @param name Name for the given object * @param position Pair of integers for its position * @param priority Priority for rendering it on the screen * * @return void */ Arm::Arm( std::string name, std::pair<int, int> position, int priority ) : Enemy( name, position, priority, 100 ) { initialize_state_map(); initialize_hitboxes(); initialize_animations(); translations = { {engine::KeyboardEvent::LEFT, "MOVE_LEFT"}, {engine::KeyboardEvent::RIGHT, "MOVE_RIGHT"}, }; }; /** * @brief Event for collisions * * This method is triggered everytime a collision happens * * @param other The other game object which collided * @param p_my_hitbox This object hitbox that received the collision * @param p_other_hitbox The other object hitbox which provided the collision */ void Arm::on_collision(engine::GameObject *other, engine::Hitbox *p_my_hitbox, engine::Hitbox *p_other_hitbox) { Platform *platform = dynamic_cast<Platform *>(other); /**< Plataform. Plataform of the game */ engine::Hitbox *my_hitbox = dynamic_cast<engine::Hitbox *>(p_my_hitbox); /**< Hitbox. Arm hitbox */ engine::Hitbox *other_hitbox = dynamic_cast<engine::Hitbox *>(p_other_hitbox); /**< Hitbox. Girl hitbox */ assert(p_my_hitbox && p_other_hitbox && other); assert(my_hitbox && other_hitbox && platform); if (get_speed_y() >= 0 && platform && my_hitbox->get_name() == "arm_hitbox") { /* If arm is not falling */ const int movement_arm_axis_y = 30; /**< const int. Movement arm in pixel */ const float speed_arm = 0.0; /**< const float. Speed arm */ set_speed_y(speed_arm); set_position_y(other_hitbox->get_coordinates() .second - movement_arm_axis_y); states.set_state("Y_STATE", "ON_GROUND"); engine::Game::get_instance() .get_actual_scene()->deactivate_game_object(name); free(); } else { /* Do nothing */ } } /** * @brief Initialize object as a physicable object * * Using this method makes the object vulnerable to forces as gravity and collisions * * @return void */ void Arm::initialize_as_physicable() { engine::Physics *physics = engine::Physics::get_instance(); /**< Instance. Instance of the game */ assert(physics); physics->add_physicable(this); collidable = true; } /** * @brief Register an event * * This method register a GameEvent to the object * * @param game_event The event to be called * * @return void */ void Arm::on_event(GameEvent game_event) { assert(!game_event.game_event_name.empty()); std::string event_name = game_event.game_event_name; const int movement_arm = 10; /**< const int. Movemet of the arm in pixels */ if (event_name == "MOVE_LEFT" && !engine::GameObject::on_limit_of_level) { /* * If arm is moving left. * Moves position 10 pixels to the right. */ set_position_x(get_position_x() + movement_arm); } else if (event_name == "MOVE_RIGHT" && !engine::GameObject::on_limit_of_level) { /* * If arm is moving right. * Moves position 10 pixels to the left. */ set_position_x(get_position_x() - movement_arm); } else { INFO("Arm are not moving"); } } /** * @brief Initialize all the Arm's animations * * @return void */ void Arm::initialize_animations() { engine::Animation *right_arm = create_animation( "../assets/images/sprites/enemies/arm/right_arm.png", 1, 4, 3.0, "RIGHT" ); right_arm->set_values( std::make_pair(405, 542), std::make_pair(405, 542), std::make_pair(0, 0) ); add_animation("right_arm", right_arm); right_arm->activate(); engine::Animation *left_arm = create_animation( "../assets/images/sprites/enemies/arm/left_arm.png", 1, 4, 3.0, "LEFT" ); left_arm->set_values( std::make_pair(405, 542), std::make_pair(405, 542), std::make_pair(0, 0) ); add_animation("left_arm", left_arm); set_actual_animation(right_arm); } /** * @brief Creates the animations * * Creates new animations for this object * * @param image_path Path for the image file * @param sprite_lines Number of lines in the spritesheet * @param sprite_columns Number of columns in the spritesheet * @param duration Duration of the animation * @param direction Direction (right or left) of the animation * * @return The animation created */ engine::Animation *Arm::create_animation( std::string image_path, int sprite_lines, int sprite_columns, double duration, std::string direction) { assert(!image_path.empty() && !direction.empty()); assert(sprite_lines >= 0 && sprite_columns >= 0 && duration >= 0.0); engine::Game &game = engine::Game::get_instance(); assert(&game); engine::Animation *animation = new engine::Animation( game.get_renderer(), image_path, false, std::make_pair(0, 0), 1, sprite_lines, sprite_columns, duration, true, direction ); animation->set_values( std::make_pair(320, 320), std::make_pair(320, 320), std::make_pair(0, 0) ); return animation; } /** * @brief Initialize hitboxes * * Initialize all the hitboxes of the object * * @return void */ void Arm::initialize_hitboxes() { engine::Game &game = engine::Game::get_instance(); assert(&game); engine::Hitbox *arm_hitbox = new engine::Hitbox( "arm_hitbox", this->get_position(), std::make_pair(10, 45), std::make_pair(60, 8), game.get_renderer() ); arm_hitbox->initialize(); add_component(arm_hitbox); } /** * @brief Initialize the object's state map * * @return void */ void Arm::initialize_state_map() { states.set_state("ACTION_STATE", "NORMAL"); states.set_state("Y_STATE", "ON_GROUND"); } <commit_msg>[MARKERS] Applies technique in arm.cpp<commit_after>/** * @file arm.cpp * @brief Purpose: Contains methods to arm class' management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include <assert.h> #include "../include/arm.hpp" #include "../include/platform.hpp" #include "../engine/include/log.hpp" using namespace mindscape; /** * @brief Arm constructor * * @param name Name for the given object * @param position Pair of integers for its position * @param priority Priority for rendering it on the screen * * @return void */ Arm::Arm( std::string name, std::pair<int, int> position, int priority ) : Enemy( name, position, priority, 100 ) { initialize_state_map(); initialize_hitboxes(); initialize_animations(); translations = { {engine::KeyboardEvent::LEFT, "MOVE_LEFT"}, {engine::KeyboardEvent::RIGHT, "MOVE_RIGHT"}, }; }; /** * @brief Event for collisions * * This method is triggered everytime a collision happens * * @param other The other game object which collided * @param p_my_hitbox This object hitbox that received the collision * @param p_other_hitbox The other object hitbox which provided the collision */ void Arm::on_collision(engine::GameObject *other, engine::Hitbox *p_my_hitbox, engine::Hitbox *p_other_hitbox) { /* Objects declaration */ Platform *platform = dynamic_cast<Platform *>(other); /**< Plataform. Plataform of the game */ engine::Hitbox *my_hitbox = dynamic_cast<engine::Hitbox *>(p_my_hitbox); /**< Hitbox. Arm hitbox */ engine::Hitbox *other_hitbox = dynamic_cast<engine::Hitbox *>(p_other_hitbox); /**< Hitbox. Girl hitbox */ /* Parameters & objects verification */ assert(p_my_hitbox && p_other_hitbox && other); assert(my_hitbox && other_hitbox && platform); if (get_speed_y() >= 0 && platform && my_hitbox->get_name() == "arm_hitbox") { /* If arm is not falling */ /* Constants declaration */ const int movement_arm_axis_y = 30; /**< const int. Movement arm in pixel */ const float speed_arm = 0.0; /**< const float. Speed arm */ /* Values set */ set_speed_y(speed_arm); set_position_y(other_hitbox->get_coordinates() .second - movement_arm_axis_y); states.set_state("Y_STATE", "ON_GROUND"); engine::Game::get_instance() .get_actual_scene()->deactivate_game_object(name); free(); } else { /* Do nothing */ } } /** * @brief Initialize object as a physicable object * * Using this method makes the object vulnerable to forces as gravity and collisions * * @return void */ void Arm::initialize_as_physicable() { /* Object declaration */ engine::Physics *physics = engine::Physics::get_instance(); /**< Instance. Instance of the game */ /* Object verification */ assert(physics); /* State of the physics and hitboxes */ physics->add_physicable(this); collidable = true; } /** * @brief Register an event * * This method register a GameEvent to the object * * @param game_event The event to be called * * @return void */ void Arm::on_event(GameEvent game_event) { /* Parameters verification */ assert(!game_event.game_event_name.empty()); /* Constants and variables declaration */ std::string event_name = game_event.game_event_name; const int movement_arm = 10; /**< const int. Movemet of the arm in pixels */ if (event_name == "MOVE_LEFT" && !engine::GameObject::on_limit_of_level) { /* * If arm is moving left. * Moves position 10 pixels to the right. */ set_position_x(get_position_x() + movement_arm); } else if (event_name == "MOVE_RIGHT" && !engine::GameObject::on_limit_of_level) { /* * If arm is moving right. * Moves position 10 pixels to the left. */ set_position_x(get_position_x() - movement_arm); } else { INFO("Arm are not moving"); } } /** * @brief Initialize all the Arm's animations * * @return void */ void Arm::initialize_animations() { /* Constants declaration */ const int default_sprite_line = 1; const int default_sprite_column = 4; const float default_animation_duration = 3.0; const std::pair<int, int> default_dimensions_arm = std::make_pair(405, 542); const std::pair<int, int> coordinates_on_texture_arm = std::make_pair(0, 0); /* Instance and values of objects */ engine::Animation *right_arm = create_animation( "../assets/images/sprites/enemies/arm/right_arm.png", default_sprite_line, default_sprite_column, default_animation_duration, "RIGHT" ); right_arm->set_values(default_dimensions_arm, default_dimensions_arm, coordinates_on_texture_arm); add_animation("right_arm", right_arm); right_arm->activate(); engine::Animation *left_arm = create_animation( "../assets/images/sprites/enemies/arm/left_arm.png", default_sprite_line, default_sprite_column, default_animation_duration, "LEFT" ); right_arm->set_values(default_dimensions_arm, default_dimensions_arm, coordinates_on_texture_arm); add_animation("left_arm", left_arm); set_actual_animation(right_arm); } /** * @brief Creates the animations * * Creates new animations for this object * * @param image_path Path for the image file * @param sprite_lines Number of lines in the spritesheet * @param sprite_columns Number of columns in the spritesheet * @param duration Duration of the animation * @param direction Direction (right or left) of the animation * * @return The animation created */ engine::Animation *Arm::create_animation( std::string image_path, int sprite_lines, int sprite_columns, double duration, std::string direction) { /* Parameters verification */ assert(!image_path.empty() && !direction.empty()); assert(sprite_lines >= 0 && sprite_columns >= 0 && duration >= 0.0); /* Object declaration */ engine::Game &game = engine::Game::get_instance(); /* Object verification */ assert(&game); engine::Animation *animation = new engine::Animation( game.get_renderer(), image_path, false, std::make_pair(0, 0), 1, sprite_lines, sprite_columns, duration, true, direction ); /* Constants declaration */ const std::pair<int, int> default_dimensions_animation = std::make_pair(320, 320); const std::pair<int, int> coordinates_on_texture_animation = std::make_pair(0, 0); /* Animation values */ animation->set_values(default_dimensions_animation, default_dimensions_animation, coordinates_on_texture_animation); return animation; } /** * @brief Initialize hitboxes * * Initialize all the hitboxes of the object * * @return void */ void Arm::initialize_hitboxes() { /* Object declaration */ engine::Game &game = engine::Game::get_instance(); /* Object verification */ assert(&game); /* Hitboxe's values */ engine::Hitbox *arm_hitbox = new engine::Hitbox( "arm_hitbox", this->get_position(), std::make_pair(10, 45), std::make_pair(60, 8), game.get_renderer() ); arm_hitbox->initialize(); add_component(arm_hitbox); } /** * @brief Initialize the object's state map * * @return void */ void Arm::initialize_state_map() { states.set_state("ACTION_STATE", "NORMAL"); states.set_state("Y_STATE", "ON_GROUND"); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // File: lstmtraining.cpp // Description: Training program for LSTM-based networks. // Author: Ray Smith // Created: Fri May 03 11:05:06 PST 2013 // // (C) Copyright 2013, Google Inc. // 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. /////////////////////////////////////////////////////////////////////// #ifdef GOOGLE_TESSERACT #include "base/commandlineflags.h" #endif #include "commontraining.h" #include "lstmtester.h" #include "lstmtrainer.h" #include "params.h" #include "strngs.h" #include "tprintf.h" #include "unicharset_training_utils.h" INT_PARAM_FLAG(debug_interval, 0, "How often to display the alignment."); STRING_PARAM_FLAG(net_spec, "", "Network specification"); INT_PARAM_FLAG(net_mode, 192, "Controls network behavior."); INT_PARAM_FLAG(perfect_sample_delay, 0, "How many imperfect samples between perfect ones."); DOUBLE_PARAM_FLAG(target_error_rate, 0.01, "Final error rate in percent."); DOUBLE_PARAM_FLAG(weight_range, 0.1, "Range of initial random weights."); DOUBLE_PARAM_FLAG(learning_rate, 10.0e-4, "Weight factor for new deltas."); DOUBLE_PARAM_FLAG(momentum, 0.5, "Decay factor for repeating deltas."); DOUBLE_PARAM_FLAG(adam_beta, 0.999, "Decay factor for repeating deltas."); INT_PARAM_FLAG(max_image_MB, 6000, "Max memory to use for images."); STRING_PARAM_FLAG(continue_from, "", "Existing model to extend"); STRING_PARAM_FLAG(model_output, "lstmtrain", "Basename for output models"); STRING_PARAM_FLAG(train_listfile, "", "File listing training files in lstmf training format."); STRING_PARAM_FLAG(eval_listfile, "", "File listing eval files in lstmf training format."); BOOL_PARAM_FLAG(stop_training, false, "Just convert the training model to a runtime model."); BOOL_PARAM_FLAG(convert_to_int, false, "Convert the recognition model to an integer model."); BOOL_PARAM_FLAG(sequential_training, false, "Use the training files sequentially instead of round-robin."); INT_PARAM_FLAG(append_index, -1, "Index in continue_from Network at which to" " attach the new network defined by net_spec"); BOOL_PARAM_FLAG(debug_network, false, "Get info on distribution of weight values"); INT_PARAM_FLAG(max_iterations, 0, "If set, exit after this many iterations"); STRING_PARAM_FLAG(traineddata, "", "Combined Dawgs/Unicharset/Recoder for language model"); STRING_PARAM_FLAG(old_traineddata, "", "When changing the character set, this specifies the old" " character set that is to be replaced"); BOOL_PARAM_FLAG(randomly_rotate, false, "Train OSD and randomly turn training samples upside-down"); // Number of training images to train between calls to MaintainCheckpoints. const int kNumPagesPerBatch = 100; // Apart from command-line flags, input is a collection of lstmf files, that // were previously created using tesseract with the lstm.train config file. // The program iterates over the inputs, feeding the data to the network, // until the error rate reaches a specified target or max_iterations is reached. int main(int argc, char **argv) { tesseract::CheckSharedLibraryVersion(); ParseArguments(&argc, &argv); // Purify the model name in case it is based on the network string. if (FLAGS_model_output.empty()) { tprintf("Must provide a --model_output!\n"); return 1; } if (FLAGS_traineddata.empty()) { tprintf("Must provide a --traineddata see training wiki\n"); return 1; } STRING model_output = FLAGS_model_output.c_str(); for (int i = 0; i < model_output.length(); ++i) { if (model_output[i] == '[' || model_output[i] == ']') model_output[i] = '-'; if (model_output[i] == '(' || model_output[i] == ')') model_output[i] = '_'; } // Setup the trainer. STRING checkpoint_file = FLAGS_model_output.c_str(); checkpoint_file += "_checkpoint"; STRING checkpoint_bak = checkpoint_file + ".bak"; tesseract::LSTMTrainer trainer( nullptr, nullptr, nullptr, nullptr, FLAGS_model_output.c_str(), checkpoint_file.c_str(), FLAGS_debug_interval, static_cast<int64_t>(FLAGS_max_image_MB) * 1048576); trainer.InitCharSet(FLAGS_traineddata.c_str()); // Reading something from an existing model doesn't require many flags, // so do it now and exit. if (FLAGS_stop_training || FLAGS_debug_network) { if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), nullptr)) { tprintf("Failed to read continue from: %s\n", FLAGS_continue_from.c_str()); return 1; } if (FLAGS_debug_network) { trainer.DebugNetwork(); } else { if (FLAGS_convert_to_int) trainer.ConvertToInt(); if (!trainer.SaveTraineddata(FLAGS_model_output.c_str())) { tprintf("Failed to write recognition model : %s\n", FLAGS_model_output.c_str()); } } return 0; } // Get the list of files to process. if (FLAGS_train_listfile.empty()) { tprintf("Must supply a list of training filenames! --train_listfile\n"); return 1; } GenericVector<STRING> filenames; if (!tesseract::LoadFileLinesToStrings(FLAGS_train_listfile.c_str(), &filenames)) { tprintf("Failed to load list of training filenames from %s\n", FLAGS_train_listfile.c_str()); return 1; } // Checkpoints always take priority if they are available. if (trainer.TryLoadingCheckpoint(checkpoint_file.string(), nullptr) || trainer.TryLoadingCheckpoint(checkpoint_bak.string(), nullptr)) { tprintf("Successfully restored trainer from %s\n", checkpoint_file.string()); } else { if (!FLAGS_continue_from.empty()) { // Load a past model file to improve upon. if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), FLAGS_append_index >= 0 ? FLAGS_continue_from.c_str() : FLAGS_old_traineddata.c_str())) { tprintf("Failed to continue from: %s\n", FLAGS_continue_from.c_str()); return 1; } tprintf("Continuing from %s\n", FLAGS_continue_from.c_str()); trainer.InitIterations(); } if (FLAGS_continue_from.empty() || FLAGS_append_index >= 0) { if (FLAGS_append_index >= 0) { tprintf("Appending a new network to an old one!!"); if (FLAGS_continue_from.empty()) { tprintf("Must set --continue_from for appending!\n"); return 1; } } // We are initializing from scratch. if (!trainer.InitNetwork(FLAGS_net_spec.c_str(), FLAGS_append_index, FLAGS_net_mode, FLAGS_weight_range, FLAGS_learning_rate, FLAGS_momentum, FLAGS_adam_beta)) { tprintf("Failed to create network from spec: %s\n", FLAGS_net_spec.c_str()); return 1; } trainer.set_perfect_delay(FLAGS_perfect_sample_delay); } } if (!trainer.LoadAllTrainingData(filenames, FLAGS_sequential_training ? tesseract::CS_SEQUENTIAL : tesseract::CS_ROUND_ROBIN, FLAGS_randomly_rotate)) { tprintf("Load of images failed!!\n"); return 1; } tesseract::LSTMTester tester(static_cast<int64_t>(FLAGS_max_image_MB) * 1048576); tesseract::TestCallback tester_callback = nullptr; if (!FLAGS_eval_listfile.empty()) { if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) { tprintf("Failed to load eval data from: %s\n", FLAGS_eval_listfile.c_str()); return 1; } tester_callback = NewPermanentTessCallback(&tester, &tesseract::LSTMTester::RunEvalAsync); } do { // Train a few. int iteration = trainer.training_iteration(); for (int target_iteration = iteration + kNumPagesPerBatch; iteration < target_iteration && (iteration < FLAGS_max_iterations || FLAGS_max_iterations == 0); iteration = trainer.training_iteration()) { trainer.TrainOnLine(&trainer, false); } STRING log_str; trainer.MaintainCheckpoints(tester_callback, &log_str); tprintf("%s\n", log_str.string()); } while (trainer.best_error_rate() > FLAGS_target_error_rate && (trainer.training_iteration() < FLAGS_max_iterations || FLAGS_max_iterations == 0)); delete tester_callback; tprintf("Finished! Error rate = %g\n", trainer.best_error_rate()); return 0; } /* main */ <commit_msg>lstmtraining: Check write permission for output model<commit_after>/////////////////////////////////////////////////////////////////////// // File: lstmtraining.cpp // Description: Training program for LSTM-based networks. // Author: Ray Smith // Created: Fri May 03 11:05:06 PST 2013 // // (C) Copyright 2013, Google Inc. // 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. /////////////////////////////////////////////////////////////////////// #ifdef GOOGLE_TESSERACT #include "base/commandlineflags.h" #endif #include "commontraining.h" #include "lstmtester.h" #include "lstmtrainer.h" #include "params.h" #include "strngs.h" #include "tprintf.h" #include "unicharset_training_utils.h" INT_PARAM_FLAG(debug_interval, 0, "How often to display the alignment."); STRING_PARAM_FLAG(net_spec, "", "Network specification"); INT_PARAM_FLAG(net_mode, 192, "Controls network behavior."); INT_PARAM_FLAG(perfect_sample_delay, 0, "How many imperfect samples between perfect ones."); DOUBLE_PARAM_FLAG(target_error_rate, 0.01, "Final error rate in percent."); DOUBLE_PARAM_FLAG(weight_range, 0.1, "Range of initial random weights."); DOUBLE_PARAM_FLAG(learning_rate, 10.0e-4, "Weight factor for new deltas."); DOUBLE_PARAM_FLAG(momentum, 0.5, "Decay factor for repeating deltas."); DOUBLE_PARAM_FLAG(adam_beta, 0.999, "Decay factor for repeating deltas."); INT_PARAM_FLAG(max_image_MB, 6000, "Max memory to use for images."); STRING_PARAM_FLAG(continue_from, "", "Existing model to extend"); STRING_PARAM_FLAG(model_output, "lstmtrain", "Basename for output models"); STRING_PARAM_FLAG(train_listfile, "", "File listing training files in lstmf training format."); STRING_PARAM_FLAG(eval_listfile, "", "File listing eval files in lstmf training format."); BOOL_PARAM_FLAG(stop_training, false, "Just convert the training model to a runtime model."); BOOL_PARAM_FLAG(convert_to_int, false, "Convert the recognition model to an integer model."); BOOL_PARAM_FLAG(sequential_training, false, "Use the training files sequentially instead of round-robin."); INT_PARAM_FLAG(append_index, -1, "Index in continue_from Network at which to" " attach the new network defined by net_spec"); BOOL_PARAM_FLAG(debug_network, false, "Get info on distribution of weight values"); INT_PARAM_FLAG(max_iterations, 0, "If set, exit after this many iterations"); STRING_PARAM_FLAG(traineddata, "", "Combined Dawgs/Unicharset/Recoder for language model"); STRING_PARAM_FLAG(old_traineddata, "", "When changing the character set, this specifies the old" " character set that is to be replaced"); BOOL_PARAM_FLAG(randomly_rotate, false, "Train OSD and randomly turn training samples upside-down"); // Number of training images to train between calls to MaintainCheckpoints. const int kNumPagesPerBatch = 100; // Apart from command-line flags, input is a collection of lstmf files, that // were previously created using tesseract with the lstm.train config file. // The program iterates over the inputs, feeding the data to the network, // until the error rate reaches a specified target or max_iterations is reached. int main(int argc, char **argv) { tesseract::CheckSharedLibraryVersion(); ParseArguments(&argc, &argv); // Purify the model name in case it is based on the network string. if (FLAGS_model_output.empty()) { tprintf("Must provide a --model_output!\n"); return EXIT_FAILURE; } if (FLAGS_traineddata.empty()) { tprintf("Must provide a --traineddata see training wiki\n"); return EXIT_FAILURE; } STRING model_output = FLAGS_model_output.c_str(); for (int i = 0; i < model_output.length(); ++i) { if (model_output[i] == '[' || model_output[i] == ']') model_output[i] = '-'; if (model_output[i] == '(' || model_output[i] == ')') model_output[i] = '_'; } // Check write permissions. STRING test_file = FLAGS_model_output.c_str(); test_file += "_wtest"; FILE* f = fopen(test_file.c_str(), "wb"); if (f != nullptr) { fclose(f); remove(test_file.c_str()); } else { tprintf("Error, model output cannot be written: %s\n", strerror(errno)); return EXIT_FAILURE; } // Setup the trainer. STRING checkpoint_file = FLAGS_model_output.c_str(); checkpoint_file += "_checkpoint"; STRING checkpoint_bak = checkpoint_file + ".bak"; tesseract::LSTMTrainer trainer( nullptr, nullptr, nullptr, nullptr, FLAGS_model_output.c_str(), checkpoint_file.c_str(), FLAGS_debug_interval, static_cast<int64_t>(FLAGS_max_image_MB) * 1048576); trainer.InitCharSet(FLAGS_traineddata.c_str()); // Reading something from an existing model doesn't require many flags, // so do it now and exit. if (FLAGS_stop_training || FLAGS_debug_network) { if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), nullptr)) { tprintf("Failed to read continue from: %s\n", FLAGS_continue_from.c_str()); return EXIT_FAILURE; } if (FLAGS_debug_network) { trainer.DebugNetwork(); } else { if (FLAGS_convert_to_int) trainer.ConvertToInt(); if (!trainer.SaveTraineddata(FLAGS_model_output.c_str())) { tprintf("Failed to write recognition model : %s\n", FLAGS_model_output.c_str()); } } return EXIT_SUCCESS; } // Get the list of files to process. if (FLAGS_train_listfile.empty()) { tprintf("Must supply a list of training filenames! --train_listfile\n"); return EXIT_FAILURE; } GenericVector<STRING> filenames; if (!tesseract::LoadFileLinesToStrings(FLAGS_train_listfile.c_str(), &filenames)) { tprintf("Failed to load list of training filenames from %s\n", FLAGS_train_listfile.c_str()); return EXIT_FAILURE; } // Checkpoints always take priority if they are available. if (trainer.TryLoadingCheckpoint(checkpoint_file.string(), nullptr) || trainer.TryLoadingCheckpoint(checkpoint_bak.string(), nullptr)) { tprintf("Successfully restored trainer from %s\n", checkpoint_file.string()); } else { if (!FLAGS_continue_from.empty()) { // Load a past model file to improve upon. if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), FLAGS_append_index >= 0 ? FLAGS_continue_from.c_str() : FLAGS_old_traineddata.c_str())) { tprintf("Failed to continue from: %s\n", FLAGS_continue_from.c_str()); return EXIT_FAILURE; } tprintf("Continuing from %s\n", FLAGS_continue_from.c_str()); trainer.InitIterations(); } if (FLAGS_continue_from.empty() || FLAGS_append_index >= 0) { if (FLAGS_append_index >= 0) { tprintf("Appending a new network to an old one!!"); if (FLAGS_continue_from.empty()) { tprintf("Must set --continue_from for appending!\n"); return EXIT_FAILURE; } } // We are initializing from scratch. if (!trainer.InitNetwork(FLAGS_net_spec.c_str(), FLAGS_append_index, FLAGS_net_mode, FLAGS_weight_range, FLAGS_learning_rate, FLAGS_momentum, FLAGS_adam_beta)) { tprintf("Failed to create network from spec: %s\n", FLAGS_net_spec.c_str()); return EXIT_FAILURE; } trainer.set_perfect_delay(FLAGS_perfect_sample_delay); } } if (!trainer.LoadAllTrainingData(filenames, FLAGS_sequential_training ? tesseract::CS_SEQUENTIAL : tesseract::CS_ROUND_ROBIN, FLAGS_randomly_rotate)) { tprintf("Load of images failed!!\n"); return EXIT_FAILURE; } tesseract::LSTMTester tester(static_cast<int64_t>(FLAGS_max_image_MB) * 1048576); tesseract::TestCallback tester_callback = nullptr; if (!FLAGS_eval_listfile.empty()) { if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) { tprintf("Failed to load eval data from: %s\n", FLAGS_eval_listfile.c_str()); return EXIT_FAILURE; } tester_callback = NewPermanentTessCallback(&tester, &tesseract::LSTMTester::RunEvalAsync); } do { // Train a few. int iteration = trainer.training_iteration(); for (int target_iteration = iteration + kNumPagesPerBatch; iteration < target_iteration && (iteration < FLAGS_max_iterations || FLAGS_max_iterations == 0); iteration = trainer.training_iteration()) { trainer.TrainOnLine(&trainer, false); } STRING log_str; trainer.MaintainCheckpoints(tester_callback, &log_str); tprintf("%s\n", log_str.string()); } while (trainer.best_error_rate() > FLAGS_target_error_rate && (trainer.training_iteration() < FLAGS_max_iterations || FLAGS_max_iterations == 0)); delete tester_callback; tprintf("Finished! Error rate = %g\n", trainer.best_error_rate()); return EXIT_SUCCESS; } /* main */ <|endoftext|>
<commit_before><commit_msg>Fix LTR/RTL handling in Language::FromLanguageTag<commit_after><|endoftext|>
<commit_before>#include "launcher.hpp" #include <dirent.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <pwd.h> #include <iostream> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/lexical_cast.hpp> #include "foreach.hpp" using std::cerr; using std::cout; using std::endl; using std::ostringstream; using std::string; using std::vector; using boost::lexical_cast; using namespace nexus; using namespace nexus::internal; using namespace nexus::internal::launcher; ExecutorLauncher::ExecutorLauncher(FrameworkID _frameworkId, const string& _executorUri, const string& _user, const string& _workDirectory, const string& _slavePid, bool _redirectIO, const string_map& _params) : frameworkId(_frameworkId), executorUri(_executorUri), user(_user), workDirectory(_workDirectory), slavePid(_slavePid), redirectIO(_redirectIO), params(_params) {} ExecutorLauncher::~ExecutorLauncher() { } void ExecutorLauncher::run() { createWorkingDirectory(); // Enter working directory if (chdir(workDirectory.c_str()) < 0) fatalerror("chdir into framework working directory failed"); // Redirect output to files in working dir if required if (redirectIO) { if (freopen("stdout", "w", stdout) == NULL) fatalerror("freopen failed"); if (freopen("stderr", "w", stderr) == NULL) fatalerror("freopen failed"); } string executor = fetchExecutor(); setupEnvironment(); switchUser(); // Execute the executor execl(executor.c_str(), executor.c_str(), (char *) NULL); // If we get here, the execl call failed fatalerror("Could not execute %s", executor.c_str()); } // Create the executor's working directory and return its path. void ExecutorLauncher::createWorkingDirectory() { // Split the path into tokens by "/" and make each directory vector<string> tokens; split(workDirectory, "/", &tokens); string dir; foreach (const string& token, tokens) { if (dir != "") dir += "/"; dir += token; if (mkdir(dir.c_str(), 0755) < 0 && errno != EEXIST) fatalerror("mkdir failed"); } // TODO: chown the final directory to the framework's user } // Download the executor's binary if required and return its path. string ExecutorLauncher::fetchExecutor() { string executor = executorUri; // Some checks to make using the executor in shell commands safe; // these should be pushed into the master and reported to the user if (executor.find_first_of('\\') != string::npos || executor.find_first_of('\'') != string::npos || executor.find_first_of('\0') != string::npos) { fatal("Illegal characters in executor path"); } // Grab the executor from HDFS if its path begins with hdfs:// // TODO: Enforce some size limits on files we get from HDFS if (executor.find("hdfs://") == 0) { const char *hadoop = getenv("HADOOP"); if (!hadoop) { hadoop = "hadoop"; // fatal("Cannot download executor from HDFS because the " // "HADOOP environment variable is not set"); } string localFile = string("./") + basename((char *) executor.c_str()); ostringstream command; command << hadoop << " fs -copyToLocal '" << executor << "' '" << localFile << "'"; cout << "Downloading executor from " << executor << endl; cout << "HDFS command: " << command.str() << endl; int ret = system(command.str().c_str()); if (ret != 0) fatal("HDFS copyToLocal failed: return code %d", ret); executor = localFile; if (chmod(executor.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) fatalerror("chmod failed"); } // If the executor was a .tgz, untar it in the work directory. The .tgz // expected to contain a single directory. This directory should contain // a program or script called "executor" to run the executor. We chdir // into this directory and run the script from in there. if (executor.rfind(".tgz") == executor.size() - strlen(".tgz")) { string command = "tar xzf '" + executor + "'"; cout << "Untarring executor: " + command << endl; int ret = system(command.c_str()); if (ret != 0) fatal("Untar failed: return code %d", ret); // The .tgz should have contained a single directory; find it if (DIR *dir = opendir(".")) { bool found = false; string dirname = ""; while (struct dirent *ent = readdir(dir)) { if (string(".") != ent->d_name && string("..") != ent->d_name) { struct stat info; if (stat(ent->d_name, &info) == 0) { if (S_ISDIR(info.st_mode)) { if (found) // Already found a directory earlier fatal("Executor .tgz must contain a single directory"); dirname = ent->d_name; found = true; } } else { fatalerror("Stat failed on %s", ent->d_name); } } } if (!found) // No directory found fatal("Executor .tgz must contain a single directory"); if (chdir(dirname.c_str()) < 0) fatalerror("Chdir failed"); executor = "./executor"; } else { fatalerror("Failed to list work directory"); } } return executor; } // Set up environment variables for launching a framework's executor. void ExecutorLauncher::setupEnvironment() { // Set any environment variables given as env.* params in the ExecutorInfo foreachpair (const string& key, const string& value, params) { if (key.find("env.") == 0) { const string& var = key.substr(strlen("env.")); setenv(var.c_str(), value.c_str(), true); } } // Set Nexus environment variables to pass slave ID, framework ID, etc. setenv("NEXUS_SLAVE_PID", slavePid.c_str(), true); setenv("NEXUS_FRAMEWORK_ID", frameworkId.c_str(), true); // Set LIBPROCESS_PORT so that we bind to a random free port. setenv("LIBPROCESS_PORT", "0", true); } void ExecutorLauncher::switchUser() { struct passwd *passwd; if ((passwd = getpwnam(user.c_str())) == NULL) fatal("failed to get username information for %s", user.c_str()); if (setgid(passwd->pw_gid) < 0) fatalerror("failed to setgid"); if (setuid(passwd->pw_uid) < 0) fatalerror("failed to setuid"); } void ExecutorLauncher::split(const string& str, const string& delims, vector<string>* tokens) { // Start and end of current token; initialize these to the first token in // the string, skipping any leading delimiters size_t start = str.find_first_not_of(delims, 0); size_t end = str.find_first_of(delims, start); while (start != string::npos || end != string::npos) { // Add current token to the vector tokens->push_back(str.substr(start, end-start)); // Advance start to first non-delimiter past the current end start = str.find_first_not_of(delims, end); // Advance end to the next delimiter after the new start end = str.find_first_of(delims, start); } } <commit_msg>Replace tabs with spaces<commit_after>#include "launcher.hpp" #include <dirent.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <pwd.h> #include <iostream> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/lexical_cast.hpp> #include "foreach.hpp" using std::cerr; using std::cout; using std::endl; using std::ostringstream; using std::string; using std::vector; using boost::lexical_cast; using namespace nexus; using namespace nexus::internal; using namespace nexus::internal::launcher; ExecutorLauncher::ExecutorLauncher(FrameworkID _frameworkId, const string& _executorUri, const string& _user, const string& _workDirectory, const string& _slavePid, bool _redirectIO, const string_map& _params) : frameworkId(_frameworkId), executorUri(_executorUri), user(_user), workDirectory(_workDirectory), slavePid(_slavePid), redirectIO(_redirectIO), params(_params) {} ExecutorLauncher::~ExecutorLauncher() { } void ExecutorLauncher::run() { createWorkingDirectory(); // Enter working directory if (chdir(workDirectory.c_str()) < 0) fatalerror("chdir into framework working directory failed"); // Redirect output to files in working dir if required if (redirectIO) { if (freopen("stdout", "w", stdout) == NULL) fatalerror("freopen failed"); if (freopen("stderr", "w", stderr) == NULL) fatalerror("freopen failed"); } string executor = fetchExecutor(); setupEnvironment(); switchUser(); // Execute the executor execl(executor.c_str(), executor.c_str(), (char *) NULL); // If we get here, the execl call failed fatalerror("Could not execute %s", executor.c_str()); } // Create the executor's working directory and return its path. void ExecutorLauncher::createWorkingDirectory() { // Split the path into tokens by "/" and make each directory vector<string> tokens; split(workDirectory, "/", &tokens); string dir; foreach (const string& token, tokens) { if (dir != "") dir += "/"; dir += token; if (mkdir(dir.c_str(), 0755) < 0 && errno != EEXIST) fatalerror("mkdir failed"); } // TODO: chown the final directory to the framework's user } // Download the executor's binary if required and return its path. string ExecutorLauncher::fetchExecutor() { string executor = executorUri; // Some checks to make using the executor in shell commands safe; // these should be pushed into the master and reported to the user if (executor.find_first_of('\\') != string::npos || executor.find_first_of('\'') != string::npos || executor.find_first_of('\0') != string::npos) { fatal("Illegal characters in executor path"); } // Grab the executor from HDFS if its path begins with hdfs:// // TODO: Enforce some size limits on files we get from HDFS if (executor.find("hdfs://") == 0) { const char *hadoop = getenv("HADOOP"); if (!hadoop) { hadoop = "hadoop"; // fatal("Cannot download executor from HDFS because the " // "HADOOP environment variable is not set"); } string localFile = string("./") + basename((char *) executor.c_str()); ostringstream command; command << hadoop << " fs -copyToLocal '" << executor << "' '" << localFile << "'"; cout << "Downloading executor from " << executor << endl; cout << "HDFS command: " << command.str() << endl; int ret = system(command.str().c_str()); if (ret != 0) fatal("HDFS copyToLocal failed: return code %d", ret); executor = localFile; if (chmod(executor.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) fatalerror("chmod failed"); } // If the executor was a .tgz, untar it in the work directory. The .tgz // expected to contain a single directory. This directory should contain // a program or script called "executor" to run the executor. We chdir // into this directory and run the script from in there. if (executor.rfind(".tgz") == executor.size() - strlen(".tgz")) { string command = "tar xzf '" + executor + "'"; cout << "Untarring executor: " + command << endl; int ret = system(command.c_str()); if (ret != 0) fatal("Untar failed: return code %d", ret); // The .tgz should have contained a single directory; find it if (DIR *dir = opendir(".")) { bool found = false; string dirname = ""; while (struct dirent *ent = readdir(dir)) { if (string(".") != ent->d_name && string("..") != ent->d_name) { struct stat info; if (stat(ent->d_name, &info) == 0) { if (S_ISDIR(info.st_mode)) { if (found) // Already found a directory earlier fatal("Executor .tgz must contain a single directory"); dirname = ent->d_name; found = true; } } else { fatalerror("Stat failed on %s", ent->d_name); } } } if (!found) // No directory found fatal("Executor .tgz must contain a single directory"); if (chdir(dirname.c_str()) < 0) fatalerror("Chdir failed"); executor = "./executor"; } else { fatalerror("Failed to list work directory"); } } return executor; } // Set up environment variables for launching a framework's executor. void ExecutorLauncher::setupEnvironment() { // Set any environment variables given as env.* params in the ExecutorInfo foreachpair (const string& key, const string& value, params) { if (key.find("env.") == 0) { const string& var = key.substr(strlen("env.")); setenv(var.c_str(), value.c_str(), true); } } // Set Nexus environment variables to pass slave ID, framework ID, etc. setenv("NEXUS_SLAVE_PID", slavePid.c_str(), true); setenv("NEXUS_FRAMEWORK_ID", frameworkId.c_str(), true); // Set LIBPROCESS_PORT so that we bind to a random free port. setenv("LIBPROCESS_PORT", "0", true); } void ExecutorLauncher::switchUser() { struct passwd *passwd; if ((passwd = getpwnam(user.c_str())) == NULL) fatal("failed to get username information for %s", user.c_str()); if (setgid(passwd->pw_gid) < 0) fatalerror("failed to setgid"); if (setuid(passwd->pw_uid) < 0) fatalerror("failed to setuid"); } void ExecutorLauncher::split(const string& str, const string& delims, vector<string>* tokens) { // Start and end of current token; initialize these to the first token in // the string, skipping any leading delimiters size_t start = str.find_first_not_of(delims, 0); size_t end = str.find_first_of(delims, start); while (start != string::npos || end != string::npos) { // Add current token to the vector tokens->push_back(str.substr(start, end-start)); // Advance start to first non-delimiter past the current end start = str.find_first_not_of(delims, end); // Advance end to the next delimiter after the new start end = str.find_first_of(delims, start); } } <|endoftext|>
<commit_before>#include <build-bot/bot.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <chrono> #include <thread> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> namespace fs = boost::filesystem; using namespace dsn::build_bot; namespace dsn { namespace build_bot { namespace priv { class Bot : public dsn::log::Base<Bot> { protected: boost::property_tree::ptree m_settings; bool loadConfig(const std::string& config_file) { BOOST_LOG_SEV(log, severity::info) << "Loading configuration from " << config_file; fs::path path(config_file); if (!fs::exists(path)) { BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " doesn't exist!"; return false; } if (!fs::is_regular_file(path)) { BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " isn't a regular file!"; return false; } try { boost::property_tree::read_ini(config_file, m_settings); } catch (boost::property_tree::ini_parser_error& ex) { BOOST_LOG_SEV(log, severity::error) << "Failed to parse config file " << config_file << ": " << ex.what(); return false; } m_configFile = config_file; return true; } bool initFifo() { std::string fifoName; try { fifoName = m_settings.get<std::string>("fifo.name"); } catch (boost::property_tree::ptree_error& ex) { BOOST_LOG_SEV(log, severity::error) << "Failed to get FIFO settings from configuration: " << ex.what(); return false; } fs::path path(fifoName); if (!fs::exists(path)) { BOOST_LOG_SEV(log, severity::warning) << "FIFO " << fifoName << " doesn't exist; trying to create it!"; if (mkfifo(fifoName.c_str(), 0666) == -1) { BOOST_LOG_SEV(log, severity::error) << "Failed to create FIFO " << fifoName << ": " << strerror(errno); return false; } } BOOST_LOG_SEV(log, severity::debug) << "Opening FIFO " << fifoName << " for reading."; int fd{ -1 }; if ((fd = open(fifoName.c_str(), O_RDWR)) == -1) { BOOST_LOG_SEV(log, severity::error) << "Failed to open FIFO " << fifoName << " for reading: " << strerror(errno); return false; } boost::system::error_code error = m_fifo.assign(fd, error); if (error) { BOOST_LOG_SEV(log, severity::error) << "Failed to assign FIFO fd to stream_descriptor: " << boost::system::system_error(error).what(); close(fd); return false; } return true; } boost::asio::io_service m_io; boost::asio::strand m_strand; std::atomic<bool> m_stopRequested; std::atomic<bool> m_restartAfterStop; std::string m_configFile; boost::asio::posix::stream_descriptor m_fifo; boost::asio::streambuf m_buffer; void read(const boost::system::error_code& error) { if (error) { BOOST_LOG_SEV(log, severity::error) << "Failed to read from FIFO: " << boost::system::system_error(error).what(); return; } std::string message; { std::istream stream(&m_buffer); std::getline(stream, message); } BOOST_LOG_SEV(log, severity::trace) << "Read line from FIFO: " << message; boost::asio::async_read_until(m_fifo, m_buffer, "\n", boost::bind(&Bot::read, this, boost::asio::placeholders::error)); } public: Bot() : m_io() , m_strand(m_io) , m_stopRequested(false) , m_restartAfterStop(false) , m_configFile("") , m_fifo(m_io) { } ~Bot() { if (m_fifo.is_open()) m_fifo.close(); } bool init(const std::string& config_file) { if (!loadConfig(config_file)) return false; if (!initFifo()) return false; return true; } void stop(bool restart = false) { if (restart) m_restartAfterStop = true; m_stopRequested = true; } dsn::build_bot::Bot::ExitCode run() { BOOST_LOG_SEV(log, severity::trace) << "Installing async read handler for FIFO"; boost::asio::async_read_until(m_fifo, m_buffer, "\n", boost::bind(&Bot::read, this, boost::asio::placeholders::error)); BOOST_LOG_SEV(log, severity::trace) << "Starting io_service"; std::thread ioServiceThread([&]() { m_io.run(); }); while (!m_stopRequested.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } BOOST_LOG_SEV(log, severity::trace) << "Stopping io_service"; m_io.stop(); ioServiceThread.join(); if (m_restartAfterStop.load()) return dsn::build_bot::Bot::ExitCode::Restart; return dsn::build_bot::Bot::ExitCode::Success; } }; } } } const std::string dsn::build_bot::Bot::DEFAULT_CONFIG_FILE{ "etc/build-bot/bot.conf" }; Bot::Bot() : m_impl(new priv::Bot()) { } Bot::~Bot() { } bool Bot::init(const std::string& config_file) { return m_impl->init(config_file); } void Bot::stop() { return m_impl->stop(); } void Bot::restart() { return m_impl->stop(true); } Bot::ExitCode Bot::run() { return m_impl->run(); } <commit_msg>Add parser function for messages on FIFO<commit_after>#include <build-bot/bot.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <chrono> #include <thread> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> namespace fs = boost::filesystem; using namespace dsn::build_bot; namespace dsn { namespace build_bot { namespace priv { class Bot : public dsn::log::Base<Bot> { protected: boost::property_tree::ptree m_settings; bool loadConfig(const std::string& config_file) { BOOST_LOG_SEV(log, severity::info) << "Loading configuration from " << config_file; fs::path path(config_file); if (!fs::exists(path)) { BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " doesn't exist!"; return false; } if (!fs::is_regular_file(path)) { BOOST_LOG_SEV(log, severity::error) << "Config file " << config_file << " isn't a regular file!"; return false; } try { boost::property_tree::read_ini(config_file, m_settings); } catch (boost::property_tree::ini_parser_error& ex) { BOOST_LOG_SEV(log, severity::error) << "Failed to parse config file " << config_file << ": " << ex.what(); return false; } m_configFile = config_file; return true; } bool initFifo() { std::string fifoName; try { fifoName = m_settings.get<std::string>("fifo.name"); } catch (boost::property_tree::ptree_error& ex) { BOOST_LOG_SEV(log, severity::error) << "Failed to get FIFO settings from configuration: " << ex.what(); return false; } fs::path path(fifoName); if (!fs::exists(path)) { BOOST_LOG_SEV(log, severity::warning) << "FIFO " << fifoName << " doesn't exist; trying to create it!"; if (mkfifo(fifoName.c_str(), 0666) == -1) { BOOST_LOG_SEV(log, severity::error) << "Failed to create FIFO " << fifoName << ": " << strerror(errno); return false; } } BOOST_LOG_SEV(log, severity::debug) << "Opening FIFO " << fifoName << " for reading."; int fd{ -1 }; if ((fd = open(fifoName.c_str(), O_RDWR)) == -1) { BOOST_LOG_SEV(log, severity::error) << "Failed to open FIFO " << fifoName << " for reading: " << strerror(errno); return false; } boost::system::error_code error = m_fifo.assign(fd, error); if (error) { BOOST_LOG_SEV(log, severity::error) << "Failed to assign FIFO fd to stream_descriptor: " << boost::system::system_error(error).what(); close(fd); return false; } return true; } boost::asio::io_service m_io; boost::asio::strand m_strand; std::atomic<bool> m_stopRequested; std::atomic<bool> m_restartAfterStop; std::string m_configFile; boost::asio::posix::stream_descriptor m_fifo; boost::asio::streambuf m_buffer; void read(const boost::system::error_code& error) { if (error) { BOOST_LOG_SEV(log, severity::error) << "Failed to read from FIFO: " << boost::system::system_error(error).what(); return; } std::string message; { std::istream stream(&m_buffer); std::getline(stream, message); } if (!parse(message)) BOOST_LOG_SEV(log, severity::warning) << "Failed to parse message from FIFO: " << message; boost::asio::async_read_until(m_fifo, m_buffer, "\n", boost::bind(&Bot::read, this, boost::asio::placeholders::error)); } bool parse(const std::string& message) { if (message == "STOP") { BOOST_LOG_SEV(log, severity::info) << "Got STOP command on FIFO!"; stop(); return true; } if (message == "RESTART") { BOOST_LOG_SEV(log, severity::info) << "Got RESTART command on FIFO!"; stop(true); return true; } return false; } public: Bot() : m_io() , m_strand(m_io) , m_stopRequested(false) , m_restartAfterStop(false) , m_configFile("") , m_fifo(m_io) { } ~Bot() { if (m_fifo.is_open()) m_fifo.close(); } bool init(const std::string& config_file) { if (!loadConfig(config_file)) return false; if (!initFifo()) return false; return true; } void stop(bool restart = false) { if (restart) m_restartAfterStop = true; m_stopRequested = true; } dsn::build_bot::Bot::ExitCode run() { BOOST_LOG_SEV(log, severity::trace) << "Installing async read handler for FIFO"; boost::asio::async_read_until(m_fifo, m_buffer, "\n", boost::bind(&Bot::read, this, boost::asio::placeholders::error)); BOOST_LOG_SEV(log, severity::trace) << "Starting io_service"; std::thread ioServiceThread([&]() { m_io.run(); }); while (!m_stopRequested.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } BOOST_LOG_SEV(log, severity::trace) << "Stopping io_service"; m_io.stop(); ioServiceThread.join(); if (m_restartAfterStop.load()) return dsn::build_bot::Bot::ExitCode::Restart; return dsn::build_bot::Bot::ExitCode::Success; } }; } } } const std::string dsn::build_bot::Bot::DEFAULT_CONFIG_FILE{ "etc/build-bot/bot.conf" }; Bot::Bot() : m_impl(new priv::Bot()) { } Bot::~Bot() { } bool Bot::init(const std::string& config_file) { return m_impl->init(config_file); } void Bot::stop() { return m_impl->stop(); } void Bot::restart() { return m_impl->stop(true); } Bot::ExitCode Bot::run() { return m_impl->run(); } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <chrono> #include <thread> #include <haywire.h> #include "lmdb.h" #include "common.h" #include "storage/store.h" #include "storage/lmdb_store.h" #include "indexing/index_dictionary.h" #include "indexing/index_writer.h" #include "haywire.h" #include "hellcat.h" using namespace std; using namespace chrono; using namespace hellcat::storage; void create_http_endpoint(); void get_root(http_request* request, hw_http_response* response, void* user_data); void response_complete(void* user_data); static unique_ptr<Store> store; int main(int argc, char* argv[]) { store = unique_ptr<Store>(new LMDBStore()); int rc = store->open("/tmp/hellcat_data", true); create_http_endpoint(); return 0; } void create_http_endpoint() { char route[] = "/"; configuration config; config.http_listen_address = "0.0.0.0"; config.http_listen_port = 8000; hw_init_with_config(&config); hw_http_add_route(route, get_root, NULL); hw_http_open(16); } #define CRLF "\r\n" void response_complete(void* user_data) { } void get_root(http_request* request, hw_http_response* response, void* user_data) { int rc = 0; hw_string status_code; hw_string body; body.length = 0; if (request->method == HW_HTTP_GET) { // Process GET request. hcat_keypair pair; pair.keyspace = string_ref(hw_get_header(request, "keyspace")); pair.key = string_ref(hw_get_header(request, "key")); if (pair.keyspace.data() != NULL) { hcat_transaction* tx; store->begin_transaction(&tx, 1); rc = tx->get(&pair); tx->commit(); if (rc == 0) { SETSTRING(status_code, HTTP_STATUS_200); body.value = (char*)pair.value; body.length = pair.value_length; } else if (rc != 0) { SETSTRING(status_code, HTTP_STATUS_404); SETSTRING(body, "hello world"); } delete tx; } else { SETSTRING(status_code, HTTP_STATUS_404); SETSTRING(body, "FAIL"); } } else if (request->method == HW_HTTP_PUT || request->method == HW_HTTP_POST) { // Process SET request. hcat_transaction* tx; store->begin_transaction(&tx, 0); hcat_keypair pair; pair.keyspace = string_ref(hw_get_header(request, "keyspace")); pair.key = string_ref(hw_get_header(request, "key")); string_ref val = string_ref(hw_get_header(request, "value")); pair.value = (void*)val.data(); pair.value_length = val.length(); if (pair.keyspace.length() != 0 && pair.key.length() != 0 && pair.value_length != 0) { rc = tx->set(&pair); rc = tx->commit(); //rc = store->sync(); SETSTRING(status_code, HTTP_STATUS_200); SETSTRING(body, "OK"); } else { tx->abort(); char* key = hw_get_header(request, "key"); pair.key = string_ref(hw_get_header(request, "key")); SETSTRING(status_code, HTTP_STATUS_404); SETSTRING(body, "FAIL"); } delete tx; } hw_string content_type_name; hw_string content_type_value; hw_string keep_alive_name; hw_string keep_alive_value; SETSTRING(content_type_name, "Content-Type"); SETSTRING(content_type_value, "text/html"); hw_set_response_header(response, &content_type_name, &content_type_value); hw_set_response_status_code(response, &status_code); hw_set_body(response, &body); if (request->keep_alive) { SETSTRING(keep_alive_name, "Connection"); SETSTRING(keep_alive_value, "Keep-Alive"); hw_set_response_header(response, &keep_alive_name, &keep_alive_value); } else { hw_set_http_version(response, 1, 0); } hw_http_response_send(response, NULL, response_complete); }<commit_msg>Trying to fix the Travis CI build.<commit_after>#include <iostream> #include <sstream> #include <fstream> //#include <chrono> #include <thread> #include <haywire.h> #include "lmdb.h" #include "common.h" #include "storage/store.h" #include "storage/lmdb_store.h" #include "indexing/index_dictionary.h" #include "indexing/index_writer.h" #include "haywire.h" #include "hellcat.h" using namespace std; //using namespace chrono; using namespace hellcat::storage; void create_http_endpoint(); void get_root(http_request* request, hw_http_response* response, void* user_data); void response_complete(void* user_data); static unique_ptr<Store> store; int main(int argc, char* argv[]) { store = unique_ptr<Store>(new LMDBStore()); int rc = store->open("/tmp/hellcat_data", true); create_http_endpoint(); return 0; } void create_http_endpoint() { char route[] = "/"; configuration config; config.http_listen_address = "0.0.0.0"; config.http_listen_port = 8000; hw_init_with_config(&config); hw_http_add_route(route, get_root, NULL); hw_http_open(16); } #define CRLF "\r\n" void response_complete(void* user_data) { } void get_root(http_request* request, hw_http_response* response, void* user_data) { int rc = 0; hw_string status_code; hw_string body; body.length = 0; if (request->method == HW_HTTP_GET) { // Process GET request. hcat_keypair pair; pair.keyspace = string_ref(hw_get_header(request, "keyspace")); pair.key = string_ref(hw_get_header(request, "key")); if (pair.keyspace.data() != NULL) { hcat_transaction* tx; store->begin_transaction(&tx, 1); rc = tx->get(&pair); tx->commit(); if (rc == 0) { SETSTRING(status_code, HTTP_STATUS_200); body.value = (char*)pair.value; body.length = pair.value_length; } else if (rc != 0) { SETSTRING(status_code, HTTP_STATUS_404); SETSTRING(body, "hello world"); } delete tx; } else { SETSTRING(status_code, HTTP_STATUS_404); SETSTRING(body, "FAIL"); } } else if (request->method == HW_HTTP_PUT || request->method == HW_HTTP_POST) { // Process SET request. hcat_transaction* tx; store->begin_transaction(&tx, 0); hcat_keypair pair; pair.keyspace = string_ref(hw_get_header(request, "keyspace")); pair.key = string_ref(hw_get_header(request, "key")); string_ref val = string_ref(hw_get_header(request, "value")); pair.value = (void*)val.data(); pair.value_length = val.length(); if (pair.keyspace.length() != 0 && pair.key.length() != 0 && pair.value_length != 0) { rc = tx->set(&pair); rc = tx->commit(); //rc = store->sync(); SETSTRING(status_code, HTTP_STATUS_200); SETSTRING(body, "OK"); } else { tx->abort(); char* key = hw_get_header(request, "key"); pair.key = string_ref(hw_get_header(request, "key")); SETSTRING(status_code, HTTP_STATUS_404); SETSTRING(body, "FAIL"); } delete tx; } hw_string content_type_name; hw_string content_type_value; hw_string keep_alive_name; hw_string keep_alive_value; SETSTRING(content_type_name, "Content-Type"); SETSTRING(content_type_value, "text/html"); hw_set_response_header(response, &content_type_name, &content_type_value); hw_set_response_status_code(response, &status_code); hw_set_body(response, &body); if (request->keep_alive) { SETSTRING(keep_alive_name, "Connection"); SETSTRING(keep_alive_value, "Keep-Alive"); hw_set_response_header(response, &keep_alive_name, &keep_alive_value); } else { hw_set_http_version(response, 1, 0); } hw_http_response_send(response, NULL, response_complete); } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2016, John Wiegley. 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 New Artisans LLC 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. */ #include <system.hh> #include "pyinterp.h" #include "pyutils.h" #include "commodity.h" #include "annotate.h" namespace ledger { using namespace boost::python; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(value_overloads, value, 0, 2) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(exchange_commodities_overloads, exchange_commodities, 1, 2) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(set_string_overloads, set_string, 0, 2) namespace { boost::optional<value_t> py_value_0(const value_t& value) { return value.value(CURRENT_TIME()); } boost::optional<value_t> py_value_1(const value_t& value, const commodity_t * in_terms_of) { return value.value(CURRENT_TIME(), in_terms_of); } boost::optional<value_t> py_value_2(const value_t& value, const commodity_t * in_terms_of, const datetime_t& moment) { return value.value(moment, in_terms_of); } boost::optional<value_t> py_value_2d(const value_t& value, const commodity_t * in_terms_of, const date_t& moment) { return value.value(datetime_t(moment), in_terms_of); } PyObject * py_base_type(value_t& value) { if (value.is_boolean()) { return (PyObject *)&PyBool_Type; } else if (value.is_long()) { return (PyObject *)&PyInt_Type; } else if (value.is_string()) { return (PyObject *)&PyUnicode_Type; } else { object typeobj(object(value).attr("__class__")); return typeobj.ptr(); } } string py_dump(const value_t& value) { std::ostringstream buf; value.dump(buf); return buf.str(); } string py_dump_relaxed(const value_t& value) { std::ostringstream buf; value.dump(buf, true); return buf.str(); } void py_set_string(value_t& value, const string& str) { return value.set_string(str); } annotation_t& py_value_annotation(value_t& value) { return value.annotation(); } value_t py_strip_annotations_0(value_t& value) { return value.strip_annotations(keep_details_t()); } value_t py_strip_annotations_1(value_t& value, const keep_details_t& keep) { return value.strip_annotations(keep); } PyObject * py_value_unicode(value_t& value) { return str_to_py_unicode(value.to_string()); } } // unnamed namespace #define EXC_TRANSLATOR(type) \ void exc_translate_ ## type(const type& err) { \ PyErr_SetString(PyExc_ArithmeticError, err.what()); \ } EXC_TRANSLATOR(value_error) void export_value() { enum_< value_t::type_t >("ValueType") .value("Void", value_t::VOID) .value("Boolean", value_t::BOOLEAN) .value("DateTime", value_t::DATETIME) .value("Date", value_t::DATE) .value("Integer", value_t::INTEGER) .value("Amount", value_t::AMOUNT) .value("Balance", value_t::BALANCE) .value("String", value_t::STRING) .value("Sequence", value_t::SEQUENCE) .value("Scope", value_t::SCOPE) ; class_< value_t > ("Value") .def("initialize", &value_t::initialize) .staticmethod("initialize") .def("shutdown", &value_t::shutdown) .staticmethod("shutdown") .def(init<bool>()) .def(init<datetime_t>()) .def(init<date_t>()) .def(init<long>()) .def(init<double>()) .def(init<amount_t>()) .def(init<balance_t>()) .def(init<mask_t>()) .def(init<std::string>()) // jww (2009-11-02): Need to support conversion of value_t::sequence_t //.def(init<value_t::sequence_t>()) .def(init<value_t>()) .def("is_equal_to", &value_t::is_equal_to) .def("is_less_than", &value_t::is_less_than) .def("is_greater_than", &value_t::is_greater_than) .def(self == self) .def(self == long()) .def(long() == self) .def(self == other<amount_t>()) .def(other<amount_t>() == self) .def(self == other<balance_t>()) .def(other<balance_t>() == self) .def(self != self) .def(self != long()) .def(long() != self) .def(self != other<amount_t>()) .def(other<amount_t>() != self) .def(self != other<balance_t>()) .def(other<balance_t>() != self) .def(! self) .def(self < self) .def(self < long()) .def(long() < self) .def(self < other<amount_t>()) .def(other<amount_t>() < self) .def(self <= self) .def(self <= long()) .def(long() <= self) .def(self <= other<amount_t>()) .def(other<amount_t>() <= self) .def(self > self) .def(self > long()) .def(long() > self) .def(self > other<amount_t>()) .def(other<amount_t>() > self) .def(self >= self) .def(self >= long()) .def(long() >= self) .def(self >= other<amount_t>()) .def(other<amount_t>() >= self) .def(self += self) .def(self += long()) .def(self += other<amount_t>()) .def(self += other<balance_t>()) .def(self + self) .def(self + long()) .def(long() + self) .def(self + other<amount_t>()) .def(other<amount_t>() + self) .def(self + other<balance_t>()) .def(self -= self) .def(self -= long()) .def(self -= other<amount_t>()) .def(self -= other<balance_t>()) .def(self - self) .def(self - long()) .def(long() - self) .def(self - other<amount_t>()) .def(other<amount_t>() - self) .def(self - other<balance_t>()) .def(self *= self) .def(self *= long()) .def(self *= other<amount_t>()) .def(self * self) .def(self * long()) .def(long() * self) .def(self * other<amount_t>()) .def(other<amount_t>() * self) .def(self /= self) .def(self /= long()) .def(self /= other<amount_t>()) .def(self / self) .def(self / long()) .def(long() / self) .def(self / other<amount_t>()) .def(other<amount_t>() / self) .def("negated", &value_t::negated) .def("in_place_negate", &value_t::in_place_negate) .def("in_place_not", &value_t::in_place_not) .def(- self) .def("abs", &value_t::abs) .def("__abs__", &value_t::abs) .def("rounded", &value_t::rounded) .def("in_place_round", &value_t::in_place_round) .def("truncated", &value_t::truncated) .def("in_place_truncate", &value_t::in_place_truncate) .def("floored", &value_t::floored) .def("in_place_floor", &value_t::in_place_floor) .def("unrounded", &value_t::unrounded) .def("in_place_unround", &value_t::in_place_unround) .def("reduced", &value_t::reduced) .def("in_place_reduce", &value_t::in_place_reduce) .def("unreduced", &value_t::unreduced) .def("in_place_unreduce", &value_t::in_place_unreduce) .def("value", py_value_0) .def("value", py_value_1, args("in_terms_of")) .def("value", py_value_2, args("in_terms_of", "moment")) .def("value", py_value_2d, args("in_terms_of", "moment")) //.def("value", &value_t::value, value_overloads()) .def("exchange_commodities", &value_t::exchange_commodities, exchange_commodities_overloads()) .def("__nonzero__", &value_t::is_nonzero) .def("is_nonzero", &value_t::is_nonzero) .def("is_realzero", &value_t::is_realzero) .def("is_zero", &value_t::is_zero) .def("is_null", &value_t::is_null) .def("type", &value_t::type) .def("is_type", &value_t::is_type) .def("is_boolean", &value_t::is_boolean) .def("set_boolean", &value_t::set_boolean) .def("is_datetime", &value_t::is_datetime) .def("set_datetime", &value_t::set_datetime) .def("is_date", &value_t::is_date) .def("set_date", &value_t::set_date) .def("is_long", &value_t::is_long) .def("set_long", &value_t::set_long) .def("is_amount", &value_t::is_amount) .def("is_amount", &value_t::is_amount) .def("is_balance", &value_t::is_balance) .def("is_balance", &value_t::is_balance) .def("is_string", &value_t::is_string) .def("set_string", py_set_string) .def("is_mask", &value_t::is_mask) .def("is_mask", &value_t::is_mask) .def("is_sequence", &value_t::is_sequence) .def("set_sequence", &value_t::set_sequence) .def("to_boolean", &value_t::to_boolean) .def("to_long", &value_t::to_long) .def("__int__", &value_t::to_long) .def("to_datetime", &value_t::to_datetime) .def("to_date", &value_t::to_date) .def("to_amount", &value_t::to_amount) .def("to_balance", &value_t::to_balance) .def("__str__", &value_t::to_string) .def("__unicode__", py_value_unicode) .def("to_string", &value_t::to_string) .def("to_mask", &value_t::to_mask) .def("to_sequence", &value_t::to_sequence) .def("__repr__", py_dump) .def("casted", &value_t::casted) .def("in_place_cast", &value_t::in_place_cast) .def("simplified", &value_t::simplified) .def("in_place_simplify", &value_t::in_place_simplify) .def("number", &value_t::number) .def("annotate", &value_t::annotate) .def("has_annotation", &value_t::has_annotation) .add_property("annotation", make_function(py_value_annotation, return_internal_reference<>())) .def("strip_annotations", py_strip_annotations_0) .def("strip_annotations", py_strip_annotations_1) #if 0 .def("__getitem__", &value_t::operator[]) #endif .def("push_back", &value_t::push_back) .def("pop_back", &value_t::pop_back) .def("size", &value_t::size) .def("label", &value_t::label) .def("valid", &value_t::valid) .def("basetype", py_base_type) ; #if 0 // jww (2010-06-10): This is not working since I switched sequence_t to // ptr_deque<value_t>. class_< value_t::sequence_t > ("ValueSequence") .def(vector_indexing_suite< value_t::sequence_t, true >()); ; #endif scope().attr("NULL_VALUE") = NULL_VALUE; scope().attr("string_value") = &string_value; scope().attr("mask_value") = &mask_value; scope().attr("value_context") = &value_context; register_optional_to_python<value_t>(); implicitly_convertible<long, value_t>(); implicitly_convertible<string, value_t>(); implicitly_convertible<amount_t, value_t>(); implicitly_convertible<balance_t, value_t>(); implicitly_convertible<mask_t, value_t>(); implicitly_convertible<date_t, value_t>(); implicitly_convertible<datetime_t, value_t>(); #define EXC_TRANSLATE(type) \ register_exception_translator<type>(&exc_translate_ ## type); EXC_TRANSLATE(value_error); } } // namespace ledger <commit_msg>Make bool implicitly convertible in Python to value_t<commit_after>/* * Copyright (c) 2003-2016, John Wiegley. 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 New Artisans LLC 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. */ #include <system.hh> #include "pyinterp.h" #include "pyutils.h" #include "commodity.h" #include "annotate.h" namespace ledger { using namespace boost::python; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(value_overloads, value, 0, 2) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(exchange_commodities_overloads, exchange_commodities, 1, 2) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(set_string_overloads, set_string, 0, 2) namespace { boost::optional<value_t> py_value_0(const value_t& value) { return value.value(CURRENT_TIME()); } boost::optional<value_t> py_value_1(const value_t& value, const commodity_t * in_terms_of) { return value.value(CURRENT_TIME(), in_terms_of); } boost::optional<value_t> py_value_2(const value_t& value, const commodity_t * in_terms_of, const datetime_t& moment) { return value.value(moment, in_terms_of); } boost::optional<value_t> py_value_2d(const value_t& value, const commodity_t * in_terms_of, const date_t& moment) { return value.value(datetime_t(moment), in_terms_of); } PyObject * py_base_type(value_t& value) { if (value.is_boolean()) { return (PyObject *)&PyBool_Type; } else if (value.is_long()) { return (PyObject *)&PyInt_Type; } else if (value.is_string()) { return (PyObject *)&PyUnicode_Type; } else { object typeobj(object(value).attr("__class__")); return typeobj.ptr(); } } string py_dump(const value_t& value) { std::ostringstream buf; value.dump(buf); return buf.str(); } string py_dump_relaxed(const value_t& value) { std::ostringstream buf; value.dump(buf, true); return buf.str(); } void py_set_string(value_t& value, const string& str) { return value.set_string(str); } annotation_t& py_value_annotation(value_t& value) { return value.annotation(); } value_t py_strip_annotations_0(value_t& value) { return value.strip_annotations(keep_details_t()); } value_t py_strip_annotations_1(value_t& value, const keep_details_t& keep) { return value.strip_annotations(keep); } PyObject * py_value_unicode(value_t& value) { return str_to_py_unicode(value.to_string()); } } // unnamed namespace #define EXC_TRANSLATOR(type) \ void exc_translate_ ## type(const type& err) { \ PyErr_SetString(PyExc_ArithmeticError, err.what()); \ } EXC_TRANSLATOR(value_error) void export_value() { enum_< value_t::type_t >("ValueType") .value("Void", value_t::VOID) .value("Boolean", value_t::BOOLEAN) .value("DateTime", value_t::DATETIME) .value("Date", value_t::DATE) .value("Integer", value_t::INTEGER) .value("Amount", value_t::AMOUNT) .value("Balance", value_t::BALANCE) .value("String", value_t::STRING) .value("Sequence", value_t::SEQUENCE) .value("Scope", value_t::SCOPE) ; class_< value_t > ("Value") .def("initialize", &value_t::initialize) .staticmethod("initialize") .def("shutdown", &value_t::shutdown) .staticmethod("shutdown") .def(init<bool>()) .def(init<datetime_t>()) .def(init<date_t>()) .def(init<long>()) .def(init<double>()) .def(init<amount_t>()) .def(init<balance_t>()) .def(init<mask_t>()) .def(init<std::string>()) // jww (2009-11-02): Need to support conversion of value_t::sequence_t //.def(init<value_t::sequence_t>()) .def(init<value_t>()) .def("is_equal_to", &value_t::is_equal_to) .def("is_less_than", &value_t::is_less_than) .def("is_greater_than", &value_t::is_greater_than) .def(self == self) .def(self == long()) .def(long() == self) .def(self == other<amount_t>()) .def(other<amount_t>() == self) .def(self == other<balance_t>()) .def(other<balance_t>() == self) .def(self != self) .def(self != long()) .def(long() != self) .def(self != other<amount_t>()) .def(other<amount_t>() != self) .def(self != other<balance_t>()) .def(other<balance_t>() != self) .def(! self) .def(self < self) .def(self < long()) .def(long() < self) .def(self < other<amount_t>()) .def(other<amount_t>() < self) .def(self <= self) .def(self <= long()) .def(long() <= self) .def(self <= other<amount_t>()) .def(other<amount_t>() <= self) .def(self > self) .def(self > long()) .def(long() > self) .def(self > other<amount_t>()) .def(other<amount_t>() > self) .def(self >= self) .def(self >= long()) .def(long() >= self) .def(self >= other<amount_t>()) .def(other<amount_t>() >= self) .def(self += self) .def(self += long()) .def(self += other<amount_t>()) .def(self += other<balance_t>()) .def(self + self) .def(self + long()) .def(long() + self) .def(self + other<amount_t>()) .def(other<amount_t>() + self) .def(self + other<balance_t>()) .def(self -= self) .def(self -= long()) .def(self -= other<amount_t>()) .def(self -= other<balance_t>()) .def(self - self) .def(self - long()) .def(long() - self) .def(self - other<amount_t>()) .def(other<amount_t>() - self) .def(self - other<balance_t>()) .def(self *= self) .def(self *= long()) .def(self *= other<amount_t>()) .def(self * self) .def(self * long()) .def(long() * self) .def(self * other<amount_t>()) .def(other<amount_t>() * self) .def(self /= self) .def(self /= long()) .def(self /= other<amount_t>()) .def(self / self) .def(self / long()) .def(long() / self) .def(self / other<amount_t>()) .def(other<amount_t>() / self) .def("negated", &value_t::negated) .def("in_place_negate", &value_t::in_place_negate) .def("in_place_not", &value_t::in_place_not) .def(- self) .def("abs", &value_t::abs) .def("__abs__", &value_t::abs) .def("rounded", &value_t::rounded) .def("in_place_round", &value_t::in_place_round) .def("truncated", &value_t::truncated) .def("in_place_truncate", &value_t::in_place_truncate) .def("floored", &value_t::floored) .def("in_place_floor", &value_t::in_place_floor) .def("unrounded", &value_t::unrounded) .def("in_place_unround", &value_t::in_place_unround) .def("reduced", &value_t::reduced) .def("in_place_reduce", &value_t::in_place_reduce) .def("unreduced", &value_t::unreduced) .def("in_place_unreduce", &value_t::in_place_unreduce) .def("value", py_value_0) .def("value", py_value_1, args("in_terms_of")) .def("value", py_value_2, args("in_terms_of", "moment")) .def("value", py_value_2d, args("in_terms_of", "moment")) //.def("value", &value_t::value, value_overloads()) .def("exchange_commodities", &value_t::exchange_commodities, exchange_commodities_overloads()) .def("__nonzero__", &value_t::is_nonzero) .def("is_nonzero", &value_t::is_nonzero) .def("is_realzero", &value_t::is_realzero) .def("is_zero", &value_t::is_zero) .def("is_null", &value_t::is_null) .def("type", &value_t::type) .def("is_type", &value_t::is_type) .def("is_boolean", &value_t::is_boolean) .def("set_boolean", &value_t::set_boolean) .def("is_datetime", &value_t::is_datetime) .def("set_datetime", &value_t::set_datetime) .def("is_date", &value_t::is_date) .def("set_date", &value_t::set_date) .def("is_long", &value_t::is_long) .def("set_long", &value_t::set_long) .def("is_amount", &value_t::is_amount) .def("is_amount", &value_t::is_amount) .def("is_balance", &value_t::is_balance) .def("is_balance", &value_t::is_balance) .def("is_string", &value_t::is_string) .def("set_string", py_set_string) .def("is_mask", &value_t::is_mask) .def("is_mask", &value_t::is_mask) .def("is_sequence", &value_t::is_sequence) .def("set_sequence", &value_t::set_sequence) .def("to_boolean", &value_t::to_boolean) .def("to_long", &value_t::to_long) .def("__int__", &value_t::to_long) .def("to_datetime", &value_t::to_datetime) .def("to_date", &value_t::to_date) .def("to_amount", &value_t::to_amount) .def("to_balance", &value_t::to_balance) .def("__str__", &value_t::to_string) .def("__unicode__", py_value_unicode) .def("to_string", &value_t::to_string) .def("to_mask", &value_t::to_mask) .def("to_sequence", &value_t::to_sequence) .def("__repr__", py_dump) .def("casted", &value_t::casted) .def("in_place_cast", &value_t::in_place_cast) .def("simplified", &value_t::simplified) .def("in_place_simplify", &value_t::in_place_simplify) .def("number", &value_t::number) .def("annotate", &value_t::annotate) .def("has_annotation", &value_t::has_annotation) .add_property("annotation", make_function(py_value_annotation, return_internal_reference<>())) .def("strip_annotations", py_strip_annotations_0) .def("strip_annotations", py_strip_annotations_1) #if 0 .def("__getitem__", &value_t::operator[]) #endif .def("push_back", &value_t::push_back) .def("pop_back", &value_t::pop_back) .def("size", &value_t::size) .def("label", &value_t::label) .def("valid", &value_t::valid) .def("basetype", py_base_type) ; #if 0 // jww (2010-06-10): This is not working since I switched sequence_t to // ptr_deque<value_t>. class_< value_t::sequence_t > ("ValueSequence") .def(vector_indexing_suite< value_t::sequence_t, true >()); ; #endif scope().attr("NULL_VALUE") = NULL_VALUE; scope().attr("string_value") = &string_value; scope().attr("mask_value") = &mask_value; scope().attr("value_context") = &value_context; register_optional_to_python<value_t>(); implicitly_convertible<bool, value_t>(); implicitly_convertible<long, value_t>(); implicitly_convertible<string, value_t>(); implicitly_convertible<amount_t, value_t>(); implicitly_convertible<balance_t, value_t>(); implicitly_convertible<mask_t, value_t>(); implicitly_convertible<date_t, value_t>(); implicitly_convertible<datetime_t, value_t>(); #define EXC_TRANSLATE(type) \ register_exception_translator<type>(&exc_translate_ ## type); EXC_TRANSLATE(value_error); } } // namespace ledger <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the libqgit2 library * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * Copyright (C) 2013 Leonardo Giordani * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtCore/QFile> #include "qgitref.h" #include "qgitoid.h" #include "qgitrepository.h" #include "qgitexception.h" namespace LibQGit2 { Reference::Reference(git_reference *ref) : d(ref, git_reference_free) { } Reference::Reference(const Reference& other) : d(other.d) { } Reference::~Reference() { } OId Reference::target() const { return OId(git_reference_target(d.data())); } QString Reference::symbolicTarget() const { return QString::fromUtf8(git_reference_symbolic_target(d.data())); } bool Reference::isDirect() const { return git_reference_type(d.data()) == GIT_REF_OID; } bool Reference::isSymbolic() const { return git_reference_type(d.data()) == GIT_REF_SYMBOLIC; } QString Reference::name() const { return QString::fromUtf8(git_reference_name(d.data())); } Reference Reference::resolve() const { git_reference *ref; qGitThrow(git_reference_resolve(&ref, d.data())); return Reference(ref); } Repository Reference::owner() const { return Repository(git_reference_owner(d.data())); } void Reference::setSymbolicTarget(const QString& target) { git_reference* rp; qGitThrow(git_reference_symbolic_set_target(&rp, data(), QFile::encodeName(target))); d = ptr_type(rp); } void Reference::setTarget(const OId& oid) { git_reference* rp; qGitThrow(git_reference_set_target(&rp, data(), oid.constData())); d = ptr_type(rp); } bool Reference::isNull() const { return data() == 0; } git_reference* Reference::data() const { return d.data(); } const git_reference* Reference::constData() const { return d.data(); } } // namespace LibQGit2 <commit_msg>Fix deletion of git_reference in some cases<commit_after>/****************************************************************************** * This file is part of the libqgit2 library * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * Copyright (C) 2013 Leonardo Giordani * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtCore/QFile> #include "qgitref.h" #include "qgitoid.h" #include "qgitrepository.h" #include "qgitexception.h" namespace LibQGit2 { Reference::Reference(git_reference *ref) : d(ref, git_reference_free) { } Reference::Reference(const Reference& other) : d(other.d) { } Reference::~Reference() { } OId Reference::target() const { return OId(git_reference_target(d.data())); } QString Reference::symbolicTarget() const { return QString::fromUtf8(git_reference_symbolic_target(d.data())); } bool Reference::isDirect() const { return git_reference_type(d.data()) == GIT_REF_OID; } bool Reference::isSymbolic() const { return git_reference_type(d.data()) == GIT_REF_SYMBOLIC; } QString Reference::name() const { return QString::fromUtf8(git_reference_name(d.data())); } Reference Reference::resolve() const { git_reference *ref; qGitThrow(git_reference_resolve(&ref, d.data())); return Reference(ref); } Repository Reference::owner() const { return Repository(git_reference_owner(d.data())); } void Reference::setSymbolicTarget(const QString& target) { git_reference* rp; qGitThrow(git_reference_symbolic_set_target(&rp, data(), QFile::encodeName(target))); d = ptr_type(rp, git_reference_free); } void Reference::setTarget(const OId& oid) { git_reference* rp; qGitThrow(git_reference_set_target(&rp, data(), oid.constData())); d = ptr_type(rp, git_reference_free); } bool Reference::isNull() const { return data() == 0; } git_reference* Reference::data() const { return d.data(); } const git_reference* Reference::constData() const { return d.data(); } } // namespace LibQGit2 <|endoftext|>
<commit_before>// This file is part of BlueSky // // BlueSky is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // BlueSky is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BlueSky; if not, see <http://www.gnu.org/licenses/>. #if defined(BSPY_EXPORTING) && defined(UNIX) // supress gcc warnings #include <boost/python/detail/wrap_python.hpp> #endif #include "bs_array.h" #include "bs_map.h" using namespace std; namespace blue_sky { // bs_array BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, bs_vector_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, bs_vector_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, bs_vector_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, bs_vector_shared)); // bs_map BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (int, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (float, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (double, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (std::string, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (sp_obj, str_val_traits)); kernel::types_enum register_bs_array() { kernel::types_enum te; te.push_back(bs_array< int, vector_traits >::bs_type()); te.push_back(bs_array< float, vector_traits >::bs_type()); te.push_back(bs_array< double, vector_traits >::bs_type()); te.push_back(bs_array< std::string, vector_traits >::bs_type()); te.push_back(bs_array< int, bs_array_shared >::bs_type()); te.push_back(bs_array< float, bs_array_shared >::bs_type()); te.push_back(bs_array< double, bs_array_shared >::bs_type()); te.push_back(bs_array< std::string, bs_array_shared >::bs_type()); te.push_back(bs_array< int, bs_vector_shared >::bs_type()); te.push_back(bs_array< float, bs_vector_shared >::bs_type()); te.push_back(bs_array< double, bs_vector_shared >::bs_type()); te.push_back(bs_array< std::string, bs_vector_shared >::bs_type()); te.push_back(bs_map< int, str_val_traits >::bs_type()); te.push_back(bs_map< float, str_val_traits >::bs_type()); te.push_back(bs_map< double, str_val_traits >::bs_type()); te.push_back(bs_map< std::string, str_val_traits >::bs_type()); te.push_back(bs_map< sp_obj, str_val_traits >::bs_type()); return te; } } // end of blue_sky namespace <commit_msg>-- KERNEL: add bs_array specializations for type long'<commit_after>// This file is part of BlueSky // // BlueSky is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // BlueSky is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BlueSky; if not, see <http://www.gnu.org/licenses/>. #if defined(BSPY_EXPORTING) && defined(UNIX) // supress gcc warnings #include <boost/python/detail/wrap_python.hpp> #endif #include "bs_array.h" #include "bs_map.h" using namespace std; namespace blue_sky { // bs_array BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, vector_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, bs_array_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, bs_vector_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, bs_vector_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, bs_vector_shared)); BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, bs_vector_shared)); // bs_map BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (int, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (float, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (double, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (std::string, str_val_traits)); BS_TYPE_IMPL_T_EXT_MEM(bs_map, 2, (sp_obj, str_val_traits)); kernel::types_enum register_bs_array() { kernel::types_enum te; te.push_back(bs_array< int, vector_traits >::bs_type()); te.push_back(bs_array< long, vector_traits >::bs_type()); te.push_back(bs_array< float, vector_traits >::bs_type()); te.push_back(bs_array< double, vector_traits >::bs_type()); te.push_back(bs_array< std::string, vector_traits >::bs_type()); te.push_back(bs_array< int, bs_array_shared >::bs_type()); te.push_back(bs_array< long, bs_array_shared >::bs_type()); te.push_back(bs_array< float, bs_array_shared >::bs_type()); te.push_back(bs_array< double, bs_array_shared >::bs_type()); te.push_back(bs_array< std::string, bs_array_shared >::bs_type()); te.push_back(bs_array< int, bs_vector_shared >::bs_type()); te.push_back(bs_array< long, bs_vector_shared >::bs_type()); te.push_back(bs_array< float, bs_vector_shared >::bs_type()); te.push_back(bs_array< double, bs_vector_shared >::bs_type()); te.push_back(bs_array< std::string, bs_vector_shared >::bs_type()); te.push_back(bs_map< int, str_val_traits >::bs_type()); te.push_back(bs_map< long, str_val_traits >::bs_type()); te.push_back(bs_map< float, str_val_traits >::bs_type()); te.push_back(bs_map< double, str_val_traits >::bs_type()); te.push_back(bs_map< std::string, str_val_traits >::bs_type()); te.push_back(bs_map< sp_obj, str_val_traits >::bs_type()); return te; } } // end of blue_sky namespace <|endoftext|>
<commit_before>// --------------------------------------------------------------------------- // // This file is part of the <kortex> library suite // // Copyright (C) 2013 Engin Tola // // See licence.txt file for licence information. // // author: Engin Tola // e-mail: engintola@gmail.com // // --------------------------------------------------------------------------- #include <kortex/rotation.h> #include <kortex/matrix.h> #include <kortex/math.h> #include <kortex/defs.h> #include <kortex/check.h> namespace kortex { /// computes the rotation matrix that rotates na to nb void rotate_normal_to_normal( const double* na, const double* nb, double* Rab ) { double Na[3]; double Nb[3]; normalize_l2norm3(na, Na); normalize_l2norm3(nb, Nb); double dot_ab = dot3(Na,Nb); double axis[4]; if( 1-dot_ab < 1e-10 ) { axis[0] = 0.0; axis[1] = 0.0; axis[2] = 1.0; axis[3] = 0.0; } else { cross3(Na, Nb, axis); normalize_l2norm3(axis); axis[3] = acos( dot_ab ); } axisangle_to_rotation( axis, Rab ); } void axisangle_to_quaternion( const double* aa, double* q ) { double t = aa[3]/2; double s = sin( t ); q[0] = aa[0] * s; q[1] = aa[1] * s; q[2] = aa[2] * s; q[3] = cos(t); } void quaternion_to_rotation( const double* q, double* R ) { double q1_2 = sq( q[0] ); double q2_2 = sq( q[1] ); double q3_2 = sq( q[2] ); double q12 = q[0]*q[1]; double q13 = q[0]*q[2]; double q14 = q[0]*q[3]; double q23 = q[1]*q[2]; double q24 = q[1]*q[3]; double q34 = q[2]*q[3]; R[0] = 1-2*(q2_2+q3_2); R[1] = 2*(q12-q34); R[2] = 2*(q13+q24); R[3] = 2*(q12+q34); R[4] = 1-2*(q1_2+q3_2); R[5] = 2*(q23-q14); R[6] = 2*(q13-q24); R[7] = 2*(q23+q14); R[8] = 1-2*(q1_2+q2_2); } void axisangle_to_rotation( const double* aa, double* R ) { double q[4]; axisangle_to_quaternion(aa, q); quaternion_to_rotation ( q, R); } void rotation_matrix_around_z( const double& angle_in_degrees, double R[9] ) { double in_plane = angle_in_degrees * RADIANS; R[0] = cos(in_plane); R[1] = -sin(in_plane); R[2] = 0; R[3] = sin(in_plane); R[4] = cos(in_plane); R[5] = 0; R[6] = 0; R[7] = 0; R[8] = 1; } void euler_to_rotation( double theta, double phi, double psi, double R[9] ) { theta *= RADIANS; phi *= RADIANS; psi *= RADIANS; double c,s; c = cos(theta); s = sin(theta); double Rx [] = { 1, 0, 0, 0, c, -s, 0, s, c }; c = cos(phi); s = sin(phi); double Ry [] = { c, 0, s, 0, 1, 0, -s, 0, c }; c = cos(psi); s = sin(psi); double Rz[] = { c, -s, 0, s, c, 0, 0, 0, 1 }; mat_mat_mat_3( Rx, Ry, Rz, R ); } // Extracting Euler Angles from a Rotation Matrix - returns in degrees // Mike Day, Insomniac Games void rotation_to_euler( const double R[9], double& theta, double& phi, double& psi ) { theta = atan2( R[5], R[8] ); double c2 = sqrt( sq( R[0] ) + sq( R[1] ) ); phi = atan2( -R[2], c2 ); double s1 = sin( theta ); double c1 = cos( theta ); psi = atan2( s1*R[6]-c1*R[3] , c1*R[4]-s1*R[7] ); theta *= -DEGREES; phi *= -DEGREES; psi *= -DEGREES; } void azel_to_cartesian( double az, double el, double n[3] ) { az *= RADIANS; el *= RADIANS; n[0] = sin( el ) * cos( az ); n[1] = sin( el ) * sin( az ); n[2] = cos( el ); } void cartesian_to_azel( const double n[3], double& az, double& el ) { double r = sqrt( sq(n[0]) + sq(n[1]) + sq(n[2]) ); double n2 = n[2]/r; if ( n2 > 1.0 ) n2 = 1.0; else if( n2 < -1.0 ) n2 = -1.0; el = acos( n2 ) * DEGREES; az = atan2( n[1], n[0] ) * DEGREES; } static const double canonical_xd[] = { 1.0, 0.0, 0.0 }; static const double canonical_yd[] = { 0.0, 1.0, 0.0 }; static const double canonical_zd[] = { 0.0, 0.0, 1.0 }; void construct_local_coordinate_frame(const double* z_normal, double* new_u, double* new_v) { assert_pointer( z_normal && new_u && new_v ); passert_statement( (z_normal != new_u) && (z_normal != new_v) && (new_u != new_v), "overlapping pointers not allowed" ); assert_statement( is_unit_norm_3(z_normal), "z should be unit normed" ); const double *tmp_n = canonical_xd; if( fabs(dot3(z_normal, tmp_n)) > 0.8 ) { tmp_n = canonical_yd; cross3_normalized(tmp_n, z_normal, new_u); cross3_normalized(z_normal, new_u, new_v); } else { cross3_normalized(z_normal, tmp_n, new_v); cross3_normalized(new_v, z_normal, new_u); } assert_statement( is_unit_norm_3(new_u) && is_unit_norm_3(new_v), "output is not unit normed" ); } } <commit_msg>fixed azel <-> cartesian conversions: elevation is not inclination<commit_after>// --------------------------------------------------------------------------- // // This file is part of the <kortex> library suite // // Copyright (C) 2013 Engin Tola // // See licence.txt file for licence information. // // author: Engin Tola // e-mail: engintola@gmail.com // // --------------------------------------------------------------------------- #include <kortex/rotation.h> #include <kortex/matrix.h> #include <kortex/math.h> #include <kortex/defs.h> #include <kortex/check.h> namespace kortex { /// computes the rotation matrix that rotates na to nb void rotate_normal_to_normal( const double* na, const double* nb, double* Rab ) { double Na[3]; double Nb[3]; normalize_l2norm3(na, Na); normalize_l2norm3(nb, Nb); double dot_ab = dot3(Na,Nb); double axis[4]; if( 1-dot_ab < 1e-10 ) { axis[0] = 0.0; axis[1] = 0.0; axis[2] = 1.0; axis[3] = 0.0; } else { cross3(Na, Nb, axis); normalize_l2norm3(axis); axis[3] = acos( dot_ab ); } axisangle_to_rotation( axis, Rab ); } void axisangle_to_quaternion( const double* aa, double* q ) { double t = aa[3]/2; double s = sin( t ); q[0] = aa[0] * s; q[1] = aa[1] * s; q[2] = aa[2] * s; q[3] = cos(t); } void quaternion_to_rotation( const double* q, double* R ) { double q1_2 = sq( q[0] ); double q2_2 = sq( q[1] ); double q3_2 = sq( q[2] ); double q12 = q[0]*q[1]; double q13 = q[0]*q[2]; double q14 = q[0]*q[3]; double q23 = q[1]*q[2]; double q24 = q[1]*q[3]; double q34 = q[2]*q[3]; R[0] = 1-2*(q2_2+q3_2); R[1] = 2*(q12-q34); R[2] = 2*(q13+q24); R[3] = 2*(q12+q34); R[4] = 1-2*(q1_2+q3_2); R[5] = 2*(q23-q14); R[6] = 2*(q13-q24); R[7] = 2*(q23+q14); R[8] = 1-2*(q1_2+q2_2); } void axisangle_to_rotation( const double* aa, double* R ) { double q[4]; axisangle_to_quaternion(aa, q); quaternion_to_rotation ( q, R); } void rotation_matrix_around_z( const double& angle_in_degrees, double R[9] ) { double in_plane = angle_in_degrees * RADIANS; R[0] = cos(in_plane); R[1] = -sin(in_plane); R[2] = 0; R[3] = sin(in_plane); R[4] = cos(in_plane); R[5] = 0; R[6] = 0; R[7] = 0; R[8] = 1; } void euler_to_rotation( double theta, double phi, double psi, double R[9] ) { theta *= RADIANS; phi *= RADIANS; psi *= RADIANS; double c,s; c = cos(theta); s = sin(theta); double Rx [] = { 1, 0, 0, 0, c, -s, 0, s, c }; c = cos(phi); s = sin(phi); double Ry [] = { c, 0, s, 0, 1, 0, -s, 0, c }; c = cos(psi); s = sin(psi); double Rz[] = { c, -s, 0, s, c, 0, 0, 0, 1 }; mat_mat_mat_3( Rx, Ry, Rz, R ); } // Extracting Euler Angles from a Rotation Matrix - returns in degrees // Mike Day, Insomniac Games void rotation_to_euler( const double R[9], double& theta, double& phi, double& psi ) { theta = atan2( R[5], R[8] ); double c2 = sqrt( sq( R[0] ) + sq( R[1] ) ); phi = atan2( -R[2], c2 ); double s1 = sin( theta ); double c1 = cos( theta ); psi = atan2( s1*R[6]-c1*R[3] , c1*R[4]-s1*R[7] ); theta *= -DEGREES; phi *= -DEGREES; psi *= -DEGREES; } void azel_to_cartesian( double az, double el, double n[3] ) { az *= RADIANS; el *= RADIANS; n[0] = cos( el ) * cos( az ); n[1] = cos( el ) * sin( az ); n[2] = sin( el ); } void cartesian_to_azel( const double n[3], double& az, double& el ) { double r = sqrt( sq(n[0]) + sq(n[1]) + sq(n[2]) ); double n2 = n[2]/r; if ( n2 > 1.0 ) n2 = 1.0; else if( n2 < -1.0 ) n2 = -1.0; el = asin( n2 ) * DEGREES; az = atan2( n[1], n[0] ) * DEGREES; } static const double canonical_xd[] = { 1.0, 0.0, 0.0 }; static const double canonical_yd[] = { 0.0, 1.0, 0.0 }; static const double canonical_zd[] = { 0.0, 0.0, 1.0 }; void construct_local_coordinate_frame(const double* z_normal, double* new_u, double* new_v) { assert_pointer( z_normal && new_u && new_v ); passert_statement( (z_normal != new_u) && (z_normal != new_v) && (new_u != new_v), "overlapping pointers not allowed" ); assert_statement( is_unit_norm_3(z_normal), "z should be unit normed" ); const double *tmp_n = canonical_xd; if( fabs(dot3(z_normal, tmp_n)) > 0.8 ) { tmp_n = canonical_yd; cross3_normalized(tmp_n, z_normal, new_u); cross3_normalized(z_normal, new_u, new_v); } else { cross3_normalized(z_normal, tmp_n, new_v); cross3_normalized(new_v, z_normal, new_u); } assert_statement( is_unit_norm_3(new_u) && is_unit_norm_3(new_v), "output is not unit normed" ); } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "rpcserver.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <iadixcoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value exportwallet(const Array& params, bool fHelp) { CKey newKey; CKeyID keyID; CKey vchSecret; Value ret; string strAddress; CBitcoinAddress address; CWalletDB *cdb; CWallet *pwalletNew; DBErrors nLoadWalletRet; if (fHelp || params.size() != 3) throw runtime_error( "exportwallet <address> <filename> <secret>\n" "Export a wallet keys in a wallet file."); EnsureWalletIsUnlocked(); strAddress = params[0].get_str(); if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); newKey = CBitcoinSecret(vchSecret).GetKey(); pwalletNew = new CWallet (params[1].get_str()); cdb = new CWalletDB (params[1].get_str(), "cr+"); nLoadWalletRet = cdb->LoadWallet (pwalletNew); if (nLoadWalletRet != DB_LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Error creating new wallet"); return Value::null; } pwalletNew->AddKey (newKey); pwalletNew->ScanForWalletTransactions (pindexGenesisBlock, true); //bitdb.dbenv.dbrename (NULL, params[1].get_str().c_str(), NULL, "wallet.dat", DB_AUTO_COMMIT); cdb->Close (); //pwalletNew->SetDefaultKey (newKey.GetPubKey()); pwalletNew->EncryptWallet (params[2].get_str().c_str()); //bitdb.CloseDb (params[1].get_str()); delete cdb; delete pwalletNew; ret = (GetDataDir() / params[1].get_str()).string(); boost::filesystem::permissions(ret.get_str(), boost::filesystem::add_perms | boost::filesystem::others_read | boost::filesystem::others_write | boost::filesystem::group_read | boost::filesystem::group_write); return ret; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <iadixcoinaddress>\n" "Reveals the private key corresponding to <iadixcoinaddress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by IadixCoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <commit_msg>fix set default key<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "rpcserver.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <iadixcoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value exportwallet(const Array& params, bool fHelp) { CKey newKey; CKeyID keyID; CKey vchSecret; Value ret; string strAddress; CBitcoinAddress address; CWalletDB *cdb; CWallet *pwalletNew; DBErrors nLoadWalletRet; if (fHelp || params.size() != 3) throw runtime_error( "exportwallet <address> <filename> <secret>\n" "Export a wallet keys in a wallet file."); EnsureWalletIsUnlocked(); strAddress = params[0].get_str(); if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); newKey = CBitcoinSecret(vchSecret).GetKey(); pwalletNew = new CWallet (params[1].get_str()); cdb = new CWalletDB (params[1].get_str(), "cr+"); nLoadWalletRet = cdb->LoadWallet (pwalletNew); if (nLoadWalletRet != DB_LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Error creating new wallet"); return Value::null; } pwalletNew->AddKey (newKey); pwalletNew->ScanForWalletTransactions (pindexGenesisBlock, true); //bitdb.dbenv.dbrename (NULL, params[1].get_str().c_str(), NULL, "wallet.dat", DB_AUTO_COMMIT); cdb->Close (); pwalletNew->SetDefaultKey (newKey.GetPubKey()); pwalletNew->EncryptWallet (params[2].get_str().c_str()); //bitdb.CloseDb (params[1].get_str()); delete cdb; delete pwalletNew; ret = (GetDataDir() / params[1].get_str()).string(); boost::filesystem::permissions(ret.get_str(), boost::filesystem::add_perms | boost::filesystem::others_read | boost::filesystem::others_write | boost::filesystem::group_read | boost::filesystem::group_write); return ret; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <iadixcoinaddress>\n" "Reveals the private key corresponding to <iadixcoinaddress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid IadixCoin address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by IadixCoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <|endoftext|>
<commit_before>/** * Copyright (c) 2005 Till Adam <adam@kde.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "copyfolderjob.h" #include "folderstorage.h" #include "kmacctcachedimap.h" #include "kmfoldercachedimap.h" #include "kmfolder.h" #include "kmfolderdir.h" #include "kmfoldertype.h" #include "kmfoldermgr.h" #include "kmcommands.h" #include "kmmsgbase.h" #include "undostack.h" #include <kdebug.h> #include <klocale.h> #include <config.h> using namespace KMail; CopyFolderJob::CopyFolderJob( FolderStorage* const storage, KMFolderDir* const newParent ) : FolderJob( 0, tOther, (storage ? storage->folder() : 0) ), mStorage( storage ), mNewParent( newParent ), mNewFolder( 0 ), mChildFolderNodeIterator( *mStorage->folder()->createChildFolder() ), mNextChildFolder( 0 ) { mStorage->open("copyfolder"); } CopyFolderJob::~CopyFolderJob() { kdDebug(5006) << k_funcinfo << endl; if ( mNewFolder ) mNewFolder->setMoveInProgress( false ); if ( mStorage ) mStorage->close("copyfolder"); } /* * The basic strategy is to first create the target folder, then copy all the mail * from the source to the target folder, then recurse for each of the folder's children */ void CopyFolderJob::execute() { if ( createTargetDir() ) { copyMessagesToTargetDir(); } } void CopyFolderJob::copyMessagesToTargetDir() { // Hmmmm. Tasty hack. Can I have fries with that? mStorage->blockSignals( true ); // move all messages to the new folder QPtrList<KMMsgBase> msgList; for ( int i = 0; i < mStorage->count(); i++ ) { const KMMsgBase* msgBase = mStorage->getMsgBase( i ); assert( msgBase ); msgList.append( msgBase ); } if ( msgList.count() == 0 ) { slotCopyNextChild(); // no contents, check subfolders mStorage->blockSignals( false ); } else { KMCommand *command = new KMCopyCommand( mNewFolder, msgList ); connect( command, SIGNAL( completed( KMCommand * ) ), this, SLOT( slotCopyCompleted( KMCommand * ) ) ); command->start(); } } void CopyFolderJob::slotCopyCompleted( KMCommand* command ) { kdDebug(5006) << k_funcinfo << (command?command->result():0) << endl; disconnect( command, SIGNAL( completed( KMCommand * ) ), this, SLOT( slotCopyCompleted( KMCommand * ) ) ); mStorage->blockSignals( false ); if ( command && command->result() != KMCommand::OK ) { rollback(); return; } // if we have children, recurse if ( mStorage->folder()->child() ) { slotCopyNextChild(); } else { emit folderCopyComplete( true ); deleteLater(); } } void CopyFolderJob::slotCopyNextChild( bool success ) { //kdDebug(5006) << k_funcinfo << endl; if ( mNextChildFolder ) mNextChildFolder->close("copyfoldernext"); // refcount // previous sibling failed if ( !success ) { kdDebug(5006) << "Failed to copy one subfolder, let's not continue: " << mNewFolder->prettyURL() << endl; rollback(); emit folderCopyComplete( false ); deleteLater(); } KMFolderNode* node = mChildFolderNodeIterator.current(); while ( node && node->isDir() ) { ++mChildFolderNodeIterator; node = mChildFolderNodeIterator.current(); } if ( node ) { mNextChildFolder = static_cast<KMFolder*>(node); ++mChildFolderNodeIterator; } else { // no more children, we are done emit folderCopyComplete( true ); deleteLater(); return; } KMFolderDir * const dir = mNewFolder->createChildFolder(); if ( !dir ) { kdDebug(5006) << "Failed to create subfolders of: " << mNewFolder->prettyURL() << endl; emit folderCopyComplete( false ); deleteLater(); return; } // let it do its thing and report back when we are ready to do the next sibling mNextChildFolder->open("copyfoldernext"); // refcount FolderJob* job = new CopyFolderJob( mNextChildFolder->storage(), dir); connect( job, SIGNAL( folderCopyComplete( bool ) ), this, SLOT( slotCopyNextChild( bool ) ) ); job->start(); } // FIXME factor into CreateFolderJob and make async, so it works with online imap // (create folder code taken from newfolderdialog.cpp) bool CopyFolderJob::createTargetDir() { // get the default mailbox type KConfig * const config = KMKernel::config(); KConfigGroupSaver saver(config, "General"); int deftype = config->readNumEntry("default-mailbox-format", 1); if ( deftype < 0 || deftype > 1 ) deftype = 1; // the type of the new folder KMFolderType typenew = ( deftype == 0 ) ? KMFolderTypeMbox : KMFolderTypeMaildir; if ( mNewParent->owner() ) typenew = mNewParent->owner()->folderType(); bool success = false, waitForFolderCreation = false; if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeImap ) { KMFolderImap* selectedStorage = static_cast<KMFolderImap*>( mNewParent->owner()->storage() ); KMAcctImap *anAccount = selectedStorage->account(); // check if a connection is available BEFORE creating the folder if (anAccount->makeConnection() == ImapAccountBase::Connected) { mNewFolder = kmkernel->imapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent ); if ( mNewFolder ) { QString imapPath; imapPath = anAccount->createImapPath( selectedStorage->imapPath(), mStorage->folder()->name() ); KMFolderImap* newStorage = static_cast<KMFolderImap*>( mNewFolder->storage() ); connect( selectedStorage, SIGNAL(folderCreationResult(const QString&, bool)), this, SLOT(folderCreationDone(const QString&, bool)) ); selectedStorage->createFolder(mStorage->folder()->name(), QString::null); // create it on the server newStorage->initializeFrom( selectedStorage, imapPath, QString::null ); static_cast<KMFolderImap*>(mNewParent->owner()->storage())->setAccount( selectedStorage->account() ); waitForFolderCreation = true; success = true; } } } else if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeCachedImap ) { mNewFolder = kmkernel->dimapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent ); if ( mNewFolder ) { KMFolderCachedImap* selectedStorage = static_cast<KMFolderCachedImap*>( mNewParent->owner()->storage() ); KMFolderCachedImap* newStorage = static_cast<KMFolderCachedImap*>( mNewFolder->storage() ); newStorage->initializeFrom( selectedStorage ); success = true; } } else { // local folder mNewFolder = kmkernel->folderMgr()->createFolder(mStorage->folder()->name(), false, typenew, mNewParent ); if ( mNewFolder ) success = true; } if ( !success ) { kdWarning(5006) << k_funcinfo << "could not create folder" << endl; emit folderCopyComplete( false ); deleteLater(); return false; } mNewFolder->setMoveInProgress( true ); // inherit the folder type // FIXME we should probably copy over most if not all settings mNewFolder->storage()->setContentsType( mStorage->contentsType(), true /*quiet*/ ); mNewFolder->storage()->writeConfig(); kdDebug(5006)<< "CopyJob::createTargetDir - " << mStorage->folder()->idString() << " |=> " << mNewFolder->idString() << endl; return !waitForFolderCreation; } void CopyFolderJob::rollback() { // copy failed - rollback the last transaction // kmkernel->undoStack()->undo(); // .. and delete the new folder if ( mNewFolder ) { if ( mNewFolder->folderType() == KMFolderTypeImap ) { kmkernel->imapFolderMgr()->remove( mNewFolder ); } else if ( mNewFolder->folderType() == KMFolderTypeCachedImap ) { // tell the account (see KMFolderCachedImap::listDirectory2) KMFolderCachedImap* folder = static_cast<KMFolderCachedImap*>(mNewFolder->storage()); KMAcctCachedImap* acct = folder->account(); if ( acct ) acct->addDeletedFolder( folder->imapPath() ); kmkernel->dimapFolderMgr()->remove( mNewFolder ); } else if ( mNewFolder->folderType() == KMFolderTypeSearch ) { // invalid kdWarning(5006) << k_funcinfo << "cannot remove a search folder" << endl; } else { kmkernel->folderMgr()->remove( mNewFolder ); } } emit folderCopyComplete( false ); deleteLater(); } void CopyFolderJob::folderCreationDone(const QString & name, bool success) { if ( mStorage->folder()->name() != name ) return; // not our business kdDebug(5006) << k_funcinfo << success << endl; if ( !success ) { rollback(); } else { copyMessagesToTargetDir(); } } #include "copyfolderjob.moc" <commit_msg>Backport SVN commit 687341 by vkrause:<commit_after>/** * Copyright (c) 2005 Till Adam <adam@kde.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "copyfolderjob.h" #include "folderstorage.h" #include "kmacctcachedimap.h" #include "kmfoldercachedimap.h" #include "kmfolder.h" #include "kmfolderdir.h" #include "kmfoldertype.h" #include "kmfoldermgr.h" #include "kmcommands.h" #include "kmmsgbase.h" #include "undostack.h" #include <kdebug.h> #include <klocale.h> #include <config.h> using namespace KMail; CopyFolderJob::CopyFolderJob( FolderStorage* const storage, KMFolderDir* const newParent ) : FolderJob( 0, tOther, (storage ? storage->folder() : 0) ), mStorage( storage ), mNewParent( newParent ), mNewFolder( 0 ), mChildFolderNodeIterator( *mStorage->folder()->createChildFolder() ), mNextChildFolder( 0 ) { mStorage->open("copyfolder"); } CopyFolderJob::~CopyFolderJob() { kdDebug(5006) << k_funcinfo << endl; if ( mNewFolder ) mNewFolder->setMoveInProgress( false ); if ( mStorage ) mStorage->close("copyfolder"); } /* * The basic strategy is to first create the target folder, then copy all the mail * from the source to the target folder, then recurse for each of the folder's children */ void CopyFolderJob::execute() { if ( createTargetDir() ) { copyMessagesToTargetDir(); } } void CopyFolderJob::copyMessagesToTargetDir() { // Hmmmm. Tasty hack. Can I have fries with that? mStorage->blockSignals( true ); // move all messages to the new folder QPtrList<KMMsgBase> msgList; for ( int i = 0; i < mStorage->count(); i++ ) { const KMMsgBase* msgBase = mStorage->getMsgBase( i ); assert( msgBase ); msgList.append( msgBase ); } if ( msgList.count() == 0 ) { mStorage->blockSignals( false ); // ### be careful, after slotCopyNextChild() the source folder // (including mStorage) might already be deleted! slotCopyNextChild(); // no contents, check subfolders } else { KMCommand *command = new KMCopyCommand( mNewFolder, msgList ); connect( command, SIGNAL( completed( KMCommand * ) ), this, SLOT( slotCopyCompleted( KMCommand * ) ) ); command->start(); } } void CopyFolderJob::slotCopyCompleted( KMCommand* command ) { kdDebug(5006) << k_funcinfo << (command?command->result():0) << endl; disconnect( command, SIGNAL( completed( KMCommand * ) ), this, SLOT( slotCopyCompleted( KMCommand * ) ) ); mStorage->blockSignals( false ); if ( command && command->result() != KMCommand::OK ) { rollback(); return; } // if we have children, recurse if ( mStorage->folder()->child() ) { slotCopyNextChild(); } else { emit folderCopyComplete( true ); deleteLater(); } } void CopyFolderJob::slotCopyNextChild( bool success ) { //kdDebug(5006) << k_funcinfo << endl; if ( mNextChildFolder ) mNextChildFolder->close("copyfoldernext"); // refcount // previous sibling failed if ( !success ) { kdDebug(5006) << "Failed to copy one subfolder, let's not continue: " << mNewFolder->prettyURL() << endl; rollback(); emit folderCopyComplete( false ); deleteLater(); } KMFolderNode* node = mChildFolderNodeIterator.current(); while ( node && node->isDir() ) { ++mChildFolderNodeIterator; node = mChildFolderNodeIterator.current(); } if ( node ) { mNextChildFolder = static_cast<KMFolder*>(node); ++mChildFolderNodeIterator; } else { // no more children, we are done emit folderCopyComplete( true ); deleteLater(); return; } KMFolderDir * const dir = mNewFolder->createChildFolder(); if ( !dir ) { kdDebug(5006) << "Failed to create subfolders of: " << mNewFolder->prettyURL() << endl; emit folderCopyComplete( false ); deleteLater(); return; } // let it do its thing and report back when we are ready to do the next sibling mNextChildFolder->open("copyfoldernext"); // refcount FolderJob* job = new CopyFolderJob( mNextChildFolder->storage(), dir); connect( job, SIGNAL( folderCopyComplete( bool ) ), this, SLOT( slotCopyNextChild( bool ) ) ); job->start(); } // FIXME factor into CreateFolderJob and make async, so it works with online imap // (create folder code taken from newfolderdialog.cpp) bool CopyFolderJob::createTargetDir() { // get the default mailbox type KConfig * const config = KMKernel::config(); KConfigGroupSaver saver(config, "General"); int deftype = config->readNumEntry("default-mailbox-format", 1); if ( deftype < 0 || deftype > 1 ) deftype = 1; // the type of the new folder KMFolderType typenew = ( deftype == 0 ) ? KMFolderTypeMbox : KMFolderTypeMaildir; if ( mNewParent->owner() ) typenew = mNewParent->owner()->folderType(); bool success = false, waitForFolderCreation = false; if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeImap ) { KMFolderImap* selectedStorage = static_cast<KMFolderImap*>( mNewParent->owner()->storage() ); KMAcctImap *anAccount = selectedStorage->account(); // check if a connection is available BEFORE creating the folder if (anAccount->makeConnection() == ImapAccountBase::Connected) { mNewFolder = kmkernel->imapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent ); if ( mNewFolder ) { QString imapPath; imapPath = anAccount->createImapPath( selectedStorage->imapPath(), mStorage->folder()->name() ); KMFolderImap* newStorage = static_cast<KMFolderImap*>( mNewFolder->storage() ); connect( selectedStorage, SIGNAL(folderCreationResult(const QString&, bool)), this, SLOT(folderCreationDone(const QString&, bool)) ); selectedStorage->createFolder(mStorage->folder()->name(), QString::null); // create it on the server newStorage->initializeFrom( selectedStorage, imapPath, QString::null ); static_cast<KMFolderImap*>(mNewParent->owner()->storage())->setAccount( selectedStorage->account() ); waitForFolderCreation = true; success = true; } } } else if ( mNewParent->owner() && mNewParent->owner()->folderType() == KMFolderTypeCachedImap ) { mNewFolder = kmkernel->dimapFolderMgr()->createFolder( mStorage->folder()->name(), false, typenew, mNewParent ); if ( mNewFolder ) { KMFolderCachedImap* selectedStorage = static_cast<KMFolderCachedImap*>( mNewParent->owner()->storage() ); KMFolderCachedImap* newStorage = static_cast<KMFolderCachedImap*>( mNewFolder->storage() ); newStorage->initializeFrom( selectedStorage ); success = true; } } else { // local folder mNewFolder = kmkernel->folderMgr()->createFolder(mStorage->folder()->name(), false, typenew, mNewParent ); if ( mNewFolder ) success = true; } if ( !success ) { kdWarning(5006) << k_funcinfo << "could not create folder" << endl; emit folderCopyComplete( false ); deleteLater(); return false; } mNewFolder->setMoveInProgress( true ); // inherit the folder type // FIXME we should probably copy over most if not all settings mNewFolder->storage()->setContentsType( mStorage->contentsType(), true /*quiet*/ ); mNewFolder->storage()->writeConfig(); kdDebug(5006)<< "CopyJob::createTargetDir - " << mStorage->folder()->idString() << " |=> " << mNewFolder->idString() << endl; return !waitForFolderCreation; } void CopyFolderJob::rollback() { // copy failed - rollback the last transaction // kmkernel->undoStack()->undo(); // .. and delete the new folder if ( mNewFolder ) { if ( mNewFolder->folderType() == KMFolderTypeImap ) { kmkernel->imapFolderMgr()->remove( mNewFolder ); } else if ( mNewFolder->folderType() == KMFolderTypeCachedImap ) { // tell the account (see KMFolderCachedImap::listDirectory2) KMFolderCachedImap* folder = static_cast<KMFolderCachedImap*>(mNewFolder->storage()); KMAcctCachedImap* acct = folder->account(); if ( acct ) acct->addDeletedFolder( folder->imapPath() ); kmkernel->dimapFolderMgr()->remove( mNewFolder ); } else if ( mNewFolder->folderType() == KMFolderTypeSearch ) { // invalid kdWarning(5006) << k_funcinfo << "cannot remove a search folder" << endl; } else { kmkernel->folderMgr()->remove( mNewFolder ); } } emit folderCopyComplete( false ); deleteLater(); } void CopyFolderJob::folderCreationDone(const QString & name, bool success) { if ( mStorage->folder()->name() != name ) return; // not our business kdDebug(5006) << k_funcinfo << success << endl; if ( !success ) { rollback(); } else { copyMessagesToTargetDir(); } } #include "copyfolderjob.moc" <|endoftext|>
<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <cstdio> #include <cstdlib> #include "BSZUtil.h" #include "FileUtil.h" #include "IniFile.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << "\n"; std::exit(EXIT_FAILURE); } const std::string CONF_FILE_PATH( "/usr/local/var/lib/tuelib/cronjobs/merge_differential_and_full_marc_updates.conf"); void LoadFilePCRE(std::string * const file_pcre) { IniFile ini_file(CONF_FILE_PATH); *file_pcre = ini_file.getString("Files", "deletion_list"); *file_pcre += "|" + ini_file.getString("Files", "complete_dump"); *file_pcre += "|" + ini_file.getString("Files", "incremental_dump"); *file_pcre += "|" + ini_file.getString("Files", "incremental_authority_dump"); *file_pcre += "|Complete-MARC-.*-\\d\\d\\d\\d\\d\\d.tar.gz"; } inline bool Contains(const std::string &haystack, const std::string &needle) { return haystack.find(needle) != std::string::npos; } // Shift a given YYMMDD to ten days after std::string ShiftDateToTenDaysAfter(const std::string &cutoff_date) { struct tm cutoff_date_tm(TimeUtil::StringToStructTm(cutoff_date, "%y%m%d")); const time_t cutoff_date_time_t(TimeUtil::TimeGm(cutoff_date_tm)); if (unlikely(cutoff_date_time_t == TimeUtil::BAD_TIME_T)) LOG_ERROR("in ShiftDateToTenDaysBefore: bad time conversion! (1)"); const time_t new_cutoff_date(TimeUtil::AddDays(cutoff_date_time_t, +10)); if (unlikely(new_cutoff_date == TimeUtil::BAD_TIME_T)) LOG_ERROR("in ShiftDateToTenDaysBefore: bad time conversion! (2)"); return TimeUtil::TimeTToString(new_cutoff_date, "%y%m%d"); } bool FileComparator(const std::string &filename1, const std::string &filename2) { auto date1(BSZUtil::ExtractDateFromFilenameOrDie(filename1)); if (Contains(filename1, "sekkor")) date1 = ShiftDateToTenDaysAfter(date1); auto date2(BSZUtil::ExtractDateFromFilenameOrDie(filename2)); if (Contains(filename2, "sekkor")) date2 = ShiftDateToTenDaysAfter(date2); if (date1 != date2) return date1 < date2; // Deletion lists come first: if (filename1[0] == 'L' and filename2[0] != 'L') return true; if (filename2[0] == 'L' and filename1[0] != 'L') return false; // Complete dumps come before anything else: if (StringUtil::StartsWith(filename1, "SA-") and not StringUtil::StartsWith(filename2, "SA-")) return true; if (StringUtil::StartsWith(filename2, "SA-") and not StringUtil::StartsWith(filename1, "SA-")) return false; // Pseudo complete dumps come before anything else: if (StringUtil::StartsWith(filename1, "Complete-MARC-") and not StringUtil::StartsWith(filename2, "Complete-MARC-")) return true; if (StringUtil::StartsWith(filename2, "Complete-MARC-") and not StringUtil::StartsWith(filename1, "Complete-MARC-")) return false; // Sekkor updates come before anything else: if (Contains(filename1, "sekkor") and not Contains(filename2, "sekkor")) return true; if (Contains(filename2, "sekkor") and not Contains(filename1, "sekkor")) return false; // Files w/o local data come before those w/ local data: if (Contains(filename1, "_o") and not Contains(filename2, "_o")) return true; if (Contains(filename2, "_o") and not Contains(filename1, "_o")) return false; LOG_ERROR("don't know how to compare \"" + filename1 + "\" with \"" + filename2 + "\"!"); } inline bool IsMtextDeletionList(const std::string &filename) { return StringUtil::StartsWith(filename, "LOEPPN_m-"); } bool MtexComparator(const std::string &filename1, const std::string &filename2) { if (IsMtextDeletionList(filename1) and IsMtextDeletionList(filename2)) return BSZUtil::ExtractDateFromFilenameOrDie(filename1) < BSZUtil::ExtractDateFromFilenameOrDie(filename2); if (IsMtextDeletionList(filename1)) return false; if (IsMtextDeletionList(filename2)) return true; return FileComparator(filename1, filename2); } // Returns file_list.end() if neither a complete dump file name nor a pseudo complete dump file name were found. std::vector<std::string>::const_iterator FindMostRecentCompleteOrPseudoCompleteDump(const std::vector<std::string> &file_list) { auto file(file_list.cend()); do { --file; if (StringUtil::StartsWith(*file, "SA-") or StringUtil::StartsWith(*file, "Complete-MARC-")) return file; } while (file != file_list.begin()); return file_list.cend(); } // If our complete dump is an SA- file, we should have a "partner" w/o local data. In that case we should return the partner. std::vector<std::string>::const_iterator EarliestReferenceDump(std::vector<std::string>::const_iterator complete_or_pseudo_complete_dump, const std::vector<std::string> &file_list) { /* If we have found an SA- file we likely have two, one w/ and one w/o local data: */ if (StringUtil::StartsWith(*complete_or_pseudo_complete_dump, "SA-")) { if (complete_or_pseudo_complete_dump == file_list.begin() or not StringUtil::StartsWith(*(complete_or_pseudo_complete_dump - 1), "SA-") or not (BSZUtil::ExtractDateFromFilenameOrDie(*complete_or_pseudo_complete_dump) == BSZUtil::ExtractDateFromFilenameOrDie(*(complete_or_pseudo_complete_dump - 1)))) LOG_WARNING("expected a pair of SA- files w/ the same date!"); else return complete_or_pseudo_complete_dump - 1; } return complete_or_pseudo_complete_dump; } } // unnamed namespace int Main(int argc, char */*argv*/[]) { if (argc != 1) Usage(); std::string file_pcre; LoadFilePCRE(&file_pcre); std::vector<std::string> file_list; if (FileUtil::GetFileNameList(file_pcre, &file_list) == 0) LOG_ERROR("no matches found for \"" + file_pcre + "\"!"); std::sort(file_list.begin(), file_list.end(), FileComparator); std::stable_sort(file_list.begin(), file_list.end(), MtexComparator); // mtex deletion list must go last // Throw away older files before our "reference" complete dump or pseudo complete dump: const auto reference_dump(FindMostRecentCompleteOrPseudoCompleteDump(file_list)); if (reference_dump == file_list.end()) LOG_ERROR("no reference dump file found!"); file_list.erase(file_list.begin(), EarliestReferenceDump(reference_dump, file_list)); for (const auto &filename : file_list) std::cout << filename << '\n'; return EXIT_SUCCESS; } <commit_msg>Fixed a function name.<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <cstdio> #include <cstdlib> #include "BSZUtil.h" #include "FileUtil.h" #include "IniFile.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << "\n"; std::exit(EXIT_FAILURE); } const std::string CONF_FILE_PATH( "/usr/local/var/lib/tuelib/cronjobs/merge_differential_and_full_marc_updates.conf"); void LoadFilePCRE(std::string * const file_pcre) { IniFile ini_file(CONF_FILE_PATH); *file_pcre = ini_file.getString("Files", "deletion_list"); *file_pcre += "|" + ini_file.getString("Files", "complete_dump"); *file_pcre += "|" + ini_file.getString("Files", "incremental_dump"); *file_pcre += "|" + ini_file.getString("Files", "incremental_authority_dump"); *file_pcre += "|Complete-MARC-.*-\\d\\d\\d\\d\\d\\d.tar.gz"; } inline bool Contains(const std::string &haystack, const std::string &needle) { return haystack.find(needle) != std::string::npos; } // Shift a given YYMMDD to ten days after std::string ShiftDateToTenDaysAfter(const std::string &cutoff_date) { struct tm cutoff_date_tm(TimeUtil::StringToStructTm(cutoff_date, "%y%m%d")); const time_t cutoff_date_time_t(TimeUtil::TimeGm(cutoff_date_tm)); if (unlikely(cutoff_date_time_t == TimeUtil::BAD_TIME_T)) LOG_ERROR("in ShiftDateToTenDaysBefore: bad time conversion! (1)"); const time_t new_cutoff_date(TimeUtil::AddDays(cutoff_date_time_t, +10)); if (unlikely(new_cutoff_date == TimeUtil::BAD_TIME_T)) LOG_ERROR("in ShiftDateToTenDaysBefore: bad time conversion! (2)"); return TimeUtil::TimeTToString(new_cutoff_date, "%y%m%d"); } bool FileComparator(const std::string &filename1, const std::string &filename2) { auto date1(BSZUtil::ExtractDateFromFilenameOrDie(filename1)); if (Contains(filename1, "sekkor")) date1 = ShiftDateToTenDaysAfter(date1); auto date2(BSZUtil::ExtractDateFromFilenameOrDie(filename2)); if (Contains(filename2, "sekkor")) date2 = ShiftDateToTenDaysAfter(date2); if (date1 != date2) return date1 < date2; // Deletion lists come first: if (filename1[0] == 'L' and filename2[0] != 'L') return true; if (filename2[0] == 'L' and filename1[0] != 'L') return false; // Complete dumps come before anything else: if (StringUtil::StartsWith(filename1, "SA-") and not StringUtil::StartsWith(filename2, "SA-")) return true; if (StringUtil::StartsWith(filename2, "SA-") and not StringUtil::StartsWith(filename1, "SA-")) return false; // Pseudo complete dumps come before anything else: if (StringUtil::StartsWith(filename1, "Complete-MARC-") and not StringUtil::StartsWith(filename2, "Complete-MARC-")) return true; if (StringUtil::StartsWith(filename2, "Complete-MARC-") and not StringUtil::StartsWith(filename1, "Complete-MARC-")) return false; // Sekkor updates come before anything else: if (Contains(filename1, "sekkor") and not Contains(filename2, "sekkor")) return true; if (Contains(filename2, "sekkor") and not Contains(filename1, "sekkor")) return false; // Files w/o local data come before those w/ local data: if (Contains(filename1, "_o") and not Contains(filename2, "_o")) return true; if (Contains(filename2, "_o") and not Contains(filename1, "_o")) return false; LOG_ERROR("don't know how to compare \"" + filename1 + "\" with \"" + filename2 + "\"!"); } inline bool IsMtexDeletionList(const std::string &filename) { return StringUtil::StartsWith(filename, "LOEPPN_m-"); } bool MtexComparator(const std::string &filename1, const std::string &filename2) { if (IsMtexDeletionList(filename1) and IsMtexDeletionList(filename2)) return BSZUtil::ExtractDateFromFilenameOrDie(filename1) < BSZUtil::ExtractDateFromFilenameOrDie(filename2); if (IsMtexDeletionList(filename1)) return false; if (IsMtexDeletionList(filename2)) return true; return FileComparator(filename1, filename2); } // Returns file_list.end() if neither a complete dump file name nor a pseudo complete dump file name were found. std::vector<std::string>::const_iterator FindMostRecentCompleteOrPseudoCompleteDump(const std::vector<std::string> &file_list) { auto file(file_list.cend()); do { --file; if (StringUtil::StartsWith(*file, "SA-") or StringUtil::StartsWith(*file, "Complete-MARC-")) return file; } while (file != file_list.begin()); return file_list.cend(); } // If our complete dump is an SA- file, we should have a "partner" w/o local data. In that case we should return the partner. std::vector<std::string>::const_iterator EarliestReferenceDump(std::vector<std::string>::const_iterator complete_or_pseudo_complete_dump, const std::vector<std::string> &file_list) { /* If we have found an SA- file we likely have two, one w/ and one w/o local data: */ if (StringUtil::StartsWith(*complete_or_pseudo_complete_dump, "SA-")) { if (complete_or_pseudo_complete_dump == file_list.begin() or not StringUtil::StartsWith(*(complete_or_pseudo_complete_dump - 1), "SA-") or not (BSZUtil::ExtractDateFromFilenameOrDie(*complete_or_pseudo_complete_dump) == BSZUtil::ExtractDateFromFilenameOrDie(*(complete_or_pseudo_complete_dump - 1)))) LOG_WARNING("expected a pair of SA- files w/ the same date!"); else return complete_or_pseudo_complete_dump - 1; } return complete_or_pseudo_complete_dump; } } // unnamed namespace int Main(int argc, char */*argv*/[]) { if (argc != 1) Usage(); std::string file_pcre; LoadFilePCRE(&file_pcre); std::vector<std::string> file_list; if (FileUtil::GetFileNameList(file_pcre, &file_list) == 0) LOG_ERROR("no matches found for \"" + file_pcre + "\"!"); std::sort(file_list.begin(), file_list.end(), FileComparator); std::stable_sort(file_list.begin(), file_list.end(), MtexComparator); // mtex deletion list must go last // Throw away older files before our "reference" complete dump or pseudo complete dump: const auto reference_dump(FindMostRecentCompleteOrPseudoCompleteDump(file_list)); if (reference_dump == file_list.end()) LOG_ERROR("no reference dump file found!"); file_list.erase(file_list.begin(), EarliestReferenceDump(reference_dump, file_list)); for (const auto &filename : file_list) std::cout << filename << '\n'; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <uv.h> #include <string> #include <dbus/dbus.h> #include "dbus.h" namespace NodeDBus { using namespace node; using namespace v8; using namespace std; Handle<Value> GetBus(const Arguments& args) { HandleScope scope; DBusConnection *connection = NULL; DBusError error; dbus_error_init(&error); if (!args[0]->IsNumber()) return ThrowException(Exception::Error(String::New("First parameter is integer"))); // Create connection switch(args[0]->IntegerValue()) { case NODE_DBUS_BUS_SYSTEM: connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); break; case NODE_DBUS_BUS_SESSION: connection = dbus_bus_get(DBUS_BUS_SESSION, &error); break; } if (connection == NULL) return ThrowException(Exception::Error(String::New("Failed to get bus object"))); // Initializing connection object Handle<ObjectTemplate> object_template = ObjectTemplate::New(); object_template->SetInternalFieldCount(1); Persistent<ObjectTemplate> object_instance = Persistent<ObjectTemplate>::New(object_template); // Create bus object BusObject *bus = new BusObject; bus->type = (BusType)args[0]->IntegerValue(); bus->connection = connection; // Create a JavaScript object to store bus object Local<Object> bus_object = object_instance->NewInstance(); bus_object->SetInternalField(0, External::New(bus)); return scope.Close(bus_object); } Handle<Value> CallMethod(const Arguments& args) { HandleScope scope; Local<Object> bus_object = args[0]->ToObject(); String::Utf8Value service_name(args[1]->ToString()); String::Utf8Value object_path(args[2]->ToString()); String::Utf8Value interface_name(args[3]->ToString()); String::Utf8Value method(args[4]->ToString()); String::Utf8Value signature(args[5]->ToString()); // Get bus from internal field BusObject *bus = (DBusGConnection*) External::Unwrap(bus_object->GetInternalField(0)); // Create message for method call DBusMessage *message = dbus_message_new_method_call(*service_name, *object_path, *interface_name, method); // Preparing method arguments if (args[6]->IsObject()) { DBusMessageIter iter; DBusSignatureIter siter; DBusError error; Local<Object> argumentObject = args[6]->ToObject(); // Initializing augument message dbus_message_iter_init_append(message, &iter); dbus_error_init(&error); // Initializing signature if (!dbus_signature_validate(signature, &error)) { ERROR("Invalid signature: %s\n", error.message); } dbus_signature_iter_init(&siter, signature); // TODO: encode arguments to message } // TODO: Process message returned } static void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "getBus", GetBus); NODE_SET_METHOD(target, "callMethod", CallMethod); } NODE_MODULE(dbus, init); } <commit_msg>make a loop to process arguments<commit_after>#include <v8.h> #include <node.h> #include <uv.h> #include <string> #include <dbus/dbus.h> #include "dbus.h" namespace NodeDBus { using namespace node; using namespace v8; using namespace std; Handle<Value> GetBus(const Arguments& args) { HandleScope scope; DBusConnection *connection = NULL; DBusError error; dbus_error_init(&error); if (!args[0]->IsNumber()) return ThrowException(Exception::Error(String::New("First parameter is integer"))); // Create connection switch(args[0]->IntegerValue()) { case NODE_DBUS_BUS_SYSTEM: connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); break; case NODE_DBUS_BUS_SESSION: connection = dbus_bus_get(DBUS_BUS_SESSION, &error); break; } if (connection == NULL) return ThrowException(Exception::Error(String::New("Failed to get bus object"))); // Initializing connection object Handle<ObjectTemplate> object_template = ObjectTemplate::New(); object_template->SetInternalFieldCount(1); Persistent<ObjectTemplate> object_instance = Persistent<ObjectTemplate>::New(object_template); // Create bus object BusObject *bus = new BusObject; bus->type = (BusType)args[0]->IntegerValue(); bus->connection = connection; // Create a JavaScript object to store bus object Local<Object> bus_object = object_instance->NewInstance(); bus_object->SetInternalField(0, External::New(bus)); return scope.Close(bus_object); } Handle<Value> CallMethod(const Arguments& args) { HandleScope scope; Local<Object> bus_object = args[0]->ToObject(); String::Utf8Value service_name(args[1]->ToString()); String::Utf8Value object_path(args[2]->ToString()); String::Utf8Value interface_name(args[3]->ToString()); String::Utf8Value method(args[4]->ToString()); String::Utf8Value signature(args[5]->ToString()); // Get bus from internal field BusObject *bus = (BusObject *) External::Unwrap(bus_object->GetInternalField(0)); // Create message for method call DBusMessage *message = dbus_message_new_method_call(*service_name, *object_path, *interface_name, *method); // Preparing method arguments if (args[6]->IsObject()) { DBusMessageIter iter; DBusSignatureIter siter; DBusError error; Local<Array> argument_arr = Local<Array>::Cast(args[6]); // Initializing augument message dbus_message_iter_init_append(message, &iter); dbus_error_init(&error); // Initializing signature if (!dbus_signature_validate(*signature, &error)) { printf("Invalid signature: %s\n", error.message); } dbus_signature_iter_init(&siter, *signature); for (unsigned int i = 0; i < argument_arr->Length(); ++i) { char *arg_sig = dbus_signature_iter_get_signature(&siter); // TODO: encode arguments to message dbus_free(arg_sig); dbus_signature_iter_next(&siter); } } // TODO: Process message returned return Undefined(); } static void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "getBus", GetBus); NODE_SET_METHOD(target, "callMethod", CallMethod); } NODE_MODULE(dbus, init); } <|endoftext|>
<commit_before> #include <utility> #include <set> #ifndef TAPAS_DEBUG #define TAPAS_DEBUG 1 // always use TAPAS_DEBUG #endif #include <tapas/common.h> #include <tapas/test.h> #include <tapas/geometry.h> SETUP_TEST; using V1 = tapas::Vec<1, double>; using V2 = tapas::Vec<2, double>; using Reg1 = tapas::Region<1, double>; using Reg2 = tapas::Region<2, double>; bool Close(double a, double b, const char *, int) { return fabs(a - b) < 1e-6; } bool Close(double a, V1 b, const char *, int) { return fabs(a - b[0]) < 1e-6; } bool Close(V1 a, double b, const char *, int) { return fabs(a[0] - b) < 1e-6; } bool Close(V1 a, V1 b, const char *file, int line) { bool ret = fabs(a[0] - b[0]) < 1e-10; if (!ret) { std::cerr << file << ":" << line << " Close(): Not close: a = " << a << ", b = " << b << std::endl; } return ret; } void Test_Center2d() { { V2 tmax = {0,0}, tmin = {-1,-1}; V2 smax = {1,1}, smin = { 0, 0}; Reg2 t(tmin, tmax), s(smin, smax); // Case 1 double dist = tapas::Distance<2, tapas::CenterClass, double>::CalcApprox(t, s); double dist_ans = 2; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } { // Case 2 V2 tmax = {0,0}, tmin = {-1,-1}; V2 smax = {1,1}, smin = {0.5, 0.5}; Reg2 t(tmin, tmax), s(smin, smax); double dist = tapas::Distance<2, tapas::CenterClass, double>::CalcApprox(t, s); double dist_ans = 2; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } { // Case 3 V2 tmax = {0,0}, tmin = {-1,-1}; V2 smax = {1,0}, smin = {0.5, - 0.5}; Reg2 t(tmin, tmax), s(smin, smax); double dist = tapas::Distance<2, tapas::CenterClass, double>::CalcApprox(t, s); double dist_ans = 1; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } } void Test_Center1d() { V1 tmax = {1}, tmin = {-1}; V1 dist, dist_ans; V1 sctr, tctr; V1 R = 0.5; Reg1 t(tmin, tmax), s; using D = tapas::Distance<1, tapas::CenterClass, double>; // Case 1 // |---+---| src // |---+-----------------| trg // -1 1 sctr = -0.8; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = -0.75; // answer : -1 + 0.25 dist = D::CalcApprox(t, s); dist_ans = (tctr - sctr) * (tctr - sctr); ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 2 // |---+---| src // |-----+---------------| trg // -1 1 sctr = -0.7; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 3 // |---+---| src // |---------------+-----| trg // -1 1 sctr = 0.4; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 4 // |---+---| src // |-----------------+---| trg // -1 1 sctr = 0.4; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 5 // |---+---| src // |-----------------+---| trg // -1 1 sctr = 0.4; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 6 // |-------------+-------------| src // |----------+----------| trg // -1 1 R = 2.5; sctr = 0.1; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = 0.0; dist = D::CalcApprox(t, s); dist_ans = 0; //std::cout << "dist = " << sqrt(dist[0]) << std::endl; //std::cout << "ditt_ans = " << sqrt(dist_ans[0]) << std::endl; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } void Test_Separated() { { V1 xmax = {1.0}, xmin = {0.0}, ymax = {3.0}, ymin = {1.1}; Reg1 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V1 xmax = {1.0}, xmin = {0.0}, ymax = {3.0}, ymin = {1.1}; Reg1 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V1 xmax = {1.0}, xmin = {0.0}, ymax = {3.0}, ymin = {1.1}; Reg1 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(!tapas::Separated(x, x)); ASSERT_TRUE(!tapas::Separated(y, y)); } { V2 xmax = { 1, 1}; V2 xmin = { 0, 0}; V2 ymax = { 0, 0}; V2 ymin = {-1,-1}; Reg2 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V2 xmax = { 2, 0}; V2 xmin = { 1,-1}; V2 ymax = { 0, 0}; V2 ymin = {-1,-1}; Reg2 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V2 xmax = { 1, 1}; V2 xmin = { -0.1, -0.1}; V2 ymax = { 0, 0}; V2 ymin = {-1,-1}; Reg2 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(!tapas::Separated(x, y)); ASSERT_TRUE(!tapas::Separated(y, x)); } } int main(int argc, char **argv) { MPI_Init(&argc, &argv); Test_Center1d(); Test_Center2d(); Test_Separated(); TEST_REPORT_RESULT(); MPI_Finalize(); return (TEST_SUCCESS() ? 0 : 1); } <commit_msg>minor fix: added header include for gcc 5.4.0<commit_after> #include <cmath> #include <utility> #include <set> #ifndef TAPAS_DEBUG #define TAPAS_DEBUG 1 // always use TAPAS_DEBUG #endif #include <tapas/common.h> #include <tapas/test.h> #include <tapas/geometry.h> SETUP_TEST; using V1 = tapas::Vec<1, double>; using V2 = tapas::Vec<2, double>; using Reg1 = tapas::Region<1, double>; using Reg2 = tapas::Region<2, double>; bool Close(double a, double b, const char *, int) { return fabs(a - b) < 1e-6; } bool Close(double a, V1 b, const char *, int) { return fabs(a - b[0]) < 1e-6; } bool Close(V1 a, double b, const char *, int) { return fabs(a[0] - b) < 1e-6; } bool Close(V1 a, V1 b, const char *file, int line) { bool ret = fabs(a[0] - b[0]) < 1e-10; if (!ret) { std::cerr << file << ":" << line << " Close(): Not close: a = " << a << ", b = " << b << std::endl; } return ret; } void Test_Center2d() { { V2 tmax = {0,0}, tmin = {-1,-1}; V2 smax = {1,1}, smin = { 0, 0}; Reg2 t(tmin, tmax), s(smin, smax); // Case 1 double dist = tapas::Distance<2, tapas::CenterClass, double>::CalcApprox(t, s); double dist_ans = 2; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } { // Case 2 V2 tmax = {0,0}, tmin = {-1,-1}; V2 smax = {1,1}, smin = {0.5, 0.5}; Reg2 t(tmin, tmax), s(smin, smax); double dist = tapas::Distance<2, tapas::CenterClass, double>::CalcApprox(t, s); double dist_ans = 2; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } { // Case 3 V2 tmax = {0,0}, tmin = {-1,-1}; V2 smax = {1,0}, smin = {0.5, - 0.5}; Reg2 t(tmin, tmax), s(smin, smax); double dist = tapas::Distance<2, tapas::CenterClass, double>::CalcApprox(t, s); double dist_ans = 1; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } } void Test_Center1d() { V1 tmax = {1}, tmin = {-1}; V1 dist, dist_ans; V1 sctr, tctr; V1 R = 0.5; Reg1 t(tmin, tmax), s; using D = tapas::Distance<1, tapas::CenterClass, double>; // Case 1 // |---+---| src // |---+-----------------| trg // -1 1 sctr = -0.8; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = -0.75; // answer : -1 + 0.25 dist = D::CalcApprox(t, s); dist_ans = (tctr - sctr) * (tctr - sctr); ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 2 // |---+---| src // |-----+---------------| trg // -1 1 sctr = -0.7; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 3 // |---+---| src // |---------------+-----| trg // -1 1 sctr = 0.4; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 4 // |---+---| src // |-----------------+---| trg // -1 1 sctr = 0.4; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 5 // |---+---| src // |-----------------+---| trg // -1 1 sctr = 0.4; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = sctr; // answer dist = D::CalcApprox(t, s); dist_ans = 0 * 0; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); // Case 6 // |-------------+-------------| src // |----------+----------| trg // -1 1 R = 2.5; sctr = 0.1; s.min() = sctr - R/2; s.max() = sctr + R/2; tctr = 0.0; dist = D::CalcApprox(t, s); dist_ans = 0; //std::cout << "dist = " << sqrt(dist[0]) << std::endl; //std::cout << "ditt_ans = " << sqrt(dist_ans[0]) << std::endl; ASSERT_TRUE(Close(dist, dist_ans, __FILE__, __LINE__)); } void Test_Separated() { { V1 xmax = {1.0}, xmin = {0.0}, ymax = {3.0}, ymin = {1.1}; Reg1 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V1 xmax = {1.0}, xmin = {0.0}, ymax = {3.0}, ymin = {1.1}; Reg1 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V1 xmax = {1.0}, xmin = {0.0}, ymax = {3.0}, ymin = {1.1}; Reg1 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(!tapas::Separated(x, x)); ASSERT_TRUE(!tapas::Separated(y, y)); } { V2 xmax = { 1, 1}; V2 xmin = { 0, 0}; V2 ymax = { 0, 0}; V2 ymin = {-1,-1}; Reg2 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V2 xmax = { 2, 0}; V2 xmin = { 1,-1}; V2 ymax = { 0, 0}; V2 ymin = {-1,-1}; Reg2 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(tapas::Separated(x, y)); ASSERT_TRUE(tapas::Separated(y, x)); } { V2 xmax = { 1, 1}; V2 xmin = { -0.1, -0.1}; V2 ymax = { 0, 0}; V2 ymin = {-1,-1}; Reg2 x(xmin, xmax), y(ymin, ymax); ASSERT_TRUE(!tapas::Separated(x, y)); ASSERT_TRUE(!tapas::Separated(y, x)); } } int main(int argc, char **argv) { MPI_Init(&argc, &argv); Test_Center1d(); Test_Center2d(); Test_Separated(); TEST_REPORT_RESULT(); MPI_Finalize(); return (TEST_SUCCESS() ? 0 : 1); } <|endoftext|>
<commit_before>#ifndef diff_hh_INCLUDED #define diff_hh_INCLUDED // Implementation of the linear space variant of the algorithm described in // "An O(ND) Difference Algorithm and Its Variations" // (http://xmailserver.org/diff2.pdf) #include "array_view.hh" #include "vector.hh" #include <functional> #include <iterator> namespace Kakoune { template<typename T> struct MirroredArray : public ArrayView<T> { MirroredArray(ArrayView<T> data, int size) : ArrayView<T>(data), size(size) { kak_assert(2 * size + 1 <= data.size()); (*this)[1] = 0; } [[gnu::always_inline]] T& operator[](int n) { return ArrayView<T>::operator[](n + size); } [[gnu::always_inline]] const T& operator[](int n) const { return ArrayView<T>::operator[](n + size); } private: int size; }; struct Snake{ int x, y, u, v; bool add; }; template<typename Iterator, typename Equal> Snake find_end_snake_of_further_reaching_dpath(Iterator a, int N, Iterator b, int M, const MirroredArray<int>& V, const int D, const int k, Equal eq) { const bool add = k == -D or (k != D and V[k-1] < V[k+1]); // if diagonal on the right goes further along x than diagonal on the left, // then we take a vertical edge from it to this diagonal, hence x = V[k+1] // else, we take an horizontal edge from our left diagonal,x = V[k-1]+1 const int x = add ? V[k+1] : V[k-1]+1; // we are by construction on diagonal k, so our position along b (y) is x - k. const int y = x - k; int u = x, v = y; // follow end snake along diagonal k while (u < N and v < M and eq(a[u], b[v])) ++u, ++v; return { x, y, u, v, add }; } struct SnakeLen : Snake { SnakeLen(Snake s, int d) : Snake(s), d(d) {} int d; }; template<typename Iterator, typename Equal> SnakeLen find_middle_snake(Iterator a, int N, Iterator b, int M, ArrayView<int> data1, ArrayView<int> data2, Equal eq) { const int delta = N - M; MirroredArray<int> V1{data1, N + M}; MirroredArray<int> V2{data2, N + M}; std::reverse_iterator<Iterator> ra{a + N}, rb{b + M}; for (int D = 0; D <= (M + N + 1) / 2; ++D) { for (int k1 = -D; k1 <= D; k1 += 2) { auto p = find_end_snake_of_further_reaching_dpath(a, N, b, M, V1, D, k1, eq); V1[k1] = p.u; const int k2 = -(k1 - delta); if ((delta % 2 != 0) and -(D-1) <= k2 and k2 <= (D-1)) { if (V1[k1] + V2[k2] >= N) return { p, 2 * D - 1 };// return last snake on forward path } } for (int k2 = -D; k2 <= D; k2 += 2) { auto p = find_end_snake_of_further_reaching_dpath(ra, N, rb, M, V2, D, k2, eq); V2[k2] = p.u; const int k1 = -(k2 - delta); if ((delta % 2 == 0) and -D <= k1 and k1 <= D) { if (V1[k1] + V2[k2] >= N) return { { N - p.u, M - p.v, N - p.x , M - p.y, p.add } , 2 * D };// return last snake on reverse path } } } kak_assert(false); return { {}, 0 }; } struct Diff { enum { Keep, Add, Remove } mode; int len; int posB; }; inline void append_diff(Vector<Diff>& diffs, Diff diff) { if (not diffs.empty() and diffs.back().mode == diff.mode and (diff.mode != Diff::Add or diffs.back().posB + diffs.back().len == diff.posB)) diffs.back().len += diff.len; else diffs.push_back(diff); } template<typename Iterator, typename Equal> void find_diff_rec(Iterator a, int offA, int lenA, Iterator b, int offB, int lenB, ArrayView<int> data1, ArrayView<int> data2, Equal eq, Vector<Diff>& diffs) { if (lenA > 0 and lenB > 0) { auto middle_snake = find_middle_snake(a + offA, lenA, b + offB, lenB, data1, data2, eq); kak_assert(middle_snake.u <= lenA and middle_snake.v <= lenB); if (middle_snake.d > 1) { find_diff_rec(a, offA, middle_snake.x, b, offB, middle_snake.y, data1, data2, eq, diffs); if (int len = middle_snake.u - middle_snake.x) append_diff(diffs, {Diff::Keep, len, 0}); find_diff_rec(a, offA + middle_snake.u, lenA - middle_snake.u, b, offB + middle_snake.v, lenB - middle_snake.v, data1, data2, eq, diffs); } else { if (middle_snake.d == 1) { const int diag = middle_snake.x - (middle_snake.add ? 0 : 1); if (diag != 0) append_diff(diffs, {Diff::Keep, diag, 0}); if (middle_snake.add) append_diff(diffs, {Diff::Add, 1, offB + diag}); else append_diff(diffs, {Diff::Remove, 1, 0}); } if (int len = middle_snake.u - middle_snake.x) append_diff(diffs, {Diff::Keep, len, 0}); } } else if (lenB > 0) append_diff(diffs, {Diff::Add, lenB, offB}); else if (lenA > 0) append_diff(diffs, {Diff::Remove, lenA, 0}); } template<typename Iterator, typename Equal = std::equal_to<typename std::iterator_traits<Iterator>::value_type>> Vector<Diff> find_diff(Iterator a, int N, Iterator b, int M, Equal eq = Equal{}) { const int max = 2 * (N + M) + 1; Vector<int> data(2*max); Vector<Diff> diffs; find_diff_rec(a, 0, N, b, 0, M, {data.data(), (size_t)max}, {data.data() + max, (size_t)max}, eq, diffs); return diffs; } } #endif // diff_hh_INCLUDED <commit_msg>Remove MirroredArray for diff implementation<commit_after>#ifndef diff_hh_INCLUDED #define diff_hh_INCLUDED // Implementation of the linear space variant of the algorithm described in // "An O(ND) Difference Algorithm and Its Variations" // (http://xmailserver.org/diff2.pdf) #include "array_view.hh" #include "vector.hh" #include <functional> #include <iterator> namespace Kakoune { struct Snake{ int x, y, u, v; bool add; }; template<typename Iterator, typename Equal> Snake find_end_snake_of_further_reaching_dpath(Iterator a, int N, Iterator b, int M, const int* V, const int D, const int k, Equal eq) { const bool add = k == -D or (k != D and V[k-1] < V[k+1]); // if diagonal on the right goes further along x than diagonal on the left, // then we take a vertical edge from it to this diagonal, hence x = V[k+1] // else, we take an horizontal edge from our left diagonal,x = V[k-1]+1 const int x = add ? V[k+1] : V[k-1]+1; // we are by construction on diagonal k, so our position along b (y) is x - k. const int y = x - k; int u = x, v = y; // follow end snake along diagonal k while (u < N and v < M and eq(a[u], b[v])) ++u, ++v; return { x, y, u, v, add }; } struct SnakeLen : Snake { SnakeLen(Snake s, int d) : Snake(s), d(d) {} int d; }; template<typename Iterator, typename Equal> SnakeLen find_middle_snake(Iterator a, int N, Iterator b, int M, int* V1, int* V2, Equal eq) { const int delta = N - M; V1[1] = 0; V2[1] = 0; std::reverse_iterator<Iterator> ra{a + N}, rb{b + M}; for (int D = 0; D <= (M + N + 1) / 2; ++D) { for (int k1 = -D; k1 <= D; k1 += 2) { auto p = find_end_snake_of_further_reaching_dpath(a, N, b, M, V1, D, k1, eq); V1[k1] = p.u; const int k2 = -(k1 - delta); if ((delta % 2 != 0) and -(D-1) <= k2 and k2 <= (D-1)) { if (V1[k1] + V2[k2] >= N) return { p, 2 * D - 1 };// return last snake on forward path } } for (int k2 = -D; k2 <= D; k2 += 2) { auto p = find_end_snake_of_further_reaching_dpath(ra, N, rb, M, V2, D, k2, eq); V2[k2] = p.u; const int k1 = -(k2 - delta); if ((delta % 2 == 0) and -D <= k1 and k1 <= D) { if (V1[k1] + V2[k2] >= N) return { { N - p.u, M - p.v, N - p.x , M - p.y, p.add } , 2 * D };// return last snake on reverse path } } } kak_assert(false); return { {}, 0 }; } struct Diff { enum { Keep, Add, Remove } mode; int len; int posB; }; inline void append_diff(Vector<Diff>& diffs, Diff diff) { if (not diffs.empty() and diffs.back().mode == diff.mode and (diff.mode != Diff::Add or diffs.back().posB + diffs.back().len == diff.posB)) diffs.back().len += diff.len; else diffs.push_back(diff); } template<typename Iterator, typename Equal> void find_diff_rec(Iterator a, int offA, int lenA, Iterator b, int offB, int lenB, int* V1, int* V2, Equal eq, Vector<Diff>& diffs) { if (lenA > 0 and lenB > 0) { auto middle_snake = find_middle_snake(a + offA, lenA, b + offB, lenB, V1, V2, eq); kak_assert(middle_snake.u <= lenA and middle_snake.v <= lenB); if (middle_snake.d > 1) { find_diff_rec(a, offA, middle_snake.x, b, offB, middle_snake.y, V1, V2, eq, diffs); if (int len = middle_snake.u - middle_snake.x) append_diff(diffs, {Diff::Keep, len, 0}); find_diff_rec(a, offA + middle_snake.u, lenA - middle_snake.u, b, offB + middle_snake.v, lenB - middle_snake.v, V1, V2, eq, diffs); } else { if (middle_snake.d == 1) { const int diag = middle_snake.x - (middle_snake.add ? 0 : 1); if (diag != 0) append_diff(diffs, {Diff::Keep, diag, 0}); if (middle_snake.add) append_diff(diffs, {Diff::Add, 1, offB + diag}); else append_diff(diffs, {Diff::Remove, 1, 0}); } if (int len = middle_snake.u - middle_snake.x) append_diff(diffs, {Diff::Keep, len, 0}); } } else if (lenB > 0) append_diff(diffs, {Diff::Add, lenB, offB}); else if (lenA > 0) append_diff(diffs, {Diff::Remove, lenA, 0}); } template<typename Iterator, typename Equal = std::equal_to<typename std::iterator_traits<Iterator>::value_type>> Vector<Diff> find_diff(Iterator a, int N, Iterator b, int M, Equal eq = Equal{}) { const int max = 2 * (N + M) + 1; Vector<int> data(2*max); Vector<Diff> diffs; find_diff_rec(a, 0, N, b, 0, M, data.data() + (N+M), data.data() + max + (N+M), eq, diffs); return diffs; } } #endif // diff_hh_INCLUDED <|endoftext|>
<commit_before>#include "drsa.h" Persistent<FunctionTemplate> DRSA::constructor; void DRSA::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(DRSA::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Rsa")); NODE_SET_PROTOTYPE_METHOD(constructor, "encrypt", RSAEncrypt); NODE_SET_PROTOTYPE_METHOD(constructor, "decrypt", RSADecrypt); Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); target->Set(String::NewSymbol("Rsa"), constructor->GetFunction()); } Handle<Value> DRSA::New(const Arguments &args) { HandleScope scope; DRSA *d = new DRSA(); d->Wrap(args.This()); return args.This(); } //I expect, pub_key, message, padding type, outencoding //Where pub_key probably should be PEM format or a CERT Handle<Value> DRSA::RSAEncrypt(const Arguments &args) { HandleScope scope; ASSERT_IS_STRING_OR_BUFFER(args[0]); ASSERT_IS_STRING_OR_BUFFER(args[1]); ASSERT_IS_STRING_OR_BUFFER(args[2]); ASSERT_IS_STRING_OR_BUFFER(args[3]); BIO *rsa_bio = BIO_new(BIO_s_mem()); RSA *rsa_pub = RSA_new(); unsigned char pad; enum encoding enc = ParseEncoding(String::New("binary")); ssize_t len = DecodeBytes(args[0], enc); char *pem_pub; size_t pub_len; if (Buffer::HasInstance(args[0])) { Local<Object> pub_obj = args[0]->ToObject(); pem_pub = Buffer::Data(pub_obj); pub_len = Buffer::Length(pub_obj); } else { pem_pub = new char[len]; ssize_t written = DecodeWrite(pem_pub, len, args[0], enc); pub_len = written; } //read in message from args char *msg; size_t msg_len; len = DecodeBytes(args[1], enc); if (Buffer::HasInstance(args[1])) { Local<Object> msg_obj = args[1]->ToObject(); msg = Buffer::Data(msg_obj); msg_len = Buffer::Length(msg_obj); } else { msg = new char[len]; ssize_t written = DecodeWrite(msg, len, args[1], enc); msg_len = written; } //read in the padding type from args String::Utf8Value padding_type(args[2]->ToString()); pad = RSA_PKCS1_PADDING; if (strcasecmp(*padding_type, "RSA_NO_PADDING") == 0) { pad = RSA_NO_PADDING; } else if (strcasecmp(*padding_type, "RSA_PKCS1_OAEP_PADDING") == 0) { pad = RSA_PKCS1_OAEP_PADDING; } else if (strcasecmp(*padding_type, "RSA_SSLV23_PADDING") == 0) { pad = RSA_SSLV23_PADDING; } if (pub_len < 0) { return ThrowException(Exception::TypeError(String::New("Bad length of key"))); } if (msg_len < 0) { return ThrowException(Exception::TypeError(String::New("Bad length of msg"))); } if(!BIO_write(rsa_bio, pem_pub, pub_len)) return ThrowException(Exception::TypeError(String::New("Bad write of key"))); rsa_pub = PEM_read_bio_RSAPublicKey(rsa_bio, NULL, NULL, 0); if (!rsa_pub) { //might not have been a key, could be an x509 cert X509 *x509 = NULL; X509_free(x509); BIO *x_bio = BIO_new(BIO_s_mem()); if (!BIO_write(x_bio, pem_pub, pub_len)) return ThrowException(Exception::TypeError(String::New("Bad write of cert"))); x509 = PEM_read_bio_X509(x_bio, NULL, 0, NULL); EVP_PKEY *pkey = EVP_PKEY_new(); pkey = X509_get_pubkey(x509); rsa_pub = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); BIO_free(x_bio); X509_free(x509); if (!rsa_pub) { return ThrowException(Exception::TypeError(String::New("Couldn't read key as a PEM key or a Certificate"))); } } //Encrypt our message int keysize = RSA_size(rsa_pub); unsigned char *encrypted = new unsigned char[keysize]; int written = RSA_public_encrypt(msg_len, (unsigned char*) msg, encrypted, rsa_pub, pad); delete [] msg; delete [] pem_pub; Local<Value> outString; String::Utf8Value encoding(args[3]->ToString()); //Encode the output in the form given in argument 4 if (written == 0) { outString = String::New(""); } else if (strcasecmp(*encoding, "hex") == 0) { char *out_hex; int out_hex_len; HexEncode(encrypted, written, &out_hex, &out_hex_len); outString = Encode(out_hex, out_hex_len, BINARY); delete [] out_hex; } else if (strcasecmp(*encoding, "base64") == 0) { char *out; int out_len; base64(encrypted, written, &out, &out_len); outString = Encode(out, out_len, BINARY); delete [] out; } else { outString = Encode(encrypted, written, BINARY); } delete [] encrypted; RSA_free(rsa_pub); BIO_free(rsa_bio); return scope.Close(outString); } //Inputs: priv key, ciphertext, padding, input_encoding Handle<Value> DRSA::RSADecrypt(const Arguments &args) { HandleScope scope; ASSERT_IS_STRING_OR_BUFFER(args[0]); ASSERT_IS_STRING_OR_BUFFER(args[1]); BIO *rsa_bio = BIO_new(BIO_s_mem()); RSA *rsa_priv = RSA_new(); ssize_t len = DecodeBytes(args[0], BINARY); if (len < 0) { return ThrowException(Exception::Error(String::New( "node`DecodeBytes() failed"))); } char *priv_buf; int priv_len; if (Buffer::HasInstance(args[0])) { } else { priv_buf = new char[len]; priv_len = DecodeWrite(priv_buf, len, args[0], BINARY); assert(priv_len == len); } //NEEDS TO BE DECODED from base64/hex to binary char *ct_buf; int ct_len; len = DecodeBytes(args[1], BINARY); String::Utf8Value encoding(args[3]->ToString()); if (Buffer::HasInstance(args[1])) { } else { ct_buf = new char[len]; ct_len = DecodeWrite(ct_buf, len, args[1], BINARY); assert(ct_len == len); } char *ciphertext; int ciphertext_len; if (strcasecmp(*encoding, "hex") == 0) { HexDecode((unsigned char*) ct_buf, ct_len, (char **)&ciphertext, &ciphertext_len); ct_buf = ciphertext; ct_len = ciphertext_len; } else if (strcasecmp(*encoding, "base64") == 0) { unbase64((unsigned char*) ct_buf, ct_len, (char **)&ciphertext, &ciphertext_len); ct_buf = ciphertext; ct_len = ciphertext_len; } else { //binary } //use the padding we might have been given unsigned char pad; String::Utf8Value padding_type(args[2]->ToString()); pad = RSA_PKCS1_PADDING; if (strcasecmp(*padding_type, "RSA_NO_PADDING") == 0) { pad = RSA_NO_PADDING; } else if (strcasecmp(*padding_type, "RSA_PKCS1_OAEP_PADDING") == 0) { pad = RSA_PKCS1_OAEP_PADDING; } else if (strcasecmp(*padding_type, "RSA_SSLV23_PADDING") == 0) { pad = RSA_SSLV23_PADDING; } if (!BIO_write(rsa_bio, priv_buf, priv_len)) { return ThrowException(Exception::Error(String::New("Problem reading Private key"))); } rsa_priv = PEM_read_bio_RSAPrivateKey(rsa_bio, NULL, 0, NULL); if (!rsa_priv) { return ThrowException(Exception::Error(String::New("Problem allocating Private key"))); } int keysize = RSA_size(rsa_priv); unsigned char *out_buf = new unsigned char[keysize]; int written = RSA_private_decrypt(ct_len, (unsigned char*)ct_buf, out_buf, rsa_priv, pad); if (written < 0) { return ThrowException(Exception::Error(String::New("Problem Decrypting Message"))); } delete [] priv_buf; delete [] ciphertext; BIO_free(rsa_bio); RSA_free(rsa_priv); Local<Value> outString = Encode(out_buf, written, BINARY); return scope.Close(outString); } DRSA::DRSA() : ObjectWrap() { } DRSA::~DRSA() { } <commit_msg>fix courier file<commit_after>#include "drsa.h" Persistent<FunctionTemplate> DRSA::constructor; void DRSA::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(DRSA::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Rsa")); NODE_SET_PROTOTYPE_METHOD(constructor, "encrypt", RSAEncrypt); NODE_SET_PROTOTYPE_METHOD(constructor, "decrypt", RSADecrypt); Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); target->Set(String::NewSymbol("Rsa"), constructor->GetFunction()); } Handle<Value> DRSA::New(const Arguments &args) { HandleScope scope; DRSA *d = new DRSA(); d->Wrap(args.This()); return args.This(); } //I expect, pub_key, message, padding type, outencoding //Where pub_key probably should be PEM format or a CERT Handle<Value> DRSA::RSAEncrypt(const Arguments &args) { HandleScope scope; ASSERT_IS_STRING_OR_BUFFER(args[0]); ASSERT_IS_STRING_OR_BUFFER(args[1]); ASSERT_IS_STRING_OR_BUFFER(args[2]); ASSERT_IS_STRING_OR_BUFFER(args[3]); BIO *rsa_bio = BIO_new(BIO_s_mem()); RSA *rsa_pub = RSA_new(); unsigned char pad; enum encoding enc = ParseEncoding(String::New("binary")); ssize_t len = DecodeBytes(args[0], enc); char *pem_pub; size_t pub_len; if (Buffer::HasInstance(args[0])) { Local<Object> pub_obj = args[0]->ToObject(); pem_pub = Buffer::Data(pub_obj); pub_len = Buffer::Length(pub_obj); } else { pem_pub = new char[len]; ssize_t written = DecodeWrite(pem_pub, len, args[0], enc); pub_len = written; } //read in message from args char *msg; size_t msg_len; len = DecodeBytes(args[1], enc); if (Buffer::HasInstance(args[1])) { Local<Object> msg_obj = args[1]->ToObject(); msg = Buffer::Data(msg_obj); msg_len = Buffer::Length(msg_obj); } else { msg = new char[len]; ssize_t written = DecodeWrite(msg, len, args[1], enc); msg_len = written; } //read in the padding type from args String::Utf8Value padding_type(args[2]->ToString()); pad = RSA_PKCS1_PADDING; if (strcasecmp(*padding_type, "RSA_NO_PADDING") == 0) { pad = RSA_NO_PADDING; } else if (strcasecmp(*padding_type, "RSA_PKCS1_OAEP_PADDING") == 0) { pad = RSA_PKCS1_OAEP_PADDING; } else if (strcasecmp(*padding_type, "RSA_SSLV23_PADDING") == 0) { pad = RSA_SSLV23_PADDING; } if (pub_len < 0) { return ThrowException(Exception::TypeError(String::New("Bad length of key"))); } if (msg_len < 0) { return ThrowException(Exception::TypeError(String::New("Bad length of msg"))); } if(!BIO_write(rsa_bio, pem_pub, pub_len)) return ThrowException(Exception::TypeError(String::New("Bad write of key"))); rsa_pub = PEM_read_bio_RSAPublicKey(rsa_bio, NULL, NULL, 0); if (!rsa_pub) { //might not have been a key, could be an x509 cert X509 *x509 = NULL; X509_free(x509); BIO *x_bio = BIO_new(BIO_s_mem()); if (!BIO_write(x_bio, pem_pub, pub_len)) return ThrowException(Exception::TypeError(String::New("Bad write of cert"))); x509 = PEM_read_bio_X509(x_bio, NULL, 0, NULL); EVP_PKEY *pkey = EVP_PKEY_new(); pkey = X509_get_pubkey(x509); rsa_pub = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); BIO_free(x_bio); X509_free(x509); if (!rsa_pub) { return ThrowException(Exception::TypeError(String::New("Couldn't read key as a PEM key or a Certificate"))); } } //Encrypt our message int keysize = RSA_size(rsa_pub); unsigned char *encrypted = new unsigned char[keysize]; int written = RSA_public_encrypt(msg_len, (unsigned char*) msg, encrypted, rsa_pub, pad); delete [] msg; delete [] pem_pub; Local<Value> outString; String::Utf8Value encoding(args[3]->ToString()); //Encode the output in the form given in argument 4 if (written == 0) { outString = String::New(""); } else if (strcasecmp(*encoding, "hex") == 0) { char *out_hex; int out_hex_len; HexEncode(encrypted, written, &out_hex, &out_hex_len); outString = Encode(out_hex, out_hex_len, BINARY); delete [] out_hex; } else if (strcasecmp(*encoding, "base64") == 0) { char *out; int out_len; base64(encrypted, written, &out, &out_len); outString = Encode(out, out_len, BINARY); delete [] out; } else { outString = Encode(encrypted, written, BINARY); } delete [] encrypted; RSA_free(rsa_pub); BIO_free(rsa_bio); return scope.Close(outString); } //Inputs: priv key, ciphertext, padding, input_encoding Handle<Value> DRSA::RSADecrypt(const Arguments &args) { HandleScope scope; ASSERT_IS_STRING_OR_BUFFER(args[0]); ASSERT_IS_STRING_OR_BUFFER(args[1]); BIO *rsa_bio = BIO_new(BIO_s_mem()); RSA *rsa_priv = RSA_new(); ssize_t len = DecodeBytes(args[0], BINARY); if (len < 0) { return ThrowException(Exception::Error(String::New( "node`DecodeBytes() failed"))); } char *priv_buf; int priv_len; if (Buffer::HasInstance(args[0])) { } else { priv_buf = new char[len]; priv_len = DecodeWrite(priv_buf, len, args[0], BINARY); assert(priv_len == len); } //NEEDS TO BE DECODED from base64/hex to binary char *ct_buf; int ct_len; len = DecodeBytes(args[1], BINARY); String::Utf8Value encoding(args[3]->ToString()); if (Buffer::HasInstance(args[1])) { } else { ct_buf = new char[len]; ct_len = DecodeWrite(ct_buf, len, args[1], BINARY); assert(ct_len == len); } char *ciphertext; int ciphertext_len; if (strcasecmp(*encoding, "hex") == 0) { HexDecode((unsigned char*) ct_buf, ct_len, (char **)&ciphertext, &ciphertext_len); ct_buf = ciphertext; ct_len = ciphertext_len; } else if (strcasecmp(*encoding, "base64") == 0) { unbase64((unsigned char*) ct_buf, ct_len, (char **)&ciphertext, &ciphertext_len); ct_buf = ciphertext; ct_len = ciphertext_len; } else { //binary } //use the padding we might have been given unsigned char pad; String::Utf8Value padding_type(args[2]->ToString()); pad = RSA_PKCS1_PADDING; if (strcasecmp(*padding_type, "RSA_NO_PADDING") == 0) { pad = RSA_NO_PADDING; } else if (strcasecmp(*padding_type, "RSA_PKCS1_OAEP_PADDING") == 0) { pad = RSA_PKCS1_OAEP_PADDING; } else if (strcasecmp(*padding_type, "RSA_SSLV23_PADDING") == 0) { pad = RSA_SSLV23_PADDING; } if (!BIO_write(rsa_bio, priv_buf, priv_len)) { return ThrowException(Exception::Error(String::New("Problem reading Private key"))); } rsa_priv = PEM_read_bio_RSAPrivateKey(rsa_bio, NULL, 0, NULL); if (!rsa_priv) { return ThrowException(Exception::Error(String::New("Problem allocating Private key"))); } int keysize = RSA_size(rsa_priv); unsigned char *out_buf = new unsigned char[keysize]; int written = RSA_private_decrypt(ct_len, (unsigned char*)ct_buf, out_buf, rsa_priv, pad); if (written < 0) { return ThrowException(Exception::Error(String::New("Problem Decrypting Message"))); } delete [] priv_buf; delete [] ciphertext; BIO_free(rsa_bio); RSA_free(rsa_priv); Local<Value> outString = Encode(out_buf, written, BINARY); return scope.Close(outString); } DRSA::DRSA() : ObjectWrap() { } DRSA::~DRSA() { } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2013 VMware, Inc. * All Rights Reserved. * * 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 <limits.h> // for CHAR_MAX #include <getopt.h> #include "cli.hpp" #include "os_string.hpp" #include "trace_parser.hpp" #include "trace_writer.hpp" static const char *synopsis = "Stream editing of a trace."; static void usage(void) { std::cout << "usage: apitrace sed [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show detailed help for sed options and exit\n" " -e s/SEARCH/REPLACE/ Search and replace a symbol.\n" " XXX: Only works for enums.\n" " -o, --output=TRACE_FILE Output trace file\n" ; } const static char * shortOptions = "ho:e:"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0} }; using namespace trace; /** * A visitor that replaces symbol constants. */ class Replacer : public Visitor { protected: std::string searchName; std::string replaceName; public: Replacer(const std::string & _searchName, const std::string & _replaceName) : searchName(_searchName), replaceName(_replaceName) { } ~Replacer() { } void visit(Null *) { } void visit(Bool *node) { } void visit(SInt *node) { } void visit(UInt *node) { } void visit(Float *node) { } void visit(Double *node) { } void visit(String *node) { } void visit(WString *node) { } void visit(Enum *node) { const EnumValue *it = node->lookup(); if (it) { if (searchName.compare(it->name) == 0) { const EnumSig *sig = node->sig; for (unsigned i = 0; i < sig->num_values; ++i) { if (replaceName.compare(sig->values[i].name) == 0) { node->value = sig->values[i].value; break; } } } } } void visit(Bitmask *bitmask) { } void visit(Struct *s) { for (unsigned i = 0; i < s->members.size(); ++i) { Value *memberValue = s->members[i]; _visit(memberValue); } } void visit(Array *array) { for (std::vector<Value *>::iterator it = array->values.begin(); it != array->values.end(); ++it) { _visit(*it); } } void visit(Blob *blob) { } void visit(Pointer *p) { } void visit(Repr *r) { _visit(r->humanValue); } void visit(Call *call) { for (unsigned i = 0; i < call->args.size(); ++i) { if (call->args[i].value) { _visit(call->args[i].value); } } if (call->ret) { _visit(call->ret); } } }; typedef std::list<Replacer> Replacements; static int sed_trace(Replacements &replacements, const char *inFileName, std::string &outFileName) { trace::Parser p; if (!p.open(inFileName)) { std::cerr << "error: failed to open " << inFileName << "\n"; return 1; } /* Prepare outFileName file and writer for outFileName. */ if (outFileName.empty()) { os::String base(inFileName); base.trimExtension(); outFileName = std::string(base.str()) + std::string("-sed.trace"); } trace::Writer writer; if (!writer.open(outFileName.c_str())) { std::cerr << "error: failed to create " << outFileName << "\n"; return 1; } trace::Call *call; while ((call = p.parse_call())) { for (Replacements::iterator it = replacements.begin(); it != replacements.end(); ++it) { it->visit(call); } writer.writeCall(call); delete call; } std::cerr << "Edited trace is available as " << outFileName << "\n"; return 0; } /** * Parse a string in the format "s/SEARCH/REPLACE/". */ static bool parseSubstOpt(Replacements &replacements, const char *opt) { if (*opt++ != 's') { return false; } if (*opt++ != '/') { return false; } // Parse the search pattern const char *search_begin = opt; while (*opt != '/') { if (*opt == 0) { return false; } ++opt; } const char *search_end = opt++; // Parse the replace pattern const char *replace_begin = opt; while (*opt != '/') { if (*opt == 0) { return false; } ++opt; } const char *replace_end = opt++; if (*opt != 0) { return false; } std::string search(search_begin, search_end); std::string replace(replace_begin, replace_end); replacements.push_back(Replacer(search, replace)); return true; } static int command(int argc, char *argv[]) { Replacements replacements; std::string outFileName; int opt; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case 'o': outFileName = optarg; break; case 'e': if (!parseSubstOpt(replacements, optarg)) { std::cerr << "error: invalid replacement patter `" << optarg << "`\n"; } break; default: std::cerr << "error: unexpected option `" << (char)opt << "`\n"; usage(); return 1; } } if (optind >= argc) { std::cerr << "error: apitrace sed requires a trace file as an argument.\n"; usage(); return 1; } if (argc > optind + 1) { std::cerr << "error: extraneous arguments:"; for (int i = optind + 1; i < argc; i++) { std::cerr << " " << argv[i]; } std::cerr << "\n"; usage(); return 1; } return sed_trace(replacements, argv[optind], outFileName); } const Command sed_command = { "sed", synopsis, usage, command }; <commit_msg>sed: @file reads pattern or replacement from a file. Useful for shader replacement.<commit_after>/************************************************************************** * * Copyright 2013 VMware, Inc. * All Rights Reserved. * * 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 <limits.h> // for CHAR_MAX #include <getopt.h> #include "cli.hpp" #include "os_string.hpp" #include "trace_parser.hpp" #include "trace_writer.hpp" static const char *synopsis = "Stream editing of a trace."; static void usage(void) { std::cout << "usage: apitrace sed [OPTIONS] TRACE_FILE...\n" << synopsis << "\n" "\n" " -h, --help Show detailed help for sed options and exit\n" " -e s/SEARCH/REPLACE/ Search and replace a symbol. Use @file(<path>)\n" " to read SEARCH or REPLACE from a file.\n" " Any character (not just /) can be used as \n" " separator.\n" " XXX: Only works for enums and strings.\n" " -o, --output=TRACE_FILE Output trace file\n" ; } const static char * shortOptions = "ho:e:"; const static struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0} }; using namespace trace; /** * A visitor that replaces symbol constants. */ class Replacer : public Visitor { protected: std::string searchName; std::string replaceName; public: Replacer(const std::string & _searchName, const std::string & _replaceName) : searchName(_searchName), replaceName(_replaceName) { } ~Replacer() { } void visit(Null *) { } void visit(Bool *node) { } void visit(SInt *node) { } void visit(UInt *node) { } void visit(Float *node) { } void visit(Double *node) { } void visit(String *node) { if (!searchName.compare(node->value)) { delete [] node->value; char *str = new char [replaceName.length() + 1]; strcpy(str, replaceName.c_str()); node->value = str; } } void visit(WString *node) { } void visit(Enum *node) { const EnumValue *it = node->lookup(); if (it) { if (searchName.compare(it->name) == 0) { const EnumSig *sig = node->sig; for (unsigned i = 0; i < sig->num_values; ++i) { if (replaceName.compare(sig->values[i].name) == 0) { node->value = sig->values[i].value; break; } } } } } void visit(Bitmask *bitmask) { } void visit(Struct *s) { for (unsigned i = 0; i < s->members.size(); ++i) { Value *memberValue = s->members[i]; _visit(memberValue); } } void visit(Array *array) { for (std::vector<Value *>::iterator it = array->values.begin(); it != array->values.end(); ++it) { _visit(*it); } } void visit(Blob *blob) { } void visit(Pointer *p) { } void visit(Repr *r) { _visit(r->humanValue); } void visit(Call *call) { for (unsigned i = 0; i < call->args.size(); ++i) { if (call->args[i].value) { _visit(call->args[i].value); } } if (call->ret) { _visit(call->ret); } } }; typedef std::list<Replacer> Replacements; static int sed_trace(Replacements &replacements, const char *inFileName, std::string &outFileName) { trace::Parser p; if (!p.open(inFileName)) { std::cerr << "error: failed to open " << inFileName << "\n"; return 1; } /* Prepare outFileName file and writer for outFileName. */ if (outFileName.empty()) { os::String base(inFileName); base.trimExtension(); outFileName = std::string(base.str()) + std::string("-sed.trace"); } trace::Writer writer; if (!writer.open(outFileName.c_str())) { std::cerr << "error: failed to create " << outFileName << "\n"; return 1; } trace::Call *call; while ((call = p.parse_call())) { for (Replacements::iterator it = replacements.begin(); it != replacements.end(); ++it) { it->visit(call); } writer.writeCall(call); delete call; } std::cerr << "Edited trace is available as " << outFileName << "\n"; return 0; } /** * Parse a string in the format "s/SEARCH/REPLACE/". */ static bool parseSubstOpt(Replacements &replacements, const char *opt) { char separator; if (*opt++ != 's') { return false; } separator = *opt++; // Parse the search pattern const char *search_begin = opt; while (*opt != separator) { if (*opt == 0) { return false; } ++opt; } const char *search_end = opt++; // Parse the replace pattern const char *replace_begin = opt; while (*opt != separator) { if (*opt == 0) { return false; } ++opt; } const char *replace_end = opt++; if (*opt != 0) { return false; } std::string search(search_begin, search_end); std::string replace(replace_begin, replace_end); // If search or replace strings are taken from a file, read the file std::string file_subst = "@file("; for (int i = 0; i < 2; i++) { std::string *str = i ? &search : &replace; if (!str->compare(0, file_subst.length(), file_subst)) { if ((*str)[str->length()-1] != ')') { return false; } std::string fname = str->substr(file_subst.length()); fname[fname.length()-1] = 0; FILE *f = fopen(fname.c_str(), "r"); if (!f) { std::cerr << "error: cannot open file " << fname << "\n"; return false; } char buf[1024]; (*str) = ""; while (!feof(f)) { if (fgets(buf, 1024, f)) { str->append(buf); } } fclose(f); } } replacements.push_back(Replacer(search, replace)); return true; } static int command(int argc, char *argv[]) { Replacements replacements; std::string outFileName; int opt; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) { switch (opt) { case 'h': usage(); return 0; case 'o': outFileName = optarg; break; case 'e': if (!parseSubstOpt(replacements, optarg)) { std::cerr << "error: invalid replacement pattern `" << optarg << "`\n"; } break; default: std::cerr << "error: unexpected option `" << (char)opt << "`\n"; usage(); return 1; } } if (optind >= argc) { std::cerr << "error: apitrace sed requires a trace file as an argument.\n"; usage(); return 1; } if (argc > optind + 1) { std::cerr << "error: extraneous arguments:"; for (int i = optind + 1; i < argc; i++) { std::cerr << " " << argv[i]; } std::cerr << "\n"; usage(); return 1; } return sed_trace(replacements, argv[optind], outFileName); } const Command sed_command = { "sed", synopsis, usage, command }; <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "headers.h" #include "irc.h" #include "net.h" #include "strlcpy.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; bool fGotExternalIP = false; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { int ip; short port; }; #pragma pack(pop) string EncodeAddress(const CAddress& addr) { struct ircaddr tmp; tmp.ip = addr.ip; tmp.port = addr.port; vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } bool DecodeAddress(string str, CAddress& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CAddress(tmp.ip, ntohs(tmp.port), NODE_NETWORK); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; loop { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { if (fShutdown) return false; if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { Sleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("IRC socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("IRC recv failed: %d\n", nErr); return false; } } } } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != -1) return 1; if (psz2 && strLine.find(psz2) != -1) return 2; if (psz3 && strLine.find(psz3) != -1) return 3; if (psz4 && strLine.find(psz4) != -1) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); if (fUseProxy) return false; CAddress addr(strHost, 0, true); if (!addr.IsValid()) return false; ipRet = addr.ip; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exiting\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (GetBoolArg("-noirc")) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; bool fNameInUse = false; while (!fShutdown) { CAddress addrConnect("92.243.23.21", 6667); // irc.lfnet.org CAddress addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } string strMyName; if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse) strMyName = EncodeAddress(addrLocalHost); else strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); fNameInUse = true; Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CAddress addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC.ip)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToStringIP().c_str()); if (!fUseProxy && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick fGotExternalIP = true; addrLocalHost.ip = addrFromIRC.ip; strMyName = EncodeAddress(addrLocalHost); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #bitcoinTEST\r"); Send(hSocket, "WHO #bitcoinTEST\r"); } else { // randomly join #bitcoin00-#bitcoin99 int channel_number = GetRandInt(100); Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (AddAddress(addr, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <commit_msg>Fix #626: RecvLine wrong error message<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "headers.h" #include "irc.h" #include "net.h" #include "strlcpy.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; bool fGotExternalIP = false; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { int ip; short port; }; #pragma pack(pop) string EncodeAddress(const CAddress& addr) { struct ircaddr tmp; tmp.ip = addr.ip; tmp.port = addr.port; vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } bool DecodeAddress(string str, CAddress& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CAddress(tmp.ip, ntohs(tmp.port), NODE_NETWORK); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; loop { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { if (fShutdown) return false; if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { Sleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != -1) return 1; if (psz2 && strLine.find(psz2) != -1) return 2; if (psz3 && strLine.find(psz3) != -1) return 3; if (psz4 && strLine.find(psz4) != -1) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); if (fUseProxy) return false; CAddress addr(strHost, 0, true); if (!addr.IsValid()) return false; ipRet = addr.ip; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exiting\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (GetBoolArg("-noirc")) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; bool fNameInUse = false; while (!fShutdown) { CAddress addrConnect("92.243.23.21", 6667); // irc.lfnet.org CAddress addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } string strMyName; if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse) strMyName = EncodeAddress(addrLocalHost); else strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); fNameInUse = true; Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CAddress addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC.ip)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToStringIP().c_str()); if (!fUseProxy && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick fGotExternalIP = true; addrLocalHost.ip = addrFromIRC.ip; strMyName = EncodeAddress(addrLocalHost); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #bitcoinTEST\r"); Send(hSocket, "WHO #bitcoinTEST\r"); } else { // randomly join #bitcoin00-#bitcoin99 int channel_number = GetRandInt(100); Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (AddAddress(addr, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { // Don't connect to IRC if we won't use IPv4 connections. if (IsLimited(NET_IPV4)) return; // ... or if we won't make outbound connections and won't accept inbound ones. if (mapArgs.count("-connect") && fNoListen) return; // ... or if IRC is not enabled. if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; // Don't use our IP as our nick if we're not listening if (!fNoListen && GetLocal(addrLocal, &addrIPv4)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); // Don't use our IP as our nick if we're not listening if (!fNoListen && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #bitcoinTEST3\r"); Send(hSocket, "WHO #bitcoinTEST3\r"); } else { // randomly join #bitcoin00-#bitcoin99 int channel_number = GetRandInt(100); Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <commit_msg>Don't retry a failing IRC nickname forever.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { // Don't connect to IRC if we won't use IPv4 connections. if (IsLimited(NET_IPV4)) return; // ... or if we won't make outbound connections and won't accept inbound ones. if (mapArgs.count("-connect") && fNoListen) return; // ... or if IRC is not enabled. if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; int nNameRetry = 0; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; // Don't use our IP as our nick if we're not listening // or if it keeps failing because the nick is already in use. if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); nNameRetry++; Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } nNameRetry = 0; Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); // Don't use our IP as our nick if we're not listening if (!fNoListen && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #bitcoinTEST3\r"); Send(hSocket, "WHO #bitcoinTEST3\r"); } else { // randomly join #bitcoin00-#bitcoin99 int channel_number = GetRandInt(100); Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIPCRERegexMatcher.cpp created: Mon Jul 27 2009 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/PCRERegexMatcher.h" #include "CEGUI/Exceptions.h" #include "CEGUI/PropertyHelper.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// PCRERegexMatcher::PCRERegexMatcher() : d_regex(0) { } //----------------------------------------------------------------------------// PCRERegexMatcher::~PCRERegexMatcher() { release(); } //----------------------------------------------------------------------------// void PCRERegexMatcher::setRegexString(const String& regex) { // release old regex string. release(); d_string.clear(); // try to compile this new regex string const char* prce_error; int pcre_erroff; d_regex = pcre_compile(regex.c_str(), PCRE_UTF8, &prce_error, &pcre_erroff, 0); // handle failure if (!d_regex) CEGUI_THROW(InvalidRequestException( "Bad RegEx set: '" + regex + "'. Additional Information: " + prce_error)); // set this last so that upon failure object is in consistant state. d_string = regex; } //----------------------------------------------------------------------------// const String& PCRERegexMatcher::getRegexString() const { return d_string; } //----------------------------------------------------------------------------// RegexMatcher::MatchState PCRERegexMatcher::getMatchStateOfString( const String& str) const { // if the regex is not valid, then an exception is thrown if (!d_regex) CEGUI_THROW(InvalidRequestException( "Attempt to use invalid RegEx '" + d_string + "'.")); int match[3]; const char* utf8_str = str.c_str(); const int len = static_cast<int>(strlen(utf8_str)); // PCRE_PARTIAL is a backwards compatible synonym for PCRE_PARTIAL_SOFT // using it is a requirement if we want to support pcre < 8.0 const int result = pcre_exec(d_regex, 0, utf8_str, len, 0, PCRE_PARTIAL | PCRE_ANCHORED, match, 3); if (result == PCRE_ERROR_PARTIAL) return MS_PARTIAL; // a match must be for the entire string if (result >= 0) return (match[1] - match[0] == len) ? MS_VALID : MS_INVALID; // no match found or if test string or regex is 0 if (result == PCRE_ERROR_NOMATCH || result == PCRE_ERROR_NULL) return MS_INVALID; // anything else is an error CEGUI_THROW(InvalidRequestException( "PCRE Error: " + PropertyHelper<int>::toString(result) + " occurred while attempting to match the RegEx '" + d_string + "'.")); } //----------------------------------------------------------------------------// void PCRERegexMatcher::release() { if (d_regex) { pcre_free(d_regex); d_regex = 0; } } } // End of CEGUI namespace section <commit_msg>Use pcre_dfa_exec for older versions of pcre<commit_after>/*********************************************************************** filename: CEGUIPCRERegexMatcher.cpp created: Mon Jul 27 2009 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/PCRERegexMatcher.h" #include "CEGUI/Exceptions.h" #include "CEGUI/PropertyHelper.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// PCRERegexMatcher::PCRERegexMatcher() : d_regex(0) { } //----------------------------------------------------------------------------// PCRERegexMatcher::~PCRERegexMatcher() { release(); } //----------------------------------------------------------------------------// void PCRERegexMatcher::setRegexString(const String& regex) { // release old regex string. release(); d_string.clear(); // try to compile this new regex string const char* prce_error; int pcre_erroff; d_regex = pcre_compile(regex.c_str(), PCRE_UTF8, &prce_error, &pcre_erroff, 0); // handle failure if (!d_regex) CEGUI_THROW(InvalidRequestException( "Bad RegEx set: '" + regex + "'. Additional Information: " + prce_error)); // set this last so that upon failure object is in consistant state. d_string = regex; } //----------------------------------------------------------------------------// const String& PCRERegexMatcher::getRegexString() const { return d_string; } //----------------------------------------------------------------------------// RegexMatcher::MatchState PCRERegexMatcher::getMatchStateOfString( const String& str) const { // if the regex is not valid, then an exception is thrown if (!d_regex) CEGUI_THROW(InvalidRequestException( "Attempt to use invalid RegEx '" + d_string + "'.")); int match[3]; const char* utf8_str = str.c_str(); const int len = static_cast<int>(strlen(utf8_str)); #ifdef PCRE_PARTIAL_SOFT // we are using a new version of pcre const int result = pcre_exec(d_regex, 0, utf8_str, len, 0, PCRE_PARTIAL_SOFT | PCRE_ANCHORED, match, 3); #else // PCRE_PARTIAL is a backwards compatible synonym for PCRE_PARTIAL_SOFT // using it is a requirement if we want to support pcre < 8.0 // Older versions of pcre have problems doing partial matching of // single repeated characters if using pcre_exec, // It is suggested to use pcre_dfa_exec instead. int workspace[100]; // FIXME: persist the workspace between match attempts const int result = pcre_dfa_exec(d_regex, 0, utf8_str, len, 0, PCRE_PARTIAL | PCRE_ANCHORED, match, 3, workspace, 100); #endif if (result == PCRE_ERROR_PARTIAL) return MS_PARTIAL; // a match must be for the entire string if (result >= 0) return (match[1] - match[0] == len) ? MS_VALID : MS_INVALID; // no match found or if test string or regex is 0 if (result == PCRE_ERROR_NOMATCH || result == PCRE_ERROR_NULL) return MS_INVALID; // anything else is an error CEGUI_THROW(InvalidRequestException( "PCRE Error: " + PropertyHelper<int>::toString(result) + " occurred while attempting to match the RegEx '" + d_string + "'.")); } //----------------------------------------------------------------------------// void PCRERegexMatcher::release() { if (d_regex) { pcre_free(d_regex); d_regex = 0; } } } // End of CEGUI namespace section <|endoftext|>
<commit_before>// 7.exercise.11.ch04.04.cpp // // Revisit two programs you wrote for the exercises in Chapter 4 or 5. Clean // up that code according to the rules outlined in this chapter. See if you // find any bugs in the process. // // ORIGINAL STATEMENT // // 4.exercise.04.cpp // // Write a program to play a numbers guessing game. The user thinks of a number // between 1 and 100 and your program ask questions to figure out what the // number is (e.g., "Is the number you are thinking of less than 50?"). Your // program should be able to identify the number after asking no more than // seven questions. Hint: User the < and <= operators and the if-else // construct. // // COMMENTS // // In summary the chapter tell us to: // // 1. Review program presentation to the user. // 2. Do testing trying to break the program and solve bugs found. // 3. Clean up the code: // a) get rid of symbolic constants // b) divide the code into functions that do just one single logical // action // c) review code layout to improve code reading // 4. Evaluate if we can recover from errors // 5. Evaluate and implement improvements to the program // // 1. // Why not give the user the chance to play again without exiting the program? // This prevents us from the kind of automatic testing we do with the script // 7.exercise.11.ch04.04.test.bash. And since it's fairly simple I will not // implement it to retain the automatic testing capability (just for fun). // As stated in the comments (perhaps not in the right place) we only ask if // the number is more or less than our guess. The original game includes // asking if our guess is correct. As it turns out, doing so at a certain // point (where we have only two candidates left) let us enforce the 7 // questions limit. // 2. // If the user lies, or in certain combinations of answers, the program will // miscalculate a new range for guessing. This is because I don't check if new // limits are logical or not. Lower limit could not be greater than upper // limit and since we are shrinking the range, lower limit could not decrease // and upper limit could not increase. As it turns out, these checks will be // useless when guess_one_from_two() is introduced, but they serve well enough // during development implemented as checked_modify_range(). // The script 7.exercise.11.ch04.04.test.bash permits us to test this program // in deep (the input domain is bounded and small enough to test it // completely). // 3.a // Answers are currently magic constants. Also the distinction for asking if // the guess is less or more than the number. // 3.b // We have all the code in the main body. Functions are demanded. // 3.c // The 'flip-flop' if-then is basically duplicated code we can make more // concise. // 4. // We read chars for answers. Each line introduced by the user could be longer // and must be cleared after a correct or incorrect answer. We could use // cin.ignore() to clear input, but it interferes with the testing script. So // I will not implement it for the same reasons exposed on point 1. // There is any possible error from we want to recover? When // checked_modify_range() was in use, a try-catch in main have been needed. // Not to recover but to be capable to use error(). // 5. // The introduction of guess_one_from_two() lend us to effectively limit the // guesses to 7, and to add the type equal to the questions we do to the user. // It feels more natural this way since guess() is able to guess the number // but it repeats questions and tends to divagate when the range consists on // two consecutive numbers. // Apart from this I don't know what to improve since the game is really // simple a well defined. Perhaps let the user say the upper limit, but then // the limit of 7 guesses will not be enforceable. #include "std_lib_facilities.h" const char yes {'y'}; const char no {'n'}; const char is_more {'M'}; const char is_less {'L'}; int first {1}; int last {100}; int candidate {0}; int question {0}; void checked_modify_range(int f, int l) // This function seems unuseful now, but it really helps while programming. { // First could not be greater than Last // First could decrease and Last coul not increase if ((f > l) || (f < first) || (l > last)) { error("You LIED!"); } first = f; last = l; } void guess() { candidate = (first+last)/2; // We do a flip-flop asking less or more to eliminate numbers at the // lower or higher limit. char guess_type; if (question%2 == 0) guess_type = is_less; else guess_type = is_more; cout << "Is your number "; if (guess_type == is_less) cout << "less"; else cout << "more"; cout << " than " << candidate << "? (y/n)\n"; char answer {' '}; cin >> answer; if (answer == yes) { ++question; // if the answer is yes, we could ignore the candidate if (guess_type == is_less) checked_modify_range(first, candidate - 1); if (guess_type == is_more) checked_modify_range(candidate + 1, last); } else if (answer == no) { ++question; // if the answer is not, the candidate must be preserved as guessable if (guess_type == is_less) checked_modify_range(candidate, last); if (guess_type == is_more) checked_modify_range(first, candidate); } else { cout << "Sorry, I don't understand your answer. Again ...\n"; } cout << first << ", " << last << '\n'; } void guess_one_from_two() // Covers the case when the first and last are two consecutive numbers. The // generalized formula from guess() kinda works but is inefficient. This one // permits us to enforce the 7 guesses limit. { cout << "Is the number you're thinking of the " << first << "? (y/n)\n"; char answer {' '}; cin >> answer; ++question; if (answer == yes) last = first; else if (answer == no) first = last; else { cout << "Sorry, I don't understand your answer. Again ...\n"; --question; } } int main() try { cout << "Please, think of a number between " << first << " and " << last << ". I'll going to guess ...\n"; while (first != last) { if (last-first == 1) guess_one_from_two(); else guess(); } cout << "The number you were thinking of is ... " << first << '\n'; cout << "I only needed " << question << " questions to guess.\n"; return 0; } catch (exception& e) { cerr << e.what() << '\n'; return 1; } catch (...) { cerr << "Unknown exception!\n"; return 2; } <commit_msg>Remove a debug cout << on 7.exercise.11.ch04.04.cpp.<commit_after>// 7.exercise.11.ch04.04.cpp // // Revisit two programs you wrote for the exercises in Chapter 4 or 5. Clean // up that code according to the rules outlined in this chapter. See if you // find any bugs in the process. // // ORIGINAL STATEMENT // // 4.exercise.04.cpp // // Write a program to play a numbers guessing game. The user thinks of a number // between 1 and 100 and your program ask questions to figure out what the // number is (e.g., "Is the number you are thinking of less than 50?"). Your // program should be able to identify the number after asking no more than // seven questions. Hint: User the < and <= operators and the if-else // construct. // // COMMENTS // // In summary the chapter tell us to: // // 1. Review program presentation to the user. // 2. Do testing trying to break the program and solve bugs found. // 3. Clean up the code: // a) get rid of symbolic constants // b) divide the code into functions that do just one single logical // action // c) review code layout to improve code reading // 4. Evaluate if we can recover from errors // 5. Evaluate and implement improvements to the program // // 1. // Why not give the user the chance to play again without exiting the program? // This prevents us from the kind of automatic testing we do with the script // 7.exercise.11.ch04.04.test.bash. And since it's fairly simple I will not // implement it to retain the automatic testing capability (just for fun). // As stated in the comments (perhaps not in the right place) we only ask if // the number is more or less than our guess. The original game includes // asking if our guess is correct. As it turns out, doing so at a certain // point (where we have only two candidates left) let us enforce the 7 // questions limit. // 2. // If the user lies, or in certain combinations of answers, the program will // miscalculate a new range for guessing. This is because I don't check if new // limits are logical or not. Lower limit could not be greater than upper // limit and since we are shrinking the range, lower limit could not decrease // and upper limit could not increase. As it turns out, these checks will be // useless when guess_one_from_two() is introduced, but they serve well enough // during development implemented as checked_modify_range(). // The script 7.exercise.11.ch04.04.test.bash permits us to test this program // in deep (the input domain is bounded and small enough to test it // completely). // 3.a // Answers are currently magic constants. Also the distinction for asking if // the guess is less or more than the number. // 3.b // We have all the code in the main body. Functions are demanded. // 3.c // The 'flip-flop' if-then is basically duplicated code we can make more // concise. // 4. // We read chars for answers. Each line introduced by the user could be longer // and must be cleared after a correct or incorrect answer. We could use // cin.ignore() to clear input, but it interferes with the testing script. So // I will not implement it for the same reasons exposed on point 1. // There is any possible error from we want to recover? When // checked_modify_range() was in use, a try-catch in main have been needed. // Not to recover but to be capable to use error(). // 5. // The introduction of guess_one_from_two() lend us to effectively limit the // guesses to 7, and to add the type equal to the questions we do to the user. // It feels more natural this way since guess() is able to guess the number // but it repeats questions and tends to divagate when the range consists on // two consecutive numbers. // Apart from this I don't know what to improve since the game is really // simple a well defined. Perhaps let the user say the upper limit, but then // the limit of 7 guesses will not be enforceable. #include "std_lib_facilities.h" const char yes {'y'}; const char no {'n'}; const char is_more {'M'}; const char is_less {'L'}; int first {1}; int last {100}; int candidate {0}; int question {0}; void checked_modify_range(int f, int l) // This function seems unuseful now, but it really helps while programming. { // First could not be greater than Last // First could decrease and Last coul not increase if ((f > l) || (f < first) || (l > last)) { error("You LIED!"); } first = f; last = l; } void guess() { candidate = (first+last)/2; // We do a flip-flop asking less or more to eliminate numbers at the // lower or higher limit. char guess_type; if (question%2 == 0) guess_type = is_less; else guess_type = is_more; cout << "Is your number "; if (guess_type == is_less) cout << "less"; else cout << "more"; cout << " than " << candidate << "? (y/n)\n"; char answer {' '}; cin >> answer; if (answer == yes) { ++question; // if the answer is yes, we could ignore the candidate if (guess_type == is_less) checked_modify_range(first, candidate - 1); if (guess_type == is_more) checked_modify_range(candidate + 1, last); } else if (answer == no) { ++question; // if the answer is not, the candidate must be preserved as guessable if (guess_type == is_less) checked_modify_range(candidate, last); if (guess_type == is_more) checked_modify_range(first, candidate); } else { cout << "Sorry, I don't understand your answer. Again ...\n"; } } void guess_one_from_two() // Covers the case when the first and last are two consecutive numbers. The // generalized formula from guess() kinda works but is inefficient. This one // permits us to enforce the 7 guesses limit. { cout << "Is the number you're thinking of the " << first << "? (y/n)\n"; char answer {' '}; cin >> answer; ++question; if (answer == yes) last = first; else if (answer == no) first = last; else { cout << "Sorry, I don't understand your answer. Again ...\n"; --question; } } int main() try { cout << "Please, think of a number between " << first << " and " << last << ". I'll going to guess ...\n"; while (first != last) { if (last-first == 1) guess_one_from_two(); else guess(); } cout << "The number you were thinking of is ... " << first << '\n'; cout << "I only needed " << question << " questions to guess.\n"; return 0; } catch (exception& e) { cerr << e.what() << '\n'; return 1; } catch (...) { cerr << "Unknown exception!\n"; return 2; } <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <map> #include <string.h> #include <vector> #include <time.h> #include <grp.h> #include <pwd.h> #include <iomanip> #define MAXROWLEN 80 // the maximum length of a row unsigned int g_leave_len = MAXROWLEN; // the length left, for aligning unsigned int g_maxlen; // store the maximum len of filename bool flagA = false; bool flagL = false; bool flagR = false; using namespace std; // print out one filename // make the filenames align in column void printSingle(char *dirname) { int len; // if the current line cannot hold the filename, then go to the next line if (g_leave_len < g_maxlen) { cout << endl; g_leave_len = MAXROWLEN; } len = strlen(dirname); len = g_maxlen - len; cout << dirname; // output the extra spaces for (int i = 0; i < len; ++i) { cout << " "; } cout << " "; // leave two spaces g_leave_len -= g_maxlen + 2; } void printLong(struct stat s, char *dirname) { //struct stat s; char time[32]; // store time if (stat(dirname, &s) == 0) { if (S_ISDIR(s.st_mode)) cout << "d"; else cout << "-"; if (s.st_mode & S_IRUSR) cout << "r"; else cout << "-"; if (s.st_mode & S_IWUSR) cout << "w"; else cout << "-"; if (s.st_mode & S_IXUSR) cout << "x"; else cout << "-"; if (s.st_mode & S_IRGRP) cout << "r"; else cout << "-"; if (s.st_mode & S_IWGRP) cout << "w"; else cout << "-"; if (s.st_mode & S_IXGRP) cout << "x"; else cout << "-"; if (s.st_mode & S_IROTH) cout << "r"; else cout << "-"; if (s.st_mode & S_IWOTH) cout << "w"; else cout << "-"; if (s.st_mode & S_IXOTH) cout << "x"; else cout << "-"; cout << " " << setw(2) << s.st_nlink << " " << getpwuid(s.st_uid)->pw_name << " " << getgrgid(s.st_gid)->gr_name << " " << setw(5) << s.st_size << " "; strftime(time, sizeof(time), "%b %d %H:%M", localtime(&s.st_mtime)); cout << time << " "; } else { perror("There was an error with stat. "); exit(1); } } void printRecur(char *dirname) { DIR *dirp; struct dirent *entry; char *temp; if (NULL == (dirp = opendir(dirname))) { perror("There was an error with opendir(). "); exit(1); } //const char *d_name; errno = 0; while (NULL != (entry = readdir(dirp))) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; if (entry->d_type & DT_DIR) { cout << entry->d_name << "####:" << endl; strcpy(temp, dirname); strcat(temp, "/"); strcat(temp, entry->d_name); printRecur(temp); } else cout << entry->d_name << endl; } if (-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } } void printF(char *dirname) { struct stat buf; char name[NAME_MAX+1]; // get filename from dirname int j = 0; for (int i = 0; i < strlen(dirname); ++i) { if (dirname[i] == '/') { j = 0; continue; } name[j] = dirname[i]; ++j; } name[j] = '\0'; if (flagA) { if (flagL) { if (flagR) { //printLong(buf, name); printRecur(dirname); } else if (!flagR) { //cout << name << " " << dirname << endl; printLong(buf, dirname); cout << name << endl; } } else if (!flagL) { if (flagR) { printRecur(dirname); } else if (!flagR) { printSingle(name); } } } else if (!flagA) { if (name[0] != '.') { if (flagL) { if (flagR) { printRecur(dirname); } else if (!flagR) { printLong(buf, dirname); cout << name << endl; } } else if (!flagL) { if (flagR) { printRecur(dirname); } // no param else if (!flagR) { printSingle(name); } } } } } // preprocess the filenames void file_sort(struct stat s, char *dirname, char name[][NAME_MAX+1]) { DIR *dirp; // the directory int count = 0; // record the file num // at most 256 files char filenames[256][PATH_MAX+1]; char nodot[256][PATH_MAX+1]; char temp[PATH_MAX+1]; int total = 0; // get the longest filename if(NULL == (dirp = opendir(dirname))) { perror("There was an error with opendir(). "); exit(1); } struct dirent *filespecs; // each entry errno = 0; while(NULL != (filespecs = readdir(dirp))) { // set g_maxlen as the longest filename if (g_maxlen < strlen(filespecs->d_name)) g_maxlen = strlen(filespecs->d_name); ++count; } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } if (count > 256) { perror("Too many files in this dir"); exit(1); } int len = strlen(dirname); // get all the filename in the dir //dirp = opendir(dirname); if(NULL == (dirp = opendir(dirname))) { perror("There was an error with opendir(). "); exit(1); } for (int i = 0; i < count; ++i) { filespecs = readdir(dirp); strncpy(filenames[i], dirname, len); // add null to the end of filenames[i] filenames[i][len] = '\0'; strcat(filenames[i], filespecs->d_name); filenames[i][len + strlen(filespecs->d_name)] = '\0'; } // sort the filenames, use bubble-sort for (int i = 0; i < count - 1; ++i) { for (int j = 0; j < count - 1 - i; ++j) { if (strcmp(filenames[j], filenames[j+1]) > 0) { // assign temp with a[j+1] strcpy(temp, filenames[j+1]); temp[strlen(filenames[j+1])] = '\0'; // assign a[j] with a[j+1] strcpy(filenames[j+1], filenames[j]); filenames[j+1][strlen(filenames[j])] = '\0'; // assign a[j] with temp strcpy(filenames[j], temp); filenames[j][strlen(temp)] = '\0'; } } } //char name[256][NAME_MAX+1]; int start = 0; for (int i = 0; i < count; ++i) { for (int j = 0; j < strlen(filenames[i]); ++j) { if (filenames[i][j] == '/') { start = 0; continue; } name[i][start] = filenames[i][j]; ++start; } name[i][start] = '\0'; } // print total for -l int i = 0; if (flagL) { if (flagA) { total = 0; for (i = 0; i < count; ++i) { if (-1 == stat(filenames[i], &s)) { perror("There was an error with stat. "); exit(1); } total += s.st_blocks; } cout << "total " << total/2 << endl; for (i = 0; i < count; ++i) { printF(filenames[i]); } } else { total = 0; char nodot[256][NAME_MAX+1]; int j = 0; int count2 = 0; for (i = 0; i < count; ++i) { if (-1 == stat(filenames[i], &s)) { perror("There was an error with stat1. "); exit(0); } if (name[i][0] != '.') { strcpy(nodot[j], filenames[i]); ++j; ++ count2; //total += s.st_blocks; } } for (i = 0; i < count2; ++i) { if (-1 == stat(nodot[i], &s)) { perror("There was an error with stat2. "); exit(1); } total += s.st_blocks; } cout << "total " << total/2 << endl; for (i = 0; i < count2; ++i) { printF(nodot[i]); } } } else { for (i = 0; i < count - 1; ++i) { printF(filenames[i]); } printF(filenames[i]); cout << endl; } closedir(dirp); } int main(int argc, char** argv) { char path[PATH_MAX+1]; int num = 0; // record the num of "-" struct stat buf; char name[256][NAME_MAX+1]; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { ++ num; for (unsigned int j = 1; j < strlen(argv[i]); ++j) { if (argv[i][j] == 'a') { flagA = true; } if (argv[i][j] == 'l') { flagL = true; } if (argv[i][j] == 'R') { flagR = true; } else if (argv[i][j] != 'a' && argv[i][j] != 'l' && argv[i][j] != 'R') { cout << "invalid parameter: " << argv[i][j] << endl; exit(1); } } } } // if there is no filename, then print out the info of curr dir if ((num + 1) == argc) { strcpy(path, "./"); // current folder path[2] = '\0'; file_sort(buf, path, name); return 0; } // if contains filename else { int k = 1; while (k < argc) { if (argv[k][0] == '-') { ++k; continue; } else { strcpy(path, argv[k]); // tell whether it's a filename if (stat(path, &buf) == -1) { perror("There was an error with stat. "); exit(1); } // if the getting path is a dir if (S_ISDIR(buf.st_mode)) { // process the input filenames if (path[strlen(argv[k]) - 1] != '/') { path[strlen(argv[k])] = '/'; path[strlen(argv[k]) + 1] = '\0'; } else { path[strlen(argv[k])] = '\0'; } file_sort(buf, path, name); ++k; } // if the getting path is not a dir else { file_sort(buf, path, name); ++k; } } } } return 0; } <commit_msg>Reimplement -R<commit_after>#include <iostream> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <map> #include <string.h> #include <vector> #include <time.h> #include <grp.h> #include <pwd.h> #include <iomanip> #define MAXROWLEN 80 // the maximum length of a row unsigned int g_leave_len = MAXROWLEN; // the length left, for aligning unsigned int g_maxlen; // store the maximum len of filename bool flagA = false; bool flagL = false; bool flagR = false; using namespace std; // print out one filename // make the filenames align in column void printSingle(char *dirname) { int len; // if the current line cannot hold the filename, then go to the next line if (g_leave_len < g_maxlen) { cout << endl; g_leave_len = MAXROWLEN; } len = strlen(dirname); len = g_maxlen - len; cout << dirname; // output the extra spaces for (int i = 0; i < len; ++i) { cout << " "; } cout << " "; // leave two spaces g_leave_len -= g_maxlen + 2; } void printLong(struct stat s, char *dirname) { //struct stat s; char time[32]; // store time if (stat(dirname, &s) == 0) { if (S_ISDIR(s.st_mode)) cout << "d"; else cout << "-"; if (s.st_mode & S_IRUSR) cout << "r"; else cout << "-"; if (s.st_mode & S_IWUSR) cout << "w"; else cout << "-"; if (s.st_mode & S_IXUSR) cout << "x"; else cout << "-"; if (s.st_mode & S_IRGRP) cout << "r"; else cout << "-"; if (s.st_mode & S_IWGRP) cout << "w"; else cout << "-"; if (s.st_mode & S_IXGRP) cout << "x"; else cout << "-"; if (s.st_mode & S_IROTH) cout << "r"; else cout << "-"; if (s.st_mode & S_IWOTH) cout << "w"; else cout << "-"; if (s.st_mode & S_IXOTH) cout << "x"; else cout << "-"; cout << " " << setw(2) << s.st_nlink << " " << getpwuid(s.st_uid)->pw_name << " " << getgrgid(s.st_gid)->gr_name << " " << setw(5) << s.st_size << " "; strftime(time, sizeof(time), "%b %d %H:%M", localtime(&s.st_mtime)); cout << time << " "; } else { perror("There was an error with stat. "); exit(1); } } void printRecur(char *dirname) { DIR *dirp; struct dirent *entry; char *temp; if (NULL == (dirp = opendir(dirname))) { perror("There was an error with opendir(). "); exit(1); } //const char *d_name; errno = 0; while (NULL != (entry = readdir(dirp))) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; if (entry->d_type & DT_DIR) { cout << entry->d_name << "####:" << endl; strcpy(temp, dirname); strcat(temp, "/"); strcat(temp, entry->d_name); printRecur(temp); } else cout << entry->d_name << endl; } if (-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } } void printF(char *dirname) { struct stat buf; char name[NAME_MAX+1]; // get filename from dirname int j = 0; for (int i = 0; i < strlen(dirname); ++i) { if (dirname[i] == '/') { j = 0; continue; } name[j] = dirname[i]; ++j; } name[j] = '\0'; } // preprocess the filenames void process(struct stat s, char *dirname, char name[][NAME_MAX+1]) { DIR *dirp; // the directory int count = 0; // record the file num // at most 256 files char filenames[256][PATH_MAX+1]; char nodot[256][PATH_MAX+1]; char temp[PATH_MAX+1]; int total = 0; // get the longest filename if(NULL == (dirp = opendir(dirname))) { perror("There was an error with opendir(). "); exit(1); } struct dirent *filespecs; // each entry errno = 0; while(NULL != (filespecs = readdir(dirp))) { // set g_maxlen as the longest filename if (g_maxlen < strlen(filespecs->d_name)) g_maxlen = strlen(filespecs->d_name); ++count; } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } if (count > 256) { perror("Too many files in this dir"); exit(1); } int len = strlen(dirname); // get all the filename in the dir //dirp = opendir(dirname); if(NULL == (dirp = opendir(dirname))) { perror("There was an error with opendir(). "); exit(1); } for (int i = 0; i < count; ++i) { filespecs = readdir(dirp); strncpy(filenames[i], dirname, len); // add null to the end of filenames[i] filenames[i][len] = '\0'; strcat(filenames[i], filespecs->d_name); filenames[i][len + strlen(filespecs->d_name)] = '\0'; } // sort the filenames, use bubble-sort for (int i = 0; i < count - 1; ++i) { for (int j = 0; j < count - 1 - i; ++j) { if (strcmp(filenames[j], filenames[j+1]) > 0) { // assign temp with a[j+1] strcpy(temp, filenames[j+1]); temp[strlen(filenames[j+1])] = '\0'; // assign a[j] with a[j+1] strcpy(filenames[j+1], filenames[j]); filenames[j+1][strlen(filenames[j])] = '\0'; // assign a[j] with temp strcpy(filenames[j], temp); filenames[j][strlen(temp)] = '\0'; } } } //char name[256][NAME_MAX+1]; int start = 0; for (int i = 0; i < count; ++i) { for (int j = 0; j < strlen(filenames[i]); ++j) { if (filenames[i][j] == '/') { start = 0; continue; } name[i][start] = filenames[i][j]; ++start; } name[i][start] = '\0'; } // print total for -l int i = 0; if (flagL) { if (flagA) { total = 0; for (i = 0; i < count; ++i) { if (-1 == stat(filenames[i], &s)) { perror("There was an error with stat. "); exit(1); } total += s.st_blocks; } cout << "total " << total/2 << endl; for (i = 0; i < count; ++i) { //printF(filenames[i]); } } else { total = 0; char nodot[256][NAME_MAX+1]; int j = 0; int count2 = 0; for (i = 0; i < count; ++i) { if (-1 == stat(filenames[i], &s)) { perror("There was an error with stat1. "); exit(0); } if (name[i][0] != '.') { strcpy(nodot[j], filenames[i]); ++j; ++ count2; //total += s.st_blocks; } } for (i = 0; i < count2; ++i) { if (-1 == stat(nodot[i], &s)) { perror("There was an error with stat2. "); exit(1); } total += s.st_blocks; } cout << "total " << total/2 << endl; for (i = 0; i < count2; ++i) { printF(nodot[i]); } } } else { for (i = 0; i < count - 1; ++i) { printF(filenames[i]); } printF(filenames[i]); cout << endl; } closedir(dirp); } int main(int argc, char** argv) { char path[PATH_MAX+1]; int num = 0; // record the num of "-" struct stat buf; char name[256][NAME_MAX+1]; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { ++ num; for (unsigned int j = 1; j < strlen(argv[i]); ++j) { if (argv[i][j] == 'a') { flagA = true; } if (argv[i][j] == 'l') { flagL = true; } if (argv[i][j] == 'R') { flagR = true; } else if (argv[i][j] != 'a' && argv[i][j] != 'l' && argv[i][j] != 'R') { cout << "invalid parameter: " << argv[i][j] << endl; exit(1); } } } } // if there is no filename, then print out the info of curr dir if ((num + 1) == argc) { strcpy(path, "./"); // current folder path[2] = '\0'; process(buf, path, name); return 0; } // if contains filename else { int k = 1; while (k < argc) { if (argv[k][0] == '-') { ++k; continue; } else { strcpy(path, argv[k]); // tell whether it's a filename if (stat(path, &buf) == -1) { perror("There was an error with stat. "); exit(1); } // if the getting path is a dir if (S_ISDIR(buf.st_mode)) { // process the input filenames if (path[strlen(argv[k]) - 1] != '/') { path[strlen(argv[k])] = '/'; path[strlen(argv[k]) + 1] = '\0'; } else { path[strlen(argv[k])] = '\0'; } process(buf, path, name); ++k; } // if the getting path is not a dir else { process(buf, path, name); ++k; } } } } return 0; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2019 Inviwo 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. * * 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. * *********************************************************************************/ #include <modules/vectorfieldvisualization/processors/datageneration/seedpointgenerator.h> #include <glm/gtx/vector_angle.hpp> #include <math.h> #define RND 1 #define PLANE 2 #define LINE 3 #define SPHERE 4 namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo SeedPointGenerator::processorInfo_{ "org.inviwo.SeedPointGenerator3D", // Class identifier "Seed Point Generator 3D", // Display name "Data Creation", // Category CodeState::Stable, // Code state "CPU, Seed Points, Generator", // Tags }; const ProcessorInfo SeedPointGenerator::getProcessorInfo() const { return processorInfo_; } SeedPointGenerator::SeedPointGenerator() : Processor() , seedPoints_("seedPoints") , lineGroup_("line", "Line") , planeGroup_("plane", "Plane") , sphereGroup_("sphere", "Sphere") , numberOfPoints_("numberOfPoints", "Number of Points", 10, 1, 1000) , planeResolution_("planeResolution", "Resolution", vec2(4, 4), vec2(2, 2), vec2(100, 100)) , planeOrigin_("planeOrigin_", "Origin", vec3(0.0f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , planeE1_("planeP1_", "Offset 1", vec3(1.0f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , planeE2_("planeP2_", "Offset 2", vec3(0.0f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , sphereCenter_("sphereCenter", "Center", vec3(0.5f, 0.5f, 0.5f), vec3(0, 0, 0), vec3(1, 1, 1)) , sphereRadius_("sphereRadius", "Radius") , lineStart_("lineStart", "Start", vec3(0.5f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , lineEnd_("lineEnd_", "End", vec3(0.5f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , generator_("generator", "Generator") , randomness_("randomness", "Randomness") , useSameSeed_("useSameSeed", "Use same seed", true) , seed_("seed", "Seed", 1, 0, 1000) , rd_() , mt_(rd_()) { addPort(seedPoints_); generator_.addOption("random", "Random", RND); generator_.addOption("line", "Line", LINE); generator_.addOption("plane", "Plane", PLANE); generator_.addOption("sphere", "Sphere", SPHERE); generator_.setCurrentStateAsDefault(); generator_.onChange([this]() { onGeneratorChange(); }); addProperty(generator_); lineGroup_.addProperty(lineStart_); lineGroup_.addProperty(lineEnd_); addProperty(lineGroup_); planeGroup_.addProperty(planeResolution_); planeGroup_.addProperty(planeOrigin_); planeGroup_.addProperty(planeE1_); planeGroup_.addProperty(planeE2_); addProperty(planeGroup_); sphereGroup_.addProperty(sphereCenter_); sphereGroup_.addProperty(sphereRadius_); sphereRadius_.set(vec2(0.45, 0.55)); sphereRadius_.setCurrentStateAsDefault(); addProperty(sphereGroup_); addProperty(numberOfPoints_); addProperty(randomness_); randomness_.addProperty(useSameSeed_); randomness_.addProperty(seed_); useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); }); onGeneratorChange(); } void SeedPointGenerator::process() { if (useSameSeed_.get()) { mt_.seed(seed_.get()); } switch (generator_.get()) { case RND: randomPoints(); break; case PLANE: planePoints(); break; case LINE: linePoints(); break; case SPHERE: spherePoints(); break; default: LogWarn("No points generated since given type is not yet implemented"); break; } } void SeedPointGenerator::onGeneratorChange() { bool rnd = generator_.get() == RND; bool plane = generator_.get() == PLANE; bool line = generator_.get() == LINE; bool sphere = generator_.get() == SPHERE; numberOfPoints_.setVisible(rnd || line || sphere); planeResolution_.setVisible(plane); planeOrigin_.setVisible(plane); planeE1_.setVisible(plane); planeE2_.setVisible(plane); sphereCenter_.setVisible(sphere); sphereRadius_.setVisible(sphere); lineStart_.setVisible(line); lineEnd_.setVisible(line); } void SeedPointGenerator::spherePoints() { std::uniform_real_distribution<float> T(0.0f, 2.0f * static_cast<float>(M_PI)); std::uniform_real_distribution<float> cos_phi(-1.0f, 1.0f); std::uniform_real_distribution<float> R(0, 1.0f); auto points = std::make_shared<std::vector<vec3>>(); for (int i = 0; i < numberOfPoints_.get(); i++) { float theta = T(mt_); float phi = std::acos(cos_phi(mt_)); vec2 range = sphereRadius_.get(); float r = std::pow(R(mt_), 1.0f / 3.0f); r = range.x + r * (range.y - range.x); float ct = std::cos(theta); float st = std::sin(theta); float sp = std::sin(phi); float cp = std::cos(phi); vec3 g = vec3(ct * sp, st * sp, cp); vec3 p = g * r + sphereCenter_.get(); points->push_back(p); } seedPoints_.setData(points); } void SeedPointGenerator::linePoints() { auto points = std::make_shared<std::vector<vec3>>(); float dt = 1.0f / (numberOfPoints_.get() - 1); for (int i = 0; i < numberOfPoints_.get(); i++) { auto p = lineStart_.get() + (lineEnd_.get() - lineStart_.get()) * (i * dt); points->push_back(p); } seedPoints_.setData(points); } void SeedPointGenerator::planePoints() { auto points = std::make_shared<std::vector<vec3>>(); float dx = 1.0f / (planeResolution_.get().x - 1); float dy = 1.0f / (planeResolution_.get().y - 1); vec3 ox = planeE1_.get(); // - planeOrigin_.get(); vec3 oy = planeE2_.get(); // - planeOrigin_.get(); for (int i = 0; i < planeResolution_.get().x; i++) { for (int j = 0; j < planeResolution_.get().y; j++) { vec3 p = planeOrigin_.get(); p += ox * (i * dx); p += oy * (j * dy); points->push_back(p); } } seedPoints_.setData(points); } void SeedPointGenerator::randomPoints() { auto points = std::make_shared<std::vector<vec3>>(); std::uniform_real_distribution<float> r(0.0f, 1.0f); for (int i = 0; i < numberOfPoints_.get(); i++) { vec3 p(r(mt_), r(mt_), r(mt_)); points->push_back(p); } seedPoints_.setData(points); } } // namespace inviwo <commit_msg>VectorVis: Ensure initialization order for random points<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2019 Inviwo 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. * * 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. * *********************************************************************************/ #include <modules/vectorfieldvisualization/processors/datageneration/seedpointgenerator.h> #include <modules/base/algorithm/randomutils.h> #include <glm/gtx/vector_angle.hpp> #include <math.h> #define RND 1 #define PLANE 2 #define LINE 3 #define SPHERE 4 namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo SeedPointGenerator::processorInfo_{ "org.inviwo.SeedPointGenerator3D", // Class identifier "Seed Point Generator 3D", // Display name "Data Creation", // Category CodeState::Stable, // Code state "CPU, Seed Points, Generator", // Tags }; const ProcessorInfo SeedPointGenerator::getProcessorInfo() const { return processorInfo_; } SeedPointGenerator::SeedPointGenerator() : Processor() , seedPoints_("seedPoints") , lineGroup_("line", "Line") , planeGroup_("plane", "Plane") , sphereGroup_("sphere", "Sphere") , numberOfPoints_("numberOfPoints", "Number of Points", 10, 1, 1000) , planeResolution_("planeResolution", "Resolution", vec2(4, 4), vec2(2, 2), vec2(100, 100)) , planeOrigin_("planeOrigin_", "Origin", vec3(0.0f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , planeE1_("planeP1_", "Offset 1", vec3(1.0f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , planeE2_("planeP2_", "Offset 2", vec3(0.0f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , sphereCenter_("sphereCenter", "Center", vec3(0.5f, 0.5f, 0.5f), vec3(0, 0, 0), vec3(1, 1, 1)) , sphereRadius_("sphereRadius", "Radius") , lineStart_("lineStart", "Start", vec3(0.5f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , lineEnd_("lineEnd_", "End", vec3(0.5f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) , generator_("generator", "Generator") , randomness_("randomness", "Randomness") , useSameSeed_("useSameSeed", "Use same seed", true) , seed_("seed", "Seed", 1, 0, 1000) , rd_() , mt_(rd_()) { addPort(seedPoints_); generator_.addOption("random", "Random", RND); generator_.addOption("line", "Line", LINE); generator_.addOption("plane", "Plane", PLANE); generator_.addOption("sphere", "Sphere", SPHERE); generator_.setCurrentStateAsDefault(); generator_.onChange([this]() { onGeneratorChange(); }); addProperty(generator_); lineGroup_.addProperty(lineStart_); lineGroup_.addProperty(lineEnd_); addProperty(lineGroup_); planeGroup_.addProperty(planeResolution_); planeGroup_.addProperty(planeOrigin_); planeGroup_.addProperty(planeE1_); planeGroup_.addProperty(planeE2_); addProperty(planeGroup_); sphereGroup_.addProperty(sphereCenter_); sphereGroup_.addProperty(sphereRadius_); sphereRadius_.set(vec2(0.45, 0.55)); sphereRadius_.setCurrentStateAsDefault(); addProperty(sphereGroup_); addProperty(numberOfPoints_); addProperty(randomness_); randomness_.addProperty(useSameSeed_); randomness_.addProperty(seed_); useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); }); onGeneratorChange(); } void SeedPointGenerator::process() { if (useSameSeed_.get()) { mt_.seed(seed_.get()); } switch (generator_.get()) { case RND: randomPoints(); break; case PLANE: planePoints(); break; case LINE: linePoints(); break; case SPHERE: spherePoints(); break; default: LogWarn("No points generated since given type is not yet implemented"); break; } } void SeedPointGenerator::onGeneratorChange() { bool rnd = generator_.get() == RND; bool plane = generator_.get() == PLANE; bool line = generator_.get() == LINE; bool sphere = generator_.get() == SPHERE; numberOfPoints_.setVisible(rnd || line || sphere); planeResolution_.setVisible(plane); planeOrigin_.setVisible(plane); planeE1_.setVisible(plane); planeE2_.setVisible(plane); sphereCenter_.setVisible(sphere); sphereRadius_.setVisible(sphere); lineStart_.setVisible(line); lineEnd_.setVisible(line); } void SeedPointGenerator::spherePoints() { auto T = [](auto&& r) { return util::randomNumber<float>(r, 0, glm::two_pi<float>()); }; auto cos_phi = [](auto&& r) { return util::randomNumber<float>(r, -1, 1); }; auto R = [](auto&& r) { return util::randomNumber<float>(r, 0, 1); }; auto points = std::make_shared<std::vector<vec3>>(); for (int i = 0; i < numberOfPoints_.get(); i++) { float theta = T(mt_); float phi = std::acos(cos_phi(mt_)); vec2 range = sphereRadius_.get(); float r = std::pow(R(mt_), 1.0f / 3.0f); r = range.x + r * (range.y - range.x); float ct = std::cos(theta); float st = std::sin(theta); float sp = std::sin(phi); float cp = std::cos(phi); vec3 g = vec3(ct * sp, st * sp, cp); vec3 p = g * r + sphereCenter_.get(); points->push_back(p); } seedPoints_.setData(points); } void SeedPointGenerator::linePoints() { auto points = std::make_shared<std::vector<vec3>>(); float dt = 1.0f / (numberOfPoints_.get() - 1); for (int i = 0; i < numberOfPoints_.get(); i++) { auto p = lineStart_.get() + (lineEnd_.get() - lineStart_.get()) * (i * dt); points->push_back(p); } seedPoints_.setData(points); } void SeedPointGenerator::planePoints() { auto points = std::make_shared<std::vector<vec3>>(); float dx = 1.0f / (planeResolution_.get().x - 1); float dy = 1.0f / (planeResolution_.get().y - 1); vec3 ox = planeE1_.get(); vec3 oy = planeE2_.get(); for (int i = 0; i < planeResolution_.get().x; i++) { for (int j = 0; j < planeResolution_.get().y; j++) { vec3 p = planeOrigin_.get(); p += ox * (i * dx); p += oy * (j * dy); points->push_back(p); } } seedPoints_.setData(points); } void SeedPointGenerator::randomPoints() { auto points = std::make_shared<std::vector<vec3>>(); for (int i = 0; i < numberOfPoints_.get(); i++) { const float x = util::randomNumber<float>(mt_); const float y = util::randomNumber<float>(mt_); const float z = util::randomNumber<float>(mt_); points->emplace_back(x, y, z); } seedPoints_.setData(points); } } // namespace inviwo <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <signal.h> #include <errno.h> #include "utils.hpp" #include "worker_pool.hpp" #include "async_io.hpp" #include "tty.hpp" #include "server.hpp" void event_handler(event_queue_t *event_queue, event_t *event) { int res; size_t sz; char buf[256]; if(event->event_type == et_sock_event) { bzero(buf, sizeof(buf)); // TODO: make sure we don't leave any data in the socket sz = read(event->source, buf, sizeof(buf)); check("Could not read from socket", sz == -1); if(sz > 0) { // See if we have a quit message if(strncmp(buf, "quit", 4) == 0) { printf("Quitting server...\n"); res = pthread_kill(event_queue->parent_pool->main_thread, SIGINT); check("Could not send kill signal to main thread", res != 0); return; } // Allocate a buffer to read file into void *gbuf = event_queue->alloc.malloc<buffer_t<512> >(); // Fire off an async IO event bzero(gbuf, 512); int offset = atoi(buf); // TODO: Using parent_pool might cause cache line // alignment issues. Can we eliminate it (perhaps by // giving each thread its own private copy of the // necessary data)? schedule_aio_read((int)(long)event_queue->parent_pool->data, offset, 512, gbuf, event_queue, (void*)event->source); } else { // No data left, close the socket printf("Closing socket %d\n", event->source); queue_forget_resource(event_queue, event->source); close(event->source); } } else if(event->event_type == et_disk_event) { // We got async IO event back // TODO: what happens to unfreed memory if event doesn't come back? (is it possible?) if(event->result < 0) { printf("File notify error (fd %d, res: %d) %s\n", event->source, event->result, strerror(-event->result)); res = write((int)(long)event->state, "err", 4); check("Could not write to socket", res == -1); // TODO: make sure we write everything we intend to } else { ((char*)event->buf)[11] = 0; res = write((int)(long)event->state, event->buf, 10); check("Could not write to socket", res == -1); // TODO: make sure we write everything we intend to } event_queue->alloc.free((buffer_t<512>*)event->buf); } else if(event->event_type == et_timer_event) { } } void term_handler(int signum) { // We'll naturally break out of the main loop because the accept // syscall will get interrupted. } void install_handlers() { int res; // Setup termination handlers struct sigaction action; bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGTERM, &action, NULL); check("Could not install TERM handler", res < 0); bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGINT, &action, NULL); check("Could not install INT handler", res < 0); }; int main(int argc, char *argv[]) { int res; // Setup signal handlers install_handlers(); // Create a pool of workers worker_pool_t worker_pool; int datafd = open("leo.txt", O_DIRECT | O_NOATIME | O_RDONLY); //int datafd = open("/mnt/ssd/test", O_DIRECT | O_NOATIME | O_RDONLY); check("Could not open data file", datafd < 0); worker_pool.data = (void*)datafd; create_worker_pool(&worker_pool, event_handler, pthread_self()); // Start the server int sockfd = start_server(&worker_pool); // Start a thread that feeds the terminal into the listening // socket do_tty_loop(sockfd); // At this point we broke out of the tty loop. Stop the server. stop_server(sockfd); // Clean up the rest destroy_worker_pool(&worker_pool); res = close((int)(long)worker_pool.data); check("Could not close served file", res != 0); printf("Server offline\n"); } <commit_msg>Quick docstring fixes<commit_after> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <signal.h> #include <errno.h> #include "utils.hpp" #include "worker_pool.hpp" #include "async_io.hpp" #include "tty.hpp" #include "server.hpp" void event_handler(event_queue_t *event_queue, event_t *event) { int res; size_t sz; char buf[256]; if(event->event_type == et_sock_event) { bzero(buf, sizeof(buf)); // TODO: make sure we don't leave any data in the socket sz = read(event->source, buf, sizeof(buf)); check("Could not read from socket", sz == -1); if(sz > 0) { // See if we have a quit message if(strncmp(buf, "quit", 4) == 0) { printf("Quitting server...\n"); res = pthread_kill(event_queue->parent_pool->main_thread, SIGINT); check("Could not send kill signal to main thread", res != 0); return; } // Allocate a buffer to read file into void *gbuf = event_queue->alloc.malloc<buffer_t<512> >(); // Fire off an async IO event bzero(gbuf, 512); int offset = atoi(buf); // TODO: Using parent_pool might cause cache line // alignment issues. Can we eliminate it (perhaps by // giving each thread its own private copy of the // necessary data)? schedule_aio_read((int)(long)event_queue->parent_pool->data, offset, 512, gbuf, event_queue, (void*)event->source); } else { // No data left, close the socket printf("Closing socket %d\n", event->source); queue_forget_resource(event_queue, event->source); close(event->source); } } else if(event->event_type == et_disk_event) { // We got async IO event back // TODO: what happens to unfreed memory if event doesn't come back? (is it possible?) if(event->result < 0) { printf("File notify error (fd %d, res: %d) %s\n", event->source, event->result, strerror(-event->result)); res = write((int)(long)event->state, "err", 4); check("Could not write to socket", res == -1); // TODO: make sure we write everything we intend to } else { ((char*)event->buf)[11] = 0; res = write((int)(long)event->state, event->buf, 10); check("Could not write to socket", res == -1); // TODO: make sure we write everything we intend to } event_queue->alloc.free((buffer_t<512>*)event->buf); } else if(event->event_type == et_timer_event) { } } void term_handler(int signum) { // We'll naturally break out of the main loop because the accept // syscall will get interrupted. } void install_handlers() { int res; // Setup termination handlers struct sigaction action; bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGTERM, &action, NULL); check("Could not install TERM handler", res < 0); bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGINT, &action, NULL); check("Could not install INT handler", res < 0); }; int main(int argc, char *argv[]) { int res; // Setup signal handlers install_handlers(); // Create a pool of workers worker_pool_t worker_pool; int datafd = open("leo.txt", O_DIRECT | O_NOATIME | O_RDONLY); //int datafd = open("/mnt/ssd/test", O_DIRECT | O_NOATIME | O_RDONLY); check("Could not open data file", datafd < 0); worker_pool.data = (void*)datafd; create_worker_pool(&worker_pool, event_handler, pthread_self()); // Start the server (in a separate thread) int sockfd = start_server(&worker_pool); // Feed the terminal into the listening socket do_tty_loop(sockfd); // At this point we broke out of the tty loop. Stop the server. stop_server(sockfd); // Clean up the rest destroy_worker_pool(&worker_pool); res = close((int)(long)worker_pool.data); check("Could not close served file", res != 0); printf("Server offline\n"); } <|endoftext|>
<commit_before><commit_msg>Make --app switch URL restrictions match normal command line restrictions.<commit_after><|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <iostream> #include <vector> using namespace std; enum Token { tok_eof = -1, tok_identifier = -2, tok_number = -3 }; static string IdentifierStr; // Filled in if tok_identifier static double NumVal; // Filled in if tok_number static int gettok() { static int LastChar = ' '; // Skip any whitespace. while (isspace(LastChar)) LastChar = getchar(); if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]* IdentifierStr = LastChar; while (isalnum((LastChar = getchar()))) IdentifierStr += LastChar; return tok_identifier; } if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+ string NumStr; do { NumStr += LastChar; LastChar = getchar(); } while (isdigit(LastChar) || LastChar == '.'); NumVal = strtod(NumStr.c_str(), 0); return tok_number; } if (LastChar == '#') { // Comment until end of line. do LastChar = getchar(); while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); if (LastChar != EOF) return gettok(); } // Check for end of file. Don't eat the EOF. if (LastChar == EOF) return tok_eof; // Otherwise, just return the character as its ascii value. int ThisChar = LastChar; LastChar = getchar(); return ThisChar; } //===----------------------------------------------------------------------===// // Abstract Syntax Tree (aka Parse Tree) //===----------------------------------------------------------------------===// namespace { /// ExprAST - Base class for all expression nodes. class ExprAST { public: virtual ~ExprAST() {} }; /// NumberExprAST - Expression class for numeric literals like "1.0". class NumberExprAST : public ExprAST { public: NumberExprAST(double val) {} }; /// VariableExprAST - Expression class for referencing a variable, like "a". class VariableExprAST : public ExprAST { std::string Name; public: VariableExprAST(const std::string &name) : Name(name) {} }; /// PrototypeAST - This class represents the "prototype" for a function, /// which captures its name, and its argument names (thus implicitly the number /// of arguments the function takes). class PrototypeAST { std::string Name; std::vector<std::string> Args; public: PrototypeAST(const std::string &name, const std::vector<std::string> &args) : Name(name), Args(args) {} }; /// FunctionAST - This class represents a function definition itself. class FunctionAST { public: FunctionAST(PrototypeAST *proto, ExprAST *body) {} }; } // end anonymous namespace static int CurTok; static int getNextToken() { return CurTok = gettok(); } ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;} PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; } static ExprAST *ParseExpression(); /// identifierexpr /// ::= identifier /// ::= identifier '(' expression* ')' static ExprAST *ParseIdentifierExpr() { std::string IdName = IdentifierStr; getNextToken(); // eat identifier. //if (CurTok != '(') // Simple variable ref. return new VariableExprAST(IdName); // Call. //getNextToken(); // eat ( //std::vector<ExprAST*> Args; //if (CurTok != ')') { //while (1) { //ExprAST *Arg = ParseExpression(); //if (!Arg) return 0; //Args.push_back(Arg); //if (CurTok == ')') break; //if (CurTok != ',') //return Error("Expected ')' or ',' in argument list"); //getNextToken(); //} //} //// Eat the ')'. //getNextToken(); //return new CallExprAST(IdName, Args); } /// numberexpr ::= number static ExprAST *ParseNumberExpr() { ExprAST *Result = new NumberExprAST(NumVal); getNextToken(); // consume the number return Result; } /// primary /// ::= identifierexpr /// ::= numberexpr /// ::= parenexpr static ExprAST *ParsePrimary() { switch (CurTok) { default: return Error("unknown token when expecting an expression"); case tok_identifier: return ParseIdentifierExpr(); case tok_number: return ParseNumberExpr(); //case '(': return ParseParenExpr(); } } /// expression /// ::= primary binoprhs /// static ExprAST *ParseExpression() { ExprAST *expr = ParsePrimary(); if (!expr) return 0; return expr; } /// toplevelexpr ::= expression static FunctionAST *ParseTopLevelExpr() { if (ExprAST *E = ParseExpression()) { // Make an anonymous proto. PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>()); return new FunctionAST(Proto, E); } return 0; } static void HandleTopLevelExpression() { // Evaluate a top-level expression into an anonymous function. if (ParseTopLevelExpr()) { fprintf(stderr, "Parsed a top-level expr\n"); } else { // Skip token for error recovery. getNextToken(); } } static void MainLoop() { while (1) { fprintf(stderr, "ready> "); switch (CurTok) { case tok_eof: return; case ';': getNextToken(); break; // ignore top-level semicolons. default: HandleTopLevelExpression(); break; } } } int main(int argc, const char ** argv) { fprintf(stderr, "ready> "); getNextToken(); MainLoop(); return 0; } <commit_msg>Starting fresh.<commit_after><|endoftext|>
<commit_before>#include "assert.hh" #include "buffer.hh" #include "buffer_manager.hh" #include "client_manager.hh" #include "color_registry.hh" #include "command_manager.hh" #include "commands.hh" #include "context.hh" #include "debug.hh" #include "event_manager.hh" #include "file.hh" #include "filters.hh" #include "highlighters.hh" #include "hook_manager.hh" #include "ncurses.hh" #include "option_manager.hh" #include "parameters_parser.hh" #include "register_manager.hh" #include "remote.hh" #include "shell_manager.hh" #include "string.hh" #include "window.hh" #if defined(__APPLE__) #include <mach-o/dyld.h> #endif #include <unordered_map> #include <locale> #include <signal.h> using namespace Kakoune; void run_unit_tests(); String runtime_directory() { char buffer[2048]; #if defined(__linux__) || defined(__CYGWIN__) ssize_t res = readlink("/proc/self/exe", buffer, 2048); kak_assert(res != -1); buffer[res] = '\0'; #elif defined(__APPLE__) uint32_t bufsize = 2048; _NSGetExecutablePath(buffer, &bufsize); char* canonical_path = realpath(buffer, nullptr); strncpy(buffer, canonical_path, 2048); free(canonical_path); #else # error "finding executable path is not implemented on this platform" #endif char* ptr = strrchr(buffer, '/'); if (not ptr) throw runtime_error("unable to determine runtime directory"); return String(buffer, ptr); } void register_env_vars() { ShellManager& shell_manager = ShellManager::instance(); shell_manager.register_env_var("bufname", [](const String& name, const Context& context) { return context.buffer().display_name(); }); shell_manager.register_env_var("timestamp", [](const String& name, const Context& context) { return to_string(context.buffer().timestamp()); }); shell_manager.register_env_var("selection", [](const String& name, const Context& context) { const Range& sel = context.editor().main_selection(); return content(context.buffer(), sel); }); shell_manager.register_env_var("selections", [](const String& name, const Context& context) { auto sels = context.editor().selections_content(); String res; for (size_t i = 0; i < sels.size(); ++i) { res += escape(sels[i], ':', '\\'); if (i != sels.size() - 1) res += ':'; } return res; }); shell_manager.register_env_var("runtime", [](const String& name, const Context& context) { return runtime_directory(); }); shell_manager.register_env_var("opt_.+", [](const String& name, const Context& context) { return context.options()[name.substr(4_byte)].get_as_string(); }); shell_manager.register_env_var("reg_.+", [](const String& name, const Context& context) { return RegisterManager::instance()[name[4]].values(context)[0]; }); shell_manager.register_env_var("socket", [](const String& name, const Context& context) { return Server::instance().filename(); }); shell_manager.register_env_var("client", [](const String& name, const Context& context) { return context.client().name(); }); shell_manager.register_env_var("cursor_line", [](const String& name, const Context& context) { return to_string(context.editor().main_selection().last().line + 1); }); shell_manager.register_env_var("cursor_column", [](const String& name, const Context& context) { return to_string(context.editor().main_selection().last().column + 1); }); shell_manager.register_env_var("selection_desc", [](const String& name, const Context& context) { auto& sel = context.editor().main_selection(); auto beg = sel.min(); return to_string(beg.line + 1) + ':' + to_string(beg.column + 1) + '+' + to_string((int)context.buffer().distance(beg, sel.max())+1); }); shell_manager.register_env_var("window_width", [](const String& name, const Context& context) { return to_string(context.window().dimensions().column); }); shell_manager.register_env_var("window_height", [](const String& name, const Context& context) { return to_string(context.window().dimensions().line); }); } void register_registers() { RegisterManager& register_manager = RegisterManager::instance(); register_manager.register_dynamic_register('%', [](const Context& context) { return std::vector<String>(1, context.buffer().display_name()); }); register_manager.register_dynamic_register('.', [](const Context& context) { return context.editor().selections_content(); }); for (size_t i = 0; i < 10; ++i) { register_manager.register_dynamic_register('0'+i, [i](const Context& context) { std::vector<String> result; for (auto& sel : context.editor().selections()) result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : ""); return result; }); } } void create_local_client(const String& init_command) { class LocalNCursesUI : public NCursesUI { ~LocalNCursesUI() { if (not ClientManager::instance().empty() and fork()) { this->NCursesUI::~NCursesUI(); puts("detached from terminal\n"); exit(0); } } }; UserInterface* ui = new LocalNCursesUI{}; static Client* client = ClientManager::instance().create_client( std::unique_ptr<UserInterface>{ui}, init_command); signal(SIGHUP, [](int) { if (client) ClientManager::instance().remove_client(*client); client = nullptr; }); } void signal_handler(int signal) { NCursesUI::abort(); const char* text = nullptr; switch (signal) { case SIGSEGV: text = "SIGSEGV"; break; case SIGFPE: text = "SIGFPE"; break; case SIGQUIT: text = "SIGQUIT"; break; case SIGTERM: text = "SIGTERM"; break; } on_assert_failed(text); abort(); } int kakoune(memoryview<String> params) { ParametersParser parser(params, { { "c", true }, { "e", true }, { "n", false }, { "s", true }, { "d", false } }); String init_command; if (parser.has_option("e")) init_command = parser.option_value("e"); if (parser.has_option("c")) { for (auto opt : { "n", "s", "d" }) { if (parser.has_option(opt)) { fprintf(stderr, "error: -%s makes not sense with -c\n", opt); return -1; } } try { EventManager event_manager; auto client = connect_to(parser.option_value("c"), std::unique_ptr<UserInterface>{new NCursesUI{}}, init_command); while (true) event_manager.handle_next_events(); } catch (peer_disconnected&) { fputs("disconnected from server\n", stderr); return -1; } return 0; } else { const bool daemon = parser.has_option("d"); static bool terminate = false; if (daemon) { if (not parser.has_option("s")) { fputs("-d needs a session name to be specified with -s\n", stderr); return -1; } if (pid_t child = fork()) { printf("Kakoune forked to background, for session '%s'\n" "send SIGTERM to process %d for closing the session\n", parser.option_value("s").c_str(), child); exit(0); } signal(SIGTERM, [](int) { terminate = true; }); } EventManager event_manager; GlobalOptions global_options; GlobalHooks global_hooks; ShellManager shell_manager; CommandManager command_manager; BufferManager buffer_manager; RegisterManager register_manager; HighlighterRegistry highlighter_registry; FilterRegistry filter_registry; ColorRegistry color_registry; ClientManager client_manager; run_unit_tests(); register_env_vars(); register_registers(); register_commands(); register_highlighters(); register_filters(); write_debug("*** This is the debug buffer, where debug info will be written ***"); write_debug("pid: " + to_string(getpid())); write_debug("utf-8 test: é á ï"); Server server(parser.has_option("s") ? parser.option_value("s") : to_string(getpid())); if (not parser.has_option("n")) try { Context initialisation_context; command_manager.execute("source " + runtime_directory() + "/kakrc", initialisation_context); } catch (Kakoune::runtime_error& error) { write_debug("error while parsing kakrc: "_str + error.what()); } catch (Kakoune::client_removed&) { write_debug("error while parsing kakrc: asked to quit"); } { Context empty_context; global_hooks.run_hook("KakBegin", "", empty_context); } if (parser.positional_count() != 0) try { // create buffers in reverse order so that the first given buffer // is the most recently created one. for (int i = parser.positional_count() - 1; i >= 0; --i) { const String& file = parser[i]; if (not create_buffer_from_file(file)) new Buffer(file, Buffer::Flags::New | Buffer::Flags::File); } } catch (Kakoune::runtime_error& error) { write_debug("error while opening command line files: "_str + error.what()); } else new Buffer("*scratch*", Buffer::Flags::None); if (not daemon) create_local_client(init_command); while (not terminate and (not client_manager.empty() or daemon)) event_manager.handle_next_events(); { Context empty_context; global_hooks.run_hook("KakEnd", "", empty_context); } return 0; } } int main(int argc, char* argv[]) { try { setlocale(LC_ALL, ""); signal(SIGSEGV, signal_handler); signal(SIGFPE, signal_handler); signal(SIGQUIT, signal_handler); signal(SIGTERM, signal_handler); std::vector<String> params; for (size_t i = 1; i < argc; ++i) params.push_back(argv[i]); kakoune(params); } catch (Kakoune::exception& error) { on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str()); return -1; } catch (std::exception& error) { on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str()); return -1; } catch (...) { on_assert_failed("uncaught exception"); return -1; } return 0; } <commit_msg>extract client main to a run_client function<commit_after>#include "assert.hh" #include "buffer.hh" #include "buffer_manager.hh" #include "client_manager.hh" #include "color_registry.hh" #include "command_manager.hh" #include "commands.hh" #include "context.hh" #include "debug.hh" #include "event_manager.hh" #include "file.hh" #include "filters.hh" #include "highlighters.hh" #include "hook_manager.hh" #include "ncurses.hh" #include "option_manager.hh" #include "parameters_parser.hh" #include "register_manager.hh" #include "remote.hh" #include "shell_manager.hh" #include "string.hh" #include "window.hh" #if defined(__APPLE__) #include <mach-o/dyld.h> #endif #include <unordered_map> #include <locale> #include <signal.h> using namespace Kakoune; void run_unit_tests(); String runtime_directory() { char buffer[2048]; #if defined(__linux__) || defined(__CYGWIN__) ssize_t res = readlink("/proc/self/exe", buffer, 2048); kak_assert(res != -1); buffer[res] = '\0'; #elif defined(__APPLE__) uint32_t bufsize = 2048; _NSGetExecutablePath(buffer, &bufsize); char* canonical_path = realpath(buffer, nullptr); strncpy(buffer, canonical_path, 2048); free(canonical_path); #else # error "finding executable path is not implemented on this platform" #endif char* ptr = strrchr(buffer, '/'); if (not ptr) throw runtime_error("unable to determine runtime directory"); return String(buffer, ptr); } void register_env_vars() { ShellManager& shell_manager = ShellManager::instance(); shell_manager.register_env_var("bufname", [](const String& name, const Context& context) { return context.buffer().display_name(); }); shell_manager.register_env_var("timestamp", [](const String& name, const Context& context) { return to_string(context.buffer().timestamp()); }); shell_manager.register_env_var("selection", [](const String& name, const Context& context) { const Range& sel = context.editor().main_selection(); return content(context.buffer(), sel); }); shell_manager.register_env_var("selections", [](const String& name, const Context& context) { auto sels = context.editor().selections_content(); String res; for (size_t i = 0; i < sels.size(); ++i) { res += escape(sels[i], ':', '\\'); if (i != sels.size() - 1) res += ':'; } return res; }); shell_manager.register_env_var("runtime", [](const String& name, const Context& context) { return runtime_directory(); }); shell_manager.register_env_var("opt_.+", [](const String& name, const Context& context) { return context.options()[name.substr(4_byte)].get_as_string(); }); shell_manager.register_env_var("reg_.+", [](const String& name, const Context& context) { return RegisterManager::instance()[name[4]].values(context)[0]; }); shell_manager.register_env_var("socket", [](const String& name, const Context& context) { return Server::instance().filename(); }); shell_manager.register_env_var("client", [](const String& name, const Context& context) { return context.client().name(); }); shell_manager.register_env_var("cursor_line", [](const String& name, const Context& context) { return to_string(context.editor().main_selection().last().line + 1); }); shell_manager.register_env_var("cursor_column", [](const String& name, const Context& context) { return to_string(context.editor().main_selection().last().column + 1); }); shell_manager.register_env_var("selection_desc", [](const String& name, const Context& context) { auto& sel = context.editor().main_selection(); auto beg = sel.min(); return to_string(beg.line + 1) + ':' + to_string(beg.column + 1) + '+' + to_string((int)context.buffer().distance(beg, sel.max())+1); }); shell_manager.register_env_var("window_width", [](const String& name, const Context& context) { return to_string(context.window().dimensions().column); }); shell_manager.register_env_var("window_height", [](const String& name, const Context& context) { return to_string(context.window().dimensions().line); }); } void register_registers() { RegisterManager& register_manager = RegisterManager::instance(); register_manager.register_dynamic_register('%', [](const Context& context) { return std::vector<String>(1, context.buffer().display_name()); }); register_manager.register_dynamic_register('.', [](const Context& context) { return context.editor().selections_content(); }); for (size_t i = 0; i < 10; ++i) { register_manager.register_dynamic_register('0'+i, [i](const Context& context) { std::vector<String> result; for (auto& sel : context.editor().selections()) result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : ""); return result; }); } } void create_local_client(const String& init_command) { class LocalNCursesUI : public NCursesUI { ~LocalNCursesUI() { if (not ClientManager::instance().empty() and fork()) { this->NCursesUI::~NCursesUI(); puts("detached from terminal\n"); exit(0); } } }; UserInterface* ui = new LocalNCursesUI{}; static Client* client = ClientManager::instance().create_client( std::unique_ptr<UserInterface>{ui}, init_command); signal(SIGHUP, [](int) { if (client) ClientManager::instance().remove_client(*client); client = nullptr; }); } void signal_handler(int signal) { NCursesUI::abort(); const char* text = nullptr; switch (signal) { case SIGSEGV: text = "SIGSEGV"; break; case SIGFPE: text = "SIGFPE"; break; case SIGQUIT: text = "SIGQUIT"; break; case SIGTERM: text = "SIGTERM"; break; } on_assert_failed(text); abort(); } int run_client(const String& session, const String& init_command) { try { EventManager event_manager; auto client = connect_to(session, std::unique_ptr<UserInterface>{new NCursesUI{}}, init_command); while (true) event_manager.handle_next_events(); } catch (peer_disconnected&) { fputs("disconnected from server\n", stderr); return -1; } return 0; } int kakoune(memoryview<String> params) { ParametersParser parser(params, { { "c", true }, { "e", true }, { "n", false }, { "s", true }, { "d", false } }); String init_command; if (parser.has_option("e")) init_command = parser.option_value("e"); if (parser.has_option("c")) { for (auto opt : { "n", "s", "d" }) { if (parser.has_option(opt)) { fprintf(stderr, "error: -%s makes not sense with -c\n", opt); return -1; } } return run_client(parser.option_value("c"), init_command); } const bool daemon = parser.has_option("d"); static bool terminate = false; if (daemon) { if (not parser.has_option("s")) { fputs("-d needs a session name to be specified with -s\n", stderr); return -1; } if (pid_t child = fork()) { printf("Kakoune forked to background, for session '%s'\n" "send SIGTERM to process %d for closing the session\n", parser.option_value("s").c_str(), child); exit(0); } signal(SIGTERM, [](int) { terminate = true; }); } EventManager event_manager; GlobalOptions global_options; GlobalHooks global_hooks; ShellManager shell_manager; CommandManager command_manager; BufferManager buffer_manager; RegisterManager register_manager; HighlighterRegistry highlighter_registry; FilterRegistry filter_registry; ColorRegistry color_registry; ClientManager client_manager; run_unit_tests(); register_env_vars(); register_registers(); register_commands(); register_highlighters(); register_filters(); write_debug("*** This is the debug buffer, where debug info will be written ***"); write_debug("pid: " + to_string(getpid())); write_debug("utf-8 test: é á ï"); Server server(parser.has_option("s") ? parser.option_value("s") : to_string(getpid())); if (not parser.has_option("n")) try { Context initialisation_context; command_manager.execute("source " + runtime_directory() + "/kakrc", initialisation_context); } catch (Kakoune::runtime_error& error) { write_debug("error while parsing kakrc: "_str + error.what()); } catch (Kakoune::client_removed&) { write_debug("error while parsing kakrc: asked to quit"); } { Context empty_context; global_hooks.run_hook("KakBegin", "", empty_context); } if (parser.positional_count() != 0) try { // create buffers in reverse order so that the first given buffer // is the most recently created one. for (int i = parser.positional_count() - 1; i >= 0; --i) { const String& file = parser[i]; if (not create_buffer_from_file(file)) new Buffer(file, Buffer::Flags::New | Buffer::Flags::File); } } catch (Kakoune::runtime_error& error) { write_debug("error while opening command line files: "_str + error.what()); } else new Buffer("*scratch*", Buffer::Flags::None); if (not daemon) create_local_client(init_command); while (not terminate and (not client_manager.empty() or daemon)) event_manager.handle_next_events(); { Context empty_context; global_hooks.run_hook("KakEnd", "", empty_context); } return 0; } int main(int argc, char* argv[]) { try { setlocale(LC_ALL, ""); signal(SIGSEGV, signal_handler); signal(SIGFPE, signal_handler); signal(SIGQUIT, signal_handler); signal(SIGTERM, signal_handler); std::vector<String> params; for (size_t i = 1; i < argc; ++i) params.push_back(argv[i]); kakoune(params); } catch (Kakoune::exception& error) { on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str()); return -1; } catch (std::exception& error) { on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str()); return -1; } catch (...) { on_assert_failed("uncaught exception"); return -1; } return 0; } <|endoftext|>
<commit_before><commit_msg>Un-mark UILayoutTests as flaky<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 "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) TEST_PPAPI_OUT_OF_PROCESS(Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) TEST_PPAPI_IN_PROCESS(PostMessage) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(PostMessage) TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/90040 TEST_F(OutOfProcessPPAPITest, FLAKY_FileSystem) { RunTestViaHTTP("FileSystem"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84295 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS <commit_msg>Added existing tests for the UMA and VideoDecoder interfaces to the PPAPI ui_tests.<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 "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) TEST_PPAPI_OUT_OF_PROCESS(Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) TEST_PPAPI_IN_PROCESS(PostMessage) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(PostMessage) TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/90040 TEST_F(OutOfProcessPPAPITest, FLAKY_FileSystem) { RunTestViaHTTP("FileSystem"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84295 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } TEST_PPAPI_IN_PROCESS(VideoDecoder) // There is no proxy yet (vrk is adding it). TEST_F(OutOfProcessPPAPITest, FAILS_VideoDecoder) { RunTest("VideoDecoder"); } <|endoftext|>
<commit_before>/** * @file veilFuse.cc * @author Rafal Slota * @copyright (C) 2013 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in 'LICENSE.txt' */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef linux /* For pread()/pwrite()/utimensat() */ #define _XOPEN_SOURCE 700 #endif #include <fuse.h> #include <fuse/fuse_opt.h> #include <fuse/fuse_lowlevel.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <dirent.h> #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif #include <boost/filesystem.hpp> #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include "veilfs.h" #include "config.h" #include "gsiHandler.h" #include "glog/logging.h" using namespace std; using namespace boost; using namespace veil; using namespace veil::client; using boost::filesystem::path; /// Main application object (filesystem state) boost::shared_ptr<VeilFS> VeilAppObject; #ifdef __cplusplus extern "C" { #endif static int wrap_access(const char *path, int mask) { return VeilAppObject->access(path, mask); } static int wrap_getattr(const char *path, struct stat *statbuf) { return VeilAppObject->getattr(path, statbuf); } static int wrap_readlink(const char *path, char *link, size_t size) { return VeilAppObject->readlink(path, link, size); } static int wrap_mknod(const char *path, mode_t mode, dev_t dev) { return VeilAppObject->mknod(path, mode, dev); } static int wrap_mkdir(const char *path, mode_t mode) { return VeilAppObject->mkdir(path, mode); } static int wrap_unlink(const char *path) { return VeilAppObject->unlink(path); } static int wrap_rmdir(const char *path) { return VeilAppObject->rmdir(path); } static int wrap_symlink(const char *path, const char *link) { return VeilAppObject->symlink(path, link); } static int wrap_rename(const char *path, const char *newpath) { return VeilAppObject->rename(path, newpath); } static int wrap_link(const char *path, const char *newpath) { return VeilAppObject->link(path, newpath); } static int wrap_chmod(const char *path, mode_t mode) { return VeilAppObject->chmod(path, mode); } static int wrap_chown(const char *path, uid_t uid, gid_t gid) { return VeilAppObject->chown(path, uid, gid); } static int wrap_truncate(const char *path, off_t newSize) { return VeilAppObject->truncate(path, newSize); } static int wrap_utime(const char *path, struct utimbuf *ubuf) { return VeilAppObject->utime(path, ubuf); } static int wrap_open(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->open(path, fileInfo); } static int wrap_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return VeilAppObject->read(path, buf, size, offset, fileInfo); } static int wrap_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return VeilAppObject->write(path, buf, size, offset, fileInfo); } static int wrap_statfs(const char *path, struct statvfs *statInfo) { return VeilAppObject->statfs(path, statInfo); } static int wrap_flush(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->flush(path, fileInfo); } static int wrap_release(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->release(path, fileInfo); } static int wrap_fsync(const char *path, int datasync, struct fuse_file_info *fi) { return VeilAppObject->fsync(path, datasync, fi); } #ifdef HAVE_SETXATTR static int wrap_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { return VeilAppObject->setxattr(path, name, value, size, flags); } static int wrap_getxattr(const char *path, const char *name, char *value, size_t size) { return VeilAppObject->getxattr(path, name, value, size); } static int wrap_listxattr(const char *path, char *list, size_t size) { return VeilAppObject->listxattr(path, list, size); } static int wrap_removexattr(const char *path, const char *name) { return VeilAppObject->removexattr(path, name); } #endif // HAVE_SETXATTR static int wrap_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo) { return VeilAppObject->readdir(path, buf, filler, offset, fileInfo); } static int wrap_opendir(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->opendir(path, fileInfo); } static int wrap_releasedir(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->releasedir(path, fileInfo); } static int wrap_fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo) { return VeilAppObject->fsyncdir(path, datasync, fileInfo); } // static int wrap_init(struct fuse_conn_info *conn) { // return VeilAppObject->init(conn); // } static int vfs_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs) { if(string(arg).find(CONFIG_ARGV_OPT_NAME) != string::npos) return 0; if(string(arg) == "-debug") return 0; return 1; } #ifdef __cplusplus } #endif static struct fuse_operations vfs_oper; static void oper_init() { vfs_oper.getattr = wrap_getattr; vfs_oper.access = wrap_access; vfs_oper.readlink = wrap_readlink; vfs_oper.readdir = wrap_readdir; vfs_oper.mknod = wrap_mknod; vfs_oper.mkdir = wrap_mkdir; vfs_oper.symlink = wrap_symlink; vfs_oper.unlink = wrap_unlink; vfs_oper.rmdir = wrap_rmdir; vfs_oper.rename = wrap_rename; vfs_oper.link = wrap_link; vfs_oper.chmod = wrap_chmod; vfs_oper.chown = wrap_chown; vfs_oper.truncate = wrap_truncate; #ifdef HAVE_UTIMENSAT vfs_oper.utimens = wrap_utimens; #endif vfs_oper.open = wrap_open; vfs_oper.read = wrap_read; vfs_oper.write = wrap_write; vfs_oper.statfs = wrap_statfs; vfs_oper.release = wrap_release; vfs_oper.fsync = wrap_fsync; vfs_oper.utime = wrap_utime; vfs_oper.flush = wrap_flush; vfs_oper.opendir = wrap_opendir; vfs_oper.releasedir = wrap_releasedir; vfs_oper.fsyncdir = wrap_fsyncdir; #ifdef HAVE_POSIX_FALLOCATE vfs_oper.fallocate = wrap_fallocate; #endif #ifdef HAVE_SETXATTR vfs_oper.setxattr = wrap_setxattr; vfs_oper.getxattr = wrap_getxattr; vfs_oper.listxattr = wrap_listxattr; vfs_oper.removexattr= wrap_removexattr; #endif } static void fuse_init() { //LOG(INFO) << "Intializing fuse callbacks"; oper_init(); } #include "gsi_utils.h" int main(int argc, char* argv[], char* envp[]) { // Turn off logging for a while google::InitGoogleLogging(argv[0]); FLAGS_alsologtostderr = false; FLAGS_logtostderr = false; FLAGS_stderrthreshold = 3; // Initialize FUSE umask(0); fuse_init(); struct fuse_args args = FUSE_ARGS_INIT(argc, argv); fuse_opt_parse(&args, NULL, NULL, vfs_opt_proc); // Enforced FUSE options fuse_opt_add_arg(&args, "-obig_writes"); bool debug = false; // Assume silent mode boost::shared_ptr<Config> config(new Config()); VeilFS::setConfig(config); // Find user config argument for(int i = 1; i < argc; ++i) { if(string(argv[i]).find(CONFIG_ARGV_OPT_NAME) != string::npos) { config->setUserConfigFile(string(argv[i]).substr(string(CONFIG_ARGV_OPT_NAME).size())); } if(string(argv[i]) == "-d") // FUSE's debug flag debug = true; if(string(argv[i]) == "-debug") // GSI Handler's debug flag gsi::debug = true; } // Setup config manager and paths path binDir = path(string(argv[0])).branch_path(); path etcDir = binDir / ".." / VeilClient_CONFIG_DIR; string configFile = GLOBAL_CONFIG_FILE; if(filesystem::exists(etcDir / GLOBAL_CONFIG_FILE)) { configFile = (etcDir / GLOBAL_CONFIG_FILE).string(); } config->setGlobalConfigFile(configFile); if(!config->parseConfig()) { std::cerr << "Cannot load/parse global/user config file. Check logs for more detials. Aborting" << std::endl; exit(1); } // proper logger setup if(config->isSet(LOG_DIR_OPT)) { string log_path = Config::absPathRelToCWD(config->getString(LOG_DIR_OPT)); if(log_path != "/tmp") { FLAGS_log_dir = log_path; LOG(INFO) << "Setting log dir to: " << log_path; // Restart Google Loggler in order ot reload log_dir path google::ShutdownGoogleLogging(); google::InitGoogleLogging(argv[0]); } } FLAGS_alsologtostderr = debug; FLAGS_logtostderr = debug; if(debug) FLAGS_stderrthreshold = 2; // Iterate over all env variables and save them in Config char** env; for (env = envp; *env != 0; env++) { std::vector<std::string> tokens; std::string tEnv = std::string(*env); boost::split(tokens, tEnv, boost::is_any_of("=")); if(tokens.size() != 2) // Invalid env variable. Expected format: NAME=VALUE continue; Config::putEnv(tokens[0], tokens[1]); } // FUSE main: struct fuse *fuse; struct fuse_chan *ch; char *mountpoint; int multithreaded; int foreground; int res; res = fuse_parse_cmdline(&args, &mountpoint, &multithreaded, &foreground); if (res == -1) exit(1); ch = fuse_mount(mountpoint, &args); if (!ch) exit(1); res = fcntl(fuse_chan_fd(ch), F_SETFD, FD_CLOEXEC); if (res == -1) perror("WARNING: failed to set FD_CLOEXEC on fuse device"); fuse = fuse_new(ch, &args, &vfs_oper, sizeof(struct fuse_operations), NULL); if (fuse == NULL) { fuse_unmount(mountpoint, ch); exit(1); } fuse_set_signal_handlers(fuse_get_session(fuse)); // Check proxy certificate if(!gsi::validateProxyConfig()) { std::cerr << "Cannot continue. Aborting" << std::endl; fuse_unmount(mountpoint, ch); exit(1); } LOG(INFO) << "Proxy certificate to be used: " << gsi::getProxyCertPath(); cout << "VeilFS has been successfully mounted in " + string(mountpoint) << endl; fuse_remove_signal_handlers(fuse_get_session(fuse)); res = fuse_daemonize(foreground); if (res != -1) res = fuse_set_signal_handlers(fuse_get_session(fuse)); if (res == -1) { fuse_unmount(mountpoint, ch); fuse_destroy(fuse); exit(1); } // Initialize VeilClient application VeilFS::setConnectionPool(boost::shared_ptr<SimpleConnectionPool> ( new SimpleConnectionPool(gsi::getClusterHostname(), config->getInt(CLUSTER_PORT_OPT), gsi::getProxyCertPath(), gsi::validateProxyCert))); // Setup veilhelpers config veil::helpers::config::setConnectionPool(VeilFS::getConnectionPool()); veil::helpers::config::buffers::writeBufferGlobalSizeLimit = config->getInt(WRITE_BUFFER_MAX_SIZE_OPT); veil::helpers::config::buffers::readBufferGlobalSizeLimit = config->getInt(READ_BUFFER_MAX_SIZE_OPT); veil::helpers::config::buffers::writeBufferPerFileSizeLimit = config->getInt(WRITE_BUFFER_MAX_FILE_SIZE_OPT); veil::helpers::config::buffers::readBufferPerFileSizeLimit = config->getInt(READ_BUFFER_MAX_FILE_SIZE_OPT); veil::helpers::config::buffers::preferedBlockSize = config->getInt(FILE_BUFFER_PREFERED_BLOCK_SIZE_OPT); // Maximum connection count setup VeilFS::getConnectionPool()->setPoolSize(SimpleConnectionPool::META_POOL, config->getInt(ALIVE_META_CONNECTIONS_COUNT_OPT)); VeilFS::getConnectionPool()->setPoolSize(SimpleConnectionPool::DATA_POOL, config->getInt(ALIVE_DATA_CONNECTIONS_COUNT_OPT)); // Start all jobSchedulers for(int i = 1; i < config->getInt(JOBSCHEDULER_THREADS_OPT); ++i) VeilFS::addScheduler(boost::shared_ptr<JobScheduler>(new JobScheduler())); // Initialize main application object VeilAppObject.reset(new VeilFS(mountpoint, config, boost::shared_ptr<JobScheduler>(new JobScheduler()), boost::shared_ptr<FslogicProxy>(new FslogicProxy()), boost::shared_ptr<MetaCache>(new MetaCache()), boost::shared_ptr<StorageMapper>(new StorageMapper(boost::shared_ptr<FslogicProxy>(new FslogicProxy()))), boost::shared_ptr<helpers::StorageHelperFactory>(new helpers::StorageHelperFactory()))); // Enter FUSE loop if (multithreaded) res = fuse_loop_mt(fuse); else res = fuse_loop(fuse); if (res == -1) res = 1; else res = 0; // Cleanup fuse_remove_signal_handlers(fuse_get_session(fuse)); fuse_unmount(mountpoint, ch); fuse_destroy(fuse); free(mountpoint); return res; } <commit_msg>VFS-292: fix config path<commit_after>/** * @file veilFuse.cc * @author Rafal Slota * @copyright (C) 2013 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in 'LICENSE.txt' */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef linux /* For pread()/pwrite()/utimensat() */ #define _XOPEN_SOURCE 700 #endif #include <fuse.h> #include <fuse/fuse_opt.h> #include <fuse/fuse_lowlevel.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <dirent.h> #ifdef HAVE_SETXATTR #include <sys/xattr.h> #endif #include <boost/filesystem.hpp> #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include "veilfs.h" #include "config.h" #include "gsiHandler.h" #include "glog/logging.h" using namespace std; using namespace boost; using namespace veil; using namespace veil::client; using boost::filesystem::path; /// Main application object (filesystem state) boost::shared_ptr<VeilFS> VeilAppObject; #ifdef __cplusplus extern "C" { #endif static int wrap_access(const char *path, int mask) { return VeilAppObject->access(path, mask); } static int wrap_getattr(const char *path, struct stat *statbuf) { return VeilAppObject->getattr(path, statbuf); } static int wrap_readlink(const char *path, char *link, size_t size) { return VeilAppObject->readlink(path, link, size); } static int wrap_mknod(const char *path, mode_t mode, dev_t dev) { return VeilAppObject->mknod(path, mode, dev); } static int wrap_mkdir(const char *path, mode_t mode) { return VeilAppObject->mkdir(path, mode); } static int wrap_unlink(const char *path) { return VeilAppObject->unlink(path); } static int wrap_rmdir(const char *path) { return VeilAppObject->rmdir(path); } static int wrap_symlink(const char *path, const char *link) { return VeilAppObject->symlink(path, link); } static int wrap_rename(const char *path, const char *newpath) { return VeilAppObject->rename(path, newpath); } static int wrap_link(const char *path, const char *newpath) { return VeilAppObject->link(path, newpath); } static int wrap_chmod(const char *path, mode_t mode) { return VeilAppObject->chmod(path, mode); } static int wrap_chown(const char *path, uid_t uid, gid_t gid) { return VeilAppObject->chown(path, uid, gid); } static int wrap_truncate(const char *path, off_t newSize) { return VeilAppObject->truncate(path, newSize); } static int wrap_utime(const char *path, struct utimbuf *ubuf) { return VeilAppObject->utime(path, ubuf); } static int wrap_open(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->open(path, fileInfo); } static int wrap_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return VeilAppObject->read(path, buf, size, offset, fileInfo); } static int wrap_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return VeilAppObject->write(path, buf, size, offset, fileInfo); } static int wrap_statfs(const char *path, struct statvfs *statInfo) { return VeilAppObject->statfs(path, statInfo); } static int wrap_flush(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->flush(path, fileInfo); } static int wrap_release(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->release(path, fileInfo); } static int wrap_fsync(const char *path, int datasync, struct fuse_file_info *fi) { return VeilAppObject->fsync(path, datasync, fi); } #ifdef HAVE_SETXATTR static int wrap_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { return VeilAppObject->setxattr(path, name, value, size, flags); } static int wrap_getxattr(const char *path, const char *name, char *value, size_t size) { return VeilAppObject->getxattr(path, name, value, size); } static int wrap_listxattr(const char *path, char *list, size_t size) { return VeilAppObject->listxattr(path, list, size); } static int wrap_removexattr(const char *path, const char *name) { return VeilAppObject->removexattr(path, name); } #endif // HAVE_SETXATTR static int wrap_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo) { return VeilAppObject->readdir(path, buf, filler, offset, fileInfo); } static int wrap_opendir(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->opendir(path, fileInfo); } static int wrap_releasedir(const char *path, struct fuse_file_info *fileInfo) { return VeilAppObject->releasedir(path, fileInfo); } static int wrap_fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo) { return VeilAppObject->fsyncdir(path, datasync, fileInfo); } // static int wrap_init(struct fuse_conn_info *conn) { // return VeilAppObject->init(conn); // } static int vfs_opt_proc(void *data, const char *arg, int key, struct fuse_args *outargs) { if(string(arg).find(CONFIG_ARGV_OPT_NAME) != string::npos) return 0; if(string(arg) == "-debug") return 0; return 1; } #ifdef __cplusplus } #endif static struct fuse_operations vfs_oper; static void oper_init() { vfs_oper.getattr = wrap_getattr; vfs_oper.access = wrap_access; vfs_oper.readlink = wrap_readlink; vfs_oper.readdir = wrap_readdir; vfs_oper.mknod = wrap_mknod; vfs_oper.mkdir = wrap_mkdir; vfs_oper.symlink = wrap_symlink; vfs_oper.unlink = wrap_unlink; vfs_oper.rmdir = wrap_rmdir; vfs_oper.rename = wrap_rename; vfs_oper.link = wrap_link; vfs_oper.chmod = wrap_chmod; vfs_oper.chown = wrap_chown; vfs_oper.truncate = wrap_truncate; #ifdef HAVE_UTIMENSAT vfs_oper.utimens = wrap_utimens; #endif vfs_oper.open = wrap_open; vfs_oper.read = wrap_read; vfs_oper.write = wrap_write; vfs_oper.statfs = wrap_statfs; vfs_oper.release = wrap_release; vfs_oper.fsync = wrap_fsync; vfs_oper.utime = wrap_utime; vfs_oper.flush = wrap_flush; vfs_oper.opendir = wrap_opendir; vfs_oper.releasedir = wrap_releasedir; vfs_oper.fsyncdir = wrap_fsyncdir; #ifdef HAVE_POSIX_FALLOCATE vfs_oper.fallocate = wrap_fallocate; #endif #ifdef HAVE_SETXATTR vfs_oper.setxattr = wrap_setxattr; vfs_oper.getxattr = wrap_getxattr; vfs_oper.listxattr = wrap_listxattr; vfs_oper.removexattr= wrap_removexattr; #endif } static void fuse_init() { //LOG(INFO) << "Intializing fuse callbacks"; oper_init(); } #include "gsi_utils.h" int main(int argc, char* argv[], char* envp[]) { // Turn off logging for a while google::InitGoogleLogging(argv[0]); FLAGS_alsologtostderr = false; FLAGS_logtostderr = false; FLAGS_stderrthreshold = 3; // Initialize FUSE umask(0); fuse_init(); struct fuse_args args = FUSE_ARGS_INIT(argc, argv); fuse_opt_parse(&args, NULL, NULL, vfs_opt_proc); // Enforced FUSE options fuse_opt_add_arg(&args, "-obig_writes"); bool debug = false; // Assume silent mode boost::shared_ptr<Config> config(new Config()); VeilFS::setConfig(config); // Find user config argument for(int i = 1; i < argc; ++i) { if(string(argv[i]).find(CONFIG_ARGV_OPT_NAME) != string::npos) { config->setUserConfigFile(string(argv[i]).substr(string(CONFIG_ARGV_OPT_NAME).size())); } if(string(argv[i]) == "-d") // FUSE's debug flag debug = true; if(string(argv[i]) == "-debug") // GSI Handler's debug flag gsi::debug = true; } // Setup config manager and paths path binDir = path(string(argv[0])).branch_path(); path etcDir = binDir / ".." / VeilClient_CONFIG_DIR; string configFile = GLOBAL_CONFIG_FILE; // if(filesystem::exists(etcDir / GLOBAL_CONFIG_FILE)) { // configFile = (etcDir / GLOBAL_CONFIG_FILE).string(); // } config->setGlobalConfigFile(configFile); if(!config->parseConfig()) { std::cerr << "Cannot load/parse global/user config file. Check logs for more detials. Aborting" << std::endl; exit(1); } // proper logger setup if(config->isSet(LOG_DIR_OPT)) { string log_path = Config::absPathRelToCWD(config->getString(LOG_DIR_OPT)); if(log_path != "/tmp") { FLAGS_log_dir = log_path; LOG(INFO) << "Setting log dir to: " << log_path; // Restart Google Loggler in order ot reload log_dir path google::ShutdownGoogleLogging(); google::InitGoogleLogging(argv[0]); } } FLAGS_alsologtostderr = debug; FLAGS_logtostderr = debug; if(debug) FLAGS_stderrthreshold = 2; // Iterate over all env variables and save them in Config char** env; for (env = envp; *env != 0; env++) { std::vector<std::string> tokens; std::string tEnv = std::string(*env); boost::split(tokens, tEnv, boost::is_any_of("=")); if(tokens.size() != 2) // Invalid env variable. Expected format: NAME=VALUE continue; Config::putEnv(tokens[0], tokens[1]); } // FUSE main: struct fuse *fuse; struct fuse_chan *ch; char *mountpoint; int multithreaded; int foreground; int res; res = fuse_parse_cmdline(&args, &mountpoint, &multithreaded, &foreground); if (res == -1) exit(1); ch = fuse_mount(mountpoint, &args); if (!ch) exit(1); res = fcntl(fuse_chan_fd(ch), F_SETFD, FD_CLOEXEC); if (res == -1) perror("WARNING: failed to set FD_CLOEXEC on fuse device"); fuse = fuse_new(ch, &args, &vfs_oper, sizeof(struct fuse_operations), NULL); if (fuse == NULL) { fuse_unmount(mountpoint, ch); exit(1); } fuse_set_signal_handlers(fuse_get_session(fuse)); // Check proxy certificate if(!gsi::validateProxyConfig()) { std::cerr << "Cannot continue. Aborting" << std::endl; fuse_unmount(mountpoint, ch); exit(1); } LOG(INFO) << "Proxy certificate to be used: " << gsi::getProxyCertPath(); cout << "VeilFS has been successfully mounted in " + string(mountpoint) << endl; fuse_remove_signal_handlers(fuse_get_session(fuse)); res = fuse_daemonize(foreground); if (res != -1) res = fuse_set_signal_handlers(fuse_get_session(fuse)); if (res == -1) { fuse_unmount(mountpoint, ch); fuse_destroy(fuse); exit(1); } // Initialize VeilClient application VeilFS::setConnectionPool(boost::shared_ptr<SimpleConnectionPool> ( new SimpleConnectionPool(gsi::getClusterHostname(), config->getInt(CLUSTER_PORT_OPT), gsi::getProxyCertPath(), gsi::validateProxyCert))); // Setup veilhelpers config veil::helpers::config::setConnectionPool(VeilFS::getConnectionPool()); veil::helpers::config::buffers::writeBufferGlobalSizeLimit = config->getInt(WRITE_BUFFER_MAX_SIZE_OPT); veil::helpers::config::buffers::readBufferGlobalSizeLimit = config->getInt(READ_BUFFER_MAX_SIZE_OPT); veil::helpers::config::buffers::writeBufferPerFileSizeLimit = config->getInt(WRITE_BUFFER_MAX_FILE_SIZE_OPT); veil::helpers::config::buffers::readBufferPerFileSizeLimit = config->getInt(READ_BUFFER_MAX_FILE_SIZE_OPT); veil::helpers::config::buffers::preferedBlockSize = config->getInt(FILE_BUFFER_PREFERED_BLOCK_SIZE_OPT); // Maximum connection count setup VeilFS::getConnectionPool()->setPoolSize(SimpleConnectionPool::META_POOL, config->getInt(ALIVE_META_CONNECTIONS_COUNT_OPT)); VeilFS::getConnectionPool()->setPoolSize(SimpleConnectionPool::DATA_POOL, config->getInt(ALIVE_DATA_CONNECTIONS_COUNT_OPT)); // Start all jobSchedulers for(int i = 1; i < config->getInt(JOBSCHEDULER_THREADS_OPT); ++i) VeilFS::addScheduler(boost::shared_ptr<JobScheduler>(new JobScheduler())); // Initialize main application object VeilAppObject.reset(new VeilFS(mountpoint, config, boost::shared_ptr<JobScheduler>(new JobScheduler()), boost::shared_ptr<FslogicProxy>(new FslogicProxy()), boost::shared_ptr<MetaCache>(new MetaCache()), boost::shared_ptr<StorageMapper>(new StorageMapper(boost::shared_ptr<FslogicProxy>(new FslogicProxy()))), boost::shared_ptr<helpers::StorageHelperFactory>(new helpers::StorageHelperFactory()))); // Enter FUSE loop if (multithreaded) res = fuse_loop_mt(fuse); else res = fuse_loop(fuse); if (res == -1) res = 1; else res = 0; // Cleanup fuse_remove_signal_handlers(fuse_get_session(fuse)); fuse_unmount(mountpoint, ch); fuse_destroy(fuse); free(mountpoint); return res; } <|endoftext|>
<commit_before>#include <stdio.h> // printf #include <math.h> // sin #include <time.h> // time #include <stdlib.h> // srand #include <string.h> // memcpy #include <vector> #include <vorbis/vorbisenc.h> struct tEncoderState { ogg_stream_state os; vorbis_info vi; vorbis_comment vc; vorbis_dsp_state vd; vorbis_block vb; ogg_packet op; int packet_id; int rate; int num_channels; int sample_rate; int granulepos; std::vector<unsigned char> output_buffer; }; static inline void append(std::vector<unsigned char> &v, unsigned char *p, long n) { v.insert(end(v), p, p + n); } // write encoded ogg page to a file or buffer void write_page(tEncoderState* state, ogg_page* page) { append(state->output_buffer, page->header, page->header_len); append(state->output_buffer, page->body, page->body_len); } // preps encoder, allocates output buffer extern "C" tEncoderState* lexy_encoder_start(int sample_rate = 48000, float vbr_quality = 0.4f) { tEncoderState *state = new tEncoderState(); state->packet_id = 0; state->granulepos = 0; srand(time(NULL)); ogg_stream_init(&state->os, rand()); int size, error; state->num_channels = 2; state->sample_rate = sample_rate; #if DEBUG printf("lexy_encoder_start(); initializing vorbis encoder with sample_rate = %i Hz and vbr quality = %3.2f\n", state->sample_rate, vbr_quality); #endif // initialize vorbis vorbis_info_init(&state->vi); if(vorbis_encode_init_vbr(&state->vi, 2, state->sample_rate, vbr_quality)) // vbr //if(vorbis_encode_init(&state->vi,state->num_channels,sample_rate,-1,192000,-1)) // abr { #if DEBUG printf("lexy_encoder_start(); error initializing vorbis encoder\n"); #endif return NULL; } vorbis_comment_init(&state->vc); vorbis_comment_add_tag(&state->vc, "ENCODER", "lexy-coder"); vorbis_analysis_init(&state->vd, &state->vi); vorbis_block_init(&state->vd, &state->vb); ogg_packet vorbis_header, vorbis_header_comment, vorbis_header_code; // write out vorbis's headers vorbis_analysis_headerout(&state->vd, &state->vc, &vorbis_header, &vorbis_header_comment, &vorbis_header_code); ogg_stream_packetin(&state->os, &vorbis_header); ogg_stream_packetin(&state->os, &vorbis_header_comment); ogg_stream_packetin(&state->os, &vorbis_header_code); ogg_page og; // flush packet into its own page while(ogg_stream_flush(&state->os, &og)) write_page(state, &og); return state; } // input should be more than 10ms long extern "C" void lexy_encoder_write(tEncoderState* state, float* input_buffer_left, float* input_buffer_right, int num_samples) { unsigned char* ogg_buffer = new unsigned char[state->rate]; // get space in which to copy uncompressed data float** buffer = vorbis_analysis_buffer(&state->vd, num_samples); // write uncompressed data memcpy(buffer[0], input_buffer_left, num_samples * sizeof(float)); memcpy(buffer[1], input_buffer_right, num_samples * sizeof(float)); vorbis_analysis_wrote(&state->vd, num_samples); ogg_page og; int num_packets = 0; while(vorbis_analysis_blockout(&state->vd, &state->vb) == 1) { vorbis_analysis(&state->vb, NULL); vorbis_bitrate_addblock(&state->vb); while(vorbis_bitrate_flushpacket(&state->vd, &state->op)) { // push packet into ogg ogg_stream_packetin(&state->os, &state->op); num_packets++; // fetch page from ogg while(ogg_stream_pageout(&state->os, &og) || (state->op.e_o_s && ogg_stream_flush(&state->os, &og))) { #if DEBUG printf("lexy_encoder_write(); writing ogg samples page after packet %i\n", num_packets); #endif write_page(state, &og); } } } } // finish encoding extern "C" void lexy_encoder_finish(tEncoderState* state) { #if DEBUG printf("lexy_encoder_finish(); ending stream\n"); #endif // write an end-of-stream packet vorbis_analysis_wrote(&state->vd, 0); ogg_page og; while(vorbis_analysis_blockout(&state->vd, &state->vb) == 1) { vorbis_analysis(&state->vb, NULL); vorbis_bitrate_addblock(&state->vb); while(vorbis_bitrate_flushpacket(&state->vd, &state->op)) { ogg_stream_packetin(&state->os, &state->op); while(ogg_stream_flush(&state->os, &og)) write_page(state, &og); } } #if DEBUG printf("lexy_encoder_finish(); final encoded stream length: %i bytes\n", state->output_buffer.size()); printf("lexy_encoder_finish(); cleaning up\n"); #endif ogg_stream_clear(&state->os); vorbis_block_clear(&state->vb); vorbis_dsp_clear(&state->vd); vorbis_comment_clear(&state->vc); vorbis_info_clear(&state->vi); } // grab buffer and its length extern "C" unsigned char* lexy_get_buffer(tEncoderState* state) { return state->output_buffer.data(); } extern "C" int lexy_get_buffer_length(tEncoderState* state) { return state->output_buffer.size(); } #if DEBUG // complete encoder test: init, encode, shutdown. extern "C" tEncoderState* lexy_test() { tEncoderState *state = lexy_encoder_start(); // generate a test sound float* input_buffer_left = new float[state->sample_rate]; // one second long buffer float* input_buffer_right = new float[state->sample_rate]; // one second long buffer float test_frequency = 400; // hz for(int i = 0; i < state->sample_rate; i ++) { float fraction = (float) i / (float) state->sample_rate; input_buffer_left[i] = sin(M_PI * 2 * test_frequency * fraction); input_buffer_right[i] = sin(M_PI * 2 * test_frequency * fraction); } lexy_encoder_write(state, input_buffer_left, input_buffer_right, state->sample_rate); lexy_encoder_finish(state); return state; } // encodes a test signal extern "C" void lexy_write_test(tEncoderState *state) { printf("lexy_write_test(); writing test sound at %i samples/sec with %i channels\n", state->sample_rate, state->num_channels); // generate a test sound float* input_buffer_left = new float[state->sample_rate]; // one second long buffer float* input_buffer_right = new float[state->sample_rate]; // one second long buffer float test_frequency = 400; // hz for(int i = 0; i < state->sample_rate; i ++) { float fraction = (float) i / (float) state->sample_rate; input_buffer_left[i] = sin(M_PI * 2 * test_frequency * fraction); input_buffer_right[i] = sin(M_PI * 2 * test_frequency * fraction); } lexy_encoder_write(state, input_buffer_left, input_buffer_right, state->sample_rate); } // for testing in console extern "C" int main() { lexy_test(); return 0; } #endif <commit_msg>remove unused line<commit_after>#include <stdio.h> // printf #include <math.h> // sin #include <time.h> // time #include <stdlib.h> // srand #include <string.h> // memcpy #include <vector> #include <vorbis/vorbisenc.h> struct tEncoderState { ogg_stream_state os; vorbis_info vi; vorbis_comment vc; vorbis_dsp_state vd; vorbis_block vb; ogg_packet op; int packet_id; int rate; int num_channels; int sample_rate; int granulepos; std::vector<unsigned char> output_buffer; }; static inline void append(std::vector<unsigned char> &v, unsigned char *p, long n) { v.insert(end(v), p, p + n); } // write encoded ogg page to a file or buffer void write_page(tEncoderState* state, ogg_page* page) { append(state->output_buffer, page->header, page->header_len); append(state->output_buffer, page->body, page->body_len); } // preps encoder, allocates output buffer extern "C" tEncoderState* lexy_encoder_start(int sample_rate = 48000, float vbr_quality = 0.4f) { tEncoderState *state = new tEncoderState(); state->packet_id = 0; state->granulepos = 0; srand(time(NULL)); ogg_stream_init(&state->os, rand()); int size, error; state->num_channels = 2; state->sample_rate = sample_rate; #if DEBUG printf("lexy_encoder_start(); initializing vorbis encoder with sample_rate = %i Hz and vbr quality = %3.2f\n", state->sample_rate, vbr_quality); #endif // initialize vorbis vorbis_info_init(&state->vi); if(vorbis_encode_init_vbr(&state->vi, 2, state->sample_rate, vbr_quality)) // vbr //if(vorbis_encode_init(&state->vi,state->num_channels,sample_rate,-1,192000,-1)) // abr { #if DEBUG printf("lexy_encoder_start(); error initializing vorbis encoder\n"); #endif return NULL; } vorbis_comment_init(&state->vc); vorbis_comment_add_tag(&state->vc, "ENCODER", "lexy-coder"); vorbis_analysis_init(&state->vd, &state->vi); vorbis_block_init(&state->vd, &state->vb); ogg_packet vorbis_header, vorbis_header_comment, vorbis_header_code; // write out vorbis's headers vorbis_analysis_headerout(&state->vd, &state->vc, &vorbis_header, &vorbis_header_comment, &vorbis_header_code); ogg_stream_packetin(&state->os, &vorbis_header); ogg_stream_packetin(&state->os, &vorbis_header_comment); ogg_stream_packetin(&state->os, &vorbis_header_code); ogg_page og; // flush packet into its own page while(ogg_stream_flush(&state->os, &og)) write_page(state, &og); return state; } // input should be more than 10ms long extern "C" void lexy_encoder_write(tEncoderState* state, float* input_buffer_left, float* input_buffer_right, int num_samples) { // get space in which to copy uncompressed data float** buffer = vorbis_analysis_buffer(&state->vd, num_samples); // write uncompressed data memcpy(buffer[0], input_buffer_left, num_samples * sizeof(float)); memcpy(buffer[1], input_buffer_right, num_samples * sizeof(float)); vorbis_analysis_wrote(&state->vd, num_samples); ogg_page og; int num_packets = 0; while(vorbis_analysis_blockout(&state->vd, &state->vb) == 1) { vorbis_analysis(&state->vb, NULL); vorbis_bitrate_addblock(&state->vb); while(vorbis_bitrate_flushpacket(&state->vd, &state->op)) { // push packet into ogg ogg_stream_packetin(&state->os, &state->op); num_packets++; // fetch page from ogg while(ogg_stream_pageout(&state->os, &og) || (state->op.e_o_s && ogg_stream_flush(&state->os, &og))) { #if DEBUG printf("lexy_encoder_write(); writing ogg samples page after packet %i\n", num_packets); #endif write_page(state, &og); } } } } // finish encoding extern "C" void lexy_encoder_finish(tEncoderState* state) { #if DEBUG printf("lexy_encoder_finish(); ending stream\n"); #endif // write an end-of-stream packet vorbis_analysis_wrote(&state->vd, 0); ogg_page og; while(vorbis_analysis_blockout(&state->vd, &state->vb) == 1) { vorbis_analysis(&state->vb, NULL); vorbis_bitrate_addblock(&state->vb); while(vorbis_bitrate_flushpacket(&state->vd, &state->op)) { ogg_stream_packetin(&state->os, &state->op); while(ogg_stream_flush(&state->os, &og)) write_page(state, &og); } } #if DEBUG printf("lexy_encoder_finish(); final encoded stream length: %i bytes\n", state->output_buffer.size()); printf("lexy_encoder_finish(); cleaning up\n"); #endif ogg_stream_clear(&state->os); vorbis_block_clear(&state->vb); vorbis_dsp_clear(&state->vd); vorbis_comment_clear(&state->vc); vorbis_info_clear(&state->vi); } // grab buffer and its length extern "C" unsigned char* lexy_get_buffer(tEncoderState* state) { return state->output_buffer.data(); } extern "C" int lexy_get_buffer_length(tEncoderState* state) { return state->output_buffer.size(); } #if DEBUG // complete encoder test: init, encode, shutdown. extern "C" tEncoderState* lexy_test() { tEncoderState *state = lexy_encoder_start(); // generate a test sound float* input_buffer_left = new float[state->sample_rate]; // one second long buffer float* input_buffer_right = new float[state->sample_rate]; // one second long buffer float test_frequency = 400; // hz for(int i = 0; i < state->sample_rate; i ++) { float fraction = (float) i / (float) state->sample_rate; input_buffer_left[i] = sin(M_PI * 2 * test_frequency * fraction); input_buffer_right[i] = sin(M_PI * 2 * test_frequency * fraction); } lexy_encoder_write(state, input_buffer_left, input_buffer_right, state->sample_rate); lexy_encoder_finish(state); return state; } // encodes a test signal extern "C" void lexy_write_test(tEncoderState *state) { printf("lexy_write_test(); writing test sound at %i samples/sec with %i channels\n", state->sample_rate, state->num_channels); // generate a test sound float* input_buffer_left = new float[state->sample_rate]; // one second long buffer float* input_buffer_right = new float[state->sample_rate]; // one second long buffer float test_frequency = 400; // hz for(int i = 0; i < state->sample_rate; i ++) { float fraction = (float) i / (float) state->sample_rate; input_buffer_left[i] = sin(M_PI * 2 * test_frequency * fraction); input_buffer_right[i] = sin(M_PI * 2 * test_frequency * fraction); } lexy_encoder_write(state, input_buffer_left, input_buffer_right, state->sample_rate); } // for testing in console extern "C" int main() { lexy_test(); return 0; } #endif <|endoftext|>
<commit_before>// @(#)root/mathcore:$Id$ // Author: L. Moneta Wed Aug 30 11:10:03 2006 /********************************************************************** * * * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT * * * * * **********************************************************************/ // Implementation file for class UnBinData #include "Fit/UnBinData.h" #include "Math/Error.h" #include <cassert> #include <cmath> namespace ROOT { namespace Fit { UnBinData::UnBinData(unsigned int maxpoints, unsigned int dim ) : FitData(), fDim(dim), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor with default option and range unsigned int n = dim*maxpoints; if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) fDataVector = new DataVector(n); } UnBinData::UnBinData (const DataRange & range, unsigned int maxpoints , unsigned int dim ) : FitData(range), fDim(dim), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor from option and default range unsigned int n = dim*maxpoints; if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) fDataVector = new DataVector(n); } UnBinData::UnBinData (const DataOptions & opt, const DataRange & range, unsigned int maxpoints, unsigned int dim ) : FitData( opt, range), fDim(dim), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor from options and range unsigned int n = dim*maxpoints; if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) fDataVector = new DataVector(n); } UnBinData::UnBinData(unsigned int n, const double * dataX ) : FitData( ), fDim(1), fNPoints(n), fDataVector(0) { // constructor for 1D external data fDataWrapper = new DataWrapper(dataX); } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY ) : FitData( ), fDim(2), fNPoints(n), fDataVector(0), fDataWrapper(0) { // constructor for 2D external data fDataWrapper = new DataWrapper(dataX, dataY, 0, 0, 0, 0); } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY, const double * dataZ ) : FitData( ), fDim(3), fNPoints(n), fDataVector(0) { // constructor for 3D external data fDataWrapper = new DataWrapper(dataX, dataY, dataZ, 0, 0, 0, 0, 0); } UnBinData::UnBinData(unsigned int n, const double * dataX, const DataRange & range ) : FitData(range), fDim(1), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor for 1D array data using a range to select the data if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) { fDataVector = new DataVector(n); for (unsigned int i = 0; i < n; ++i) if ( range.IsInside(dataX[i]) ) Add(dataX[i] ); if (fNPoints < n) (fDataVector->Data()).resize(fNPoints); } } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY, const DataRange & range ) : FitData(range), fDim(2), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor for 2D array data using a range to select the data if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) { fDataVector = new DataVector(2*n); for (unsigned int i = 0; i < n; ++i) if ( range.IsInside(dataX[i],0) && range.IsInside(dataY[i],1) ) Add(dataX[i], dataY[i] ); if (fNPoints < n) (fDataVector->Data()).resize(2*fNPoints); } } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY, const double * dataZ, const DataRange & range ) : FitData(range ), fDim(3), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor for 3D array data using a range to select the data if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) { fDataVector = new DataVector(3*n); for (unsigned int i = 0; i < n; ++i) if ( range.IsInside(dataX[i],0) && range.IsInside(dataY[i],1) && range.IsInside(dataZ[i],2) ) Add(dataX[i], dataY[i], dataZ[i] ); if (fNPoints < n) (fDataVector->Data()).resize(3*fNPoints); } } void UnBinData::Initialize(unsigned int maxpoints, unsigned int dim ) { // preallocate a data set given size and dimension if ( dim != fDim && fDataVector) { // MATH_INFO_MSGVAL("BinData::Initialize"," Reset amd re-initialize with a new fit point size of ", // dim); delete fDataVector; fDataVector = 0; } fDim = dim; unsigned int n = fDim*maxpoints; if ( n > MaxSize() ) { MATH_ERROR_MSGVAL("UnBinData::Initialize","Invalid data size", n ); return; } if (fDataVector) (fDataVector->Data()).resize( fDataVector->Size() + n ); else fDataVector = new DataVector( n); } void UnBinData::Resize(unsigned int npoints) { // resize vector to new points if (fDim == 0) return; if ( npoints > MaxSize() ) { MATH_ERROR_MSGVAL("BinData::Resize"," Invalid data size ", npoints ); return; } int nextraPoints = npoints - DataSize()/fDim; if (nextraPoints == 0) return; else if (nextraPoints < 0) { // delete extra points if (!fDataVector) return; (fDataVector->Data()).resize( npoints * fDim); } else Initialize(nextraPoints, fDim ); } } // end namespace Fit } // end namespace ROOT <commit_msg>fix coding convention<commit_after>// @(#)root/mathcore:$Id$ // Author: L. Moneta Wed Aug 30 11:10:03 2006 /********************************************************************** * * * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT * * * * * **********************************************************************/ // Implementation file for class UnBinData #include "Fit/UnBinData.h" #include "Math/Error.h" #include <cassert> #include <cmath> namespace ROOT { namespace Fit { UnBinData::UnBinData(unsigned int maxpoints, unsigned int dim ) : FitData(), fDim(dim), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor with default option and range unsigned int n = dim*maxpoints; if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) fDataVector = new DataVector(n); } UnBinData::UnBinData (const DataRange & range, unsigned int maxpoints , unsigned int dim ) : FitData(range), fDim(dim), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor from option and default range unsigned int n = dim*maxpoints; if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) fDataVector = new DataVector(n); } UnBinData::UnBinData (const DataOptions & opt, const DataRange & range, unsigned int maxpoints, unsigned int dim ) : FitData( opt, range), fDim(dim), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor from options and range unsigned int n = dim*maxpoints; if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) fDataVector = new DataVector(n); } UnBinData::UnBinData(unsigned int n, const double * dataX ) : FitData( ), fDim(1), fNPoints(n), fDataVector(0) { // constructor for 1D external data fDataWrapper = new DataWrapper(dataX); } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY ) : FitData( ), fDim(2), fNPoints(n), fDataVector(0), fDataWrapper(0) { // constructor for 2D external data fDataWrapper = new DataWrapper(dataX, dataY, 0, 0, 0, 0); } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY, const double * dataZ ) : FitData( ), fDim(3), fNPoints(n), fDataVector(0) { // constructor for 3D external data fDataWrapper = new DataWrapper(dataX, dataY, dataZ, 0, 0, 0, 0, 0); } UnBinData::UnBinData(unsigned int n, const double * dataX, const DataRange & range ) : FitData(range), fDim(1), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor for 1D array data using a range to select the data if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) { fDataVector = new DataVector(n); for (unsigned int i = 0; i < n; ++i) if ( range.IsInside(dataX[i]) ) Add(dataX[i] ); if (fNPoints < n) (fDataVector->Data()).resize(fNPoints); } } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY, const DataRange & range ) : FitData(range), fDim(2), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor for 2D array data using a range to select the data if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) { fDataVector = new DataVector(2*n); for (unsigned int i = 0; i < n; ++i) if ( range.IsInside(dataX[i],0) && range.IsInside(dataY[i],1) ) Add(dataX[i], dataY[i] ); if (fNPoints < n) (fDataVector->Data()).resize(2*fNPoints); } } UnBinData::UnBinData(unsigned int n, const double * dataX, const double * dataY, const double * dataZ, const DataRange & range ) : FitData(range ), fDim(3), fNPoints(0), fDataVector(0), fDataWrapper(0) { // constructor for 3D array data using a range to select the data if ( n > MaxSize() ) MATH_ERROR_MSGVAL("UnBinData","Invalid data size n - no allocation done", n ) else if (n > 0) { fDataVector = new DataVector(3*n); for (unsigned int i = 0; i < n; ++i) if ( range.IsInside(dataX[i],0) && range.IsInside(dataY[i],1) && range.IsInside(dataZ[i],2) ) Add(dataX[i], dataY[i], dataZ[i] ); if (fNPoints < n) (fDataVector->Data()).resize(3*fNPoints); } } void UnBinData::Initialize(unsigned int maxpoints, unsigned int dim ) { // preallocate a data set given size and dimension if ( dim != fDim && fDataVector) { // MATH_INFO_MSGVAL("BinData::Initialize"," Reset amd re-initialize with a new fit point size of ", // dim); delete fDataVector; fDataVector = 0; } fDim = dim; unsigned int n = fDim*maxpoints; if ( n > MaxSize() ) { MATH_ERROR_MSGVAL("UnBinData::Initialize","Invalid data size", n ); return; } if (fDataVector) (fDataVector->Data()).resize( fDataVector->Size() + n ); else fDataVector = new DataVector( n); } void UnBinData::Resize(unsigned int npoints) { // resize vector to new points if (fDim == 0) return; if ( npoints > MaxSize() ) { MATH_ERROR_MSGVAL("BinData::Resize"," Invalid data size ", npoints ); return; } int nextraPoints = npoints - DataSize()/fDim; if (nextraPoints == 0) return; else if (nextraPoints < 0) { // delete extra points if (!fDataVector) return; (fDataVector->Data()).resize( npoints * fDim); } else Initialize(nextraPoints, fDim ); } } // end namespace Fit } // end namespace ROOT <|endoftext|>
<commit_before>#ifndef mmm_hpp #define mmm_hpp #include <cstddef> #include <cstdlib> #include <type_traits> #include <utility> #include <cmath> #include <iostream> /* TODO: be consistent about using upper case for template vars change all mentions of size_t n to size_t N also Elems, and L, -------------------------------------------------------- typefu/ traits restrict promote components gen mat/ swizzle/ swizzle swizzle1 opr/ asig enum vec/ mostly complete vecType no explicit tests tvec complete! tvec2 no explicit tests opr/ complete! asig complete! enum complete! num complete! comp complete! io complete! func/ lacking some functions trig failed test 'atan2'! exp complete! common 2 missing: smoothstep geo 3 missing: faceforward, reflect, refract rel complete! reduct complete! io complete! */ #include <typefu/traits.hpp> #include <typefu/restrict.hpp> #include <typefu/promote.hpp> #include <typefu/components.hpp> #include <typefu/gen.hpp> #include <vec/vecType.hpp> #include <swizzle/swizzle.hpp> #include <swizzle/swizzle1.hpp> #include <vec/tvec.hpp> #include <vec/tvec2.hpp> #include <vec/opr/asig.hpp> #include <vec/opr/enum.hpp> #include <vec/opr/num.hpp> #include <vec/opr/comp.hpp> #include <vec/opr/io.hpp> #include <vec/func/trig.hpp> #include <vec/func/exp.hpp> #include <vec/func/common.hpp> #include <vec/func/geo.hpp> #include <vec/func/rel.hpp> #include <vec/func/reduct.hpp> #include <vec/func/io.hpp> #include <vec/vecType.tpp> #include <swizzle/swizzle.tpp> #include <swizzle/swizzle1.tpp> #include <vec/tvec.tpp> #include <vec/tvec2.tpp> #include <vec/opr/asig.tpp> #include <vec/opr/enum.tpp> #include <vec/opr/num.tpp> #include <vec/opr/comp.tpp> #include <vec/opr/io.tpp> #include <vec/func/trig.tpp> #include <vec/func/exp.tpp> #include <vec/func/common.tpp> #include <vec/func/geo.tpp> #include <vec/func/rel.tpp> #include <vec/func/reduct.tpp> #include <vec/func/io.tpp> template <size_t n> using vec = tvec<float,n>; template <size_t n> using dvec = tvec<double,n>; template <size_t n> using bvec = tvec<bool,n>; template <size_t n> using ivec = tvec<int,n>; template <size_t n> using uvec = tvec<unsigned int,n>; typedef vec<2> vec2; typedef vec<3> vec3; typedef vec<4> vec4; typedef dvec<2> dvec2; typedef dvec<3> dvec3; typedef dvec<4> dvec4; typedef bvec<2> bvec2; typedef bvec<3> bvec3; typedef bvec<4> bvec4; typedef ivec<2> ivec2; typedef ivec<3> ivec3; typedef ivec<4> ivec4; typedef uvec<2> uvec2; typedef uvec<3> uvec3; typedef uvec<4> uvec4; #endif<commit_msg>changed from typedefs to using c++11 type alias<commit_after>#ifndef mmm_hpp #define mmm_hpp #include <cstddef> #include <cstdlib> #include <type_traits> #include <utility> #include <cmath> #include <iostream> #include <typefu/traits.hpp> #include <typefu/restrict.hpp> #include <typefu/promote.hpp> #include <typefu/components.hpp> #include <typefu/gen.hpp> #include <vec/vecType.hpp> #include <swizzle/swizzle.hpp> #include <swizzle/swizzle1.hpp> #include <vec/tvec.hpp> #include <vec/tvec2.hpp> #include <vec/opr/asig.hpp> #include <vec/opr/enum.hpp> #include <vec/opr/num.hpp> #include <vec/opr/comp.hpp> #include <vec/opr/io.hpp> #include <vec/func/trig.hpp> #include <vec/func/exp.hpp> #include <vec/func/common.hpp> #include <vec/func/geo.hpp> #include <vec/func/rel.hpp> #include <vec/func/reduct.hpp> #include <vec/func/io.hpp> #include <vec/vecType.tpp> #include <swizzle/swizzle.tpp> #include <swizzle/swizzle1.tpp> #include <vec/tvec.tpp> #include <vec/tvec2.tpp> #include <vec/opr/asig.tpp> #include <vec/opr/enum.tpp> #include <vec/opr/num.tpp> #include <vec/opr/comp.tpp> #include <vec/opr/io.tpp> #include <vec/func/trig.tpp> #include <vec/func/exp.tpp> #include <vec/func/common.tpp> #include <vec/func/geo.tpp> #include <vec/func/rel.tpp> #include <vec/func/reduct.tpp> #include <vec/func/io.tpp> template <size_t n> using vec = tvec<float,n>; using vec2 = vec<2>; using vec3 = vec<3>; using vec4 = vec<4>; template <size_t n> using dvec = tvec<double,n>; using dvec2 = dvec<2>; using dvec3 = dvec<3>; using dvec4 = dvec<4>; template <size_t n> using bvec = tvec<bool,n>; using bvec2 = bvec<2>; using bvec3 = bvec<3>; using bvec4 = bvec<4>; template <size_t n> using ivec = tvec<int,n>; using ivec2 = ivec<2>; using ivec3 = ivec<3>; using ivec4 = ivec<4>; template <size_t n> using uvec = tvec<unsigned int,n>; using uvec2 = uvec<2>; using uvec3 = uvec<3>; using uvec4 = uvec<4>; #endif<|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010-2011 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // Demo code about // // - collisions and contacts // - use Irrlicht to display objects. // // (This is just a possible method of integration // of Chrono::Engine + Irrlicht: many others // are possible.) // // CHRONO // ------ // Multibody dinamics engine // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "physics/ChApidll.h" #include "physics/ChSystem.h" #include "physics/ChBodyEasy.h" #include "assets/ChTexture.h" #include "irrlicht_interface/ChIrrApp.h" // Use the namespace of Chrono using namespace chrono; // Use the main namespaces of Irrlicht using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; void create_some_falling_items(ChSystem& mphysicalSystem, ISceneManager* msceneManager, IVideoDriver* driver) { ChBodySceneNode* mrigidBody; for (int bi = 0; bi < 29; bi++) { // Create a bunch of ChronoENGINE rigid bodies (spheres and // boxes etc.) which will fall.. ChSharedPtr<ChBodyEasySphere> msphereBody(new ChBodyEasySphere( 1.1, // radius size 1000, // density true, // collide enable? true)); // visualization? msphereBody->SetPos( ChVector<>(-5+ChRandom()*10, 4+bi*0.05, -5+ChRandom()*10) ); msphereBody->SetFriction(0.2f); mphysicalSystem.Add(msphereBody); // optional, attach a texture for better visualization ChSharedPtr<ChTexture> mtexture(new ChTexture()); mtexture->SetTextureFilename("../data/bluwhite.png"); msphereBody->AddAsset(mtexture); ChSharedPtr<ChBodyEasyBox> mboxBody(new ChBodyEasyBox( 1.5, 1.5, 1.5, // x,y,z size 100, // density true, // collide enable? true)); // visualization? mboxBody->SetPos( ChVector<>(-5+ChRandom()*10, 4+bi*0.05, -5+ChRandom()*10) ); mphysicalSystem.Add(mboxBody); // optional, attach a texture for better visualization ChSharedPtr<ChTexture> mtexturebox(new ChTexture()); mtexturebox->SetTextureFilename("../data/cubetexture_bluwhite.png"); mboxBody->AddAsset(mtexturebox); ChSharedPtr<ChBodyEasyCylinder> mcylBody(new ChBodyEasyCylinder( 0.75, 0.5, // radius, height 100, // density true, // collide enable? true)); // visualization? mcylBody->SetPos( ChVector<>(-5+ChRandom()*10, 4+bi*0.05, -5+ChRandom()*10) ); mphysicalSystem.Add(mcylBody); // optional, attach a texture for better visualization ChSharedPtr<ChTexture> mtexturecyl(new ChTexture()); mtexturecyl->SetTextureFilename("../data/pinkwhite.png"); mcylBody->AddAsset(mtexturecyl); } // Create the five walls of the rectangular container, using // fixed rigid bodies of 'box' type: ChSharedPtr<ChBodyEasyBox> floorBody(new ChBodyEasyBox( 20,1,20, 1000, true, true)); floorBody->SetPos( ChVector<>(0,-5,0) ); floorBody->SetBodyFixed(true); mphysicalSystem.Add(floorBody); ChSharedPtr<ChBodyEasyBox> wallBody1(new ChBodyEasyBox(1,10,20.99, 1000, true, true)); wallBody1->SetPos( ChVector<>(-10,0,0) ); wallBody1->SetBodyFixed(true); mphysicalSystem.Add(wallBody1); ChSharedPtr<ChBodyEasyBox> wallBody2(new ChBodyEasyBox( 1,10,20.99, 1000, true, true)); wallBody2->SetPos( ChVector<>(10,0,0) ); wallBody2->SetBodyFixed(true); mphysicalSystem.Add(wallBody2); ChSharedPtr<ChBodyEasyBox> wallBody3(new ChBodyEasyBox( 20.99,10,1, 1000, true, true)); wallBody3->SetPos( ChVector<>(0,0,-10) ); wallBody3->SetBodyFixed(true); mphysicalSystem.Add(wallBody3); ChSharedPtr<ChBodyEasyBox> wallBody4(new ChBodyEasyBox( 20.99,10,1, 1000, true, true)); wallBody4->SetPos( ChVector<>(0,0,10) ); wallBody4->SetBodyFixed(true); mphysicalSystem.Add(wallBody4); // optional, attach textures for better visualization ChSharedPtr<ChTexture> mtexturewall(new ChTexture()); mtexturewall->SetTextureFilename("../data/concrete.jpg"); wallBody1->AddAsset(mtexturewall); // note: most assets can be shared wallBody2->AddAsset(mtexturewall); wallBody3->AddAsset(mtexturewall); wallBody4->AddAsset(mtexturewall); floorBody->AddAsset(mtexturewall); // Add the rotating mixer ChSharedPtr<ChBodyEasyBox> rotatingBody(new ChBodyEasyBox( 10,5,1, // x,y,z size 4000, // density true, // collide enable? true)); // visualization? rotatingBody->SetPos( ChVector<>(0,-1.6,0) ); rotatingBody->SetFriction(0.4f); mphysicalSystem.Add(rotatingBody); // .. an engine between mixer and truss ChSharedPtr<ChLinkEngine> my_motor(new ChLinkEngine); my_motor->Initialize(rotatingBody, floorBody, ChCoordsys<>(ChVector<>(0,0,0), Q_from_AngAxis(CH_C_PI_2, VECT_X)) ); my_motor->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (ChFunction_Const* mfun = dynamic_cast<ChFunction_Const*>(my_motor->Get_spe_funct())) mfun->Set_yconst(CH_C_PI/2.0); // speed w=90/s mphysicalSystem.AddLink(my_motor); /* /// NOTE: Instead of creating five separate 'box' bodies to make /// the walls of the bowl, you could have used a single body /// made of five box shapes, which build a single collision description, /// as in the alternative approach: // create a plain ChBody (no colliding shape nor visualization mesh is used yet) ChSharedPtr<ChBodyEasyBox> mrigidBody(new ChBody); // set the ChBodySceneNode as fixed body, and turn collision ON, otherwise no collide by default mrigidBody->SetBodyFixed(true); mrigidBody->SetCollide(true); // Clear model. The colliding shape description MUST be between ClearModel() .. BuildModel() pair. mrigidBody->GetCollisionModel()->ClearModel(); // Describe the (invisible) colliding shape by adding five boxes (the walls and floor) mrigidBody->GetCollisionModel()->AddBox(20,1,20, ChVector<>( 0,-10, 0)); mrigidBody->GetCollisionModel()->AddBox(1,40,20, ChVector<>(-11, 0, 0)); mrigidBody->GetCollisionModel()->AddBox(1,40,20, ChVector<>( 11, 0, 0)); mrigidBody->GetCollisionModel()->AddBox(20,40,1, ChVector<>( 0, 0,-11)); mrigidBody->GetCollisionModel()->AddBox(20,40,1, ChVector<>( 0, 0, 11)); // Complete the description of collision shape. mrigidBody->GetCollisionModel()->BuildModel(); // Attach some visualization shapes if needed: ChSharedPtr<ChBoxShape> vshape (new ChBoxShape() ); vshape->GetBoxGeometry().SetLenghts( ChVector<> (20,1,20) ); vshape->GetBoxGeometry().Pos = ChVector<> (0,-5,0); this->AddAsset( vshape ); // etc. for other 4 box shapes.. */ /* // Add also an oddly shaped object, loading from a mesh saved in '.X' fileformat. // ***OBSOLETE*** the addChBodySceneNode_xxxx methods will be deprecated in future ChBodySceneNode* meshBody = (ChBodySceneNode*)addChBodySceneNode_easyGenericMesh(&mphysicalSystem, msceneManager, 1.0, ChVector<>(0,2,0), QUNIT, "../data/rock.X" , false, // not static true); // true=convex; false=concave(do convex decomposition of concave mesh) meshBody->addShadowVolumeSceneNode(); */ /* // Add also a 'barrel' type object // ***OBSOLETE*** the addChBodySceneNode_xxxx methods will be deprecated in future mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easyBarrel( &mphysicalSystem, msceneManager, 1.0, ChVector<>(0,6,1), 2, 4, -0.8, 0.8, -0.5); mrigidBody->GetBody()->SetWvel_loc(ChVector<>(0.3,0,0)); video::ITexture* barrellMap = driver->getTexture("../data/pinkwhite.png"); mrigidBody->setMaterialTexture(0, barrellMap); */ /* // Add also few spherical particles ChParticlesSceneNode* mParticles = (ChParticlesSceneNode*)addChParticlesSceneNode_easySpheres( &mphysicalSystem, application.GetSceneManager(), 0.8, // mass 0.4 // radius ); for (int np = 0; np <10; np++) { mParticles->GetParticles()->AddParticle(ChCoordsys<>(ChVector<>(-1,np,0), QUNIT)); } */ } int main(int argc, char* argv[]) { // In CHRONO engine, The DLL_CreateGlobals() - DLL_DeleteGlobals(); pair is needed if // global functions are needed. DLL_CreateGlobals(); // Create a ChronoENGINE physical system ChSystem mphysicalSystem; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&mphysicalSystem, L"Collisions between objects",core::dimension2d<u32>(800,600),false); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: ChIrrWizard::add_typical_Logo(application.GetDevice()); ChIrrWizard::add_typical_Sky(application.GetDevice()); ChIrrWizard::add_typical_Lights(application.GetDevice()); ChIrrWizard::add_typical_Camera(application.GetDevice(), core::vector3df(0,14,-20)); // Create all the rigid bodies. create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver()); // Use this function for adding a ChIrrNodeAsset to all items // Otherwise use application.AssetBind(myitem); on a per-item basis. application.AssetBindAll(); // Use this function for 'converting' assets into Irrlicht meshes application.AssetUpdateAll(); // Modify some setting of the physical system for the simulation, if you want mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR); mphysicalSystem.SetIterLCPmaxItersSpeed(20); mphysicalSystem.SetIterLCPmaxItersStab(5); //mphysicalSystem.SetUseSleeping(true); application.SetStepManage(true); application.SetTimestep(0.02); // // THE SOFT-REAL-TIME CYCLE // while(application.GetDevice()->run()) { application.GetVideoDriver()->beginScene(true, true, SColor(255,140,161,192)); application.DrawAll(); application.DoStep(); application.GetVideoDriver()->endScene(); } // Remember this at the end of the program, if you started // with DLL_CreateGlobals(); DLL_DeleteGlobals(); return 0; } <commit_msg>The demo_collision.cpp contains an optional code for testing also the ChParticlesClones, updated to the new 'asset' system for visualization.<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010-2011 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // Demo code about // // - collisions and contacts // - use Irrlicht to display objects. // // (This is just a possible method of integration // of Chrono::Engine + Irrlicht: many others // are possible.) // // CHRONO // ------ // Multibody dinamics engine // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "physics/ChApidll.h" #include "physics/ChSystem.h" #include "physics/ChBodyEasy.h" #include "physics/ChParticlesClones.h" #include "assets/ChTexture.h" #include "irrlicht_interface/ChIrrApp.h" // Use the namespace of Chrono using namespace chrono; // Use the main namespaces of Irrlicht using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; void create_some_falling_items(ChSystem& mphysicalSystem, ISceneManager* msceneManager, IVideoDriver* driver) { ChBodySceneNode* mrigidBody; for (int bi = 0; bi < 29; bi++) { // Create a bunch of ChronoENGINE rigid bodies (spheres and // boxes etc.) which will fall.. ChSharedPtr<ChBodyEasySphere> msphereBody(new ChBodyEasySphere( 1.1, // radius size 1000, // density true, // collide enable? true)); // visualization? msphereBody->SetPos( ChVector<>(-5+ChRandom()*10, 4+bi*0.05, -5+ChRandom()*10) ); msphereBody->SetFriction(0.2f); mphysicalSystem.Add(msphereBody); // optional, attach a texture for better visualization ChSharedPtr<ChTexture> mtexture(new ChTexture()); mtexture->SetTextureFilename("../data/bluwhite.png"); msphereBody->AddAsset(mtexture); ChSharedPtr<ChBodyEasyBox> mboxBody(new ChBodyEasyBox( 1.5, 1.5, 1.5, // x,y,z size 100, // density true, // collide enable? true)); // visualization? mboxBody->SetPos( ChVector<>(-5+ChRandom()*10, 4+bi*0.05, -5+ChRandom()*10) ); mphysicalSystem.Add(mboxBody); // optional, attach a texture for better visualization ChSharedPtr<ChTexture> mtexturebox(new ChTexture()); mtexturebox->SetTextureFilename("../data/cubetexture_bluwhite.png"); mboxBody->AddAsset(mtexturebox); ChSharedPtr<ChBodyEasyCylinder> mcylBody(new ChBodyEasyCylinder( 0.75, 0.5, // radius, height 100, // density true, // collide enable? true)); // visualization? mcylBody->SetPos( ChVector<>(-5+ChRandom()*10, 4+bi*0.05, -5+ChRandom()*10) ); mphysicalSystem.Add(mcylBody); // optional, attach a texture for better visualization ChSharedPtr<ChTexture> mtexturecyl(new ChTexture()); mtexturecyl->SetTextureFilename("../data/pinkwhite.png"); mcylBody->AddAsset(mtexturecyl); } // Create the five walls of the rectangular container, using // fixed rigid bodies of 'box' type: ChSharedPtr<ChBodyEasyBox> floorBody(new ChBodyEasyBox( 20,1,20, 1000, true, true)); floorBody->SetPos( ChVector<>(0,-5,0) ); floorBody->SetBodyFixed(true); mphysicalSystem.Add(floorBody); ChSharedPtr<ChBodyEasyBox> wallBody1(new ChBodyEasyBox(1,10,20.99, 1000, true, true)); wallBody1->SetPos( ChVector<>(-10,0,0) ); wallBody1->SetBodyFixed(true); mphysicalSystem.Add(wallBody1); ChSharedPtr<ChBodyEasyBox> wallBody2(new ChBodyEasyBox( 1,10,20.99, 1000, true, true)); wallBody2->SetPos( ChVector<>(10,0,0) ); wallBody2->SetBodyFixed(true); mphysicalSystem.Add(wallBody2); ChSharedPtr<ChBodyEasyBox> wallBody3(new ChBodyEasyBox( 20.99,10,1, 1000, true, true)); wallBody3->SetPos( ChVector<>(0,0,-10) ); wallBody3->SetBodyFixed(true); mphysicalSystem.Add(wallBody3); ChSharedPtr<ChBodyEasyBox> wallBody4(new ChBodyEasyBox( 20.99,10,1, 1000, true, true)); wallBody4->SetPos( ChVector<>(0,0,10) ); wallBody4->SetBodyFixed(true); mphysicalSystem.Add(wallBody4); // optional, attach textures for better visualization ChSharedPtr<ChTexture> mtexturewall(new ChTexture()); mtexturewall->SetTextureFilename("../data/concrete.jpg"); wallBody1->AddAsset(mtexturewall); // note: most assets can be shared wallBody2->AddAsset(mtexturewall); wallBody3->AddAsset(mtexturewall); wallBody4->AddAsset(mtexturewall); floorBody->AddAsset(mtexturewall); // Add the rotating mixer ChSharedPtr<ChBodyEasyBox> rotatingBody(new ChBodyEasyBox( 10,5,1, // x,y,z size 4000, // density true, // collide enable? true)); // visualization? rotatingBody->SetPos( ChVector<>(0,-1.6,0) ); rotatingBody->SetFriction(0.4f); mphysicalSystem.Add(rotatingBody); // .. an engine between mixer and truss ChSharedPtr<ChLinkEngine> my_motor(new ChLinkEngine); my_motor->Initialize(rotatingBody, floorBody, ChCoordsys<>(ChVector<>(0,0,0), Q_from_AngAxis(CH_C_PI_2, VECT_X)) ); my_motor->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (ChFunction_Const* mfun = dynamic_cast<ChFunction_Const*>(my_motor->Get_spe_funct())) mfun->Set_yconst(CH_C_PI/2.0); // speed w=90/s mphysicalSystem.AddLink(my_motor); /* /// NOTE: Instead of creating five separate 'box' bodies to make /// the walls of the bowl, you could have used a single body /// made of five box shapes, which build a single collision description, /// as in the alternative approach: // create a plain ChBody (no colliding shape nor visualization mesh is used yet) ChSharedPtr<ChBodyEasyBox> mrigidBody(new ChBody); // set the ChBodySceneNode as fixed body, and turn collision ON, otherwise no collide by default mrigidBody->SetBodyFixed(true); mrigidBody->SetCollide(true); // Clear model. The colliding shape description MUST be between ClearModel() .. BuildModel() pair. mrigidBody->GetCollisionModel()->ClearModel(); // Describe the (invisible) colliding shape by adding five boxes (the walls and floor) mrigidBody->GetCollisionModel()->AddBox(20,1,20, ChVector<>( 0,-10, 0)); mrigidBody->GetCollisionModel()->AddBox(1,40,20, ChVector<>(-11, 0, 0)); mrigidBody->GetCollisionModel()->AddBox(1,40,20, ChVector<>( 11, 0, 0)); mrigidBody->GetCollisionModel()->AddBox(20,40,1, ChVector<>( 0, 0,-11)); mrigidBody->GetCollisionModel()->AddBox(20,40,1, ChVector<>( 0, 0, 11)); // Complete the description of collision shape. mrigidBody->GetCollisionModel()->BuildModel(); // Attach some visualization shapes if needed: ChSharedPtr<ChBoxShape> vshape (new ChBoxShape() ); vshape->GetBoxGeometry().SetLenghts( ChVector<> (20,1,20) ); vshape->GetBoxGeometry().Pos = ChVector<> (0,-5,0); this->AddAsset( vshape ); // etc. for other 4 box shapes.. */ /* // Add also an oddly shaped object, loading from a mesh saved in '.X' fileformat. // ***OBSOLETE*** the addChBodySceneNode_xxxx methods will be deprecated in future ChBodySceneNode* meshBody = (ChBodySceneNode*)addChBodySceneNode_easyGenericMesh(&mphysicalSystem, msceneManager, 1.0, ChVector<>(0,2,0), QUNIT, "../data/rock.X" , false, // not static true); // true=convex; false=concave(do convex decomposition of concave mesh) meshBody->addShadowVolumeSceneNode(); */ /* // Add also a 'barrel' type object // ***OBSOLETE*** the addChBodySceneNode_xxxx methods will be deprecated in future mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easyBarrel( &mphysicalSystem, msceneManager, 1.0, ChVector<>(0,6,1), 2, 4, -0.8, 0.8, -0.5); mrigidBody->GetBody()->SetWvel_loc(ChVector<>(0.3,0,0)); video::ITexture* barrellMap = driver->getTexture("../data/pinkwhite.png"); mrigidBody->setMaterialTexture(0, barrellMap); */ /* // OPTIONAL TEST: Add also few spherical particles // using the memory-saving 'particle clones': ChSharedPtr<ChParticlesClones> mparticles(new ChParticlesClones); // We want to visualize this particle clones stuff, so: ChSharedPtr<ChSphereShape> mspherepart(new ChSphereShape); mspherepart->GetSphereGeometry().rad = 0.4; mparticles->AddAsset(mspherepart); // Note: coll. shape, if needed, must be specified before creating particles mparticles->GetCollisionModel()->ClearModel(); mparticles->GetCollisionModel()->AddSphere(0.4); mparticles->GetCollisionModel()->BuildModel(); mparticles->SetCollide(true); // Add particles here for (int bi = 0; bi < 10; bi++) { mparticles->AddParticle(ChCoordsys<>(ChVector<>(ChRandom(), ChRandom(), ChRandom()))); } mphysicalSystem.Add(mparticles); */ } int main(int argc, char* argv[]) { // In CHRONO engine, The DLL_CreateGlobals() - DLL_DeleteGlobals(); pair is needed if // global functions are needed. DLL_CreateGlobals(); // Create a ChronoENGINE physical system ChSystem mphysicalSystem; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&mphysicalSystem, L"Collisions between objects",core::dimension2d<u32>(800,600),false); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: ChIrrWizard::add_typical_Logo(application.GetDevice()); ChIrrWizard::add_typical_Sky(application.GetDevice()); ChIrrWizard::add_typical_Lights(application.GetDevice()); ChIrrWizard::add_typical_Camera(application.GetDevice(), core::vector3df(0,14,-20)); // Create all the rigid bodies. create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver()); // Use this function for adding a ChIrrNodeAsset to all items // Otherwise use application.AssetBind(myitem); on a per-item basis. application.AssetBindAll(); // Use this function for 'converting' assets into Irrlicht meshes application.AssetUpdateAll(); // Modify some setting of the physical system for the simulation, if you want mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR); mphysicalSystem.SetIterLCPmaxItersSpeed(20); mphysicalSystem.SetIterLCPmaxItersStab(5); //mphysicalSystem.SetUseSleeping(true); application.SetStepManage(true); application.SetTimestep(0.02); // // THE SOFT-REAL-TIME CYCLE // while(application.GetDevice()->run()) { application.GetVideoDriver()->beginScene(true, true, SColor(255,140,161,192)); application.DrawAll(); application.DoStep(); application.GetVideoDriver()->endScene(); } // Remember this at the end of the program, if you started // with DLL_CreateGlobals(); DLL_DeleteGlobals(); return 0; } <|endoftext|>
<commit_before>#include <fstream> #include "Set.hpp" void BFS_corners(std::ofstream *file, int end); void BFS_edges1(std::ofstream *file); void BFS_edges2(std::ofstream *file); int main(int argc, char const *argv[]) { std::ofstream file; int end = -1; if (argc > 1) { end = 1 + atoi(argv[1]); } file.open("../pdbs/cPDB.txt"); BFS_corners(&file, end); file.close(); // file.open("../pdbs/ePDB.txt"); // BFS_edges(&file); // file.close(); return 0; } void BFS_corners(std::ofstream *file, int end) { std::queue<std::tuple<int, int, int8_t>> queue; std::queue<Cube*> *succ; Set closed(1); Cube* cube = new Cube; int info, size; int8_t level = 0, last_level = -1; int *corners; int last; std::tuple<int, int, int> node; corners = cube->get_corners(); info = rank(8, corners, 8, 3); last = cube->get_last(); node = std::make_tuple(info, last, level); queue.push(node); closed.insert(info, level); delete cube; std::cout << "Closed: " << closed.size() << std::endl; while (!queue.empty()) { std::tie(info, last, level) = queue.front(); queue.pop(); cube = new Cube(info, 0, last); if (level == end) { delete cube; break; } if (level != last_level) { last_level = level; std::cout << "LEVEL " << int_to_string(last_level) << " | queue " << queue.size(); std::cout << " | closed " << closed.size() << std::endl; std::cout << std::flush; } (*file) << level << " " << info << "\n"; succ = cube->succ(); size = succ->size(); delete cube; for (int i = 0; i < size; ++i) { cube = succ->front(); succ->pop(); corners = cube->get_corners(); info = rank(8, corners, 8, 3); last = cube->get_last(); if (!closed.contains(info)) { node = std::make_tuple(info, last, level+1); queue.push(node); closed.insert(info, level); } delete cube; } delete succ; } while (!queue.empty()) { std::tie(info, last, level) = queue.front(); queue.pop(); } std::cout << "ending\n"; } void BFS_edges1(std::ofstream *file, int end) { std::queue<std::tuple<int, int, int>> queue; std::queue<Cube*> *succ; Set closed(1); Cube* cube = new Cube; int info, size, level = 0, last_level = -1; int *corners; int last; std::tuple<int, int, int> node; corners = cube->get_edges(); info = rank(8,corners, 8, 3); last = cube->get_last(); node = std::make_tuple(info, last, level); queue.push(node); closed.insert(info, level); delete cube; while (!queue.empty()) { std::tie (info, last, level) = queue.front(); queue.pop(); cube = new Cube(info, 0, last); if (level == end) { delete cube; break; } if (level != last_level) { last_level = level; std::cout << "LEVEL " << last_level << " | queue " << queue.size(); std::cout << " | closed " << closed.size() << std::endl; std::cout << std::flush; } (*file) << level << "\n"; succ = cube->succ(); size = succ->size(); delete cube; for (int i = 0; i < size; ++i) { cube = succ->front(); succ->pop(); corners = cube->get_corners(); info = rank(8, corners, 8, 3); last = cube->get_last(); if (!closed.contains(info)) { node = std::make_tuple(info, last, level+1); queue.push(node); closed.insert(info, level); } delete cube; } delete succ; } while (!queue.empty()) { std::tie(info, last, level) = queue.front(); queue.pop(); } std::cout << "ending\n"; } <commit_msg>Se cambia detalle de escritura de archivo (igual eso se modificará a binario en un futuro)<commit_after>#include <fstream> #include "Set.hpp" void BFS_corners(std::ofstream *file, int end); void BFS_edges1(std::ofstream *file); void BFS_edges2(std::ofstream *file); int main(int argc, char const *argv[]) { std::ofstream file; int end = -1; if (argc > 1) { end = 1 + atoi(argv[1]); } file.open("../pdbs/cPDB.txt"); BFS_corners(&file, end); file.close(); // file.open("../pdbs/ePDB.txt"); // BFS_edges(&file); // file.close(); return 0; } void BFS_corners(std::ofstream *file, int end) { std::queue<std::tuple<int, int, int8_t>> queue; std::queue<Cube*> *succ; Set closed(1); Cube* cube = new Cube; int info, size; int8_t level = 0, last_level = -1; int *corners; int last; std::tuple<int, int, int> node; corners = cube->get_corners(); info = rank(8, corners, 8, 3); last = cube->get_last(); node = std::make_tuple(info, last, level); queue.push(node); closed.insert(info, level); delete cube; std::cout << "Closed: " << closed.size() << std::endl; while (!queue.empty()) { std::tie(info, last, level) = queue.front(); queue.pop(); cube = new Cube(info, 0, last); if (level == end) { delete cube; break; } if (level != last_level) { last_level = level; std::cout << "LEVEL " << int_to_string(last_level) << " | queue " << queue.size(); std::cout << " | closed " << closed.size() << std::endl; std::cout << std::flush; } (*file) << int_to_string(level) << "\n"; succ = cube->succ(); size = succ->size(); delete cube; for (int i = 0; i < size; ++i) { cube = succ->front(); succ->pop(); corners = cube->get_corners(); info = rank(8, corners, 8, 3); last = cube->get_last(); if (!closed.contains(info)) { node = std::make_tuple(info, last, level+1); queue.push(node); closed.insert(info, level); } delete cube; } delete succ; } while (!queue.empty()) { std::tie(info, last, level) = queue.front(); queue.pop(); } std::cout << "ending\n"; } void BFS_edges1(std::ofstream *file, int end) { std::queue<std::tuple<int, int, int>> queue; std::queue<Cube*> *succ; Set closed(1); Cube* cube = new Cube; int info, size, level = 0, last_level = -1; int *corners; int last; std::tuple<int, int, int> node; corners = cube->get_edges(); info = rank(8,corners, 8, 3); last = cube->get_last(); node = std::make_tuple(info, last, level); queue.push(node); closed.insert(info, level); delete cube; while (!queue.empty()) { std::tie (info, last, level) = queue.front(); queue.pop(); cube = new Cube(info, 0, last); if (level == end) { delete cube; break; } if (level != last_level) { last_level = level; std::cout << "LEVEL " << last_level << " | queue " << queue.size(); std::cout << " | closed " << closed.size() << std::endl; std::cout << std::flush; } (*file) << level << "\n"; succ = cube->succ(); size = succ->size(); delete cube; for (int i = 0; i < size; ++i) { cube = succ->front(); succ->pop(); corners = cube->get_corners(); info = rank(8, corners, 8, 3); last = cube->get_last(); if (!closed.contains(info)) { node = std::make_tuple(info, last, level+1); queue.push(node); closed.insert(info, level); } delete cube; } delete succ; } while (!queue.empty()) { std::tie(info, last, level) = queue.front(); queue.pop(); } std::cout << "ending\n"; } <|endoftext|>
<commit_before>#include "codecvt/codecvt" #include "unit_codecvt_base.h" // // Seperate impl of this calculation here for the sake of testing // static int utf8_chars_needed(unsigned long char_value) { int ret = -1; if (char_value < 0x80) ret = 1; else if (char_value < 0x800) ret = 2; else if (char_value < 0x10000) ret = 3; else if (char_value < 0x2000000) ret = 4; else if (char_value < 0x4000000) ret = 5; else if (char_value < 0x80000000) ret = 6; return ret; } template <typename C, unsigned long N, int M> class Test_codecvt_utf8 : public Test_codecvt_base<std::codecvt_utf8<C, N, (std::codecvt_mode)M>> { typedef Test_codecvt_base< std::codecvt_utf8<C, N, (std::codecvt_mode)M>> base; typedef C ictype; CPPUNIT_TEST_SUITE(Test_codecvt_utf8); CPPUNIT_TEST(construction); CPPUNIT_TEST(encoding); CPPUNIT_TEST(always_noconv); CPPUNIT_TEST(max_length); CPPUNIT_TEST(encode_decode_char_range); CPPUNIT_TEST_SUITE_END(); public: virtual ~Test_codecvt_utf8() { } void max_length() override { typename base::cvt_t cvt; unsigned long max_value = std::min(N, static_cast<unsigned long>(std::numeric_limits<C>::max())); std::codecvt_mode m = static_cast<std::codecvt_mode>(M); if (m & std::consume_header) { CPPUNIT_ASSERT( (utf8_chars_needed(max_value) + utf8_chars_needed(bom_value()) == cvt.max_length())); } else { CPPUNIT_ASSERT(utf8_chars_needed(max_value) == cvt.max_length()); } } void encode_decode_char_range() override { typename base::cvt_t cvt; unsigned long max_value = std::min(N, static_cast<unsigned long>(std::numeric_limits<C>::max())); // printf("\n---> max = %lu\n", max_value); const int obufsz = 10; char outbuffer[obufsz]; std::codecvt_base::result rc = std::codecvt_base::ok; char * end = nullptr; unsigned long cval = 0; for (; cval <= std::min(0xd7fful, max_value); ++cval) { end = outbuffer + obufsz; rc = out_for_ictype(cval, outbuffer, end); CPPUNIT_ASSERT( (rc == std::codecvt_base::ok) || ( (N < static_cast<unsigned long>(bom_value())) && (static_cast<std::codecvt_mode>(M) & std::generate_header) && (rc == std::codecvt_base::error)) ); ictype x = 0; const char * end2 = end; in_for_ictype(x, outbuffer, end2); } for (cval = 0xe000ul; cval <= std::min(0x10fffful, max_value); cval += 0x100ul) { // N end = outbuffer + obufsz; rc = out_for_ictype(cval, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N + 1 end = outbuffer + obufsz; rc = out_for_ictype(cval + 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N - 1 end = outbuffer + obufsz; rc = out_for_ictype(cval + 0x100ul - 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); } for (cval = 0x110000ul; cval <= max_value; cval += 0x10000ul) { // N - 1 end = outbuffer + obufsz; rc = out_for_ictype(cval - 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N end = outbuffer + obufsz; rc = out_for_ictype(cval, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N + 1 end = outbuffer + obufsz; rc = out_for_ictype(cval + 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); } } private: std::codecvt_base::result out_for_ictype(ictype c, char * buffer, char *& buffer_end) { typename base::cvt_t cvt; std::codecvt_base::result rc = std::codecvt_base::ok; std::mbstate_t state = {0, {0}}; ictype internarray[2] = { c , 0 }; const ictype * from_next = nullptr; char * to_next = nullptr; rc = cvt.out(state, internarray, internarray + 1, from_next, buffer, buffer_end, to_next); CPPUNIT_ASSERT( (rc == std::codecvt_base::error) || (to_next <= buffer_end)); CPPUNIT_ASSERT( (rc == std::codecvt_base::error) || (from_next == internarray + 1)); state = std::mbstate_t(); int len = cvt.length(state, buffer, to_next, 4); if(rc == std::codecvt_base::error || len == (to_next - buffer) || (M & std::consume_header)) { } else { printf("\nLENGTH = %d, %zd, rc = %d\n", len, to_next - buffer, rc); for (auto p = buffer; p < to_next; ++p) printf("%02hhx ", *p); printf("\n"); } CPPUNIT_ASSERT(rc == std::codecvt_base::error || len == (to_next - buffer) || (M & std::consume_header)); buffer_end = to_next; return rc; } std::codecvt_base::result in_for_ictype(ictype & c, const char * buffer, const char *& end) { typename base::cvt_t cvt; std::mbstate_t state = std::mbstate_t(); std::codecvt_base::result rc = std::codecvt_base::ok; ictype conv_buffer[10]; ictype * last = nullptr; const char * saved_end = end; // for (auto p = buffer; p < end; ++p) // printf("%02hhX ", *p); c = 0; rc = cvt.in(state, buffer, end, end, conv_buffer, conv_buffer + 10, last); bool has_bom = ( static_cast<std::codecvt_mode>(M) & std::generate_header); bool eats_bom = ( static_cast<std::codecvt_mode>(M) & std::consume_header); #if 0 // printf("RC = %d\n", rc); // for (auto p = buffer; p < end; ++p) // printf("%02hhX ", *p); #endif CPPUNIT_ASSERT(rc == std::codecvt_base::ok); if( (has_bom && eats_bom && ((last - conv_buffer) == 1)) || (!has_bom && eats_bom && ((last - conv_buffer) == 1)) || (has_bom && !eats_bom && ((last - conv_buffer) == 2)) || (!has_bom && !eats_bom && ((last - conv_buffer) == 1)) ) { } else { printf("\n"); for (auto p = buffer; p < saved_end; ++p) printf("%02hhX ", *p); printf("\nhas %d eats %d\n", has_bom, eats_bom); printf("num eaten = %zd\n", last - conv_buffer); CPPUNIT_ASSERT(false); } return rc; } }; #define REGISTER_CVT_UTF8(C, N, M) \ static CppUnit::AutoRegisterSuite< \ Test_codecvt_utf8<C, N, M>> \ autoRegisterRegistry__CVTUTF8_ ## C ## N ## M; #define REGISTER_CVT_UTF8_ALL_MODES(C, MAX) \ REGISTER_CVT_UTF8(C, MAX, 0) \ REGISTER_CVT_UTF8(C, MAX, 1) \ REGISTER_CVT_UTF8(C, MAX, 2) \ REGISTER_CVT_UTF8(C, MAX, 3) \ REGISTER_CVT_UTF8(C, MAX, 4) \ REGISTER_CVT_UTF8(C, MAX, 5) \ REGISTER_CVT_UTF8(C, MAX, 6) \ REGISTER_CVT_UTF8(C, MAX, 7) #if 0 #endif REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0x7f); REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0xff); #if 0 REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0xffff); REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0x10ffff); REGISTER_CVT_UTF8_ALL_MODES(char16_t, 0x7f); REGISTER_CVT_UTF8_ALL_MODES(char16_t, 0xff); REGISTER_CVT_UTF8_ALL_MODES(char16_t, 0x10ffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x7f); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0xff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0xffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x10ffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x3ffffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x7fffffff); #endif <commit_msg>Making my way towards correctness... slowly<commit_after>#include "codecvt/codecvt" #include "unit_codecvt_base.h" // // Seperate impl of this calculation here for the sake of testing // static int utf8_chars_needed(unsigned long char_value) { int ret = -1; if (char_value < 0x80) ret = 1; else if (char_value < 0x800) ret = 2; else if (char_value < 0x10000) ret = 3; else if (char_value < 0x2000000) ret = 4; else if (char_value < 0x4000000) ret = 5; else if (char_value < 0x80000000) ret = 6; return ret; } template <typename C, unsigned long N, int M> class Test_codecvt_utf8 : public Test_codecvt_base<std::codecvt_utf8<C, N, (std::codecvt_mode)M>> { typedef Test_codecvt_base< std::codecvt_utf8<C, N, (std::codecvt_mode)M>> base; typedef C ictype; CPPUNIT_TEST_SUITE(Test_codecvt_utf8); CPPUNIT_TEST(construction); CPPUNIT_TEST(encoding); CPPUNIT_TEST(always_noconv); CPPUNIT_TEST(max_length); CPPUNIT_TEST(encode_decode_char_range); CPPUNIT_TEST_SUITE_END(); static const bool has_bom = ( static_cast<std::codecvt_mode>(M) & std::generate_header); static const bool eats_bom = ( static_cast<std::codecvt_mode>(M) & std::consume_header); public: virtual ~Test_codecvt_utf8() { } void max_length() override { typename base::cvt_t cvt; unsigned long max_value = std::min(N, static_cast<unsigned long>(std::numeric_limits<C>::max())); std::codecvt_mode m = static_cast<std::codecvt_mode>(M); if (m & std::consume_header) { CPPUNIT_ASSERT( (utf8_chars_needed(max_value) + utf8_chars_needed(bom_value()) == cvt.max_length())); } else { CPPUNIT_ASSERT(utf8_chars_needed(max_value) == cvt.max_length()); } } void encode_decode_char_range() override { typename base::cvt_t cvt; unsigned long max_value = std::min(N, static_cast<unsigned long>(std::numeric_limits<C>::max())); const int obufsz = 10; char outbuffer[obufsz]; std::codecvt_base::result rc = std::codecvt_base::ok; char * end = nullptr; unsigned long cval = 0; for (; cval <= std::min(0xd7fful, max_value); ++cval) { end = outbuffer + obufsz; rc = out_for_ictype(cval, outbuffer, end); CPPUNIT_ASSERT( (rc == std::codecvt_base::ok) || ( (N < static_cast<unsigned long>(bom_value())) && (static_cast<std::codecvt_mode>(M) & std::generate_header) && (rc == std::codecvt_base::error)) ); ictype x = 0; const char * end2 = end; in_for_ictype(x, outbuffer, end2); } for (cval = 0xe000ul; cval <= std::min(0x10fffful, max_value); cval += 0x100ul) { // N end = outbuffer + obufsz; rc = out_for_ictype(cval, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N + 1 end = outbuffer + obufsz; rc = out_for_ictype(cval + 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N - 1 end = outbuffer + obufsz; rc = out_for_ictype(cval + 0x100ul - 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); } for (cval = 0x110000ul; cval <= max_value; cval += 0x10000ul) { // N - 1 end = outbuffer + obufsz; rc = out_for_ictype(cval - 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N end = outbuffer + obufsz; rc = out_for_ictype(cval, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); // N + 1 end = outbuffer + obufsz; rc = out_for_ictype(cval + 1, outbuffer, end); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); } } private: std::codecvt_base::result out_for_ictype(ictype c, char * buffer, char *& buffer_end) { typename base::cvt_t cvt; std::codecvt_base::result rc = std::codecvt_base::ok; std::mbstate_t state = {0, {0}}; ictype internarray[2] = { c , 0 }; const ictype * from_next = nullptr; char * to_next = nullptr; rc = cvt.out(state, internarray, internarray + 1, from_next, buffer, buffer_end, to_next); CPPUNIT_ASSERT( (rc == std::codecvt_base::error) || (to_next <= buffer_end)); CPPUNIT_ASSERT( (rc == std::codecvt_base::error) || (from_next == internarray + 1)); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); state = std::mbstate_t(); int len = cvt.length(state, buffer, to_next, 4); if(rc == std::codecvt_base::error || len == (to_next - buffer) || (M & std::consume_header)) { } else { printf("\nLENGTH = %d, %zd, rc = %d\n", len, to_next - buffer, rc); for (auto p = buffer; p < to_next; ++p) printf("%02hhx ", *p); printf("\n"); } // CPPUNIT_ASSERT(rc == std::codecvt_base::error // || len == (to_next - buffer) // || (M & std::consume_header)); printf("\nhas %d eats %d\n", has_bom, eats_bom); printf("num eaten = %zd\n", to_next - buffer); if( (has_bom && eats_bom && ((to_next - buffer) == 4)) || (!has_bom && eats_bom && ((to_next - buffer) == 1)) || (has_bom && !eats_bom && ((to_next - buffer) == 3)) || (!has_bom && !eats_bom && ((to_next - buffer) == 1)) ) { } else { CPPUNIT_ASSERT(false); } buffer_end = to_next; return rc; } std::codecvt_base::result in_for_ictype(ictype & c, const char * buffer, const char *& end) { typename base::cvt_t cvt; std::mbstate_t state = std::mbstate_t(); std::codecvt_base::result rc = std::codecvt_base::ok; ictype conv_buffer[10]; ictype * last = nullptr; const char * saved_end = end; // for (auto p = buffer; p < end; ++p) // printf("%02hhX ", *p); c = 0; rc = cvt.in(state, buffer, end, end, conv_buffer, conv_buffer + 10, last); CPPUNIT_ASSERT(rc == std::codecvt_base::ok); if( (has_bom && eats_bom && ((last - conv_buffer) == 1)) || (!has_bom && eats_bom && ((last - conv_buffer) == 1)) || (has_bom && !eats_bom && ((last - conv_buffer) == 2)) || (!has_bom && !eats_bom && ((last - conv_buffer) == 1)) ) { } else { printf("\n"); for (auto p = buffer; p < saved_end; ++p) printf("%02hhX ", *p); printf("\nhas %d eats %d\n", has_bom, eats_bom); printf("num eaten = %zd\n", last - conv_buffer); CPPUNIT_ASSERT(false); } return rc; } }; #define REGISTER_CVT_UTF8(C, N, M) \ static CppUnit::AutoRegisterSuite< \ Test_codecvt_utf8<C, N, M>> \ autoRegisterRegistry__CVTUTF8_ ## C ## N ## M; #define REGISTER_CVT_UTF8_ALL_MODES(C, MAX) \ REGISTER_CVT_UTF8(C, MAX, 0) \ REGISTER_CVT_UTF8(C, MAX, 1) \ REGISTER_CVT_UTF8(C, MAX, 2) \ REGISTER_CVT_UTF8(C, MAX, 3) \ REGISTER_CVT_UTF8(C, MAX, 4) \ REGISTER_CVT_UTF8(C, MAX, 5) \ REGISTER_CVT_UTF8(C, MAX, 6) \ REGISTER_CVT_UTF8(C, MAX, 7) #if 0 #endif REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0x7f); REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0xff); #if 0 REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0xffff); REGISTER_CVT_UTF8_ALL_MODES(wchar_t, 0x10ffff); REGISTER_CVT_UTF8_ALL_MODES(char16_t, 0x7f); REGISTER_CVT_UTF8_ALL_MODES(char16_t, 0xff); REGISTER_CVT_UTF8_ALL_MODES(char16_t, 0x10ffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x7f); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0xff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0xffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x10ffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x3ffffff); REGISTER_CVT_UTF8_ALL_MODES(char32_t, 0x7fffffff); #endif <|endoftext|>
<commit_before>#include <nekit/utils/boost_tcp_socket.h> namespace nekit { namespace utils { BoostTcpSocket::BoostTcpSocket(boost::asio::io_service &service) : BoostTcpSocket(service, nullptr) {} BoostTcpSocket::BoostTcpSocket(boost::asio::io_service &service, DelegatePointer delegate) : socket_(service), delegate_(delegate), connected_(false), eof_(false), shutdown_(false), closed_(false) {} BoostTcpSocket::Pointer BoostTcpSocket::CreateSocket( boost::asio::io_service &service) { // Not using `make_shared` since the ctor is private. This class if final thus // it is not able to workaround it. Anyway, considering this is a heavy class, // the overhead is negligible. return std::shared_ptr<BoostTcpSocket>(new BoostTcpSocket(service)); } BoostTcpSocket::Pointer BoostTcpSocket::CreateSocket( boost::asio::io_service &service, DelegatePointer delegate) { return std::shared_ptr<BoostTcpSocket>(new BoostTcpSocket(service, delegate)); } void BoostTcpSocket::set_delegate(DelegatePointer delegate) { delegate_ = delegate; } void BoostTcpSocket::Connect(const boost::asio::ip::tcp::endpoint endpoint) { auto self(this->shared_from_this()); socket_.async_connect(endpoint, [this, self](const boost::system::error_code &ec) { if (ec) { HandleError(ec); return; } if (delegate_) delegate_->DidConnect(this->shared_from_this()); }); } Error BoostTcpSocket::Bind(const boost::asio::ip::tcp::endpoint endpoint) { boost::system::error_code ec; socket_.bind(endpoint, ec); return ConvertBoostError(ec); } Error BoostTcpSocket::Shutdown() { boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); shutdown_ = true; CheckClose(); return ConvertBoostError(ec); } void BoostTcpSocket::Read(std::shared_ptr<Buffer> buffer) { auto self(this->shared_from_this()); socket_.async_read_some( boost::asio::mutable_buffers_1(buffer->buffer(), buffer->capacity()), [this, self, buffer](const boost::system::error_code &ec, std::size_t bytes_transferred) { if (ec) { HandleError(ec); return; } if (delegate_) { buffer->ReserveBack(buffer->capacity() - bytes_transferred); delegate_->DidRead(buffer, self); return; } }); } void BoostTcpSocket::Write(const std::shared_ptr<Buffer> buffer) { auto self(this->shared_from_this()); socket_.async_send( boost::asio::const_buffers_1(buffer->buffer(), buffer->capacity()), [this, self, buffer](const boost::system::error_code &ec, std::size_t bytes_transferred) { (void)bytes_transferred; if (ec) { HandleError(ec); return; } if (delegate_) { delegate_->DidWrite(buffer, self); return; } }); } void BoostTcpSocket::HandleError(const boost::system::error_code &ec) { if (ec.category() == boost::asio::error::get_system_category()) { if (ec.value() == boost::asio::error::operation_aborted) { return; } } else if (ec.category() == boost::asio::error::get_misc_category()) { if (ec.value() == boost::asio::error::eof) { if (delegate_) { eof_ = true; delegate_->DidEOF(this->shared_from_this()); CheckClose(); return; } } } if (delegate_) { delegate_->DidError(ConvertBoostError(ec), this->shared_from_this()); return; } } Error BoostTcpSocket::ConvertBoostError(const boost::system::error_code &ec) { (void)ec; // TODO: Convert boost error to custom tcp error. return std::make_error_code(TcpSocketInterface::kUnknownError); } void BoostTcpSocket::CheckClose() { if (!closed_ && connected_ && eof_ && shutdown_) { closed_ = true; auto self(this->shared_from_this()); socket_.get_io_service().post([this, self]() { if (this->delegate_) { this->delegate_->DidClose(self); } }); } } } // namespace utils } // namespace nekit <commit_msg>Upcast shared_ptr explicitly<commit_after>#include <nekit/utils/boost_tcp_socket.h> namespace nekit { namespace utils { BoostTcpSocket::BoostTcpSocket(boost::asio::io_service &service) : BoostTcpSocket(service, nullptr) {} BoostTcpSocket::BoostTcpSocket(boost::asio::io_service &service, DelegatePointer delegate) : socket_(service), delegate_(delegate), connected_(false), eof_(false), shutdown_(false), closed_(false) {} BoostTcpSocket::Pointer BoostTcpSocket::CreateSocket( boost::asio::io_service &service) { // Not using `make_shared` since the ctor is private. This class if final thus // it is not able to workaround it. Anyway, considering this is a heavy class, // the overhead is negligible. return std::static_pointer_cast<TcpSocketInterface>( std::shared_ptr<BoostTcpSocket>(new BoostTcpSocket(service))); } BoostTcpSocket::Pointer BoostTcpSocket::CreateSocket( boost::asio::io_service &service, DelegatePointer delegate) { return std::static_pointer_cast<TcpSocketInterface>( std::shared_ptr<BoostTcpSocket>(new BoostTcpSocket(service, delegate))); } // namespace utils void BoostTcpSocket::set_delegate(DelegatePointer delegate) { delegate_ = delegate; } void BoostTcpSocket::Connect(const boost::asio::ip::tcp::endpoint endpoint) { auto self(this->shared_from_this()); socket_.async_connect(endpoint, [this, self](const boost::system::error_code &ec) { if (ec) { HandleError(ec); return; } if (delegate_) delegate_->DidConnect(this->shared_from_this()); }); } Error BoostTcpSocket::Bind(const boost::asio::ip::tcp::endpoint endpoint) { boost::system::error_code ec; socket_.bind(endpoint, ec); return ConvertBoostError(ec); } Error BoostTcpSocket::Shutdown() { boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); shutdown_ = true; CheckClose(); return ConvertBoostError(ec); } void BoostTcpSocket::Read(std::shared_ptr<Buffer> buffer) { auto self(this->shared_from_this()); socket_.async_read_some( boost::asio::mutable_buffers_1(buffer->buffer(), buffer->capacity()), [this, self, buffer](const boost::system::error_code &ec, std::size_t bytes_transferred) { if (ec) { HandleError(ec); return; } if (delegate_) { buffer->ReserveBack(buffer->capacity() - bytes_transferred); delegate_->DidRead(buffer, self); return; } }); } void BoostTcpSocket::Write(const std::shared_ptr<Buffer> buffer) { auto self(this->shared_from_this()); socket_.async_send( boost::asio::const_buffers_1(buffer->buffer(), buffer->capacity()), [this, self, buffer](const boost::system::error_code &ec, std::size_t bytes_transferred) { (void)bytes_transferred; if (ec) { HandleError(ec); return; } if (delegate_) { delegate_->DidWrite(buffer, self); return; } }); } void BoostTcpSocket::HandleError(const boost::system::error_code &ec) { if (ec.category() == boost::asio::error::get_system_category()) { if (ec.value() == boost::asio::error::operation_aborted) { return; } } else if (ec.category() == boost::asio::error::get_misc_category()) { if (ec.value() == boost::asio::error::eof) { if (delegate_) { eof_ = true; delegate_->DidEOF(this->shared_from_this()); CheckClose(); return; } } } if (delegate_) { delegate_->DidError(ConvertBoostError(ec), this->shared_from_this()); return; } } Error BoostTcpSocket::ConvertBoostError(const boost::system::error_code &ec) { (void)ec; // TODO: Convert boost error to custom tcp error. return std::make_error_code(TcpSocketInterface::kUnknownError); } void BoostTcpSocket::CheckClose() { if (!closed_ && connected_ && eof_ && shutdown_) { closed_ = true; auto self(this->shared_from_this()); socket_.get_io_service().post([this, self]() { if (this->delegate_) { this->delegate_->DidClose(self); } }); } } } // namespace utils } // namespace nekit <|endoftext|>
<commit_before>#include "vast/util/command_line.h" namespace vast { namespace util { bool command_line::add_mode(std::string name, std::string desc, std::string prompt) { if (modes_.count(name)) return false; auto m = std::make_shared<mode>( std::move(name), std::move(desc), std::move(prompt)); modes_.emplace(m->name, m); return true; } bool command_line::add_command(std::string const& mode, std::string cmd, callback f) { if (! modes_.count(mode)) return false; auto& m = *modes_[mode]; if (m.callbacks.count(cmd)) return false; m.el.complete(cmd); m.callbacks.emplace(std::move(cmd), std::move(f)); return true; } bool command_line::on_unknown_command(std::string const& mode, callback f) { if (! modes_.count(mode)) return false; auto& m = *modes_[mode]; m.unknown_command = f; return true; } bool command_line::push_mode(std::string const& mode) { if (! modes_.count(mode)) return false; mode_stack_.push_back(modes_[mode]); return true; } bool command_line::pop_mode() { if (mode_stack_.empty()) return false; mode_stack_.pop_back(); return true; } bool command_line::append_to_history(std::string const& entry) { if (mode_stack_.empty()) return false; mode_stack_.back()->hist.enter(entry); return true; } bool command_line::process(bool& callback_result) { if (mode_stack_.empty()) return false; std::string cmd; auto current = mode_stack_.back(); current->el.reset(); // Fixes TTY weirdness when switching between modes. if (! current->el.get(cmd)) return false; auto first_space = cmd.find(' '); auto key = cmd.substr(0, first_space); if (! current->callbacks.count(key)) { if (current->unknown_command) current->unknown_command(std::move(cmd)); return false; } auto args = first_space == std::string::npos ? cmd : cmd.substr(first_space); callback_result = current->callbacks[key](std::move(args)); current->hist.enter(cmd); return true; } command_line::mode::mode(std::string name, std::string desc, std::string prompt) : name{std::move(name)}, description{std::move(desc)} { el.source(); el.set(hist); if (! prompt.empty()) el.set(editline::prompt{std::move(prompt)}); } } // namespace util } // namespace vast <commit_msg>Consider unknown command callback as "valid."<commit_after>#include "vast/util/command_line.h" namespace vast { namespace util { bool command_line::add_mode(std::string name, std::string desc, std::string prompt) { if (modes_.count(name)) return false; auto m = std::make_shared<mode>( std::move(name), std::move(desc), std::move(prompt)); modes_.emplace(m->name, m); return true; } bool command_line::add_command(std::string const& mode, std::string cmd, callback f) { if (! modes_.count(mode)) return false; auto& m = *modes_[mode]; if (m.callbacks.count(cmd)) return false; m.el.complete(cmd); m.callbacks.emplace(std::move(cmd), std::move(f)); return true; } bool command_line::on_unknown_command(std::string const& mode, callback f) { if (! modes_.count(mode)) return false; auto& m = *modes_[mode]; m.unknown_command = f; return true; } bool command_line::push_mode(std::string const& mode) { if (! modes_.count(mode)) return false; mode_stack_.push_back(modes_[mode]); return true; } bool command_line::pop_mode() { if (mode_stack_.empty()) return false; mode_stack_.pop_back(); return true; } bool command_line::append_to_history(std::string const& entry) { if (mode_stack_.empty()) return false; mode_stack_.back()->hist.enter(entry); return true; } bool command_line::process(bool& callback_result) { if (mode_stack_.empty()) return false; std::string cmd; auto current = mode_stack_.back(); current->el.reset(); // Fixes TTY weirdness when switching between modes. if (! current->el.get(cmd)) return false; auto first_space = cmd.find(' '); auto key = cmd.substr(0, first_space); if (! current->callbacks.count(key)) { if (! current->unknown_command) return false; callback_result = current->unknown_command(std::move(cmd)); return true; } auto args = first_space == std::string::npos ? cmd : cmd.substr(first_space); callback_result = current->callbacks[key](std::move(args)); current->hist.enter(cmd); return true; } command_line::mode::mode(std::string name, std::string desc, std::string prompt) : name{std::move(name)}, description{std::move(desc)} { el.source(); el.set(hist); if (! prompt.empty()) el.set(editline::prompt{std::move(prompt)}); } } // namespace util } // namespace vast <|endoftext|>
<commit_before>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2014 Steven Lovegrove * * 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 <pangolin/video/drivers/debayer.h> #ifdef HAVE_DC1394 # include <dc1394/conversions.h> const bool have_dc1394 = true; #else const bool have_dc1394 = false; #endif namespace pangolin { pangolin::StreamInfo BayerOutputFormat( const StreamInfo& stream_in, bayer_method_t method, size_t start_offset) { const bool downsample = (method == BAYER_METHOD_DOWNSAMPLE) || (method == BAYER_METHOD_DOWNSAMPLE_MONO); const size_t w = downsample ? stream_in.Width() / 2 : stream_in.Width(); const size_t h = downsample ? stream_in.Height() / 2 : stream_in.Height(); pangolin::VideoPixelFormat fmt = (method == BAYER_METHOD_NONE) ? stream_in.PixFormat() : pangolin::VideoFormatFromString( (stream_in.PixFormat().bpp == 16) ? (method == BAYER_METHOD_DOWNSAMPLE_MONO ? "GRAY16LE" : "RGB48") : (method == BAYER_METHOD_DOWNSAMPLE_MONO ? "GRAY8" : "RGB24") ); return pangolin::StreamInfo( fmt, w, h, w*fmt.bpp / 8, (unsigned char*)0 + start_offset ); } DebayerVideo::DebayerVideo(VideoInterface* src, const std::vector<bayer_method_t>& bayer_method, color_filter_t tile) : size_bytes(0), buffer(0), methods(bayer_method), tile(tile) { if(!src) { throw VideoException("DebayerVideo: VideoInterface in must not be null"); } videoin.push_back(src); while(methods.size() < src->Streams().size()) { methods.push_back(BAYER_METHOD_NONE); } for(size_t s=0; s< src->Streams().size(); ++s) { if( (methods[s] < BAYER_METHOD_NONE) && (!have_dc1394 || src->Streams()[0].IsPitched()) ) { pango_print_warn("debayer: Switching to simple downsampling method because No DC1394 or image is pitched.\n"); methods[s] = BAYER_METHOD_DOWNSAMPLE; } const StreamInfo& stin = src->Streams()[s]; streams.push_back(BayerOutputFormat(stin, methods[s], size_bytes)); size_bytes += streams.back().SizeBytes(); } buffer = new unsigned char[src->SizeBytes()]; } DebayerVideo::~DebayerVideo() { delete[] buffer; delete videoin[0]; } //! Implement VideoInput::Start() void DebayerVideo::Start() { videoin[0]->Start(); } //! Implement VideoInput::Stop() void DebayerVideo::Stop() { videoin[0]->Stop(); } //! Implement VideoInput::SizeBytes() size_t DebayerVideo::SizeBytes() const { return size_bytes; } //! Implement VideoInput::Streams() const std::vector<StreamInfo>& DebayerVideo::Streams() const { return streams; } unsigned int DebayerVideo::AvailableFrames() const { BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]); if(!vpi) { pango_print_warn("Debayer: child interface is not buffer aware."); return 0; } else { return vpi->AvailableFrames(); } } bool DebayerVideo::DropNFrames(uint32_t n) { BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]); if(!vpi) { pango_print_warn("Debayer: child interface is not buffer aware."); return false; } else { return vpi->DropNFrames(n); } } template<typename Tup, typename Tout, typename Tin> void DownsampleToMono(Image<Tout>& out, const Image<Tin>& in) { for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { Tup val = ((Tup)irow0[0] + (Tup)irow0[1] + (Tup)irow1[0] + (Tup)irow1[1]) / 4; *(pixout++) = (Tout)std::min(std::max(static_cast<Tup>(0), val), static_cast<Tup>(std::numeric_limits<Tout>::max())); irow0 += 2; irow1 += 2; } } } template<typename Tout, typename Tin> void DownsampleDebayer(Image<Tout>& out, const Image<Tin>& in, color_filter_t tile) { switch(tile) { case DC1394_COLOR_FILTER_RGGB: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow0[2*x]; *(pixout++) = (irow0[2*x+1] + irow1[2*x]) >> 1; *(pixout++) = irow1[2*x+1]; } } break; case DC1394_COLOR_FILTER_GBRG: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow1[2*x]; *(pixout++) = (irow0[2*x] + irow1[2*x+1]) >> 1; *(pixout++) = irow0[2*x+1]; } } break; case DC1394_COLOR_FILTER_GRBG: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow0[2*x+1]; *(pixout++) = (irow0[2*x] + irow1[2*x+1]) >> 1; *(pixout++) = irow1[2*x]; } } break; case DC1394_COLOR_FILTER_BGGR: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow1[2*x+1]; *(pixout++) = (irow0[2*x+1] + irow1[2*x]) >> 1; *(pixout++) = irow0[2*x]; } } break; } } template<typename T> void PitchedImageCopy( Image<T>& img_out, const Image<T>& img_in ) { if( img_out.w != img_in.w || img_out.h != img_in.h || sizeof(T) * img_in.w > img_out.pitch) { throw std::runtime_error("PitchedImageCopy: Incompatible image sizes"); } for(size_t y=0; y < img_out.h; ++y) { std::memcpy(img_out.RowPtr((int)y), img_in.RowPtr((int)y), sizeof(T) * img_in.w); } } template<typename Tout, typename Tin> void ProcessImage(Image<Tout>& img_out, const Image<Tin>& img_in, bayer_method_t method, color_filter_t tile) { if(method == BAYER_METHOD_NONE) { PitchedImageCopy(img_out, img_in.template Reinterpret<Tout>() ); }else if(method == BAYER_METHOD_DOWNSAMPLE_MONO) { if( sizeof(Tout) == 1) { DownsampleToMono<int,Tout, Tin>(img_out, img_in); }else{ DownsampleToMono<double,Tout, Tin>(img_out, img_in); } }else if(method == BAYER_METHOD_DOWNSAMPLE) { DownsampleDebayer(img_out, img_in, tile); }else{ #ifdef HAVE_DC1394 if(sizeof(Tout) == 8) { dc1394_bayer_decoding_8bit( (uint8_t*)img_in.ptr, (uint8_t*)img_out.ptr, img_in.w, img_in.h, (dc1394color_filter_t)tile, (dc1394bayer_method_t)method ); }else if(sizeof(Tout) == 16) { dc1394_bayer_decoding_16bit( (uint16_t*)img_in.ptr, (uint16_t*)img_out.ptr, img_in.w, img_in.h, (dc1394color_filter_t)tile, (dc1394bayer_method_t)method, 16 ); } #endif } } void DebayerVideo::ProcessStreams(unsigned char* out, const unsigned char *in) { for(size_t s=0; s<streams.size(); ++s) { const StreamInfo& stin = videoin[0]->Streams()[s]; if(stin.PixFormat().bpp == 8) { Image<unsigned char> img_in = stin.StreamImage(in); Image<unsigned char> img_out = Streams()[s].StreamImage(out); ProcessImage(img_out, img_in, methods[s], tile); }else if(stin.PixFormat().bpp == 16){ Image<uint16_t> img_in = stin.StreamImage(in).Reinterpret<uint16_t>(); Image<uint16_t> img_out = Streams()[s].StreamImage(out).Reinterpret<uint16_t>(); ProcessImage(img_out, img_in, methods[s], tile); }else{ throw std::runtime_error("debayer: unhandled format combination."); } } } //! Implement VideoInput::GrabNext() bool DebayerVideo::GrabNext( unsigned char* image, bool wait ) { if(videoin[0]->GrabNext(buffer,wait)) { ProcessStreams(image, buffer); return true; }else{ return false; } } //! Implement VideoInput::GrabNewest() bool DebayerVideo::GrabNewest( unsigned char* image, bool wait ) { if(videoin[0]->GrabNewest(buffer,wait)) { ProcessStreams(image, buffer); return true; }else{ return false; } } const json::value& DebayerVideo::DeviceProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); return in_prop ? in_prop->DeviceProperties() : device_properties; } const json::value& DebayerVideo::FrameProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); return in_prop ? in_prop->FrameProperties() : frame_properties; } std::vector<VideoInterface*>& DebayerVideo::InputStreams() { return videoin; } color_filter_t DebayerVideo::ColorFilterFromString(std::string str) { if(!str.compare("rggb") || !str.compare("RGGB")) return DC1394_COLOR_FILTER_RGGB; else if(!str.compare("gbrg") || !str.compare("GBRG")) return DC1394_COLOR_FILTER_GBRG; else if(!str.compare("grbg") || !str.compare("GRBG")) return DC1394_COLOR_FILTER_GRBG; else if(!str.compare("bggr") || !str.compare("BGGR")) return DC1394_COLOR_FILTER_BGGR; else { pango_print_error("Debayer error, %s is not a valid tile type using RGGB\n", str.c_str()); return DC1394_COLOR_FILTER_RGGB; } } bayer_method_t DebayerVideo::BayerMethodFromString(std::string str) { if(!str.compare("nearest")) return BAYER_METHOD_NEAREST; else if(!str.compare("simple")) return BAYER_METHOD_SIMPLE; else if(!str.compare("bilinear")) return BAYER_METHOD_BILINEAR; else if(!str.compare("hqlinear")) return BAYER_METHOD_HQLINEAR; else if(!str.compare("downsample")) return BAYER_METHOD_DOWNSAMPLE; else if(!str.compare("edgesense")) return BAYER_METHOD_EDGESENSE; else if(!str.compare("vng")) return BAYER_METHOD_VNG; else if(!str.compare("ahd")) return BAYER_METHOD_AHD; else if(!str.compare("mono")) return BAYER_METHOD_DOWNSAMPLE_MONO; else if(!str.compare("none")) return BAYER_METHOD_NONE; else { pango_print_error("Debayer error, %s is not a valid debayer method using downsample\n", str.c_str()); return BAYER_METHOD_DOWNSAMPLE; } } } <commit_msg>bayer bpp fix<commit_after>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2014 Steven Lovegrove * * 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 <pangolin/video/drivers/debayer.h> #ifdef HAVE_DC1394 # include <dc1394/conversions.h> const bool have_dc1394 = true; #else const bool have_dc1394 = false; #endif namespace pangolin { pangolin::StreamInfo BayerOutputFormat( const StreamInfo& stream_in, bayer_method_t method, size_t start_offset) { const bool downsample = (method == BAYER_METHOD_DOWNSAMPLE) || (method == BAYER_METHOD_DOWNSAMPLE_MONO); const size_t w = downsample ? stream_in.Width() / 2 : stream_in.Width(); const size_t h = downsample ? stream_in.Height() / 2 : stream_in.Height(); pangolin::VideoPixelFormat fmt = (method == BAYER_METHOD_NONE) ? stream_in.PixFormat() : pangolin::VideoFormatFromString( (stream_in.PixFormat().bpp == 16) ? (method == BAYER_METHOD_DOWNSAMPLE_MONO ? "GRAY16LE" : "RGB48") : (method == BAYER_METHOD_DOWNSAMPLE_MONO ? "GRAY8" : "RGB24") ); return pangolin::StreamInfo( fmt, w, h, w*fmt.bpp / 8, (unsigned char*)0 + start_offset ); } DebayerVideo::DebayerVideo(VideoInterface* src, const std::vector<bayer_method_t>& bayer_method, color_filter_t tile) : size_bytes(0), buffer(0), methods(bayer_method), tile(tile) { if(!src) { throw VideoException("DebayerVideo: VideoInterface in must not be null"); } videoin.push_back(src); while(methods.size() < src->Streams().size()) { methods.push_back(BAYER_METHOD_NONE); } for(size_t s=0; s< src->Streams().size(); ++s) { if( (methods[s] < BAYER_METHOD_NONE) && (!have_dc1394 || src->Streams()[0].IsPitched()) ) { pango_print_warn("debayer: Switching to simple downsampling method because No DC1394 or image is pitched.\n"); methods[s] = BAYER_METHOD_DOWNSAMPLE; } const StreamInfo& stin = src->Streams()[s]; streams.push_back(BayerOutputFormat(stin, methods[s], size_bytes)); size_bytes += streams.back().SizeBytes(); } buffer = new unsigned char[src->SizeBytes()]; } DebayerVideo::~DebayerVideo() { delete[] buffer; delete videoin[0]; } //! Implement VideoInput::Start() void DebayerVideo::Start() { videoin[0]->Start(); } //! Implement VideoInput::Stop() void DebayerVideo::Stop() { videoin[0]->Stop(); } //! Implement VideoInput::SizeBytes() size_t DebayerVideo::SizeBytes() const { return size_bytes; } //! Implement VideoInput::Streams() const std::vector<StreamInfo>& DebayerVideo::Streams() const { return streams; } unsigned int DebayerVideo::AvailableFrames() const { BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]); if(!vpi) { pango_print_warn("Debayer: child interface is not buffer aware."); return 0; } else { return vpi->AvailableFrames(); } } bool DebayerVideo::DropNFrames(uint32_t n) { BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]); if(!vpi) { pango_print_warn("Debayer: child interface is not buffer aware."); return false; } else { return vpi->DropNFrames(n); } } template<typename Tup, typename Tout, typename Tin> void DownsampleToMono(Image<Tout>& out, const Image<Tin>& in) { for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { Tup val = ((Tup)irow0[0] + (Tup)irow0[1] + (Tup)irow1[0] + (Tup)irow1[1]) / 4; *(pixout++) = (Tout)std::min(std::max(static_cast<Tup>(0), val), static_cast<Tup>(std::numeric_limits<Tout>::max())); irow0 += 2; irow1 += 2; } } } template<typename Tout, typename Tin> void DownsampleDebayer(Image<Tout>& out, const Image<Tin>& in, color_filter_t tile) { switch(tile) { case DC1394_COLOR_FILTER_RGGB: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow0[2*x]; *(pixout++) = (irow0[2*x+1] + irow1[2*x]) >> 1; *(pixout++) = irow1[2*x+1]; } } break; case DC1394_COLOR_FILTER_GBRG: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow1[2*x]; *(pixout++) = (irow0[2*x] + irow1[2*x+1]) >> 1; *(pixout++) = irow0[2*x+1]; } } break; case DC1394_COLOR_FILTER_GRBG: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow0[2*x+1]; *(pixout++) = (irow0[2*x] + irow1[2*x+1]) >> 1; *(pixout++) = irow1[2*x]; } } break; case DC1394_COLOR_FILTER_BGGR: for(int y=0; y< (int)out.h; ++y) { Tout* pixout = out.RowPtr(y); const Tin* irow0 = in.RowPtr(2*y); const Tin* irow1 = in.RowPtr(2*y+1); for(size_t x=0; x<out.w; ++x) { *(pixout++) = irow1[2*x+1]; *(pixout++) = (irow0[2*x+1] + irow1[2*x]) >> 1; *(pixout++) = irow0[2*x]; } } break; } } template<typename T> void PitchedImageCopy( Image<T>& img_out, const Image<T>& img_in ) { if( img_out.w != img_in.w || img_out.h != img_in.h || sizeof(T) * img_in.w > img_out.pitch) { throw std::runtime_error("PitchedImageCopy: Incompatible image sizes"); } for(size_t y=0; y < img_out.h; ++y) { std::memcpy(img_out.RowPtr((int)y), img_in.RowPtr((int)y), sizeof(T) * img_in.w); } } template<typename Tout, typename Tin> void ProcessImage(Image<Tout>& img_out, const Image<Tin>& img_in, bayer_method_t method, color_filter_t tile) { if(method == BAYER_METHOD_NONE) { PitchedImageCopy(img_out, img_in.template Reinterpret<Tout>() ); }else if(method == BAYER_METHOD_DOWNSAMPLE_MONO) { if( sizeof(Tout) == 1) { DownsampleToMono<int,Tout, Tin>(img_out, img_in); }else{ DownsampleToMono<double,Tout, Tin>(img_out, img_in); } }else if(method == BAYER_METHOD_DOWNSAMPLE) { DownsampleDebayer(img_out, img_in, tile); }else{ #ifdef HAVE_DC1394 if(sizeof(Tout) == 1) { dc1394_bayer_decoding_8bit( (uint8_t*)img_in.ptr, (uint8_t*)img_out.ptr, img_in.w, img_in.h, (dc1394color_filter_t)tile, (dc1394bayer_method_t)method ); }else if(sizeof(Tout) == 2) { dc1394_bayer_decoding_16bit( (uint16_t*)img_in.ptr, (uint16_t*)img_out.ptr, img_in.w, img_in.h, (dc1394color_filter_t)tile, (dc1394bayer_method_t)method, 16 ); } #endif } } void DebayerVideo::ProcessStreams(unsigned char* out, const unsigned char *in) { for(size_t s=0; s<streams.size(); ++s) { const StreamInfo& stin = videoin[0]->Streams()[s]; if(stin.PixFormat().bpp == 8) { Image<unsigned char> img_in = stin.StreamImage(in); Image<unsigned char> img_out = Streams()[s].StreamImage(out); ProcessImage(img_out, img_in, methods[s], tile); }else if(stin.PixFormat().bpp == 16){ Image<uint16_t> img_in = stin.StreamImage(in).Reinterpret<uint16_t>(); Image<uint16_t> img_out = Streams()[s].StreamImage(out).Reinterpret<uint16_t>(); ProcessImage(img_out, img_in, methods[s], tile); }else{ throw std::runtime_error("debayer: unhandled format combination."); } } } //! Implement VideoInput::GrabNext() bool DebayerVideo::GrabNext( unsigned char* image, bool wait ) { if(videoin[0]->GrabNext(buffer,wait)) { ProcessStreams(image, buffer); return true; }else{ return false; } } //! Implement VideoInput::GrabNewest() bool DebayerVideo::GrabNewest( unsigned char* image, bool wait ) { if(videoin[0]->GrabNewest(buffer,wait)) { ProcessStreams(image, buffer); return true; }else{ return false; } } const json::value& DebayerVideo::DeviceProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); return in_prop ? in_prop->DeviceProperties() : device_properties; } const json::value& DebayerVideo::FrameProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); return in_prop ? in_prop->FrameProperties() : frame_properties; } std::vector<VideoInterface*>& DebayerVideo::InputStreams() { return videoin; } color_filter_t DebayerVideo::ColorFilterFromString(std::string str) { if(!str.compare("rggb") || !str.compare("RGGB")) return DC1394_COLOR_FILTER_RGGB; else if(!str.compare("gbrg") || !str.compare("GBRG")) return DC1394_COLOR_FILTER_GBRG; else if(!str.compare("grbg") || !str.compare("GRBG")) return DC1394_COLOR_FILTER_GRBG; else if(!str.compare("bggr") || !str.compare("BGGR")) return DC1394_COLOR_FILTER_BGGR; else { pango_print_error("Debayer error, %s is not a valid tile type using RGGB\n", str.c_str()); return DC1394_COLOR_FILTER_RGGB; } } bayer_method_t DebayerVideo::BayerMethodFromString(std::string str) { if(!str.compare("nearest")) return BAYER_METHOD_NEAREST; else if(!str.compare("simple")) return BAYER_METHOD_SIMPLE; else if(!str.compare("bilinear")) return BAYER_METHOD_BILINEAR; else if(!str.compare("hqlinear")) return BAYER_METHOD_HQLINEAR; else if(!str.compare("downsample")) return BAYER_METHOD_DOWNSAMPLE; else if(!str.compare("edgesense")) return BAYER_METHOD_EDGESENSE; else if(!str.compare("vng")) return BAYER_METHOD_VNG; else if(!str.compare("ahd")) return BAYER_METHOD_AHD; else if(!str.compare("mono")) return BAYER_METHOD_DOWNSAMPLE_MONO; else if(!str.compare("none")) return BAYER_METHOD_NONE; else { pango_print_error("Debayer error, %s is not a valid debayer method using downsample\n", str.c_str()); return BAYER_METHOD_DOWNSAMPLE; } } } <|endoftext|>
<commit_before>#include "TCPSocket.h" #ifndef WIN32 /* UNIX */ #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #endif /** * Default Constructor, this constructor should only be used by * clients wanting to use a TCPServer. Hence no initialisation is * required. The socket should by default be in an invalid state. */ TCPSocket::TCPSocket() {} /** * Create a TCPSocket and attempt to connect the socket to the specified * server on the given port. The first available local port is used for the * connection. * * @param server The server to connect to, this can be a string based ip, or hostname * @param port The remote port to connect to * @throws SocketError If there was a problem resolving the hostname or connecting to the host */ TCPSocket::TCPSocket( const std::string server, const unsigned port ) { struct hostent *he; // Create a new socket if ( !this->create()){ throw new SocketException(this); } // Setup the address to connect too address.sin_family = AF_INET; address.sin_port = htons ( port ); #ifdef WIN32 // If we can't do a quick conversion, try the long way he = gethostbyname( server.c_str()); if ( he == NULL ){ throw new SocketException(this); } memcpy(&address.sin_addr, he->h_addr_list[0], he->h_length); #else /* Unix */ // Attempt to perform a quick conversion, this only works provided the server string // passed in is a fully qualified name/ip. if ( inet_pton( AF_INET, server.c_str(), &address.sin_addr ) == 0 ){ // If we can't do a quick conversion, try the long way he = gethostbyname( server.c_str()); if ( he == NULL ){ throw new SocketException(this); } memcpy(&address.sin_addr, he->h_addr_list[0], he->h_length); } #endif } /** * Actually attempt to perform the connection **/ void TCPSocket::connect() { // Perform the connection if ( ::connect( this->sockfd, (sockaddr *)&address, sizeof(address)) == -1 ){ this->close(); throw new SocketException(this); } } /** * Create a socket of type SOCK_STREAM and allow more than one socket to listen on * the one port if required * * @return true if The socket was created successfully, else false */ bool TCPSocket::create() { this->sockfd = socket( AF_INET, SOCK_STREAM, 0 ); if ( !this->isValid()){ return false; } // Allow multiple sockets to listen on the one port for the application int on =1; if ( setsockopt ( this->sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on)) == -1 ){ this->close(); return false; } #ifndef WIN32 /* UNIX */ // XXX/FIXME: For some reason this fails under MSVC // with error 10042 - Unknown, invalid option (SO_BROADCAST) // I don't know why at present - Ben 20060529 // Enable the user to send to the broadcast address on = 1; if (setsockopt (this->sockfd, SOL_SOCKET, SO_BROADCAST, (const char *)&on, sizeof (on)) == -1){ this->close(); return false; } #endif return true; } void TCPSocket::setFileDescriptor( int input) { this->sockfd = input; } void TCPSocket::setRemoteAddress( sockaddr_in address) { this->address = address; } <commit_msg>Revert 1ba1eb52d6bcfcc9eb8b8a578c4d4427039633fe, added connect method<commit_after>#include "TCPSocket.h" #ifndef WIN32 /* UNIX */ #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #endif /** * Default Constructor, this constructor should only be used by * clients wanting to use a TCPServer. Hence no initialisation is * required. The socket should by default be in an invalid state. */ TCPSocket::TCPSocket() {} /** * Create a TCPSocket and attempt to connect the socket to the specified * server on the given port. The first available local port is used for the * connection. * * @param server The server to connect to, this can be a string based ip, or hostname * @param port The remote port to connect to * @throws SocketError If there was a problem resolving the hostname or connecting to the host */ TCPSocket::TCPSocket( const std::string server, const unsigned port ) { struct hostent *he; // Create a new socket if ( !this->create()){ throw new SocketException(this); } // Setup the address to connect too address.sin_family = AF_INET; address.sin_port = htons ( port ); #ifdef WIN32 // If we can't do a quick conversion, try the long way he = gethostbyname( server.c_str()); if ( he == NULL ){ throw new SocketException(this); } memcpy(&address.sin_addr, he->h_addr_list[0], he->h_length); #else /* Unix */ // Attempt to perform a quick conversion, this only works provided the server string // passed in is a fully qualified name/ip. if ( inet_pton( AF_INET, server.c_str(), &address.sin_addr ) == 0 ){ // If we can't do a quick conversion, try the long way he = gethostbyname( server.c_str()); if ( he == NULL ){ throw new SocketException(this); } memcpy(&address.sin_addr, he->h_addr_list[0], he->h_length); } #endif // Perform the connection if ( ::connect( this->sockfd, (sockaddr *)&address, sizeof(address)) == -1 ){ this->close(); throw new SocketException(this); } } /** * Create a socket of type SOCK_STREAM and allow more than one socket to listen on * the one port if required * * @return true if The socket was created successfully, else false */ bool TCPSocket::create() { this->sockfd = socket( AF_INET, SOCK_STREAM, 0 ); if ( !this->isValid()){ return false; } // Allow multiple sockets to listen on the one port for the application int on =1; if ( setsockopt ( this->sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on)) == -1 ){ this->close(); return false; } #ifndef WIN32 /* UNIX */ // XXX/FIXME: For some reason this fails under MSVC // with error 10042 - Unknown, invalid option (SO_BROADCAST) // I don't know why at present - Ben 20060529 // Enable the user to send to the broadcast address on = 1; if (setsockopt (this->sockfd, SOL_SOCKET, SO_BROADCAST, (const char *)&on, sizeof (on)) == -1){ this->close(); return false; } #endif return true; } void TCPSocket::setFileDescriptor( int input) { this->sockfd = input; } void TCPSocket::setRemoteAddress( sockaddr_in address) { this->address = address; } <|endoftext|>
<commit_before>#include "ms_layer.hpp" #include "ms_common.hpp" #include "ms_map.hpp" Persistent<FunctionTemplate> MSLayer::constructor; void MSLayer::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(MSLayer::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Layer")); NODE_SET_PROTOTYPE_METHOD(constructor, "getGridIntersectionCoordinates", GetGridIntersectionCoordinates); NODE_SET_PROTOTYPE_METHOD(constructor, "updateFromString", UpdateFromString); RW_PROPERTY(constructor, "name", PropertyGetter, PropertySetter); RW_PROPERTY(constructor, "status", PropertyGetter, PropertySetter); target->Set(String::NewSymbol("Layer"), constructor->GetFunction()); } MSLayer::MSLayer(layerObj *layer) : ObjectWrap(), this_(layer) {} MSLayer::MSLayer() : ObjectWrap(), this_(0) {} MSLayer::~MSLayer() { } Handle<Value> MSLayer::New(const Arguments &args) { HandleScope scope; layerObj *layer; MSLayer *obj; if (!args.IsConstructCall()) { return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); } if (args[0]->IsExternal()) { Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); obj = static_cast<MSLayer*>(ptr); obj->Wrap(args.This()); return args.This(); } REQ_STR_ARG(0, layer_name); layer = (layerObj*)calloc(1,sizeof(layerObj)); initLayer(layer, (mapObj*)NULL); REPLACE_STRING(layer->name, String::New(*layer_name)); obj = new MSLayer(layer); obj->Wrap(args.This()); return args.This(); } Handle<Value> MSLayer::New(layerObj *layer) { return ClosedPtr<MSLayer, layerObj>::Closed(layer); } Handle<Value> MSLayer::PropertyGetter (Local<String> property, const AccessorInfo& info) { MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(info.This()); v8::String::AsciiValue n(property); if (strcmp(*n, "name") == 0) { RETURN_STRING(layer->this_->name); } else if (strcmp(*n, "status") == 0) { RETURN_NUMBER(layer->this_->status); } return Undefined(); } void MSLayer::PropertySetter (Local<String> property, Local<Value> value, const AccessorInfo& info) { MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(info.Holder()); v8::String::AsciiValue n(property); if (strcmp(*n, "name") == 0) { REPLACE_STRING(layer->this_->name, value) } else if (strcmp(*n, "status") == 0) { layer->this_->status = value->NumberValue(); } } Handle<Value> MSLayer::GetGridIntersectionCoordinates (const Arguments& args) { HandleScope scope; MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(args.This()); int i = 0; graticuleIntersectionObj *values = msGraticuleLayerGetIntersectionPoints(layer->this_->map, layer->this_); Handle<ObjectTemplate> objTempl = ObjectTemplate::New(); objTempl->SetInternalFieldCount(1); Handle<Array> left = Array::New(values->nLeft); Handle<Array> top = Array::New(values->nTop); Handle<Array> right = Array::New(values->nRight); Handle<Array> bottom = Array::New(values->nBottom); for (i=0; i<values->nLeft; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasLeft[i].x)); val->Set(String::New("y"), Number::New(values->pasLeft[i].y)); val->Set(String::New("label"), String::New(values->papszLeftLabels[i])); left->Set(i, val); } for (i=0; i<values->nTop; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasTop[i].x)); val->Set(String::New("y"), Number::New(values->pasTop[i].y)); val->Set(String::New("label"), String::New(values->papszTopLabels[i])); top->Set(i, val); } for (i=0; i<values->nRight; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasRight[i].x)); val->Set(String::New("y"), Number::New(values->pasRight[i].y)); val->Set(String::New("label"), String::New(values->papszRightLabels[i])); right->Set(i, val); } for (i=0; i<values->nBottom; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasBottom[i].x)); val->Set(String::New("y"), Number::New(values->pasBottom[i].y)); val->Set(String::New("label"), String::New(values->papszBottomLabels[i])); bottom->Set(i, val); } // return object like this: // { // left: [{position: 0, label: '123.00'}], // top: [{position: 0, label: '123.00'}], // right: [{position: 0, label: '123.00'}], // bottom: [{position: 0, label: '123.00'}], // } Local<Object> result = objTempl->NewInstance(); result->Set(String::New("left"), left); result->Set(String::New("top"), top); result->Set(String::New("right"), right); result->Set(String::New("bottom"), bottom); return scope.Close(result); } Handle<Value> MSLayer::UpdateFromString (const Arguments& args) { HandleScope scope; int result; MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(args.This()); REQ_STR_ARG(0, snippet); result = msUpdateLayerFromString(layer->this_, *snippet, MS_FALSE); return scope.Close(Number::New(result)); } <commit_msg>improve layer constructor string handling<commit_after>#include "ms_layer.hpp" #include "ms_common.hpp" #include "ms_map.hpp" Persistent<FunctionTemplate> MSLayer::constructor; void MSLayer::Initialize(Handle<Object> target) { HandleScope scope; constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(MSLayer::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Layer")); NODE_SET_PROTOTYPE_METHOD(constructor, "getGridIntersectionCoordinates", GetGridIntersectionCoordinates); NODE_SET_PROTOTYPE_METHOD(constructor, "updateFromString", UpdateFromString); RW_PROPERTY(constructor, "name", PropertyGetter, PropertySetter); RW_PROPERTY(constructor, "status", PropertyGetter, PropertySetter); target->Set(String::NewSymbol("Layer"), constructor->GetFunction()); } MSLayer::MSLayer(layerObj *layer) : ObjectWrap(), this_(layer) {} MSLayer::MSLayer() : ObjectWrap(), this_(0) {} MSLayer::~MSLayer() { } Handle<Value> MSLayer::New(const Arguments &args) { HandleScope scope; layerObj *layer; MSLayer *obj; if (!args.IsConstructCall()) { return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); } if (args[0]->IsExternal()) { Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); obj = static_cast<MSLayer*>(ptr); obj->Wrap(args.This()); return args.This(); } REQ_STR_ARG(0, layer_name); layer = (layerObj*)calloc(1,sizeof(layerObj)); initLayer(layer, (mapObj*)NULL); layer->name = strdup(*layer_name); obj = new MSLayer(layer); obj->Wrap(args.This()); return args.This(); } Handle<Value> MSLayer::New(layerObj *layer) { return ClosedPtr<MSLayer, layerObj>::Closed(layer); } Handle<Value> MSLayer::PropertyGetter (Local<String> property, const AccessorInfo& info) { MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(info.This()); v8::String::AsciiValue n(property); if (strcmp(*n, "name") == 0) { RETURN_STRING(layer->this_->name); } else if (strcmp(*n, "status") == 0) { RETURN_NUMBER(layer->this_->status); } return Undefined(); } void MSLayer::PropertySetter (Local<String> property, Local<Value> value, const AccessorInfo& info) { MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(info.Holder()); v8::String::AsciiValue n(property); if (strcmp(*n, "name") == 0) { REPLACE_STRING(layer->this_->name, value) } else if (strcmp(*n, "status") == 0) { layer->this_->status = value->NumberValue(); } } Handle<Value> MSLayer::GetGridIntersectionCoordinates (const Arguments& args) { HandleScope scope; MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(args.This()); int i = 0; graticuleIntersectionObj *values = msGraticuleLayerGetIntersectionPoints(layer->this_->map, layer->this_); Handle<ObjectTemplate> objTempl = ObjectTemplate::New(); objTempl->SetInternalFieldCount(1); Handle<Array> left = Array::New(values->nLeft); Handle<Array> top = Array::New(values->nTop); Handle<Array> right = Array::New(values->nRight); Handle<Array> bottom = Array::New(values->nBottom); for (i=0; i<values->nLeft; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasLeft[i].x)); val->Set(String::New("y"), Number::New(values->pasLeft[i].y)); val->Set(String::New("label"), String::New(values->papszLeftLabels[i])); left->Set(i, val); } for (i=0; i<values->nTop; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasTop[i].x)); val->Set(String::New("y"), Number::New(values->pasTop[i].y)); val->Set(String::New("label"), String::New(values->papszTopLabels[i])); top->Set(i, val); } for (i=0; i<values->nRight; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasRight[i].x)); val->Set(String::New("y"), Number::New(values->pasRight[i].y)); val->Set(String::New("label"), String::New(values->papszRightLabels[i])); right->Set(i, val); } for (i=0; i<values->nBottom; i++) { Local<Object> val = objTempl->NewInstance(); val->Set(String::New("x"), Number::New(values->pasBottom[i].x)); val->Set(String::New("y"), Number::New(values->pasBottom[i].y)); val->Set(String::New("label"), String::New(values->papszBottomLabels[i])); bottom->Set(i, val); } // return object like this: // { // left: [{position: 0, label: '123.00'}], // top: [{position: 0, label: '123.00'}], // right: [{position: 0, label: '123.00'}], // bottom: [{position: 0, label: '123.00'}], // } Local<Object> result = objTempl->NewInstance(); result->Set(String::New("left"), left); result->Set(String::New("top"), top); result->Set(String::New("right"), right); result->Set(String::New("bottom"), bottom); return scope.Close(result); } Handle<Value> MSLayer::UpdateFromString (const Arguments& args) { HandleScope scope; int result; MSLayer *layer = ObjectWrap::Unwrap<MSLayer>(args.This()); REQ_STR_ARG(0, snippet); result = msUpdateLayerFromString(layer->this_, *snippet, MS_FALSE); return scope.Close(Number::New(result)); } <|endoftext|>
<commit_before>#include "vest.h" #include "gif_lib.h" #include "gifs.h" GifByteType nyan_cat_bytes[] = { 0x47,0x49,0x46,0x38,0x39,0x61,0x18,0x00,0x10,0x00,0xf3,0x00,0x00,0x1a,0x1a,0x1a, 0xff,0x00,0x00,0x66,0x33,0xff,0xff,0x33,0x99,0x00,0x99,0xff,0x99,0x99,0x99,0xff, 0x99,0x00,0xff,0x99,0x99,0xff,0x99,0xff,0x33,0xff,0x00,0xff,0xcc,0x99,0xf7,0xf7, 0xf7,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21,0xff,0x0b, 0x4e,0x45,0x54,0x53,0x43,0x41,0x50,0x45,0x32,0x2e,0x30,0x03,0x01,0x00,0x00,0x00, 0x21,0xfe,0x16,0x43,0x72,0x6f,0x70,0x70,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20, 0x65,0x7a,0x67,0x69,0x66,0x2e,0x63,0x6f,0x6d,0x00,0x21,0xf9,0x04,0x09,0x0a,0x00, 0x09,0x00,0x2c,0x00,0x00,0x00,0x00,0x18,0x00,0x10,0x00,0x00,0x04,0x6f,0x30,0xc9, 0x49,0xab,0xbd,0x12,0xe8,0xcd,0x37,0xce,0x4a,0x28,0x2a,0xda,0x08,0x24,0x5a,0x05, 0x84,0x48,0xeb,0x02,0x05,0xd0,0x86,0xf0,0x09,0x04,0xc1,0xaa,0xb8,0x3c,0x1c,0x6f, 0x85,0x58,0x22,0x66,0x58,0xb9,0x06,0xbd,0xa0,0x52,0x79,0x0a,0x96,0x78,0xaf,0xe5, 0x02,0x36,0xfd,0x39,0x77,0x50,0x84,0xcf,0x59,0xab,0x11,0x36,0x58,0x64,0x74,0x49, 0x06,0x08,0xce,0xc6,0xac,0xef,0x70,0xa8,0xc5,0xda,0x13,0xdd,0xb1,0xb5,0x6e,0x73, 0xe0,0x71,0x16,0x74,0x5b,0xb6,0xe8,0x46,0x34,0x1d,0x29,0x2a,0x3f,0x82,0x82,0x18, 0x3e,0x89,0x19,0x4e,0x4e,0x1f,0x29,0x83,0x19,0x36,0x27,0x14,0x11,0x00,0x21,0xf9, 0x04,0x09,0x0a,0x00,0x04,0x00,0x2c,0x00,0x00,0x00,0x00,0x18,0x00,0x10,0x00,0x00, 0x04,0x6d,0x90,0xc8,0x49,0xab,0xbd,0x12,0xe8,0xcd,0x37,0xce,0x4a,0x28,0x2a,0xda, 0x08,0x10,0x5a,0x05,0x84,0x48,0xeb,0x02,0x05,0xd0,0x86,0xf0,0x19,0xdc,0xab,0xe2, 0xee,0x70,0xbc,0x15,0x31,0x82,0x61,0xb8,0x72,0x0d,0x78,0xc0,0x64,0xf2,0xc4,0xd1, 0xed,0x5a,0x3d,0xe0,0x02,0x36,0x8d,0x2d,0x9d,0xcf,0xa8,0x6f,0xdb,0x71,0x1e,0x5f, 0xca,0x70,0x4c,0x40,0x2e,0x3e,0x11,0xbd,0xc3,0xa1,0x16,0x5b,0x4f,0x72,0x46,0x28, 0x50,0xdd,0x71,0xbf,0x59,0x59,0x31,0xf0,0xa4,0x1a,0x99,0x3a,0x29,0x16,0x80,0x83, 0x35,0x18,0x3d,0x87,0x19,0x7b,0x7b,0x1f,0x29,0x81,0x19,0x4c,0x7c,0x12,0x11,0x00, 0x21,0xf9,0x04,0x09,0x0a,0x00,0x06,0x00,0x2c,0x00,0x00,0x00,0x00,0x18,0x00,0x10, 0x00,0x00,0x04,0x72,0xd0,0xc8,0x09,0xaa,0xbd,0x76,0x6a,0xaa,0xba,0x57,0xd5,0x07, 0x18,0xd5,0x06,0x74,0x48,0xaa,0x02,0x05,0x90,0x76,0xec,0xc8,0x29,0x6a,0xcd,0xb6, 0x56,0xd1,0x6a,0xa7,0x3a,0xd8,0xba,0x60,0x70,0x14,0xb0,0xd0,0x6a,0xa9,0x9b,0x6e, 0xc1,0x62,0xe2,0x74,0x3d,0x24,0x42,0xf9,0xac,0xb4,0xa0,0xd1,0xdf,0x4a,0xc8,0xbd, 0x02,0x12,0x51,0xe4,0xed,0x70,0x88,0xb5,0xca,0x00,0x02,0xe1,0x74,0x44,0x68,0xc7, 0x68,0x4b,0x59,0x40,0x27,0xa1,0xc4,0x5d,0xe8,0xc6,0xfe,0xf1,0x60,0x32,0x7b,0x24, 0x7f,0x83,0x81,0x12,0x37,0x87,0x86,0x50,0x7a,0x81,0x87,0x8b,0x8d,0x3b,0x85,0x25, 0x25,0x14,0x23,0x93,0x12,0x11,0x00,0x21,0xf9,0x04,0x01,0x0a,0x00,0x01,0x00,0x2c, 0x00,0x00,0x00,0x00,0x18,0x00,0x10,0x00,0x00,0x04,0x70,0x30,0xc8,0x09,0xaa,0xbd, 0x76,0x6a,0xaa,0xba,0x57,0xd5,0x07,0x04,0xd5,0x06,0x74,0x48,0xaa,0x02,0x05,0x90, 0x76,0xec,0xc8,0x29,0x6a,0xcd,0xb6,0x56,0xd1,0x6a,0xa7,0x3a,0xd8,0xba,0x60,0x70, 0x74,0xa1,0xd5,0x52,0x37,0xdd,0x82,0xb5,0x6c,0x0d,0x8d,0xc7,0x24,0x6e,0x8a,0x31, 0xfe,0x56,0xc2,0x6c,0x2b,0xc1,0xed,0x1d,0x11,0xb7,0xc3,0x21,0xd6,0x1a,0x13,0xce, 0x27,0xe8,0x35,0x3c,0xbe,0x8c,0x05,0x70,0x12,0x2a,0xaa,0xd5,0xc9,0x78,0x1f,0x11, 0xa6,0xb4,0x21,0xed,0xff,0x7d,0x14,0x76,0x76,0x12,0x37,0x86,0x81,0x24,0x83,0x3b, 0x89,0x4e,0x8b,0x81,0x25,0x7c,0x85,0x44,0x77,0x12,0x11,0x00,0x3b }; typedef struct GifLiteral { GifByteType* bytes; int size; int cursor; // Points to the first unread byte (should be initialized to 0) } GifLiteral; extern CRGB leds[NUM_LEDS]; static void nyan_loop() { FastLED.show(); while(1){ FastLED.delay(1000); // FastLED.delay(1000 / FPS); } } void nyan_cat() { GifLiteral nyan_cat = { .bytes = nyan_cat_bytes, .size = sizeof(nyan_cat_bytes), .cursor = 0 }; int Error; GifFileType* gifFile = DGifOpen(&nyan_cat, read_gif_literal, &Error); if(gifFile == NULL){ leds[0] = CRGB::Red; nyan_loop(); } Error = DGifSlurp(gifFile); if(Error != GIF_OK){ leds[(uint8_t)Error] = CRGB::Red; nyan_loop(); } while(1) { for(uint8_t i = 0; i < gifFile->ImageCount; i++){ SavedImage* img = &gifFile->SavedImages[i]; if(img == NULL){ leds[2] = CRGB::Red; nyan_loop(); } GifColorType* colors = img->ImageDesc.ColorMap->Colors; uint16_t num_pixels = img->ImageDesc.Width * img->ImageDesc.Height; for(uint16_t p = 0; p < num_pixels; p++) { uint16_t pixel = img->RasterBits[p]; if(pixel >= img->ImageDesc.ColorMap->ColorCount) { //Pixel is outside pallette range leds[rasterToMatrix(p)] = CRGB::White; } else { GifColorType c = colors[pixel]; leds[rasterToMatrix(p)] = CRGB(c.Red,c.Green,c.Blue); } } FastLED.show(); FastLED.delay(250); } } } <commit_msg>Updated to use new gifs.h<commit_after>#include "vest.h" #include "gifs.h" GifByteType nyan_cat_bytes[] = { 0x47,0x49,0x46,0x38,0x39,0x61,0x18,0x00,0x10,0x00,0xf3,0x00,0x00,0x1a,0x1a,0x1a, 0xff,0x00,0x00,0x66,0x33,0xff,0xff,0x33,0x99,0x00,0x99,0xff,0x99,0x99,0x99,0xff, 0x99,0x00,0xff,0x99,0x99,0xff,0x99,0xff,0x33,0xff,0x00,0xff,0xcc,0x99,0xf7,0xf7, 0xf7,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21,0xff,0x0b, 0x4e,0x45,0x54,0x53,0x43,0x41,0x50,0x45,0x32,0x2e,0x30,0x03,0x01,0x00,0x00,0x00, 0x21,0xfe,0x16,0x43,0x72,0x6f,0x70,0x70,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20, 0x65,0x7a,0x67,0x69,0x66,0x2e,0x63,0x6f,0x6d,0x00,0x21,0xf9,0x04,0x09,0x0a,0x00, 0x09,0x00,0x2c,0x00,0x00,0x00,0x00,0x18,0x00,0x10,0x00,0x00,0x04,0x6f,0x30,0xc9, 0x49,0xab,0xbd,0x12,0xe8,0xcd,0x37,0xce,0x4a,0x28,0x2a,0xda,0x08,0x24,0x5a,0x05, 0x84,0x48,0xeb,0x02,0x05,0xd0,0x86,0xf0,0x09,0x04,0xc1,0xaa,0xb8,0x3c,0x1c,0x6f, 0x85,0x58,0x22,0x66,0x58,0xb9,0x06,0xbd,0xa0,0x52,0x79,0x0a,0x96,0x78,0xaf,0xe5, 0x02,0x36,0xfd,0x39,0x77,0x50,0x84,0xcf,0x59,0xab,0x11,0x36,0x58,0x64,0x74,0x49, 0x06,0x08,0xce,0xc6,0xac,0xef,0x70,0xa8,0xc5,0xda,0x13,0xdd,0xb1,0xb5,0x6e,0x73, 0xe0,0x71,0x16,0x74,0x5b,0xb6,0xe8,0x46,0x34,0x1d,0x29,0x2a,0x3f,0x82,0x82,0x18, 0x3e,0x89,0x19,0x4e,0x4e,0x1f,0x29,0x83,0x19,0x36,0x27,0x14,0x11,0x00,0x21,0xf9, 0x04,0x09,0x0a,0x00,0x04,0x00,0x2c,0x00,0x00,0x00,0x00,0x18,0x00,0x10,0x00,0x00, 0x04,0x6d,0x90,0xc8,0x49,0xab,0xbd,0x12,0xe8,0xcd,0x37,0xce,0x4a,0x28,0x2a,0xda, 0x08,0x10,0x5a,0x05,0x84,0x48,0xeb,0x02,0x05,0xd0,0x86,0xf0,0x19,0xdc,0xab,0xe2, 0xee,0x70,0xbc,0x15,0x31,0x82,0x61,0xb8,0x72,0x0d,0x78,0xc0,0x64,0xf2,0xc4,0xd1, 0xed,0x5a,0x3d,0xe0,0x02,0x36,0x8d,0x2d,0x9d,0xcf,0xa8,0x6f,0xdb,0x71,0x1e,0x5f, 0xca,0x70,0x4c,0x40,0x2e,0x3e,0x11,0xbd,0xc3,0xa1,0x16,0x5b,0x4f,0x72,0x46,0x28, 0x50,0xdd,0x71,0xbf,0x59,0x59,0x31,0xf0,0xa4,0x1a,0x99,0x3a,0x29,0x16,0x80,0x83, 0x35,0x18,0x3d,0x87,0x19,0x7b,0x7b,0x1f,0x29,0x81,0x19,0x4c,0x7c,0x12,0x11,0x00, 0x21,0xf9,0x04,0x09,0x0a,0x00,0x06,0x00,0x2c,0x00,0x00,0x00,0x00,0x18,0x00,0x10, 0x00,0x00,0x04,0x72,0xd0,0xc8,0x09,0xaa,0xbd,0x76,0x6a,0xaa,0xba,0x57,0xd5,0x07, 0x18,0xd5,0x06,0x74,0x48,0xaa,0x02,0x05,0x90,0x76,0xec,0xc8,0x29,0x6a,0xcd,0xb6, 0x56,0xd1,0x6a,0xa7,0x3a,0xd8,0xba,0x60,0x70,0x14,0xb0,0xd0,0x6a,0xa9,0x9b,0x6e, 0xc1,0x62,0xe2,0x74,0x3d,0x24,0x42,0xf9,0xac,0xb4,0xa0,0xd1,0xdf,0x4a,0xc8,0xbd, 0x02,0x12,0x51,0xe4,0xed,0x70,0x88,0xb5,0xca,0x00,0x02,0xe1,0x74,0x44,0x68,0xc7, 0x68,0x4b,0x59,0x40,0x27,0xa1,0xc4,0x5d,0xe8,0xc6,0xfe,0xf1,0x60,0x32,0x7b,0x24, 0x7f,0x83,0x81,0x12,0x37,0x87,0x86,0x50,0x7a,0x81,0x87,0x8b,0x8d,0x3b,0x85,0x25, 0x25,0x14,0x23,0x93,0x12,0x11,0x00,0x21,0xf9,0x04,0x01,0x0a,0x00,0x01,0x00,0x2c, 0x00,0x00,0x00,0x00,0x18,0x00,0x10,0x00,0x00,0x04,0x70,0x30,0xc8,0x09,0xaa,0xbd, 0x76,0x6a,0xaa,0xba,0x57,0xd5,0x07,0x04,0xd5,0x06,0x74,0x48,0xaa,0x02,0x05,0x90, 0x76,0xec,0xc8,0x29,0x6a,0xcd,0xb6,0x56,0xd1,0x6a,0xa7,0x3a,0xd8,0xba,0x60,0x70, 0x74,0xa1,0xd5,0x52,0x37,0xdd,0x82,0xb5,0x6c,0x0d,0x8d,0xc7,0x24,0x6e,0x8a,0x31, 0xfe,0x56,0xc2,0x6c,0x2b,0xc1,0xed,0x1d,0x11,0xb7,0xc3,0x21,0xd6,0x1a,0x13,0xce, 0x27,0xe8,0x35,0x3c,0xbe,0x8c,0x05,0x70,0x12,0x2a,0xaa,0xd5,0xc9,0x78,0x1f,0x11, 0xa6,0xb4,0x21,0xed,0xff,0x7d,0x14,0x76,0x76,0x12,0x37,0x86,0x81,0x24,0x83,0x3b, 0x89,0x4e,0x8b,0x81,0x25,0x7c,0x85,0x44,0x77,0x12,0x11,0x00,0x3b }; extern CRGB leds[NUM_LEDS]; static void nyan_loop() { FastLED.show(); while(1){ FastLED.delay(1000); // FastLED.delay(1000 / FPS); } } void nyan_cat() { GifLiteral nyan_cat = { .bytes = nyan_cat_bytes, .size = sizeof(nyan_cat_bytes), .cursor = 0 }; int Error; GifFileType* gifFile = DGifOpen(&nyan_cat, read_gif_literal, &Error); if(gifFile == NULL){ leds[0] = CRGB::Red; nyan_loop(); } Error = DGifSlurp(gifFile); if(Error != GIF_OK){ leds[(uint8_t)Error] = CRGB::Red; nyan_loop(); } while(1) { for(uint8_t i = 0; i < gifFile->ImageCount; i++){ SavedImage* img = &gifFile->SavedImages[i]; if(img == NULL){ leds[2] = CRGB::Red; nyan_loop(); } GifColorType* colors = img->ImageDesc.ColorMap->Colors; uint16_t num_pixels = img->ImageDesc.Width * img->ImageDesc.Height; for(uint16_t p = 0; p < num_pixels; p++) { uint16_t pixel = img->RasterBits[p]; if(pixel >= img->ImageDesc.ColorMap->ColorCount) { //Pixel is outside pallette range leds[R(p)] = CRGB::White; } else { GifColorType c = colors[pixel]; leds[R(p)] = CRGB(c.Red,c.Green,c.Blue); } } FastLED.show(); FastLED.delay(250); } } } <|endoftext|>
<commit_before>/* editinteractor.cpp - Interface for edit interactors Copyright (C) 2007 Klarälvdalens Datakonsult AB This file is part of GPGME++. GPGME++ is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GPGME++ 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with GPGME++; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "editinteractor.h" #include "callbacks.h" #include "error.h" #include <gpg-error.h> #ifdef _WIN32 # include <io.h> #include <windows.h> #else # include <unistd.h> #endif #include <cstring> using namespace GpgME; class EditInteractor::Private { friend class ::GpgME::EditInteractor; friend class ::GpgME::CallbackHelper; EditInteractor * const q; public: explicit Private( EditInteractor * qq ); ~Private(); private: unsigned int state; Error error; std::FILE * debug; }; class GpgME::CallbackHelper { private: static int writeAll( int fd, const void * buf, uint count ) { uint toWrite = count; while ( toWrite > 0 ) { #ifdef Q_OS_WIN DWORD n; if ( !WriteFile( (HANDLE)fd, buf, toWrite, &n, NULL ) ) return -1; #else const int n = write( fd, buf, toWrite ); #endif if ( n < 0 ) return n; toWrite -= n; } return count; } public: static int edit_interactor_callback_impl( void * opaque, gpgme_status_code_t status, const char * args, int fd ) { EditInteractor::Private * ei = (EditInteractor::Private*)opaque; Error err; // advance to next state based on input: const unsigned int oldState = ei->state; ei->state = ei->q->nextState( status, args, err ); if ( err ) { ei->state = oldState; goto error; } if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: %u -> nextState( %u, %s ) -> %u\n", oldState, (unsigned int)status, args ? args : "<null>", ei->state ); if ( ei->state != oldState && // if there was an error from before, we stop here (### this looks weird, can this happen at all?) gpg_err_code( ei->error.code() ) == GPG_ERR_NO_ERROR ) { // successful state change -> call action if ( const char * const result = ei->q->action( err ) ) { if ( err ) goto error; if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: action result \"%s\"\n", result ); // if there's a result, write it: if ( *result ) writeAll( fd, result, std::strlen( result ) ); writeAll( fd, "\n", 1 ); } else { if ( err ) goto error; if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: no action result\n" ); } } else { if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: no action executed\n" ); } error: if ( err ) { ei->error = err; ei->state = EditInteractor::ErrorState; } if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: error now %u (%s)\n", ei->error.encodedError(), gpg_strerror( ei->error.encodedError() ) ); return ei->error.encodedError(); } }; static gpgme_error_t edit_interactor_callback( void * opaque, gpgme_status_code_t status, const char * args, int fd ) { return CallbackHelper::edit_interactor_callback_impl( opaque, status, args, fd ); } gpgme_edit_cb_t GpgME::edit_interactor_callback = ::edit_interactor_callback; EditInteractor::Private::Private( EditInteractor * qq ) : q( qq ), state( StartState ), error(), debug(0) { } EditInteractor::Private::~Private() {} EditInteractor::EditInteractor() : d( new Private( this ) ) { } EditInteractor::~EditInteractor() { delete d; d = 0; } unsigned int EditInteractor::state() const { return d->state; } Error EditInteractor::lastError() const { return d->error; } bool EditInteractor::needsNoResponse( unsigned int status ) const { switch ( status ) { case GPGME_STATUS_EOF: case GPGME_STATUS_GOT_IT: case GPGME_STATUS_NEED_PASSPHRASE: case GPGME_STATUS_NEED_PASSPHRASE_SYM: case GPGME_STATUS_GOOD_PASSPHRASE: case GPGME_STATUS_BAD_PASSPHRASE: case GPGME_STATUS_USERID_HINT: case GPGME_STATUS_SIGEXPIRED: case GPGME_STATUS_KEYEXPIRED: return true; default: return false; } } void EditInteractor::setDebugChannel( std::FILE * debug ) { d->debug = debug; } <commit_msg>check for write errors<commit_after>/* editinteractor.cpp - Interface for edit interactors Copyright (C) 2007 Klarälvdalens Datakonsult AB This file is part of GPGME++. GPGME++ is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GPGME++ 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with GPGME++; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "editinteractor.h" #include "callbacks.h" #include "error.h" #include <gpg-error.h> #ifdef _WIN32 # include <io.h> #include <windows.h> #else # include <unistd.h> #endif #include <cerrno> #include <cstring> using namespace GpgME; class EditInteractor::Private { friend class ::GpgME::EditInteractor; friend class ::GpgME::CallbackHelper; EditInteractor * const q; public: explicit Private( EditInteractor * qq ); ~Private(); private: unsigned int state; Error error; std::FILE * debug; }; class GpgME::CallbackHelper { private: static int writeAll( int fd, const void * buf, uint count ) { uint toWrite = count; while ( toWrite > 0 ) { #ifdef Q_OS_WIN DWORD n; if ( !WriteFile( (HANDLE)fd, buf, toWrite, &n, NULL ) ) return -1; #else const int n = write( fd, buf, toWrite ); #endif if ( n < 0 ) return n; toWrite -= n; } return count; } public: static int edit_interactor_callback_impl( void * opaque, gpgme_status_code_t status, const char * args, int fd ) { EditInteractor::Private * ei = (EditInteractor::Private*)opaque; Error err; // advance to next state based on input: const unsigned int oldState = ei->state; ei->state = ei->q->nextState( status, args, err ); if ( err ) { ei->state = oldState; goto error; } if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: %u -> nextState( %u, %s ) -> %u\n", oldState, (unsigned int)status, args ? args : "<null>", ei->state ); if ( ei->state != oldState && // if there was an error from before, we stop here (### this looks weird, can this happen at all?) gpg_err_code( ei->error.code() ) == GPG_ERR_NO_ERROR ) { // successful state change -> call action if ( const char * const result = ei->q->action( err ) ) { if ( err ) goto error; if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: action result \"%s\"\n", result ); // if there's a result, write it: if ( *result ) { errno = 0; if ( writeAll( fd, result, std::strlen( result ) != std::strlen( result ) ) ) { if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: Could not write to fd %d (%s)\n", fd, strerror( errno ) ); err = Error( GPG_ERR_GENERAL ); goto error; } } errno = 0; if ( writeAll( fd, "\n", 1 ) != 1 ) { if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: Could not write to fd %d (%s)\n", fd, strerror( errno ) ); err = Error( GPG_ERR_GENERAL ); goto error; } } else { if ( err ) goto error; if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: no action result\n" ); } } else { if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: no action executed\n" ); } error: if ( err ) { ei->error = err; ei->state = EditInteractor::ErrorState; } if ( ei->debug ) std::fprintf( ei->debug, "EditInteractor: error now %u (%s)\n", ei->error.encodedError(), gpg_strerror( ei->error.encodedError() ) ); return ei->error.encodedError(); } }; static gpgme_error_t edit_interactor_callback( void * opaque, gpgme_status_code_t status, const char * args, int fd ) { return CallbackHelper::edit_interactor_callback_impl( opaque, status, args, fd ); } gpgme_edit_cb_t GpgME::edit_interactor_callback = ::edit_interactor_callback; EditInteractor::Private::Private( EditInteractor * qq ) : q( qq ), state( StartState ), error(), debug(0) { } EditInteractor::Private::~Private() {} EditInteractor::EditInteractor() : d( new Private( this ) ) { } EditInteractor::~EditInteractor() { delete d; d = 0; } unsigned int EditInteractor::state() const { return d->state; } Error EditInteractor::lastError() const { return d->error; } bool EditInteractor::needsNoResponse( unsigned int status ) const { switch ( status ) { case GPGME_STATUS_EOF: case GPGME_STATUS_GOT_IT: case GPGME_STATUS_NEED_PASSPHRASE: case GPGME_STATUS_NEED_PASSPHRASE_SYM: case GPGME_STATUS_GOOD_PASSPHRASE: case GPGME_STATUS_BAD_PASSPHRASE: case GPGME_STATUS_USERID_HINT: case GPGME_STATUS_SIGEXPIRED: case GPGME_STATUS_KEYEXPIRED: return true; default: return false; } } void EditInteractor::setDebugChannel( std::FILE * debug ) { d->debug = debug; } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "AlbumTrack.h" #include "Album.h" #include "Artist.h" #include "Media.h" #include "Genre.h" #include "database/SqliteTools.h" #include "logging/Logger.h" namespace medialibrary { const std::string policy::AlbumTrackTable::Name = "AlbumTrack"; const std::string policy::AlbumTrackTable::PrimaryKeyColumn = "id_track"; int64_t AlbumTrack::* const policy::AlbumTrackTable::PrimaryKey = &AlbumTrack::m_id; AlbumTrack::AlbumTrack( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) { int64_t dummyDuration; row >> m_id >> m_mediaId >> dummyDuration >> m_artistId >> m_genreId >> m_trackNumber >> m_albumId >> m_discNumber >> m_isPresent; } AlbumTrack::AlbumTrack( MediaLibraryPtr ml, int64_t mediaId, int64_t artistId, int64_t genreId, unsigned int trackNumber, int64_t albumId, unsigned int discNumber ) : m_ml( ml ) , m_id( 0 ) , m_mediaId( mediaId ) , m_artistId( artistId ) , m_genreId( genreId ) , m_trackNumber( trackNumber ) , m_albumId( albumId ) , m_discNumber( discNumber ) , m_isPresent( true ) { } int64_t AlbumTrack::id() const { return m_id; } ArtistPtr AlbumTrack::artist() const { if ( m_artistId == 0 ) return nullptr; auto lock = m_artist.lock(); if ( m_artist.isCached() == false ) { m_artist = Artist::fetch( m_ml, m_artistId ); } return m_artist.get(); } bool AlbumTrack::setArtist( std::shared_ptr<Artist> artist ) { static const std::string req = "UPDATE " + policy::AlbumTrackTable::Name + " SET artist_id = ? WHERE id_track = ?"; if ( artist->id() == m_artistId ) return true; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, artist->id(), m_id ) == false ) return false; m_artistId = artist->id(); m_artist = artist; return true; } bool AlbumTrack::createTable( sqlite::Connection* dbConnection ) { const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::AlbumTrackTable::Name + "(" "id_track INTEGER PRIMARY KEY AUTOINCREMENT," "media_id INTEGER," "duration INTEGER NOT NULL," "artist_id UNSIGNED INTEGER," "genre_id INTEGER," "track_number UNSIGNED INTEGER," "album_id UNSIGNED INTEGER NOT NULL," "disc_number UNSIGNED INTEGER," "is_present BOOLEAN NOT NULL DEFAULT 1," "FOREIGN KEY (media_id) REFERENCES " + policy::MediaTable::Name + "(id_media)" " ON DELETE CASCADE," "FOREIGN KEY (artist_id) REFERENCES " + policy::ArtistTable::Name + "(id_artist)" " ON DELETE CASCADE," "FOREIGN KEY (genre_id) REFERENCES " + policy::GenreTable::Name + "(id_genre)," "FOREIGN KEY (album_id) REFERENCES Album(id_album) " " ON DELETE CASCADE" ")"; const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_track_present AFTER UPDATE OF is_present " "ON " + policy::MediaTable::Name + " BEGIN" " UPDATE " + policy::AlbumTrackTable::Name + " SET is_present = new.is_present WHERE media_id = new.id_media;" " END"; const std::string indexReq = "CREATE INDEX IF NOT EXISTS album_media_artist_genre_album_idx ON " + policy::AlbumTrackTable::Name + "(media_id, artist_id, genre_id, album_id)"; return sqlite::Tools::executeRequest( dbConnection, req ) && sqlite::Tools::executeRequest( dbConnection, triggerReq ) && sqlite::Tools::executeRequest( dbConnection, indexReq ); } std::shared_ptr<AlbumTrack> AlbumTrack::create( MediaLibraryPtr ml, int64_t albumId, std::shared_ptr<Media> media, unsigned int trackNb, unsigned int discNumber, int64_t artistId, int64_t genreId, int64_t duration ) { auto self = std::make_shared<AlbumTrack>( ml, media->id(), artistId, genreId, trackNb, albumId, discNumber ); static const std::string req = "INSERT INTO " + policy::AlbumTrackTable::Name + "(media_id, duration, artist_id, genre_id, track_number, album_id, disc_number) VALUES(?, ?, ?, ?, ?, ?, ?)"; if ( insert( ml, self, req, media->id(), duration >= 0 ? duration : 0, sqlite::ForeignKey( artistId ), sqlite::ForeignKey( genreId ), trackNb, albumId, discNumber ) == false ) return nullptr; self->m_media = media; return self; } AlbumTrackPtr AlbumTrack::fromMedia( MediaLibraryPtr ml, int64_t mediaId ) { static const std::string req = "SELECT * FROM " + policy::AlbumTrackTable::Name + " WHERE media_id = ?"; return fetch( ml, req, mediaId ); } std::vector<MediaPtr> AlbumTrack::fromGenre( MediaLibraryPtr ml, int64_t genreId, SortingCriteria sort, bool desc ) { std::string req = "SELECT m.* FROM " + policy::MediaTable::Name + " m" " INNER JOIN " + policy::AlbumTrackTable::Name + " t ON m.id_media = t.media_id" " WHERE t.genre_id = ? ORDER BY "; switch ( sort ) { case SortingCriteria::Duration: req += "m.duration"; break; case SortingCriteria::InsertionDate: req += "m.insertion_date"; break; case SortingCriteria::ReleaseDate: req += "m.release_date"; break; case SortingCriteria::Alpha: req += "m.title"; break; default: if ( desc == true ) req += "t.artist_id DESC, t.album_id DESC, t.disc_number DESC, t.track_number DESC, m.filename"; else req += "t.artist_id, t.album_id, t.disc_number, t.track_number, m.filename"; break; } if ( desc == true ) req += " DESC"; return Media::fetchAll<IMedia>( ml, req, genreId ); } GenrePtr AlbumTrack::genre() { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) { m_genre = Genre::fetch( m_ml, m_genreId ); } return m_genre.get(); } bool AlbumTrack::setGenre( std::shared_ptr<Genre> genre ) { // We need to fetch the old genre entity now, in case it gets deleted through // the nbTracks reaching 0 trigger. if ( m_genreId > 0 ) { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) m_genre = Genre::fetch( m_ml, m_genreId ); } static const std::string req = "UPDATE " + policy::AlbumTrackTable::Name + " SET genre_id = ? WHERE id_track = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, sqlite::ForeignKey( genre != nullptr ? genre->id() : 0 ), m_id ) == false ) return false; { auto l = m_genre.lock(); if ( m_genreId > 0 ) m_genre.get()->updateCachedNbTracks( -1 ); m_genre = genre; } if ( genre != nullptr ) { genre->updateCachedNbTracks( 1 ); m_genreId = genre->id(); } else m_genreId = 0; return true; } unsigned int AlbumTrack::trackNumber() { return m_trackNumber; } unsigned int AlbumTrack::discNumber() const { return m_discNumber; } std::shared_ptr<IAlbum> AlbumTrack::album() { // "Fail" early in case there's no album to fetch if ( m_albumId == 0 ) return nullptr; auto lock = m_album.lock(); if ( m_album.isCached() == false ) m_album = Album::fetch( m_ml, m_albumId ); return m_album.get().lock(); } std::shared_ptr<IMedia> AlbumTrack::media() { auto lock = m_media.lock(); if ( m_media.isCached() == false ) { m_media = Media::fetch( m_ml, m_mediaId ); } return m_media.get().lock(); } } <commit_msg>AlbumTrack: Cosmetics<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "AlbumTrack.h" #include "Album.h" #include "Artist.h" #include "Media.h" #include "Genre.h" #include "database/SqliteTools.h" #include "logging/Logger.h" namespace medialibrary { const std::string policy::AlbumTrackTable::Name = "AlbumTrack"; const std::string policy::AlbumTrackTable::PrimaryKeyColumn = "id_track"; int64_t AlbumTrack::* const policy::AlbumTrackTable::PrimaryKey = &AlbumTrack::m_id; AlbumTrack::AlbumTrack( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) { int64_t dummyDuration; row >> m_id >> m_mediaId >> dummyDuration >> m_artistId >> m_genreId >> m_trackNumber >> m_albumId >> m_discNumber >> m_isPresent; } AlbumTrack::AlbumTrack( MediaLibraryPtr ml, int64_t mediaId, int64_t artistId, int64_t genreId, unsigned int trackNumber, int64_t albumId, unsigned int discNumber ) : m_ml( ml ) , m_id( 0 ) , m_mediaId( mediaId ) , m_artistId( artistId ) , m_genreId( genreId ) , m_trackNumber( trackNumber ) , m_albumId( albumId ) , m_discNumber( discNumber ) , m_isPresent( true ) { } int64_t AlbumTrack::id() const { return m_id; } ArtistPtr AlbumTrack::artist() const { if ( m_artistId == 0 ) return nullptr; auto lock = m_artist.lock(); if ( m_artist.isCached() == false ) { m_artist = Artist::fetch( m_ml, m_artistId ); } return m_artist.get(); } bool AlbumTrack::setArtist( std::shared_ptr<Artist> artist ) { static const std::string req = "UPDATE " + policy::AlbumTrackTable::Name + " SET artist_id = ? WHERE id_track = ?"; if ( artist->id() == m_artistId ) return true; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, artist->id(), m_id ) == false ) return false; m_artistId = artist->id(); m_artist = artist; return true; } bool AlbumTrack::createTable( sqlite::Connection* dbConnection ) { const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::AlbumTrackTable::Name + "(" "id_track INTEGER PRIMARY KEY AUTOINCREMENT," "media_id INTEGER," "duration INTEGER NOT NULL," "artist_id UNSIGNED INTEGER," "genre_id INTEGER," "track_number UNSIGNED INTEGER," "album_id UNSIGNED INTEGER NOT NULL," "disc_number UNSIGNED INTEGER," "is_present BOOLEAN NOT NULL DEFAULT 1," "FOREIGN KEY (media_id) REFERENCES " + policy::MediaTable::Name + "(id_media)" " ON DELETE CASCADE," "FOREIGN KEY (artist_id) REFERENCES " + policy::ArtistTable::Name + "(id_artist)" " ON DELETE CASCADE," "FOREIGN KEY (genre_id) REFERENCES " + policy::GenreTable::Name + "(id_genre)," "FOREIGN KEY (album_id) REFERENCES Album(id_album) " " ON DELETE CASCADE" ")"; const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_track_present" "AFTER UPDATE OF is_present " "ON " + policy::MediaTable::Name + " " "BEGIN " "UPDATE " + policy::AlbumTrackTable::Name + " " "SET is_present = new.is_present WHERE media_id = new.id_media;" "END"; const std::string indexReq = "CREATE INDEX IF NOT EXISTS " "album_media_artist_genre_album_idx ON " + policy::AlbumTrackTable::Name + "(media_id, artist_id, genre_id, album_id)"; return sqlite::Tools::executeRequest( dbConnection, req ) && sqlite::Tools::executeRequest( dbConnection, triggerReq ) && sqlite::Tools::executeRequest( dbConnection, indexReq ); } std::shared_ptr<AlbumTrack> AlbumTrack::create( MediaLibraryPtr ml, int64_t albumId, std::shared_ptr<Media> media, unsigned int trackNb, unsigned int discNumber, int64_t artistId, int64_t genreId, int64_t duration ) { auto self = std::make_shared<AlbumTrack>( ml, media->id(), artistId, genreId, trackNb, albumId, discNumber ); static const std::string req = "INSERT INTO " + policy::AlbumTrackTable::Name + "(media_id, duration, artist_id, genre_id, track_number, album_id, disc_number) VALUES(?, ?, ?, ?, ?, ?, ?)"; if ( insert( ml, self, req, media->id(), duration >= 0 ? duration : 0, sqlite::ForeignKey( artistId ), sqlite::ForeignKey( genreId ), trackNb, albumId, discNumber ) == false ) return nullptr; self->m_media = media; return self; } AlbumTrackPtr AlbumTrack::fromMedia( MediaLibraryPtr ml, int64_t mediaId ) { static const std::string req = "SELECT * FROM " + policy::AlbumTrackTable::Name + " WHERE media_id = ?"; return fetch( ml, req, mediaId ); } std::vector<MediaPtr> AlbumTrack::fromGenre( MediaLibraryPtr ml, int64_t genreId, SortingCriteria sort, bool desc ) { std::string req = "SELECT m.* FROM " + policy::MediaTable::Name + " m" " INNER JOIN " + policy::AlbumTrackTable::Name + " t ON m.id_media = t.media_id" " WHERE t.genre_id = ? ORDER BY "; switch ( sort ) { case SortingCriteria::Duration: req += "m.duration"; break; case SortingCriteria::InsertionDate: req += "m.insertion_date"; break; case SortingCriteria::ReleaseDate: req += "m.release_date"; break; case SortingCriteria::Alpha: req += "m.title"; break; default: if ( desc == true ) req += "t.artist_id DESC, t.album_id DESC, t.disc_number DESC, t.track_number DESC, m.filename"; else req += "t.artist_id, t.album_id, t.disc_number, t.track_number, m.filename"; break; } if ( desc == true ) req += " DESC"; return Media::fetchAll<IMedia>( ml, req, genreId ); } GenrePtr AlbumTrack::genre() { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) { m_genre = Genre::fetch( m_ml, m_genreId ); } return m_genre.get(); } bool AlbumTrack::setGenre( std::shared_ptr<Genre> genre ) { // We need to fetch the old genre entity now, in case it gets deleted through // the nbTracks reaching 0 trigger. if ( m_genreId > 0 ) { auto l = m_genre.lock(); if ( m_genre.isCached() == false ) m_genre = Genre::fetch( m_ml, m_genreId ); } static const std::string req = "UPDATE " + policy::AlbumTrackTable::Name + " SET genre_id = ? WHERE id_track = ?"; if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, sqlite::ForeignKey( genre != nullptr ? genre->id() : 0 ), m_id ) == false ) return false; { auto l = m_genre.lock(); if ( m_genreId > 0 ) m_genre.get()->updateCachedNbTracks( -1 ); m_genre = genre; } if ( genre != nullptr ) { genre->updateCachedNbTracks( 1 ); m_genreId = genre->id(); } else m_genreId = 0; return true; } unsigned int AlbumTrack::trackNumber() { return m_trackNumber; } unsigned int AlbumTrack::discNumber() const { return m_discNumber; } std::shared_ptr<IAlbum> AlbumTrack::album() { // "Fail" early in case there's no album to fetch if ( m_albumId == 0 ) return nullptr; auto lock = m_album.lock(); if ( m_album.isCached() == false ) m_album = Album::fetch( m_ml, m_albumId ); return m_album.get().lock(); } std::shared_ptr<IMedia> AlbumTrack::media() { auto lock = m_media.lock(); if ( m_media.isCached() == false ) { m_media = Media::fetch( m_ml, m_mediaId ); } return m_media.get().lock(); } } <|endoftext|>
<commit_before>/* SWARM Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #include "db.h" #include "search8.h" #include "search16.h" #include "threads.h" static pthread_mutex_t scan_mutex; static ThreadRunner * search_threads = nullptr; struct search_data { BYTE ** qtable; WORD ** qtable_w; BYTE * dprofile; WORD * dprofile_w; BYTE * hearray; uint64_t * dir_array; uint64_t target_count; uint64_t target_index; }; static struct search_data * sd; static uint64_t master_next; static uint64_t master_length; static uint64_t remainingchunks; static uint64_t * master_targets; static uint64_t * master_scores; static uint64_t * master_diffs; static uint64_t * master_alignlengths; static int master_bits; static uint64_t dirbufferbytes; queryinfo_t query; uint64_t longestdbsequence; void search_alloc(struct search_data * sdp) { constexpr unsigned int one_kilobyte {1024}; constexpr unsigned int nt_per_uint64 {32}; constexpr unsigned int bytes_per_uint64 {8}; dirbufferbytes = bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4; sdp->qtable = new BYTE*[longestdbsequence]; sdp->qtable_w = new WORD*[longestdbsequence]; sdp->dprofile = new BYTE[2 * one_kilobyte]; // 4 * 16 * 32 sdp->dprofile_w = new WORD[2 * one_kilobyte]; // 4 * 2 * 8 * 32 sdp->hearray = new BYTE[longestdbsequence * nt_per_uint64] { }; sdp->dir_array = new uint64_t[dirbufferbytes] { }; } void search_free(struct search_data * sdp) { delete [] sdp->qtable; sdp->qtable = nullptr; delete [] sdp->qtable_w; sdp->qtable_w = nullptr; delete [] sdp->dprofile; sdp->dprofile = nullptr; delete [] sdp->dprofile_w; sdp->dprofile_w = nullptr; delete [] sdp->hearray; sdp->hearray = nullptr; delete [] sdp->dir_array; sdp->dir_array = nullptr; } void search_init(struct search_data * sdp) { constexpr int byte_multiplier {64}; constexpr int word_multiplier {32}; for(auto i = 0U; i < query.len; i++) { const int nt_value {nt_extract(query.seq, i) + 1}; // 1, 2, 3, or 4 const int byte_offset {byte_multiplier * nt_value}; // 1, 64, 128, or 192 const int word_offset {word_multiplier * nt_value}; // 1, 32, 64, or 128 sdp->qtable[i] = sdp->dprofile + byte_offset; sdp->qtable_w[i] = sdp->dprofile_w + word_offset; } } void search_chunk(struct search_data * sdp, const int64_t bits) { constexpr unsigned int bit_mode_16 {16}; assert(sdp->target_count != 0); assert((bits == bit_mode_16) || (bits == bit_mode_16 / 2)); if (bits == bit_mode_16) { search16(sdp->qtable_w, static_cast<WORD>(penalty_gapopen), static_cast<WORD>(penalty_gapextend), static_cast<WORD*>(score_matrix_16), sdp->dprofile_w, reinterpret_cast<WORD*>(sdp->hearray), sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } else { search8(sdp->qtable, static_cast<BYTE>(penalty_gapopen), static_cast<BYTE>(penalty_gapextend), static_cast<BYTE*>(score_matrix_8), sdp->dprofile, sdp->hearray, sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } } auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool { // * countref = how many sequences to search // * firstref = index into master_targets/scores/diffs where thread should start bool status {false}; pthread_mutex_lock(&scan_mutex); if (master_next < master_length) { const uint64_t chunksize = ((master_length - master_next + remainingchunks - 1) / remainingchunks); * countref = chunksize; * firstref = master_next; master_next += chunksize; remainingchunks--; status = true; } pthread_mutex_unlock(&scan_mutex); return status; } void search_worker_core(int64_t t) { search_init(sd + t); while(search_getwork(& sd[t].target_count, & sd[t].target_index)) { search_chunk(sd + t, master_bits); } } auto adjust_thread_number(const int n_bits, const uint64_t remaining_sequences, uint64_t n_threads) -> uint64_t { constexpr unsigned int channels_8 {8}; constexpr unsigned int channels_16 {16}; constexpr unsigned int bit_mode_16 {16}; auto channels {channels_16}; assert(remaining_sequences > 0); assert(n_threads > 0); assert((n_bits == bit_mode_16) || (n_bits == bit_mode_16 / 2)); if (n_bits == bit_mode_16) { channels = channels_8; } while (remaining_sequences <= (n_threads - 1) * channels) { --n_threads; } return n_threads; } // arguments: bits, master_length, thr // static_assert(adjust_thread_number( 8, 32, 10) == 2); // static_assert(adjust_thread_number( 8, 32, 3) == 2); // static_assert(adjust_thread_number( 8, 31, 2) == 2); // static_assert(adjust_thread_number( 8, 17, 2) == 2); // static_assert(adjust_thread_number( 8, 16, 2) == 1); // static_assert(adjust_thread_number( 8, 1, 2) == 1); // static_assert(adjust_thread_number( 8, 32, 1) == 1); // static_assert(adjust_thread_number(16, 17, 10) == 3); // static_assert(adjust_thread_number(16, 17, 3) == 3); // static_assert(adjust_thread_number(16, 16, 3) == 2); // static_assert(adjust_thread_number(16, 15, 2) == 2); // static_assert(adjust_thread_number(16, 1, 3) == 1); // static_assert(adjust_thread_number(16, 17, 1) == 1); void search_do(uint64_t query_no, uint64_t listlength, uint64_t * targets, uint64_t * scores, uint64_t * diffs, uint64_t * alignlengths, int bits) { unsigned int query_len = 0; query.qno = query_no; db_getsequenceandlength(query_no, &query.seq, &query_len); query.len = query_len; master_next = 0; master_length = listlength; master_targets = targets; master_scores = scores; master_diffs = diffs; master_alignlengths = alignlengths; master_bits = bits; auto thr = static_cast<uint64_t>(opt_threads); thr = adjust_thread_number(bits, master_length, thr); remainingchunks = thr; if (thr == 1) { search_worker_core(0); } else { search_threads->run(); } } void search_begin() { longestdbsequence = db_getlongestsequence(); sd = new struct search_data[static_cast<uint64_t>(opt_threads)]; for(auto t = 0LL; t < opt_threads; t++) { search_alloc(sd+t); } pthread_mutex_init(& scan_mutex, nullptr); /* start threads */ search_threads = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core); } void search_end() { /* finish and clean up worker threads */ delete search_threads; search_threads = nullptr; pthread_mutex_destroy(& scan_mutex); for(auto t = 0LL; t < opt_threads; t++) { search_free(sd+t); } delete [] sd; sd = nullptr; } <commit_msg>assert variables are not zero<commit_after>/* SWARM Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #include "db.h" #include "search8.h" #include "search16.h" #include "threads.h" static pthread_mutex_t scan_mutex; static ThreadRunner * search_threads = nullptr; struct search_data { BYTE ** qtable; WORD ** qtable_w; BYTE * dprofile; WORD * dprofile_w; BYTE * hearray; uint64_t * dir_array; uint64_t target_count; uint64_t target_index; }; static struct search_data * sd; static uint64_t master_next; static uint64_t master_length; static uint64_t remainingchunks; static uint64_t * master_targets; static uint64_t * master_scores; static uint64_t * master_diffs; static uint64_t * master_alignlengths; static int master_bits; static uint64_t dirbufferbytes; queryinfo_t query; uint64_t longestdbsequence; void search_alloc(struct search_data * sdp) { constexpr unsigned int one_kilobyte {1024}; constexpr unsigned int nt_per_uint64 {32}; constexpr unsigned int bytes_per_uint64 {8}; dirbufferbytes = bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4; sdp->qtable = new BYTE*[longestdbsequence]; sdp->qtable_w = new WORD*[longestdbsequence]; sdp->dprofile = new BYTE[2 * one_kilobyte]; // 4 * 16 * 32 sdp->dprofile_w = new WORD[2 * one_kilobyte]; // 4 * 2 * 8 * 32 sdp->hearray = new BYTE[longestdbsequence * nt_per_uint64] { }; sdp->dir_array = new uint64_t[dirbufferbytes] { }; } void search_free(struct search_data * sdp) { delete [] sdp->qtable; sdp->qtable = nullptr; delete [] sdp->qtable_w; sdp->qtable_w = nullptr; delete [] sdp->dprofile; sdp->dprofile = nullptr; delete [] sdp->dprofile_w; sdp->dprofile_w = nullptr; delete [] sdp->hearray; sdp->hearray = nullptr; delete [] sdp->dir_array; sdp->dir_array = nullptr; } void search_init(struct search_data * sdp) { constexpr int byte_multiplier {64}; constexpr int word_multiplier {32}; for(auto i = 0U; i < query.len; i++) { const int nt_value {nt_extract(query.seq, i) + 1}; // 1, 2, 3, or 4 const int byte_offset {byte_multiplier * nt_value}; // 1, 64, 128, or 192 const int word_offset {word_multiplier * nt_value}; // 1, 32, 64, or 128 sdp->qtable[i] = sdp->dprofile + byte_offset; sdp->qtable_w[i] = sdp->dprofile_w + word_offset; } } void search_chunk(struct search_data * sdp, const int64_t bits) { constexpr unsigned int bit_mode_16 {16}; assert(sdp->target_count != 0); assert((bits == bit_mode_16) || (bits == bit_mode_16 / 2)); if (bits == bit_mode_16) { search16(sdp->qtable_w, static_cast<WORD>(penalty_gapopen), static_cast<WORD>(penalty_gapextend), static_cast<WORD*>(score_matrix_16), sdp->dprofile_w, reinterpret_cast<WORD*>(sdp->hearray), sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } else { search8(sdp->qtable, static_cast<BYTE>(penalty_gapopen), static_cast<BYTE>(penalty_gapextend), static_cast<BYTE*>(score_matrix_8), sdp->dprofile, sdp->hearray, sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } } auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool { // * countref = how many sequences to search // * firstref = index into master_targets/scores/diffs where thread should start bool status {false}; pthread_mutex_lock(&scan_mutex); if (master_next < master_length) { const uint64_t chunksize = ((master_length - master_next + remainingchunks - 1) / remainingchunks); * countref = chunksize; * firstref = master_next; master_next += chunksize; remainingchunks--; status = true; } pthread_mutex_unlock(&scan_mutex); return status; } void search_worker_core(int64_t t) { search_init(sd + t); while(search_getwork(& sd[t].target_count, & sd[t].target_index)) { search_chunk(sd + t, master_bits); } } auto adjust_thread_number(const int n_bits, const uint64_t remaining_sequences, uint64_t n_threads) -> uint64_t { constexpr unsigned int channels_8 {8}; constexpr unsigned int channels_16 {16}; constexpr unsigned int bit_mode_16 {16}; auto channels {channels_16}; assert(remaining_sequences != 0); assert(n_threads != 0); assert((n_bits == bit_mode_16) || (n_bits == bit_mode_16 / 2)); if (n_bits == bit_mode_16) { channels = channels_8; } while (remaining_sequences <= (n_threads - 1) * channels) { --n_threads; } return n_threads; } // arguments: bits, master_length, thr // static_assert(adjust_thread_number( 8, 32, 10) == 2); // static_assert(adjust_thread_number( 8, 32, 3) == 2); // static_assert(adjust_thread_number( 8, 31, 2) == 2); // static_assert(adjust_thread_number( 8, 17, 2) == 2); // static_assert(adjust_thread_number( 8, 16, 2) == 1); // static_assert(adjust_thread_number( 8, 1, 2) == 1); // static_assert(adjust_thread_number( 8, 32, 1) == 1); // static_assert(adjust_thread_number(16, 17, 10) == 3); // static_assert(adjust_thread_number(16, 17, 3) == 3); // static_assert(adjust_thread_number(16, 16, 3) == 2); // static_assert(adjust_thread_number(16, 15, 2) == 2); // static_assert(adjust_thread_number(16, 1, 3) == 1); // static_assert(adjust_thread_number(16, 17, 1) == 1); void search_do(uint64_t query_no, uint64_t listlength, uint64_t * targets, uint64_t * scores, uint64_t * diffs, uint64_t * alignlengths, int bits) { unsigned int query_len = 0; query.qno = query_no; db_getsequenceandlength(query_no, &query.seq, &query_len); query.len = query_len; master_next = 0; master_length = listlength; master_targets = targets; master_scores = scores; master_diffs = diffs; master_alignlengths = alignlengths; master_bits = bits; auto thr = static_cast<uint64_t>(opt_threads); thr = adjust_thread_number(bits, master_length, thr); remainingchunks = thr; if (thr == 1) { search_worker_core(0); } else { search_threads->run(); } } void search_begin() { longestdbsequence = db_getlongestsequence(); sd = new struct search_data[static_cast<uint64_t>(opt_threads)]; for(auto t = 0LL; t < opt_threads; t++) { search_alloc(sd+t); } pthread_mutex_init(& scan_mutex, nullptr); /* start threads */ search_threads = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core); } void search_end() { /* finish and clean up worker threads */ delete search_threads; search_threads = nullptr; pthread_mutex_destroy(& scan_mutex); for(auto t = 0LL; t < opt_threads; t++) { search_free(sd+t); } delete [] sd; sd = nullptr; } <|endoftext|>
<commit_before>/* Copyright (c) 2009, Sebastien Mirolo 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 fortylines 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 Sebastien Mirolo ''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 Sebastien Mirolo 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 <unistd.h> #include <cstdlib> #include <sstream> #include <iostream> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include "auth.hh" #include "changelist.hh" #include "composer.hh" #include "docbook.hh" #include "projfiles.hh" #include "logview.hh" #include "projindex.hh" #include "invoices.hh" #include "checkstyle.hh" #include "webserve.hh" #if 0 /* We use this flag to trigger features that are currently in development. */ #define devsite #endif int main( int argc, char *argv[] ) { using namespace std; using namespace boost::program_options; using namespace boost::filesystem; try { /* parse command line arguments */ variables_map params; options_description authOptions("authentication"); authOptions.add_options() ("help","produce help message") ("credentials",value<std::string>(),"credentials") ("document",value<std::string>(),"document") ("right",value<std::string>(),"commit tag for right pane of diff") ("session",value<std::string>(),"session") ("username",value<std::string>(),"username") ("message,m",value<std::string>(),"message") ("view",value<std::string>(),"view") ("client",value<std::string>(),"client") ("month",value<std::string>(),"month") ("editedText",value<std::string>(),"text submitted after an online edit"); positional_options_description pd; pd.add("view", 1); char *pathInfo = getenv("PATH_INFO"); if( pathInfo != NULL ) { store(parse_cgi_options(authOptions),params); } else { /* There is no PATH_INFO environment variable so we might be running the application as a non-cgi from the command line. */ command_line_parser parser(argc, argv); parser.options(authOptions).positional(pd); store(parser.run(),params); } if( params.count("help") ) { cout << authOptions << endl; return 0; } session s; s.restore(params); /* by default bring the index page */ if( s.vars["view"].empty() || s.vars["view"] == "/" ) { cout << redirect("index.corp") << htmlContent << endl; } else { gitcmd revision(s.valueOf("binDir") + "/git"); dispatchDoc docs(s.valueOf("srcTop")); /* The pattern need to be inserted in more specific to more generic order since the matcher will apply each the first one that yields a positive match. */ #ifdef devsite composer invoice(s.valueOf("themeDir") + std::string("/invoice.template"), composer::create); statement stmt; docs.add("document",boost::regex("/statement"),stmt); docs.add("view",boost::regex("/statement"),invoice); docs.add("view",boost::regex("/cancel"),cel); composer edit(s.vars["themeDir"] + std::string("/edit.ui"), composer::create); docs.add("view",boost::regex("/edit"),edit); login li; docs.add("view",boost::regex("/login"),li); logout lo; docs.add("view",boost::regex("/logout"),lo); docs.add("view",boost::regex("/save"),chg); #endif /* Login and Logout pages generates HTML to be displayed in a web browser. It is very often convinient to quickly start and stop recording worked hours from the command line. In that case, "work" and "rest" can be used as substitute. */ auth work; deauth rest; docs.add("view",boost::regex("work"),work); docs.add("view",boost::regex("rest"),rest); /* The build "document" gives an overview of the set of all projects at a glance and can be used to assess the stability of the whole as a release candidate. */ logview logv; docs.add("document",boost::regex(".*/log"),logv); /* A project index.xml "document" file show a description, commits and unit test status of a single project through a project "view". */ regressions rgs; docs.add("regressions",boost::regex(".*regression\\.log"),rgs); boost::filesystem::path regressname = s.build(boost::filesystem::path(s.valueOf("document")).parent_path() / std::string("test/regression.log")); s.vars["regressions"] = regressname.string(); changedescr checkinHist(&revision); docs.add("history",boost::regex(".*index\\.xml"),checkinHist); projindex pind; docs.add("document",boost::regex(".*index\\.xml"),pind); /* Composer for a project view */ composer project(s.valueOf("themeDir") + std::string("/project.template"), composer::error); docs.add("view",boost::regex(".*index\\.xml"),project); /* Source code "document" files are syntax-highlighted and presented inside a source.template "view" */ path sourceTmpl(s.valueOf("themeDir") + std::string("/source.template")); changediff diff(sourceTmpl,&revision); docs.add("view",boost::regex("/diff"),diff); composer source(sourceTmpl,composer::error); linkLight leftLinkStrm(s); linkLight rightLinkStrm(s); cppLight leftCppStrm; cppLight rightCppStrm; decoratorChain leftChain; decoratorChain rightChain; leftChain.push_back(leftLinkStrm); leftChain.push_back(leftCppStrm); rightChain.push_back(rightLinkStrm); rightChain.push_back(rightCppStrm); text cpp(leftChain,rightChain); cppCheckfile cppCheck; projfiles::filterContainer filters; filters.push_back(boost::regex(".*\\.c")); filters.push_back(boost::regex(".*\\.h")); filters.push_back(boost::regex(".*\\.cc")); filters.push_back(boost::regex(".*\\.hh")); filters.push_back(boost::regex(".*\\.tcc")); for( projfiles::filterContainer::const_iterator f = filters.begin(); f != filters.end(); ++f ) { docs.add("check",*f,cppCheck); docs.add("document",*f,cpp); docs.add("view",*f,source); } shCheckfile shCheck; htmlEscaper leftLinkText; htmlEscaper rightLinkText; text rawtext(leftLinkText,rightLinkText); boost::regex shFilterPats[] = { boost::regex(".*\\.mk"), boost::regex(".*\\.py"), boost::regex(".*Makefile") }; for( boost::regex *pat = shFilterPats; pat != &shFilterPats[sizeof(shFilterPats)/sizeof(boost::regex)]; ++pat ) { docs.add("check",*pat,shCheck); docs.add("document",*pat,rawtext); docs.add("view",*pat,source); filters.push_back(*pat); } /* We transform docbook formatted text into HTML for .book and .corp "document" files and interpret all other unknown extension files as raw text. In all cases we use a default document.template interface "view" to present those files. */ composer entry(s.valueOf("themeDir") + std::string("/document.template"), composer::error); linkLight leftFormatedText(s); linkLight rightFormatedText(s); docbook formatedDoc(leftFormatedText,rightFormatedText); docs.add("document",boost::regex(".*\\.book"),formatedDoc); docs.add("document",boost::regex(".*\\.corp"),formatedDoc); /* \todo !!! Hack for current tmpl_include implementation */ text formatedText(leftFormatedText,rightFormatedText); docs.add("document",boost::regex(".*\\.template"),formatedText); docs.add("document",boost::regex(".*"),rawtext); #if devsite /* We insert advertisement in non corporate pages so we need to use a different template composer for corporate pages. */ composer corporate(s.valueOf("themeDir") + std::string("/corporate.template"), composer::error); docs.add("view",boost::regex(".*\\.corp"),corporate); #endif docs.add("view",boost::regex(".*"),entry); /* Widget to display status of static analysis of a project source files in the absence of a more restrictive pattern. */ checkstyle cks(filters.begin(),filters.end()); docs.add("checkstyle",boost::regex(".*"),cks); s.vars["checkstyle"] = s.valueOf("document"); /* Widget to display the history of a file under revision control in the absence of a more restrictive pattern. */ changehistory diffHist(&revision); docs.add("history",boost::regex(".*"),diffHist); s.vars["history"] = s.valueOf("document"); /* Widget to display a list of files which are part of a project. This widget is used through different "view"s to browse the source repository. */ projfiles filelist(filters.begin(),filters.end()); docs.add("projfiles",boost::regex(".*"),filelist); s.vars["projfiles"] = s.valueOf("document"); /* Widget to generate a rss feed. */ changerss rss(&revision); docs.add("view",boost::regex(".*rss\\.xml"),rss); docs.fetch(s,"view"); } } catch( exception& e ) { cout << htmlContent << endl; cout << "<html>" << endl; cout << "<head>" << endl; cout << "<TITLE>Response</TITLE>" << endl; cout << "</head>" << endl; cout << "<body>" << endl; cout << "<p>" << endl; cout << "caught exception: " << e.what() << endl; cout << "</p>" << endl; cout << "</body>" << endl; cout << "</html>" << endl; return 1; } return 0; } <commit_msg>redirect to index.html<commit_after>/* Copyright (c) 2009, Sebastien Mirolo 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 fortylines 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 Sebastien Mirolo ''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 Sebastien Mirolo 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 <unistd.h> #include <cstdlib> #include <sstream> #include <iostream> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include "auth.hh" #include "changelist.hh" #include "composer.hh" #include "docbook.hh" #include "projfiles.hh" #include "logview.hh" #include "projindex.hh" #include "invoices.hh" #include "checkstyle.hh" #include "webserve.hh" #if 1 /* We use this flag to trigger features that are currently in development. */ #define devsite #endif int main( int argc, char *argv[] ) { using namespace std; using namespace boost::program_options; using namespace boost::filesystem; try { /* parse command line arguments */ variables_map params; options_description authOptions("authentication"); authOptions.add_options() ("help","produce help message") ("credentials",value<std::string>(),"credentials") ("document",value<std::string>(),"document") ("right",value<std::string>(),"commit tag for right pane of diff") ("session",value<std::string>(),"session") ("username",value<std::string>(),"username") ("message,m",value<std::string>(),"message") ("view",value<std::string>(),"view") ("client",value<std::string>(),"client") ("month",value<std::string>(),"month") ("editedText",value<std::string>(),"text submitted after an online edit"); positional_options_description pd; pd.add("view", 1); char *pathInfo = getenv("PATH_INFO"); if( pathInfo != NULL ) { store(parse_cgi_options(authOptions),params); } else { /* There is no PATH_INFO environment variable so we might be running the application as a non-cgi from the command line. */ command_line_parser parser(argc, argv); parser.options(authOptions).positional(pd); store(parser.run(),params); } if( params.count("help") ) { cout << authOptions << endl; return 0; } session s; s.restore(params); /* by default bring the index page */ if( s.vars["view"].empty() || s.vars["view"] == "/" ) { cout << redirect("index.html") << htmlContent << endl; } else { gitcmd revision(s.valueOf("binDir") + "/git"); dispatchDoc docs(s.valueOf("srcTop")); /* The pattern need to be inserted in more specific to more generic order since the matcher will apply each the first one that yields a positive match. */ #if 0 composer invoice(s.valueOf("themeDir") + std::string("/invoice.template"), composer::create); statement stmt; docs.add("document",boost::regex("/statement"),stmt); docs.add("view",boost::regex("/statement"),invoice); docs.add("view",boost::regex("/cancel"),cel); composer edit(s.vars["themeDir"] + std::string("/edit.ui"), composer::create); docs.add("view",boost::regex("/edit"),edit); login li; docs.add("view",boost::regex("/login"),li); logout lo; docs.add("view",boost::regex("/logout"),lo); docs.add("view",boost::regex("/save"),chg); #endif /* Login and Logout pages generates HTML to be displayed in a web browser. It is very often convinient to quickly start and stop recording worked hours from the command line. In that case, "work" and "rest" can be used as substitute. */ auth work; deauth rest; docs.add("view",boost::regex("work"),work); docs.add("view",boost::regex("rest"),rest); /* The build "document" gives an overview of the set of all projects at a glance and can be used to assess the stability of the whole as a release candidate. */ logview logv; docs.add("document",boost::regex(".*/log"),logv); /* A project index.xml "document" file show a description, commits and unit test status of a single project through a project "view". */ regressions rgs; docs.add("regressions",boost::regex(".*regression\\.log"),rgs); boost::filesystem::path regressname = s.build(boost::filesystem::path(s.valueOf("document")).parent_path() / std::string("test/regression.log")); s.vars["regressions"] = regressname.string(); changedescr checkinHist(&revision); docs.add("history",boost::regex(".*index\\.xml"),checkinHist); projindex pind; docs.add("document",boost::regex(".*index\\.xml"),pind); /* Composer for a project view */ composer project(s.valueOf("themeDir") + std::string("/project.template"), composer::error); docs.add("view",boost::regex(".*index\\.xml"),project); /* Source code "document" files are syntax-highlighted and presented inside a source.template "view" */ path sourceTmpl(s.valueOf("themeDir") + std::string("/source.template")); changediff diff(sourceTmpl,&revision); docs.add("view",boost::regex("/diff"),diff); composer source(sourceTmpl,composer::error); linkLight leftLinkStrm(s); linkLight rightLinkStrm(s); cppLight leftCppStrm; cppLight rightCppStrm; decoratorChain leftChain; decoratorChain rightChain; leftChain.push_back(leftLinkStrm); leftChain.push_back(leftCppStrm); rightChain.push_back(rightLinkStrm); rightChain.push_back(rightCppStrm); text cpp(leftChain,rightChain); cppCheckfile cppCheck; projfiles::filterContainer filters; filters.push_back(boost::regex(".*\\.c")); filters.push_back(boost::regex(".*\\.h")); filters.push_back(boost::regex(".*\\.cc")); filters.push_back(boost::regex(".*\\.hh")); filters.push_back(boost::regex(".*\\.tcc")); for( projfiles::filterContainer::const_iterator f = filters.begin(); f != filters.end(); ++f ) { docs.add("check",*f,cppCheck); docs.add("document",*f,cpp); docs.add("view",*f,source); } shCheckfile shCheck; htmlEscaper leftLinkText; htmlEscaper rightLinkText; text rawtext(leftLinkText,rightLinkText); boost::regex shFilterPats[] = { boost::regex(".*\\.mk"), boost::regex(".*\\.py"), boost::regex(".*Makefile") }; for( boost::regex *pat = shFilterPats; pat != &shFilterPats[sizeof(shFilterPats)/sizeof(boost::regex)]; ++pat ) { docs.add("check",*pat,shCheck); docs.add("document",*pat,rawtext); docs.add("view",*pat,source); filters.push_back(*pat); } /* We transform docbook formatted text into HTML for .book and .corp "document" files and interpret all other unknown extension files as raw text. In all cases we use a default document.template interface "view" to present those files. */ composer entry(s.valueOf("themeDir") + std::string("/document.template"), composer::error); linkLight leftFormatedText(s); linkLight rightFormatedText(s); docbook formatedDoc(leftFormatedText,rightFormatedText); docs.add("document",boost::regex(".*\\.book"),formatedDoc); docs.add("document",boost::regex(".*\\.corp"),formatedDoc); /* \todo !!! Hack for current tmpl_include implementation */ text formatedText(leftFormatedText,rightFormatedText); docs.add("document",boost::regex(".*\\.template"),formatedText); docs.add("document",boost::regex(".*"),rawtext); #ifdef devsite /* We insert advertisement in non corporate pages so we need to use a different template composer for corporate pages. */ composer corporate(s.valueOf("themeDir") + std::string("/corporate.template"), composer::error); docs.add("view",boost::regex(".*\\.corp"),corporate); #endif docs.add("view",boost::regex(".*"),entry); /* Widget to display status of static analysis of a project source files in the absence of a more restrictive pattern. */ checkstyle cks(filters.begin(),filters.end()); docs.add("checkstyle",boost::regex(".*"),cks); s.vars["checkstyle"] = s.valueOf("document"); /* Widget to display the history of a file under revision control in the absence of a more restrictive pattern. */ changehistory diffHist(&revision); docs.add("history",boost::regex(".*"),diffHist); s.vars["history"] = s.valueOf("document"); /* Widget to display a list of files which are part of a project. This widget is used through different "view"s to browse the source repository. */ projfiles filelist(filters.begin(),filters.end()); docs.add("projfiles",boost::regex(".*"),filelist); s.vars["projfiles"] = s.valueOf("document"); /* Widget to generate a rss feed. */ changerss rss(&revision); docs.add("view",boost::regex(".*rss\\.xml"),rss); docs.fetch(s,"view"); } } catch( exception& e ) { cout << htmlContent << endl; cout << "<html>" << endl; cout << "<head>" << endl; cout << "<TITLE>Response</TITLE>" << endl; cout << "</head>" << endl; cout << "<body>" << endl; cout << "<p>" << endl; cout << "caught exception: " << e.what() << endl; cout << "</p>" << endl; cout << "</body>" << endl; cout << "</html>" << endl; return 1; } return 0; } <|endoftext|>
<commit_before>// Copyright 2013, Alex Horn. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "smt.h" namespace smt { Expr::SolverPtrs Expr::s_solver_ptrs; unsigned Expr::s_counter = 0; constexpr const char* const Logics::acronyms[24]; static constexpr size_t MAX_BV_SIZE = 1024; static const Sort* bv_sorts[2][MAX_BV_SIZE] = { nullptr }; const Sort& bv_sort(bool is_signed, size_t size) { assert(size < MAX_BV_SIZE); if (bv_sorts[is_signed][size] == nullptr) { bv_sorts[is_signed][size] = new Sort( false, false, false, true, is_signed, size); } return *bv_sorts[is_signed][size]; } SharedExpr constant(const UnsafeDecl& decl) { return make_shared_expr<ConstantExpr>(decl); } SharedExpr apply( const UnsafeDecl& func_decl, const SharedExpr& arg) { constexpr size_t arity = 1; std::array<SharedExpr, arity> args = { arg }; return make_shared_expr<FuncAppExpr<arity>>( func_decl, std::move(args)); } SharedExpr apply( const UnsafeDecl& func_decl, const SharedExpr& larg, const SharedExpr& rarg) { constexpr size_t arity = 2; std::array<SharedExpr, arity> args = { larg, rarg }; return make_shared_expr<FuncAppExpr<arity>>( func_decl, std::move(args)); } SharedExpr distinct(SharedExprs&& terms) { return make_shared_expr<NaryExpr<NEQ>>( internal::sort<Bool>(), std::move(terms)); } SharedExpr select( const SharedExpr& array, const SharedExpr& index) { return make_shared_expr<ArraySelectExpr>( array, index); } SharedExpr implies( const SharedExpr& larg, const SharedExpr& rarg) { return make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg); } SharedExpr implies( const Bool& larg, const SharedExpr& rarg) { return make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg); } SharedExpr implies( const SharedExpr& larg, const Bool& rarg) { return make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg); } Bool implies( const Bool& larg, const Bool& rarg) { return Bool(make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg)); } SharedExpr store( const SharedExpr& array, const SharedExpr& index, const SharedExpr& value) { return make_shared_expr<ArrayStoreExpr>( array, index, value); } Solver::Solver() : m_stats{0}, m_is_timer_on(false) { m_stats.encode_elapsed_time = ElapsedTime::zero(); m_stats.check_elapsed_time = ElapsedTime::zero(); Expr::register_solver(this); } Solver::Solver(Logic logic) : m_stats{0}, m_is_timer_on(false) { m_stats.encode_elapsed_time = ElapsedTime::zero(); m_stats.check_elapsed_time = ElapsedTime::zero(); Expr::register_solver(this); } Solver::~Solver() { Expr::unregister_solver(this); } Error Solver::encode_constant( const Expr* const expr, const UnsafeDecl& decl) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); m_stats.constants++; return __encode_constant(expr, decl); } Error Solver::encode_func_app( const Expr* const expr, const UnsafeDecl& func_decl, const size_t arity, const SharedExpr* const args) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(0 < arity); assert(args != nullptr); m_stats.func_apps++; return __encode_func_app(expr, func_decl, arity, args); } Error Solver::encode_const_array( const Expr* const expr, const Sort& sort, const SharedExpr& init) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!init.is_null()); return __encode_const_array(expr, sort, init); } Error Solver::encode_array_select( const Expr* const expr, const SharedExpr& array, const SharedExpr& index) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!array.is_null()); assert(!index.is_null()); m_stats.array_selects++; return __encode_array_select(expr, array, index); } Error Solver::encode_array_store( const Expr* const expr, const SharedExpr& array, const SharedExpr& index, const SharedExpr& value) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!array.is_null()); assert(!index.is_null()); assert(!value.is_null()); m_stats.array_stores++; return __encode_array_store(expr, array, index, value); } Error Solver::encode_nary( const Expr* const expr, Opcode opcode, const Sort& sort, const SharedExprs& args) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!args.empty()); switch (opcode) { case EQL: m_stats.equalities += args.size(); break; case NEQ: m_stats.disequalities += args.size(); break; case LAND: m_stats.conjunctions += args.size(); break; case LOR: m_stats.disjunctions += args.size(); break; default: ; } m_stats.nary_ops++; return __encode_nary(expr, opcode, sort, args); } Error Solver::encode_bv_zero_extend( const Expr* const expr, const Sort& sort, const SharedExpr& bv, const unsigned ext) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(bv.sort().is_bv()); return __encode_bv_zero_extend(expr, sort, bv, ext); } Error Solver::encode_bv_sign_extend( const Expr* const expr, const Sort& sort, const SharedExpr& bv, const unsigned ext) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(bv.sort().is_bv()); return __encode_bv_sign_extend(expr, sort, bv, ext); } Error Solver::encode_bv_extract( const Expr* const expr, const Sort& sort, const SharedExpr& bv, const unsigned high, const unsigned low) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(bv.sort().is_bv()); return __encode_bv_extract(expr, sort, bv, high, low); } void Solver::reset() { return __reset(); } void Solver::push() { return __push(); } void Solver::pop() { return __pop(); } void Solver::unsafe_add(const SharedExpr& condition) { NonReentrantTimer<ElapsedTime> timer(m_stats.encode_elapsed_time); assert(condition.sort().is_bool()); const Error err = __unsafe_add(condition); assert(err == OK); } void Solver::add(const Bool& condition) { const Error err = __unsafe_add(condition); assert(err == OK); } CheckResult Solver::check() { NonReentrantTimer<ElapsedTime> timer(m_stats.check_elapsed_time); return __check(); } Bool Identity<LAND, Bool>::term(literal<Bool>(true)); } <commit_msg>Fix push() and pop() non-returns<commit_after>// Copyright 2013, Alex Horn. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "smt.h" namespace smt { Expr::SolverPtrs Expr::s_solver_ptrs; unsigned Expr::s_counter = 0; constexpr const char* const Logics::acronyms[24]; static constexpr size_t MAX_BV_SIZE = 1024; static const Sort* bv_sorts[2][MAX_BV_SIZE] = { nullptr }; const Sort& bv_sort(bool is_signed, size_t size) { assert(size < MAX_BV_SIZE); if (bv_sorts[is_signed][size] == nullptr) { bv_sorts[is_signed][size] = new Sort( false, false, false, true, is_signed, size); } return *bv_sorts[is_signed][size]; } SharedExpr constant(const UnsafeDecl& decl) { return make_shared_expr<ConstantExpr>(decl); } SharedExpr apply( const UnsafeDecl& func_decl, const SharedExpr& arg) { constexpr size_t arity = 1; std::array<SharedExpr, arity> args = { arg }; return make_shared_expr<FuncAppExpr<arity>>( func_decl, std::move(args)); } SharedExpr apply( const UnsafeDecl& func_decl, const SharedExpr& larg, const SharedExpr& rarg) { constexpr size_t arity = 2; std::array<SharedExpr, arity> args = { larg, rarg }; return make_shared_expr<FuncAppExpr<arity>>( func_decl, std::move(args)); } SharedExpr distinct(SharedExprs&& terms) { return make_shared_expr<NaryExpr<NEQ>>( internal::sort<Bool>(), std::move(terms)); } SharedExpr select( const SharedExpr& array, const SharedExpr& index) { return make_shared_expr<ArraySelectExpr>( array, index); } SharedExpr implies( const SharedExpr& larg, const SharedExpr& rarg) { return make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg); } SharedExpr implies( const Bool& larg, const SharedExpr& rarg) { return make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg); } SharedExpr implies( const SharedExpr& larg, const Bool& rarg) { return make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg); } Bool implies( const Bool& larg, const Bool& rarg) { return Bool(make_shared_expr<BinaryExpr<IMP>>( internal::sort<Bool>(), larg, rarg)); } SharedExpr store( const SharedExpr& array, const SharedExpr& index, const SharedExpr& value) { return make_shared_expr<ArrayStoreExpr>( array, index, value); } Solver::Solver() : m_stats{0}, m_is_timer_on(false) { m_stats.encode_elapsed_time = ElapsedTime::zero(); m_stats.check_elapsed_time = ElapsedTime::zero(); Expr::register_solver(this); } Solver::Solver(Logic logic) : m_stats{0}, m_is_timer_on(false) { m_stats.encode_elapsed_time = ElapsedTime::zero(); m_stats.check_elapsed_time = ElapsedTime::zero(); Expr::register_solver(this); } Solver::~Solver() { Expr::unregister_solver(this); } Error Solver::encode_constant( const Expr* const expr, const UnsafeDecl& decl) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); m_stats.constants++; return __encode_constant(expr, decl); } Error Solver::encode_func_app( const Expr* const expr, const UnsafeDecl& func_decl, const size_t arity, const SharedExpr* const args) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(0 < arity); assert(args != nullptr); m_stats.func_apps++; return __encode_func_app(expr, func_decl, arity, args); } Error Solver::encode_const_array( const Expr* const expr, const Sort& sort, const SharedExpr& init) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!init.is_null()); return __encode_const_array(expr, sort, init); } Error Solver::encode_array_select( const Expr* const expr, const SharedExpr& array, const SharedExpr& index) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!array.is_null()); assert(!index.is_null()); m_stats.array_selects++; return __encode_array_select(expr, array, index); } Error Solver::encode_array_store( const Expr* const expr, const SharedExpr& array, const SharedExpr& index, const SharedExpr& value) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!array.is_null()); assert(!index.is_null()); assert(!value.is_null()); m_stats.array_stores++; return __encode_array_store(expr, array, index, value); } Error Solver::encode_nary( const Expr* const expr, Opcode opcode, const Sort& sort, const SharedExprs& args) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(!args.empty()); switch (opcode) { case EQL: m_stats.equalities += args.size(); break; case NEQ: m_stats.disequalities += args.size(); break; case LAND: m_stats.conjunctions += args.size(); break; case LOR: m_stats.disjunctions += args.size(); break; default: ; } m_stats.nary_ops++; return __encode_nary(expr, opcode, sort, args); } Error Solver::encode_bv_zero_extend( const Expr* const expr, const Sort& sort, const SharedExpr& bv, const unsigned ext) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(bv.sort().is_bv()); return __encode_bv_zero_extend(expr, sort, bv, ext); } Error Solver::encode_bv_sign_extend( const Expr* const expr, const Sort& sort, const SharedExpr& bv, const unsigned ext) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(bv.sort().is_bv()); return __encode_bv_sign_extend(expr, sort, bv, ext); } Error Solver::encode_bv_extract( const Expr* const expr, const Sort& sort, const SharedExpr& bv, const unsigned high, const unsigned low) { ElapsedTimer timer(m_stats.encode_elapsed_time, m_is_timer_on); assert(bv.sort().is_bv()); return __encode_bv_extract(expr, sort, bv, high, low); } void Solver::reset() { __reset(); } void Solver::push() { __push(); } void Solver::pop() { __pop(); } void Solver::unsafe_add(const SharedExpr& condition) { NonReentrantTimer<ElapsedTime> timer(m_stats.encode_elapsed_time); assert(condition.sort().is_bool()); const Error err = __unsafe_add(condition); assert(err == OK); } void Solver::add(const Bool& condition) { const Error err = __unsafe_add(condition); assert(err == OK); } CheckResult Solver::check() { NonReentrantTimer<ElapsedTime> timer(m_stats.check_elapsed_time); return __check(); } Bool Identity<LAND, Bool>::term(literal<Bool>(true)); } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * 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 General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "uri.h" class URIPrivate { public: ///Strings associated with SchemeType constexpr static const char* schemeNames[] = { /*NONE = */ "" , /*SIP = */ "sip:" , /*SIPS = */ "sips:", /*IAX = */ "iax:" , /*IAX2 = */ "iax2:", /*RING = */ "ring:", }; URIPrivate(QString* uri); //Attributes QString m_Hostname ; QString m_Userinfo ; QStringList m_lAttributes ; QString m_Stripped ; URI::SchemeType m_HeaderType ; bool m_hasChevrons ; bool m_Parsed ; bool m_HasAt ; URI::ProtocolHint m_ProtocolHint; bool m_HintParsed ; //Helper static QString strip(const QString& uri, URI::SchemeType& scheme); void parse(); static bool checkIp(const QString& str, bool &isHash, const URI::SchemeType& scheme); private: QString* q_ptr; }; constexpr const char* URIPrivate::schemeNames[]; URIPrivate::URIPrivate(QString* uri) : m_Parsed(false),m_HeaderType(URI::SchemeType::NONE),q_ptr(uri), m_hasChevrons(false),m_HasAt(false),m_ProtocolHint(URI::ProtocolHint::SIP_OTHER),m_HintParsed(false) { } ///Constructor URI::URI(const QString& other):QString(), d_ptr(new URIPrivate(this)) { d_ptr->m_Stripped = URIPrivate::strip(other,d_ptr->m_HeaderType); (*static_cast<QString*>(this)) = d_ptr->m_Stripped ; } ///Copy constructor URI::URI(const URI& o):QString(), d_ptr(new URIPrivate(this)) { //TODO see if a copy on write kind of algo could be used for this d_ptr->m_Parsed = o.d_ptr->m_Parsed ; d_ptr->m_HintParsed = o.d_ptr->m_HintParsed; d_ptr->m_Hostname = o.d_ptr->m_Hostname ; d_ptr->m_HasAt = o.d_ptr->m_HasAt ; d_ptr->m_HeaderType = o.d_ptr->m_HeaderType; d_ptr->m_Userinfo = o.d_ptr->m_Userinfo ; d_ptr->m_Stripped = o.d_ptr->m_Stripped ; (*static_cast<QString*>(this)) = o.d_ptr->m_Stripped; } ///Destructor URI::~URI() { (*static_cast<QString*>(this)) = QString(); d_ptr->m_Stripped = QString(); // delete d_ptr; } /// Copy operator, make sure the cache is also copied URI& URI::operator=(const URI& o) { d_ptr->m_Parsed = o.d_ptr->m_Parsed ; d_ptr->m_HintParsed = o.d_ptr->m_HintParsed; d_ptr->m_Hostname = o.d_ptr->m_Hostname ; d_ptr->m_HasAt = o.d_ptr->m_HasAt ; d_ptr->m_HeaderType = o.d_ptr->m_HeaderType; d_ptr->m_Userinfo = o.d_ptr->m_Userinfo ; d_ptr->m_Stripped = o.d_ptr->m_Stripped ; (*static_cast<QString*>(this)) = o.d_ptr->m_Stripped; return (*this); } ///Strip out <sip:****> from the URI QString URIPrivate::strip(const QString& uri, URI::SchemeType& scheme) { if (uri.isEmpty()) return {}; int start(uri[0] == '<'?1:0),end(uri.size()-1); //Other type of comparisons were too slow if (start == end+1) return {}; const uchar c = uri[start].toLatin1(); //Assume the scheme is either iax, sip or ring using the first letter and length, this //is dangerous and can cause undefined behaviour that will cause the call to fail //later on, but this is not really a problem for now if (end > start+3 && uri[start+3] == ':') { switch (c) { case 'i': scheme = URI::SchemeType::IAX; break; case 's': scheme = URI::SchemeType::SIP; break; } start = start +4; } else if (end > start+4 && uri[start+4] == ':') { switch (c) { case 'i': scheme = URI::SchemeType::IAX2; break; case 'r': scheme = URI::SchemeType::RING; break; case 's': scheme = URI::SchemeType::SIPS; break; } start = start +5; } if (end && uri[end] == '>') end--; else if (start) { //TODO there may be a ';' section with arguments, check } return uri.mid(start,end-start+1); } /** * Return the domaine of an URI * * For example, example.com in <sip:12345@example.com> */ QString URI::hostname() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return d_ptr->m_Hostname; } /** * Check if the URI has an hostname * * This will return true if there is something between '@' and ';' (or an end of line) */ bool URI::hasHostname() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return !d_ptr->m_Hostname.isEmpty(); } /** * Return the URI SchemeType */ URI::SchemeType URI::schemeType() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return d_ptr->m_HeaderType; } /** * "Fast" Ipv4 and Ipv6 check, accept 999.999.999.999, :::::::::FF and other * atrocities, but at least perform a O(N) ish check and validate the hash * * @param str an uservalue (faster the scheme and before the "at" sign) * @param [out] isHash if the content is pure hexadecimal ASCII */ bool URIPrivate::checkIp(const QString& str, bool &isHash, const URI::SchemeType& scheme) { char* raw = str.toLatin1().data(); ushort max = str.size(); if (max < 3 || max > 45 || (!isHash && scheme == URI::SchemeType::RING)) return false; uchar dc(0),sc(0),i(0),d(0),hx(1); while (i < max) { switch(raw[i]) { case '.': isHash = false; d = 0; dc++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (++d > 3 && dc) return false; break; case ':': isHash = false; sc++; //No break case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': hx = 0; break; default: isHash = false; return false; }; i++; } return (hx && dc == 3 && d < 4) ^ (sc > 1 && dc==0); } /** * This method return an hint to guess the protocol that could be used to call * this URI. It is a quick guess, not something that should be trusted * * @warning, this method is O(N) when called for the first time on an URI */ URI::ProtocolHint URI::protocolHint() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); if (!d_ptr->m_HintParsed) { bool isHash = d_ptr->m_Userinfo.size() == 40; d_ptr->m_ProtocolHint = \ ( //Step one : Check IAX protocol, is has already been detected at this point d_ptr->m_HeaderType == URI::SchemeType::IAX2 || d_ptr->m_HeaderType == URI::SchemeType::IAX ? URI::ProtocolHint::IAX : ( //Step two : check IP URIPrivate::checkIp(d_ptr->m_Userinfo,isHash,d_ptr->m_HeaderType) ? URI::ProtocolHint::IP : ( //Step three : Check RING protocol, is has already been detected at this point d_ptr->m_HeaderType == URI::SchemeType::RING && isHash ? URI::ProtocolHint::RING : ( //Step four : Differentiate between ***@*** and *** type URIs d_ptr->m_HasAt ? URI::ProtocolHint::SIP_HOST : URI::ProtocolHint::SIP_OTHER )))); d_ptr->m_HintParsed = true; } return d_ptr->m_ProtocolHint; } ///Keep a cache of the values to avoid re-parsing them void URIPrivate::parse() { //FIXME the indexOf is done twice, the second time could be avoided if (q_ptr->indexOf('@') != -1) { const QStringList split = q_ptr->split('@'); m_HasAt = true; m_Hostname = split[1]; m_Userinfo = split[0]; m_Parsed = true; } else m_Userinfo = (*q_ptr); } /** * Extract the user info field from the URI * * For example, "123" in sip:123@myserver.net */ QString URI::userinfo() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return d_ptr->m_Userinfo; } /** * Some feature, like SIP presence, require a properly formatted URI */ QString URI::fullUri() const { return QString("<%1%2>") .arg(URIPrivate::schemeNames[static_cast<int>(d_ptr->m_HeaderType == SchemeType::NONE?SchemeType::SIP:d_ptr->m_HeaderType)]) .arg(*this); } QDataStream& operator<<( QDataStream& stream, const URI::ProtocolHint& ph ) { switch(ph) { case URI::ProtocolHint::SIP_OTHER: stream << "SIP_OTHER"; break; case URI::ProtocolHint::IAX : stream << "IAX"; break; case URI::ProtocolHint::RING : stream << "RING"; break; case URI::ProtocolHint::IP : stream << "IP"; break; case URI::ProtocolHint::SIP_HOST : stream << "SIP_HOST"; break; } return stream; } <commit_msg>uri: Add missing copy constructor attribute<commit_after>/**************************************************************************** * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * 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 General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "uri.h" class URIPrivate { public: ///Strings associated with SchemeType constexpr static const char* schemeNames[] = { /*NONE = */ "" , /*SIP = */ "sip:" , /*SIPS = */ "sips:", /*IAX = */ "iax:" , /*IAX2 = */ "iax2:", /*RING = */ "ring:", }; URIPrivate(QString* uri); //Attributes QString m_Hostname ; QString m_Userinfo ; QStringList m_lAttributes ; QString m_Stripped ; URI::SchemeType m_HeaderType ; bool m_hasChevrons ; bool m_Parsed ; bool m_HasAt ; URI::ProtocolHint m_ProtocolHint; bool m_HintParsed ; //Helper static QString strip(const QString& uri, URI::SchemeType& scheme); void parse(); static bool checkIp(const QString& str, bool &isHash, const URI::SchemeType& scheme); private: QString* q_ptr; }; constexpr const char* URIPrivate::schemeNames[]; URIPrivate::URIPrivate(QString* uri) : m_Parsed(false),m_HeaderType(URI::SchemeType::NONE),q_ptr(uri), m_hasChevrons(false),m_HasAt(false),m_ProtocolHint(URI::ProtocolHint::SIP_OTHER),m_HintParsed(false) { } ///Constructor URI::URI(const QString& other):QString(), d_ptr(new URIPrivate(this)) { d_ptr->m_Stripped = URIPrivate::strip(other,d_ptr->m_HeaderType); (*static_cast<QString*>(this)) = d_ptr->m_Stripped ; } ///Copy constructor URI::URI(const URI& o):QString(), d_ptr(new URIPrivate(this)) { //TODO see if a copy on write kind of algo could be used for this d_ptr->m_Parsed = o.d_ptr->m_Parsed ; d_ptr->m_HintParsed = o.d_ptr->m_HintParsed ; d_ptr->m_Hostname = o.d_ptr->m_Hostname ; d_ptr->m_HasAt = o.d_ptr->m_HasAt ; d_ptr->m_ProtocolHint = o.d_ptr->m_ProtocolHint; d_ptr->m_HeaderType = o.d_ptr->m_HeaderType ; d_ptr->m_Userinfo = o.d_ptr->m_Userinfo ; d_ptr->m_Stripped = o.d_ptr->m_Stripped ; (*static_cast<QString*>(this)) = o.d_ptr->m_Stripped; } ///Destructor URI::~URI() { (*static_cast<QString*>(this)) = QString(); d_ptr->m_Stripped = QString(); // delete d_ptr; } /// Copy operator, make sure the cache is also copied URI& URI::operator=(const URI& o) { d_ptr->m_Parsed = o.d_ptr->m_Parsed ; d_ptr->m_HintParsed = o.d_ptr->m_HintParsed ; d_ptr->m_Hostname = o.d_ptr->m_Hostname ; d_ptr->m_HasAt = o.d_ptr->m_HasAt ; d_ptr->m_ProtocolHint = o.d_ptr->m_ProtocolHint; d_ptr->m_HeaderType = o.d_ptr->m_HeaderType ; d_ptr->m_Userinfo = o.d_ptr->m_Userinfo ; d_ptr->m_Stripped = o.d_ptr->m_Stripped ; (*static_cast<QString*>(this)) = o.d_ptr->m_Stripped; return (*this); } ///Strip out <sip:****> from the URI QString URIPrivate::strip(const QString& uri, URI::SchemeType& scheme) { if (uri.isEmpty()) return {}; int start(uri[0] == '<'?1:0),end(uri.size()-1); //Other type of comparisons were too slow if (start == end+1) return {}; const uchar c = uri[start].toLatin1(); //Assume the scheme is either iax, sip or ring using the first letter and length, this //is dangerous and can cause undefined behaviour that will cause the call to fail //later on, but this is not really a problem for now if (end > start+3 && uri[start+3] == ':') { switch (c) { case 'i': scheme = URI::SchemeType::IAX; break; case 's': scheme = URI::SchemeType::SIP; break; } start = start +4; } else if (end > start+4 && uri[start+4] == ':') { switch (c) { case 'i': scheme = URI::SchemeType::IAX2; break; case 'r': scheme = URI::SchemeType::RING; break; case 's': scheme = URI::SchemeType::SIPS; break; } start = start +5; } if (end && uri[end] == '>') end--; else if (start) { //TODO there may be a ';' section with arguments, check } return uri.mid(start,end-start+1); } /** * Return the domaine of an URI * * For example, example.com in <sip:12345@example.com> */ QString URI::hostname() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return d_ptr->m_Hostname; } /** * Check if the URI has an hostname * * This will return true if there is something between '@' and ';' (or an end of line) */ bool URI::hasHostname() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return !d_ptr->m_Hostname.isEmpty(); } /** * Return the URI SchemeType */ URI::SchemeType URI::schemeType() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return d_ptr->m_HeaderType; } /** * "Fast" Ipv4 and Ipv6 check, accept 999.999.999.999, :::::::::FF and other * atrocities, but at least perform a O(N) ish check and validate the hash * * @param str an uservalue (faster the scheme and before the "at" sign) * @param [out] isHash if the content is pure hexadecimal ASCII */ bool URIPrivate::checkIp(const QString& str, bool &isHash, const URI::SchemeType& scheme) { char* raw = str.toLatin1().data(); ushort max = str.size(); if (max < 3 || max > 45 || (!isHash && scheme == URI::SchemeType::RING)) return false; uchar dc(0),sc(0),i(0),d(0),hx(1); while (i < max) { switch(raw[i]) { case '.': isHash = false; d = 0; dc++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (++d > 3 && dc) return false; break; case ':': isHash = false; sc++; //No break case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': hx = 0; break; default: isHash = false; return false; }; i++; } return (hx && dc == 3 && d < 4) ^ (sc > 1 && dc==0); } /** * This method return an hint to guess the protocol that could be used to call * this URI. It is a quick guess, not something that should be trusted * * @warning, this method is O(N) when called for the first time on an URI */ URI::ProtocolHint URI::protocolHint() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); if (!d_ptr->m_HintParsed) { bool isHash = d_ptr->m_Userinfo.size() == 40; d_ptr->m_ProtocolHint = \ ( //Step one : Check IAX protocol, is has already been detected at this point d_ptr->m_HeaderType == URI::SchemeType::IAX2 || d_ptr->m_HeaderType == URI::SchemeType::IAX ? URI::ProtocolHint::IAX : ( //Step two : check IP URIPrivate::checkIp(d_ptr->m_Userinfo,isHash,d_ptr->m_HeaderType) ? URI::ProtocolHint::IP : ( //Step three : Check RING protocol, is has already been detected at this point d_ptr->m_HeaderType == URI::SchemeType::RING && isHash ? URI::ProtocolHint::RING : ( //Step four : Differentiate between ***@*** and *** type URIs d_ptr->m_HasAt ? URI::ProtocolHint::SIP_HOST : URI::ProtocolHint::SIP_OTHER )))); d_ptr->m_HintParsed = true; } return d_ptr->m_ProtocolHint; } ///Keep a cache of the values to avoid re-parsing them void URIPrivate::parse() { //FIXME the indexOf is done twice, the second time could be avoided if (q_ptr->indexOf('@') != -1) { const QStringList split = q_ptr->split('@'); m_HasAt = true; m_Hostname = split[1]; m_Userinfo = split[0]; m_Parsed = true; } else m_Userinfo = (*q_ptr); } /** * Extract the user info field from the URI * * For example, "123" in sip:123@myserver.net */ QString URI::userinfo() const { if (!d_ptr->m_Parsed) const_cast<URI*>(this)->d_ptr->parse(); return d_ptr->m_Userinfo; } /** * Some feature, like SIP presence, require a properly formatted URI */ QString URI::fullUri() const { return QString("<%1%2>") .arg(URIPrivate::schemeNames[static_cast<int>(d_ptr->m_HeaderType == SchemeType::NONE?SchemeType::SIP:d_ptr->m_HeaderType)]) .arg(*this); } QDataStream& operator<<( QDataStream& stream, const URI::ProtocolHint& ph ) { switch(ph) { case URI::ProtocolHint::SIP_OTHER: stream << "SIP_OTHER"; break; case URI::ProtocolHint::IAX : stream << "IAX"; break; case URI::ProtocolHint::RING : stream << "RING"; break; case URI::ProtocolHint::IP : stream << "IP"; break; case URI::ProtocolHint::SIP_HOST : stream << "SIP_HOST"; break; } return stream; } <|endoftext|>
<commit_before> #include "var.hpp" genotype::~genotype(){} zvar::~zvar(){} void zvar::setPopName(string popName){ name = popName; } pooled::~pooled(){} double pooled::bound(double v){ if(v <= 0.00001){ return 0.00001; } if(v >= 0.99999){ return 0.99999; } return v; } gl::~gl(){} gl::gl(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } pl::~pl(){} pl::pl(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } gp::~gp(){} gp::gp(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } gt::~gt(){} gt::gt(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } pooled::pooled(void){ npop = 0; afsum = 0; nalt = 0; nref = 0; af = 0; npop = 0; ntot = 0; alpha = 0.01; beta = 0.01; } // polymorphism for GL and PL double gt::unphred(map< string, vector<string> > & geno, int index){ return -1; } double gl::unphred(map< string, vector<string> > & geno, int index){ double unphreded = atof(geno["GL"][index].c_str()); return unphreded; } double gp::unphred(map< string, vector<string> > & geno, int index){ double unphreded = atof(geno["GP"][index].c_str()); return log(unphreded) ; } double pl::unphred(map< string, vector<string> > & geno, int index){ double unphreded = atof(geno["PL"][index].c_str()); unphreded = log(pow(10, (-unphreded/10))); return unphreded; } void pooled::loadPop(vector< map< string, vector<string> > > & group, string seqid, long int position){ vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string genotype = (*targ_it)["GT"].front(); if(genotype == "./."){ continue; } string allelecounts = (*targ_it)["AD"].front(); vector<string> ac = (*targ_it)["AD"]; npop += 1; double af = atof(ac[1].c_str()) / ( atof(ac[0].c_str()) + atof(ac[1].c_str()) ); if(atof(ac[1].c_str()) == 0){ af = 0; } if(atof(ac[0].c_str()) == 0){ af = 1; } afsum += af; afs.push_back(af); nrefs.push_back(atof(ac[0].c_str())); nalts.push_back(atof(ac[1].c_str())); nref += atof(ac[0].c_str()); ntot += atof(ac[0].c_str()); nalt += atof(ac[1].c_str()); ntot += atof(ac[1].c_str()); } if(npop < 1){ af = -1; } else{ af = afsum / npop; } } void genotype::estimatePosterior(void){ int ng = genoIndex.size(); for(int i = 0 ; i < ng; i++){ if(genoIndex[i] == -1){ continue; } double aa = genoLikelihoods[i][0] ; double ab = genoLikelihoods[i][1] ; double bb = genoLikelihoods[i][2] ; alpha += exp(ab); beta += exp(ab); alpha += 2 * exp(aa); beta += 2 * exp(bb); } } void pooled::estimatePosterior(void){ if(npop < 2){ cerr << "FATAL: not enough pooled populations in the target or background\n"; exit(1); } double xbar = af; double ss = 0; for(int i = 0 ; i < npop; i++){ ss += pow(( afs[i] - xbar),2); } double var = (1/(npop-1))*ss; xbar = bound(xbar); if(var < 0.01){ var = 0.01; } if(var < xbar*(1-xbar)){ alpha = xbar * (((xbar*(1-xbar))/var) -1); beta = (1 - xbar) * (((xbar*(1-xbar))/var) -1); } else{ alpha = -1; beta = -1; } } void genotype::loadPop( vector< map< string, vector<string> > >& group, string seqid, long int position){ seqid = seqid; pos = position ; vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string genotype = (*targ_it)["GT"].front(); gts.push_back(genotype); vector<double> phreds; vector<double> phredsCDF; double sum = 0; if(genotype != "./."){ double pa = unphred( (*targ_it), 0) ; double pab = unphred( (*targ_it), 1) ; double pbb = unphred( (*targ_it), 2) ; double norm = log(exp(pa) + exp(pab) + exp(pbb)) ; phreds.push_back(pa - norm); phreds.push_back(pab - norm); phreds.push_back(pbb - norm); // cerr << exp(pa - norm) << endl; // cerr << exp(pab - norm) << endl; // cerr << exp(pbb - norm) << endl; // cerr << endl; sum += exp(pa - norm); // cerr << sum << endl; phredsCDF.push_back(sum); sum += exp(pab - norm); // cerr << sum << endl; phredsCDF.push_back(sum); sum += exp(pbb - norm); // cerr << sum << endl; // cerr << endl; phredsCDF.push_back(sum); } else{ phreds.push_back(log(1/3)); phreds.push_back(log(1/3)); phreds.push_back(log(1/3)); phredsCDF.push_back(1/3); phredsCDF.push_back(2/3); phredsCDF.push_back(1); } genoLikelihoods.push_back(phreds); genoLikelihoodsCDF.push_back(phredsCDF); if(genotype == "./0" || genotype == "./1"){ genotype = "./."; } while(1){ if(genotype == "./."){ genoIndex.push_back(-1); break; } if(genotype == "0/0"){ ngeno += 1; nhomr += 1; nref += 2; genoIndex.push_back(0); break; } if(genotype == "0/1"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1/0"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1/1"){ ngeno += 1; nhoma += 1; nalt += 2; genoIndex.push_back(2); break; } if(genotype == "0|0"){ ngeno += 1; nhomr += 1; nref += 2; genoIndex.push_back(0); break; } if(genotype == "0|1"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1|0"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1|1"){ ngeno += 1; nhoma += 1; nalt += 2; genoIndex.push_back(2); break; } cerr << "FATAL: unknown genotype: " << genotype << endl; exit(1); } } if(nalt == 0 && nref == 0){ af = -1; } else{ af = (nalt / (nref + nalt)); if(nhet > 0){ fis = ( 1 - ((nhet/ngeno) / (2*af*(1 - af)))); } else{ fis = 1; } if(fis < 0){ fis = 0.00001; } } hfrq = nhet / ngeno; npop = ngeno; } <commit_msg>some callers use . and ./. for nocall<commit_after> #include "var.hpp" genotype::~genotype(){} zvar::~zvar(){} void zvar::setPopName(string popName){ name = popName; } pooled::~pooled(){} double pooled::bound(double v){ if(v <= 0.00001){ return 0.00001; } if(v >= 0.99999){ return 0.99999; } return v; } gl::~gl(){} gl::gl(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } pl::~pl(){} pl::pl(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } gp::~gp(){} gp::gp(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } gt::~gt(){} gt::gt(void){ nalt = 0; nref = 0; af = 0; nhomr = 0; nhoma = 0; nhet = 0; ngeno = 0; fis = 0; hfrq = 0; alpha = 0.01; beta = 0.01; } pooled::pooled(void){ npop = 0; afsum = 0; nalt = 0; nref = 0; af = 0; npop = 0; ntot = 0; alpha = 0.01; beta = 0.01; } // polymorphism for GL and PL double gt::unphred(map< string, vector<string> > & geno, int index){ return -1; } double gl::unphred(map< string, vector<string> > & geno, int index){ double unphreded = atof(geno["GL"][index].c_str()); return unphreded; } double gp::unphred(map< string, vector<string> > & geno, int index){ double unphreded = atof(geno["GP"][index].c_str()); return log(unphreded) ; } double pl::unphred(map< string, vector<string> > & geno, int index){ double unphreded = atof(geno["PL"][index].c_str()); unphreded = log(pow(10, (-unphreded/10))); return unphreded; } void pooled::loadPop(vector< map< string, vector<string> > > & group, string seqid, long int position){ vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string genotype = (*targ_it)["GT"].front(); if(genotype == "./."){ continue; } string allelecounts = (*targ_it)["AD"].front(); vector<string> ac = (*targ_it)["AD"]; npop += 1; double af = atof(ac[1].c_str()) / ( atof(ac[0].c_str()) + atof(ac[1].c_str()) ); if(atof(ac[1].c_str()) == 0){ af = 0; } if(atof(ac[0].c_str()) == 0){ af = 1; } afsum += af; afs.push_back(af); nrefs.push_back(atof(ac[0].c_str())); nalts.push_back(atof(ac[1].c_str())); nref += atof(ac[0].c_str()); ntot += atof(ac[0].c_str()); nalt += atof(ac[1].c_str()); ntot += atof(ac[1].c_str()); } if(npop < 1){ af = -1; } else{ af = afsum / npop; } } void genotype::estimatePosterior(void){ int ng = genoIndex.size(); for(int i = 0 ; i < ng; i++){ if(genoIndex[i] == -1){ continue; } double aa = genoLikelihoods[i][0] ; double ab = genoLikelihoods[i][1] ; double bb = genoLikelihoods[i][2] ; alpha += exp(ab); beta += exp(ab); alpha += 2 * exp(aa); beta += 2 * exp(bb); } } void pooled::estimatePosterior(void){ if(npop < 2){ cerr << "FATAL: not enough pooled populations in the target or background\n"; exit(1); } double xbar = af; double ss = 0; for(int i = 0 ; i < npop; i++){ ss += pow(( afs[i] - xbar),2); } double var = (1/(npop-1))*ss; xbar = bound(xbar); if(var < 0.01){ var = 0.01; } if(var < xbar*(1-xbar)){ alpha = xbar * (((xbar*(1-xbar))/var) -1); beta = (1 - xbar) * (((xbar*(1-xbar))/var) -1); } else{ alpha = -1; beta = -1; } } void genotype::loadPop( vector< map< string, vector<string> > >& group, string seqid, long int position){ seqid = seqid; pos = position ; vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string genotype = (*targ_it)["GT"].front(); if(genotype == "./0" || genotype == "./1" || genotype == "."){ genotype = "./."; } gts.push_back(genotype); vector<double> phreds; vector<double> phredsCDF; double sum = 0; if(genotype != "./."){ double pa = unphred( (*targ_it), 0) ; double pab = unphred( (*targ_it), 1) ; double pbb = unphred( (*targ_it), 2) ; double norm = log(exp(pa) + exp(pab) + exp(pbb)) ; phreds.push_back(pa - norm); phreds.push_back(pab - norm); phreds.push_back(pbb - norm); sum += exp(pa - norm); // cerr << sum << endl; phredsCDF.push_back(sum); sum += exp(pab - norm); // cerr << sum << endl; phredsCDF.push_back(sum); sum += exp(pbb - norm); // cerr << sum << endl; // cerr << endl; phredsCDF.push_back(sum); } else{ phreds.push_back(log(1/3)); phreds.push_back(log(1/3)); phreds.push_back(log(1/3)); phredsCDF.push_back(1/3); phredsCDF.push_back(2/3); phredsCDF.push_back(1); } genoLikelihoods.push_back(phreds); genoLikelihoodsCDF.push_back(phredsCDF); while(1){ if(genotype == "./."){ genoIndex.push_back(-1); break; } if(genotype == "0/0"){ ngeno += 1; nhomr += 1; nref += 2; genoIndex.push_back(0); break; } if(genotype == "0/1"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1/0"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1/1"){ ngeno += 1; nhoma += 1; nalt += 2; genoIndex.push_back(2); break; } if(genotype == "0|0"){ ngeno += 1; nhomr += 1; nref += 2; genoIndex.push_back(0); break; } if(genotype == "0|1"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1|0"){ ngeno += 1; nhet += 1; nref += 1; nalt += 1; genoIndex.push_back(1); break; } if(genotype == "1|1"){ ngeno += 1; nhoma += 1; nalt += 2; genoIndex.push_back(2); break; } cerr << "FATAL: unknown genotype: " << genotype << endl; exit(1); } } if(nalt == 0 && nref == 0){ af = -1; } else{ af = (nalt / (nref + nalt)); if(nhet > 0){ fis = ( 1 - ((nhet/ngeno) / (2*af*(1 - af)))); } else{ fis = 1; } if(fis < 0){ fis = 0.00001; } } hfrq = nhet / ngeno; npop = ngeno; } <|endoftext|>
<commit_before>/* * File: cobject.cpp * Author: Oleg Zharkov * */ #include "waf.h" #include <boost/algorithm/string.hpp> #include <boost/range/iterator_range.hpp> #include <boost/tokenizer.hpp> #include <boost/regex.hpp> void ModsecRecord::GetAuditHeader(const string str) { int pointer = str.find("[file"); parameters = str.substr(pointer); } void ModsecRecord::RemoveAuditParametersName(const string field, const string str) { int b = field.length(); int l = str.length() - b - 2; buffer = str.substr(b, l); } void ModsecRecord::CheckAuditFields(const string str) { if(str.find("file") == 0) { RemoveAuditParametersName("file", str); ma.file = buffer; return; } if(str.find("id") == 0) { RemoveAuditParametersName("id", str); try { // string -> integer ma.id = std::stoi(buffer); } catch (const std::exception & ex) { ma.id = 0; } return; } if(str.find("severity") == 0) { RemoveAuditParametersName("severity", str); try { // string -> integer ma.severity = std::stoi(buffer); } catch (const std::exception & ex) { ma.severity = 0; } return; } if(str.find("tag") == 0) { RemoveAuditParametersName("tag", str); ma.list_tags.push_back(buffer); return; } if(str.find("msg") == 0) { RemoveAuditParametersName("msg", str); ma.msg = buffer; return; } if(str.find("hostname") == 0) { RemoveAuditParametersName("hostname", str); ma.hostname = buffer; return; } if(str.find("uri") == 0) { RemoveAuditParametersName("uri", str); ma.uri = buffer; return; } } int ModsecRecord::ParsRecord(const string rec) { GetAuditHeader(rec); boost::split(strs,parameters,boost::is_any_of("[")); std::vector<string>::iterator i, end; for (vector<string>::const_iterator it = strs.begin(); it != strs.end(); ++it) { CheckAuditFields(*it); } return 1; } <commit_msg>Update waf.cpp<commit_after>/* * File: waf.cpp * Author: Oleg Zharkov * */ #include "waf.h" #include <boost/algorithm/string.hpp> #include <boost/range/iterator_range.hpp> #include <boost/tokenizer.hpp> #include <boost/regex.hpp> void ModsecRecord::GetAuditHeader(const string str) { int pointer = str.find("[file"); parameters = str.substr(pointer); } void ModsecRecord::RemoveAuditParametersName(const string field, const string str) { int b = field.length(); int l = str.length() - b - 2; buffer = str.substr(b, l); } void ModsecRecord::CheckAuditFields(const string str) { if(str.find("file") == 0) { RemoveAuditParametersName("file", str); ma.file = buffer; return; } if(str.find("id") == 0) { RemoveAuditParametersName("id", str); try { // string -> integer ma.id = std::stoi(buffer); } catch (const std::exception & ex) { ma.id = 0; } return; } if(str.find("severity") == 0) { RemoveAuditParametersName("severity", str); try { // string -> integer ma.severity = std::stoi(buffer); } catch (const std::exception & ex) { ma.severity = 0; } return; } if(str.find("tag") == 0) { RemoveAuditParametersName("tag", str); ma.list_tags.push_back(buffer); return; } if(str.find("msg") == 0) { RemoveAuditParametersName("msg", str); ma.msg = buffer; return; } if(str.find("hostname") == 0) { RemoveAuditParametersName("hostname", str); ma.hostname = buffer; return; } if(str.find("uri") == 0) { RemoveAuditParametersName("uri", str); ma.uri = buffer; return; } } int ModsecRecord::ParsRecord(const string rec) { GetAuditHeader(rec); boost::split(strs,parameters,boost::is_any_of("[")); std::vector<string>::iterator i, end; for (vector<string>::const_iterator it = strs.begin(); it != strs.end(); ++it) { CheckAuditFields(*it); } return 1; } <|endoftext|>
<commit_before>#include "command.h" #include "memory.h" #include "progressbar.h" #include "algo/threaded_loop.h" #include "image.h" #include "dwi/gradient.h" #include "dwi/shells.h" #include "dwi/sdeconv/constrained.h" using namespace MR; using namespace App; void usage () { DESCRIPTION + "perform non-negativity constrained spherical deconvolution." + "Note that this program makes use of implied symmetries in the diffusion " "profile. First, the fact the signal attenuation profile is real implies " "that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes " "the complex conjugate). Second, the diffusion profile should be " "antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l " "components should be zero. Therefore, this program only computes the even " "elements." + "Note that the spherical harmonics equations used here differ slightly " "from those conventionally used, in that the (-1)^m factor has been " "omitted. This should be taken into account in all subsequent calculations." + Math::SH::encoding_description; REFERENCES + "Tournier, J.-D.; Calamante, F. & Connelly, A. " "Robust determination of the fibre orientation distribution in diffusion MRI: " "Non-negativity constrained super-resolved spherical deconvolution. " "NeuroImage, 2007, 35, 1459-1472"; ARGUMENTS + Argument ("dwi", "the input diffusion-weighted image.").type_image_in() + Argument ("response", "a text file containing the diffusion-weighted signal response function " "coefficients for a single fibre population, ").type_file_in() + Argument ("SH", "the output spherical harmonics coefficients image.").type_image_out(); OPTIONS + DWI::GradImportOptions() + DWI::ShellOption + DWI::CSD_options + Stride::Options; } typedef float value_type; typedef double cost_value_type; class Processor { public: Processor (const DWI::CSDeconv::Shared& shared, Image<bool>& mask) : sdeconv (shared), data (shared.dwis.size()), mask (mask) { } template <class DWIType, class FODType> void operator () (DWIType& dwi, FODType& fod) { if (!load_data (dwi)) return; sdeconv.set (data); size_t n; for (n = 0; n < sdeconv.shared.niter; n++) if (sdeconv.iterate()) break; if (n >= sdeconv.shared.niter) INFO ("voxel [ " + str (dwi.index(0)) + " " + str (dwi.index(1)) + " " + str (dwi.index(2)) + " ] did not reach full convergence"); write_back (fod); } private: DWI::CSDeconv sdeconv; Eigen::VectorXd data; Image<bool> mask; template <class DWIType> bool load_data (DWIType& dwi) { if (mask.valid()) { assign_pos_of (dwi, 0, 3).to (mask); if (!mask.value()) return false; } for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) { dwi.index(3) = sdeconv.shared.dwis[n]; data[n] = dwi.value(); if (!std::isfinite (data[n])) return false; if (data[n] < 0.0) data[n] = 0.0; } return true; } template <class FODType> void write_back (FODType& fod) { for (auto l = Loop (3) (fod); l; ++l) fod.value() = sdeconv.FOD() [fod.index(3)]; } }; void run () { auto dwi = Image<value_type>::open (argument[0]).with_direct_io (Stride::contiguous_along_axis(3)); auto mask = Image<bool>(); auto opt = get_options ("mask"); if (opt.size()) { mask = Header::open (opt[0][0]).get_image<bool>(); check_dimensions (dwi, mask, 0, 3); } DWI::CSDeconv::Shared shared (dwi.header()); shared.parse_cmdline_options(); shared.set_response (argument[1]); shared.init(); auto header = Header(dwi); header.set_ndim (4); header.size(3) = shared.nSH(); header.datatype() = DataType::Float32; Stride::set_from_command_line (header); auto fod = Image<value_type>::create (argument[2], header); Processor processor (shared, mask); ThreadedLoop ("performing constrained spherical deconvolution...", dwi, 0, 3) .run (processor, dwi, fod); } <commit_msg>Small fix to dwi2fod to ensure non-masks voxel are initalised to zero<commit_after>#include "command.h" #include "memory.h" #include "progressbar.h" #include "algo/threaded_loop.h" #include "image.h" #include "dwi/gradient.h" #include "dwi/shells.h" #include "dwi/sdeconv/constrained.h" using namespace MR; using namespace App; void usage () { DESCRIPTION + "perform non-negativity constrained spherical deconvolution." + "Note that this program makes use of implied symmetries in the diffusion " "profile. First, the fact the signal attenuation profile is real implies " "that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes " "the complex conjugate). Second, the diffusion profile should be " "antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l " "components should be zero. Therefore, this program only computes the even " "elements." + "Note that the spherical harmonics equations used here differ slightly " "from those conventionally used, in that the (-1)^m factor has been " "omitted. This should be taken into account in all subsequent calculations." + Math::SH::encoding_description; REFERENCES + "Tournier, J.-D.; Calamante, F. & Connelly, A. " "Robust determination of the fibre orientation distribution in diffusion MRI: " "Non-negativity constrained super-resolved spherical deconvolution. " "NeuroImage, 2007, 35, 1459-1472"; ARGUMENTS + Argument ("dwi", "the input diffusion-weighted image.").type_image_in() + Argument ("response", "a text file containing the diffusion-weighted signal response function " "coefficients for a single fibre population, ").type_file_in() + Argument ("SH", "the output spherical harmonics coefficients image.").type_image_out(); OPTIONS + DWI::GradImportOptions() + DWI::ShellOption + DWI::CSD_options + Stride::Options; } typedef float value_type; typedef double cost_value_type; class Processor { public: Processor (const DWI::CSDeconv::Shared& shared, Image<bool>& mask) : sdeconv (shared), data (shared.dwis.size()), mask (mask) { } template <class DWIType, class FODType> void operator () (DWIType& dwi, FODType& fod) { if (!load_data (dwi)) { for (auto l = Loop (3) (fod); l; ++l) fod.value() = 0.0; return; } sdeconv.set (data); size_t n; for (n = 0; n < sdeconv.shared.niter; n++) if (sdeconv.iterate()) break; if (n >= sdeconv.shared.niter) INFO ("voxel [ " + str (dwi.index(0)) + " " + str (dwi.index(1)) + " " + str (dwi.index(2)) + " ] did not reach full convergence"); write_back (fod); } private: DWI::CSDeconv sdeconv; Eigen::VectorXd data; Image<bool> mask; template <class DWIType> bool load_data (DWIType& dwi) { if (mask.valid()) { assign_pos_of (dwi, 0, 3).to (mask); if (!mask.value()) return false; } for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) { dwi.index(3) = sdeconv.shared.dwis[n]; data[n] = dwi.value(); if (!std::isfinite (data[n])) return false; if (data[n] < 0.0) data[n] = 0.0; } return true; } template <class FODType> void write_back (FODType& fod) { for (auto l = Loop (3) (fod); l; ++l) fod.value() = sdeconv.FOD() [fod.index(3)]; } }; void run () { auto dwi = Image<value_type>::open (argument[0]).with_direct_io (Stride::contiguous_along_axis(3)); auto mask = Image<bool>(); auto opt = get_options ("mask"); if (opt.size()) { mask = Header::open (opt[0][0]).get_image<bool>(); check_dimensions (dwi, mask, 0, 3); } DWI::CSDeconv::Shared shared (dwi.header()); shared.parse_cmdline_options(); shared.set_response (argument[1]); shared.init(); auto header = Header(dwi); header.set_ndim (4); header.size(3) = shared.nSH(); header.datatype() = DataType::Float32; Stride::set_from_command_line (header); auto fod = Image<value_type>::create (argument[2], header); Processor processor (shared, mask); ThreadedLoop ("performing constrained spherical deconvolution...", dwi, 0, 3) .run (processor, dwi, fod); } <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "command.h" #include "image/header.h" #include "math/matrix.h" using namespace MR; using namespace App; void usage () { DESCRIPTION + "edit transformation matrices." + "This is needed in particular to convert the transformation matrix provided " "FSL's flirt command to a format usable in MRtrix."; ARGUMENTS + Argument ("input", "input transformation matrix").type_file_in () + Argument ("from", "the image the input transformation matrix maps from").type_image_in () + Argument ("to", "the image the input transformation matrix maps onto").type_image_in () + Argument ("output", "the output transformation matrix.").type_file_out (); } void run () { Math::Matrix<float> input; input.load (argument[0]); const Image::Header from (argument[1]); const Image::Header to (argument[2]); Math::Matrix<float> R(4,4); R.identity(); R(0,0) = -1.0; R(0,3) = (to.dim(0)-1) * to.vox(0); VAR (R); VAR (input); Math::Matrix<float> M; Math::mult (M, R, input); VAR (M); R(0,3) = (from.dim(0)-1) * from.vox(0); VAR (R); Math::mult (input, M, R); VAR (input); Math::mult (R, to.transform(), input); R.save (argument[3]); } <commit_msg>new command 'mtxedit' to convert transform matrices<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "command.h" #include "image/header.h" #include "file/nifti1_utils.h" #include "math/matrix.h" #include "math/LU.h" using namespace MR; using namespace App; void usage () { DESCRIPTION + "edit transformation matrices." + "This is needed in particular to convert the transformation matrix provided " "FSL's flirt command to a format usable in MRtrix."; ARGUMENTS + Argument ("input", "input transformation matrix").type_file_in () + Argument ("from", "the image the input transformation matrix maps from").type_image_in () + Argument ("to", "the image the input transformation matrix maps onto").type_image_in () + Argument ("output", "the output transformation matrix.").type_file_out (); } Math::Matrix<float> get_flirt_transform (const Image::Header& header) { std::vector<size_t> axes; Math::Matrix<float> nifti_transform = File::NIfTI::adjust_transform (header, axes); if (Math::LU::sgndet (nifti_transform) < 0.0) return nifti_transform; Math::Matrix<float> coord_switch (4,4); coord_switch.identity(); coord_switch(0,0) = -1.0f; coord_switch(0,3) = (header.dim(axes[0])-1) * header.vox(axes[0]); Math::Matrix<float> updated_transform; return Math::mult (updated_transform, nifti_transform, coord_switch); } void run () { Math::Matrix<float> flirt_transform; flirt_transform.load (argument[0]); Image::Header src_header (argument[1]); Math::Matrix<float> src_flirt_to_scanner = get_flirt_transform (src_header); Image::Header dest_header (argument[2]); Math::Matrix<float> dest_flirt_to_scanner = get_flirt_transform (dest_header); Math::Matrix<float> scanner_to_src_flirt = Math::LU::inv (src_flirt_to_scanner); Math::Matrix<float> scanner_to_transformed_dest_flirt; Math::mult (scanner_to_transformed_dest_flirt, flirt_transform, scanner_to_src_flirt); Math::Matrix<float> output; Math::mult (output, dest_flirt_to_scanner, scanner_to_transformed_dest_flirt); output.save (argument[3]); } <|endoftext|>
<commit_before><commit_msg>we will need automatic calculation of flags buffer also for oriented linear curve once we support it<commit_after><|endoftext|>
<commit_before>#ifndef CNN_HEADER #define CNN_HEADER #include "util.hpp" #include "convolution.hpp" #include "maxpool.hpp" #include "fullconnect.hpp" #define BUFSIZE (64 * 1024 * 1024) namespace cnn { class CNN { public: CNN(const std::string &xmlFileName, const std::string &xclbinFile = "NONE") { // Parse the xml file. char *buf = new char[BUFSIZE]; fileToChar(xmlFileName, buf, BUFSIZE); rapidxml::xml_document<> doc; doc.parse<0>(buf); rapidxml::xml_node<> *root = doc.first_node(); // Get the kernel file name. std::string kernelFileName(root->first_node("kernelFileName")->value()); // Get the input size. size_t inSize = getSizeT(root, "inSize"); // Initialize the OpenCL. if (xclbinFile == "NONE") { initOpenCL(kernelFileName, false, inSize); } else { initOpenCL(xclbinFile, true, inSize); } // For every layer. bool isFront = true; for (rapidxml::xml_node<> *layer = root->first_node("layer"); layer; layer = layer->next_sibling("layer")) { Flag flag = INNER; if (isFront) { flag |= FRONT; isFront = false; } if (!(layer->next_sibling())) { flag |= BACK; } layers.push_back(createLayer(layer, flag)); } delete buf; } ~CNN() { for (int i = 0; i < layers.size(); ++i) { delete layers[i]; } clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context); } // Forward with CPU. unsigned long long forwardCPU(const vec &in) { unsigned long long totalTime = layers[0]->forwardCPU(in); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCPU(layers[i - 1]->out); } return totalTime; } unsigned long long forwardCL(const vec &in) { // Prepare the input cl_mem. cl_int err; err = clEnqueueWriteBuffer(queue, clIn, CL_TRUE, 0, in.size() * sizeof(cl_float), (void *)&in[0], 0, NULL, NULL); handleError(err, "Failed copy input buffer. "); // Enqueue the first kernel. unsigned long long totalTime = layers[0]->forwardCL(queue); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCL(queue); } // Get the result to the last layer's out vec. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_TRUE, 0, getOutSize() * sizeof(cl_float), &(layers[layers.size() - 1]->out[0]), 0, NULL, NULL); return totalTime; } // For OpenCL. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_program program; cl_mem clIn; std::vector<Layer *> layers; size_t getInSize() const { return layers[0]->iWidth * layers[0]->iHeight * layers[0]->iDepth; } size_t getOutSize() const { size_t last = layers.size() - 1; return layers[last]->out.size(); } const vec &getOut() const { return layers[layers.size() - 1]->out; } private: void initOpenCL(const std::string &kernelFileName, bool isBinary, size_t inSize) { cl_int err; // Choose the first platform. err = clGetPlatformIDs(1, &platform, NULL); // Choose the first device. err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL); printDeviceInfo(std::cout, device); cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; context = clCreateContext( properties, 1, &device, NULL, NULL, &err); handleError(err, "Failed creating context. "); clRetainContext(context); queue = clCreateCommandQueue( context, device, CL_QUEUE_PROFILING_ENABLE, &err); handleError(err, "Failed creating command queue. "); clRetainCommandQueue(queue); if (isBinary) { program = buildProgramFromBinary(kernelFileName.c_str(), context, device); } else { program = buildProgramFromSource(kernelFileName.c_str(), context, device); } err = clRetainProgram(program); handleError(err, "Failed retaining program. "); clIn = clCreateBuffer( context, CL_MEM_READ_ONLY, inSize * sizeof(cl_float), NULL, &err); handleError(err, "Failed creating clIn"); err = clRetainMemObject(clIn); handleError(err, "Failed retaining clIn"); } // Create a layer. Layer *createLayer(rapidxml::xml_node<> *root, Flag flag) { std::string type = getString(root, "type"); if (type == "conv") { return createConvLayer(root, flag); } else if (type == "max") { return createMaxLayer(root, flag); } else if (type == "full") { return createFullLayer(root, flag); } else { std::cerr << "createLayer: Unsupported layer: " << type << std::endl; exit(-1); } } Layer *createFullLayer(rapidxml::xml_node<> *root, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.oWidth = getSizeT(root, "oWidth"); params.oHeight = getSizeT(root, "oHeight"); params.oDepth = getSizeT(root, "oDepth"); // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); assert(weight.size() == params.oWidth * params.oHeight * params.oDepth * params.iDepth * params.iWidth * params.iHeight); // Create the offset vector. cnn::vec offset; for (rapidxml::xml_node<> *node = root->first_node("offset")->first_node(); node; node = node->next_sibling()) { offset.push_back((float)std::atof(node->value())); } assert(offset.size() == params.oWidth * params.oHeight * params.oDepth); return new cnn::FullConnectLayer(params, weight, offset, context, program, clIn ); } Layer *createMaxLayer(rapidxml::xml_node<> *root, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.kernelSize = getSizeT(root, "kernelSize"); params.oDepth = params.iDepth; params.oWidth = params.iWidth / params.kernelSize; params.oHeight = params.iHeight / params.kernelSize; // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); assert(weight.size() == params.oWidth * params.oHeight * params.oDepth * params.iDepth * params.iWidth * params.iHeight); // Create the offset vector. cnn::vec offset; for (rapidxml::xml_node<> *node = root->first_node("offset")->first_node(); node; node = node->next_sibling()) { offset.push_back((float)std::atof(node->value())); } return new cnn::MaxPoolLayer(params, weight, offset, context, program, clIn ); } Layer *createConvLayer(rapidxml::xml_node<> *root, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.kernelSize = getSizeT(root, "kernelSize"); params.oDepth = getSizeT(root, "oDepth"); params.oWidth = params.iWidth - params.kernelSize + 1; params.oHeight = params.iHeight - params.kernelSize + 1; // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); assert(weight.size() == params.oDepth * params.iDepth * params.kernelSize * params.kernelSize); // Create the offset vector. cnn::vec offset; for (rapidxml::xml_node<> *node = root->first_node("offset")->first_node(); node; node = node->next_sibling()) { offset.push_back((float)std::atof(node->value())); } assert(offset.size() == params.oDepth); return new cnn::ConvolutionLayer(params, weight, offset, context, program, clIn ); } }; } #endif<commit_msg>fix bug<commit_after>#ifndef CNN_HEADER #define CNN_HEADER #include "util.hpp" #include "convolution.hpp" #include "maxpool.hpp" #include "fullconnect.hpp" #define BUFSIZE (64 * 1024 * 1024) namespace cnn { class CNN { public: CNN(const std::string &xmlFileName, const std::string &xclbinFile = "NONE") { // Parse the xml file. char *buf = new char[BUFSIZE]; fileToChar(xmlFileName, buf, BUFSIZE); rapidxml::xml_document<> doc; doc.parse<0>(buf); rapidxml::xml_node<> *root = doc.first_node(); // Get the kernel file name. std::string kernelFileName(root->first_node("kernelFileName")->value()); // Get the input size. size_t inSize = getSizeT(root, "inSize"); // Initialize the OpenCL. if (xclbinFile == "NONE") { initOpenCL(kernelFileName, false, inSize); } else { initOpenCL(xclbinFile, true, inSize); } // For every layer. bool isFront = true; for (rapidxml::xml_node<> *layer = root->first_node("layer"); layer; layer = layer->next_sibling("layer")) { Flag flag = INNER; if (isFront) { flag |= FRONT; isFront = false; } if (!(layer->next_sibling())) { flag |= BACK; } layers.push_back(createLayer(layer, flag)); } delete buf; } ~CNN() { for (int i = 0; i < layers.size(); ++i) { delete layers[i]; } clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context); } // Forward with CPU. unsigned long long forwardCPU(const vec &in) { unsigned long long totalTime = layers[0]->forwardCPU(in); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCPU(layers[i - 1]->out); } return totalTime; } unsigned long long forwardCL(const vec &in) { // Prepare the input cl_mem. cl_int err; err = clEnqueueWriteBuffer(queue, clIn, CL_TRUE, 0, in.size() * sizeof(cl_float), (void *)&in[0], 0, NULL, NULL); handleError(err, "Failed copy input buffer. "); // Enqueue the first kernel. unsigned long long totalTime = layers[0]->forwardCL(queue); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCL(queue); } // Get the result to the last layer's out vec. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_TRUE, 0, getOutSize() * sizeof(cl_float), &(layers[layers.size() - 1]->out[0]), 0, NULL, NULL); return totalTime; } // For OpenCL. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_program program; cl_mem clIn; std::vector<Layer *> layers; size_t getInSize() const { return layers[0]->iWidth * layers[0]->iHeight * layers[0]->iDepth; } size_t getOutSize() const { size_t last = layers.size() - 1; return layers[last]->out.size(); } const vec &getOut() const { return layers[layers.size() - 1]->out; } private: void initOpenCL(const std::string &kernelFileName, bool isBinary, size_t inSize) { cl_int err; // Choose the first platform. err = clGetPlatformIDs(1, &platform, NULL); // Choose the first device. err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL); printDeviceInfo(std::cout, device); cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; context = clCreateContext( properties, 1, &device, NULL, NULL, &err); handleError(err, "Failed creating context. "); clRetainContext(context); queue = clCreateCommandQueue( context, device, CL_QUEUE_PROFILING_ENABLE, &err); handleError(err, "Failed creating command queue. "); clRetainCommandQueue(queue); if (isBinary) { program = buildProgramFromBinary(kernelFileName.c_str(), context, device); } else { program = buildProgramFromSource(kernelFileName.c_str(), context, device); } err = clRetainProgram(program); handleError(err, "Failed retaining program. "); clIn = clCreateBuffer( context, CL_MEM_READ_ONLY, inSize * sizeof(cl_float), NULL, &err); handleError(err, "Failed creating clIn"); err = clRetainMemObject(clIn); handleError(err, "Failed retaining clIn"); } // Create a layer. Layer *createLayer(rapidxml::xml_node<> *root, Flag flag) { std::string type = getString(root, "type"); if (type == "conv") { return createConvLayer(root, flag); } else if (type == "max") { return createMaxLayer(root, flag); } else if (type == "full") { return createFullLayer(root, flag); } else { std::cerr << "createLayer: Unsupported layer: " << type << std::endl; exit(-1); } } Layer *createFullLayer(rapidxml::xml_node<> *root, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.oWidth = getSizeT(root, "oWidth"); params.oHeight = getSizeT(root, "oHeight"); params.oDepth = getSizeT(root, "oDepth"); // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); assert(weight.size() == params.oWidth * params.oHeight * params.oDepth * params.iDepth * params.iWidth * params.iHeight); // Create the offset vector. cnn::vec offset; for (rapidxml::xml_node<> *node = root->first_node("offset")->first_node(); node; node = node->next_sibling()) { offset.push_back((float)std::atof(node->value())); } assert(offset.size() == params.oWidth * params.oHeight * params.oDepth); return new cnn::FullConnectLayer(params, weight, offset, context, program, clIn ); } Layer *createMaxLayer(rapidxml::xml_node<> *root, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.kernelSize = getSizeT(root, "kernelSize"); params.oDepth = params.iDepth; params.oWidth = params.iWidth / params.kernelSize; params.oHeight = params.iHeight / params.kernelSize; // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); assert(weight.size() == params.oDepth); // Create the offset vector. cnn::vec offset; for (rapidxml::xml_node<> *node = root->first_node("offset")->first_node(); node; node = node->next_sibling()) { offset.push_back((float)std::atof(node->value())); } return new cnn::MaxPoolLayer(params, weight, offset, context, program, clIn ); } Layer *createConvLayer(rapidxml::xml_node<> *root, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.kernelSize = getSizeT(root, "kernelSize"); params.oDepth = getSizeT(root, "oDepth"); params.oWidth = params.iWidth - params.kernelSize + 1; params.oHeight = params.iHeight - params.kernelSize + 1; // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); assert(weight.size() == params.oDepth * params.iDepth * params.kernelSize * params.kernelSize); // Create the offset vector. cnn::vec offset; for (rapidxml::xml_node<> *node = root->first_node("offset")->first_node(); node; node = node->next_sibling()) { offset.push_back((float)std::atof(node->value())); } assert(offset.size() == params.oDepth); return new cnn::ConvolutionLayer(params, weight, offset, context, program, clIn ); } }; } #endif<|endoftext|>
<commit_before>#ifndef CNN_HEADER #define CNN_HEADER #include "util.hpp" #include "convolution.hpp" #include "maxpool.hpp" #include "fullconnect.hpp" #include "rbf.hpp" #include "eventpool.hpp" #define BUFSIZE (64 * 1024 * 1024) namespace cnn { class CNN { public: CNN(const std::string &xmlFileName, bool isQueueInOrder = true, const std::string &xclbinFile = "NONE") { this->isQueueInOrder = isQueueInOrder; // Parse the xml file. char *buf = new char[BUFSIZE]; fileToChar(xmlFileName, buf, BUFSIZE); rapidxml::xml_document<> doc; doc.parse<0>(buf); rapidxml::xml_node<> *root = doc.first_node(); // Get the kernel file name. std::string kernelFileName(root->first_node("kernelFileName")->value()); // Get the input size. size_t inSize = getSizeT(root, "inSize"); // Get the queue barrier. queueBarrier = getSizeT(root, "queueBarrier"); initOpenCL(isQueueInOrder, inSize); //// Initialize the OpenCL. //if (xclbinFile == "NONE") { // initOpenCL(kernelFileName, isQueueInOrder, inSize); //} //else { // initOpenCL(xclbinFile, isQueueInOrder, inSize); //} // For every layer. bool isFront = true; for (rapidxml::xml_node<> *layer = root->first_node("layer"); layer; layer = layer->next_sibling("layer")) { Flag flag = INNER; if (isFront) { flag |= FRONT; isFront = false; } if (!(layer->next_sibling())) { flag |= BACK; } layers.push_back(createLayer(layer, xclbinFile != "NONE", flag)); } delete[] buf; } ~CNN() { for (int i = 0; i < layers.size(); ++i) { delete layers[i]; } //clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context); } // Forward with CPU. unsigned long long forwardCPU(const vec &in) { unsigned long long totalTime = layers[0]->forwardCPU(in); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCPU(layers[i - 1]->out); } return totalTime; } // Forward with OpenCL. unsigned long long forwardCL(const vec &in) { // Prepare the input cl_mem. cl_int err; err = clEnqueueWriteBuffer(queue, clIn, CL_TRUE, 0, in.size() * sizeof(cl_float), (void *)&in[0], 0, NULL, NULL); handleError(err, "Failed copy input buffer. "); // Enqueue the first kernel. unsigned long long totalTime = layers[0]->forwardCL(queue); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCL(queue); } // Get the result to the last layer's out vec. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_TRUE, 0, getOutSize() * sizeof(cl_float), &(layers[layers.size() - 1]->out[0]), 0, NULL, NULL); return totalTime; } // Forward more than one input with in order command queue. std::vector<cl_event> forwardCLBatch(const vec &in, vec &out, size_t n, double *averageTime) { // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // Reserve the event buffer. // One event for each layer plus two events for IO. std::vector<cl_event> events(n * eventSize); // For OpenCL error. cl_int err; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], i == 0 ? 0 : 1, i == 0 ? NULL : &events[(i - 1) * eventSize], &events[i * eventSize]); handleError(err, "Failed copy input buffer. "); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, 1, &events[i * eventSize + l], &events[i * eventSize + l + 1]); handleError(err, "Failed enqueuing kernel. "); // Wait for this layer. // err = clWaitForEvents(1, &events[i * eventSize + l + 1]); // handleError(err, "Failed waiting for event. "); } // Get the output. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], 1, &events[i * eventSize + layers.size()], &events[i * eventSize + layers.size() + 1]); handleError(err, "Failed enqueuing reading buffer. "); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Average time: " << *averageTime << "s" << std::endl; return events; } // Forward with pipelined command queue. std::vector<cl_event> forwardCLPipeline(const vec &in, vec &out, size_t n, double *averageTime) { // Check if the command queue supports out of order queue. if (isQueueInOrder) { std::cout << "Warning: using an in order command queue for pipeline cnn!" << std::endl; } // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } // Initialize the event pool. EventPool events(layers.size() + 2, n); clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // For OpenCL error. cl_int err; // Temporary holder for returned event. cl_event event; uint32_t len; cl_event *eventList; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. eventList = events.getDependentEventList(0, i, &len); err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], len, eventList, &event); handleError(err, "Failed copy input buffer. "); events.pushEvent(0, i, event); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { eventList = events.getDependentEventList(l + 1, i, &len); err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, len, eventList, &event); handleError(err, "Failed enqueuing kernel. "); events.pushEvent(l + 1, i, event); } // Get the output. eventList = events.getDependentEventList(layers.size() + 1, i, &len); err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], len, eventList, &event); handleError(err, "Failed enqueuing reading buffer. "); events.pushEvent(layers.size() + 1, i, event); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Pipelined average time: " << *averageTime << "s" << std::endl; return events.sort(); } // For OpenCL. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; //cl_program program; cl_mem clIn; size_t queueBarrier; bool isQueueInOrder; std::vector<Layer *> layers; size_t getInSize() const { return layers[0]->iWidth * layers[0]->iHeight * layers[0]->iDepth; } size_t getOutSize() const { size_t last = layers.size() - 1; return layers[last]->out.size(); } const vec &getOut() const { return layers[layers.size() - 1]->out; } private: void initOpenCL(/*const std::string &kernelFileName*//*, bool isBinary, */bool isQueueInOrder, size_t inSize) { cl_int err; // Choose the first platform. err = clGetPlatformIDs(1, &platform, NULL); // Choose the first device. err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL); printDeviceInfo(std::cout, device); cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; context = clCreateContext( properties, 1, &device, NULL, NULL, &err); handleError(err, "Failed creating context. "); clRetainContext(context); queue = clCreateCommandQueue( context, device, CL_QUEUE_PROFILING_ENABLE | (isQueueInOrder ? 0 : CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE), &err); handleError(err, "Failed creating command queue. "); clRetainCommandQueue(queue); /*if (isBinary) { program = buildProgramFromBinary(kernelFileName.c_str(), context, device); } else { program = buildProgramFromSource(kernelFileName.c_str(), context, device); } err = clRetainProgram(program); handleError(err, "Failed retaining program. ");*/ clIn = clCreateBuffer( context, CL_MEM_READ_ONLY, inSize * sizeof(cl_float), NULL, &err); handleError(err, "Failed creating clIn"); err = clRetainMemObject(clIn); handleError(err, "Failed retaining clIn"); } // Create a layer. Layer *createLayer(rapidxml::xml_node<> *root, bool isBinary, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.oWidth = getSizeT(root, "oWidth"); params.oHeight = getSizeT(root, "oHeight"); params.oDepth = getSizeT(root, "oDepth"); params.oWidthTile = getSizeT(root, "oWidthTile"); params.oHeightTile = getSizeT(root, "oHeightTile"); params.oDepthTile = getSizeT(root, "oDepthTile"); params.iDepthTile = getSizeT(root, "iDepthTile"); params.kernelSize = getSizeT(root, "kernelSize"); // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); // Create the offset vector. cnn::vec offset; getAllItem(root->first_node("offset"), offset); // Create the program. cl_program program; cl_int err; if (isBinary) { std::string xclbinFileName = getString(root, "xclbinName"); program = buildProgramFromBinary(xclbinFileName.c_str(), context, device); } else { std::string kernelFileName = getString(root, "kernelFileName"); program = buildProgramFromSource(kernelFileName.c_str(), context, device); } /*err = clRetainProgram(program); handleError(err, "Failed retaining program. ");*/ std::string type = getString(root, "type"); if (type == "conv") { return new cnn::ConvolutionLayer(params, weight, offset, context, program, clIn ); } else if (type == "pool") { return new cnn::MaxPoolLayer(params, weight, offset, context, program, clIn ); } else if (type == "full") { return new cnn::FullConnectLayer(params, weight, offset, context, program, clIn ); } else if (type == "rbf") { return new cnn::RBFLayer(params, weight, offset, context, program, clIn ); } else { std::cerr << "createLayer: Unsupported layer: " << type << std::endl; exit(-1); } } }; } #endif <commit_msg>fix typo<commit_after>#ifndef CNN_HEADER #define CNN_HEADER #include "util.hpp" #include "convolution.hpp" #include "maxpool.hpp" #include "fullconnect.hpp" #include "rbf.hpp" #include "eventpool.hpp" #define BUFSIZE (64 * 1024 * 1024) namespace cnn { class CNN { public: CNN(const std::string &xmlFileName, bool isQueueInOrder = true, const std::string &xclbinFile = "NONE") { this->isQueueInOrder = isQueueInOrder; // Parse the xml file. char *buf = new char[BUFSIZE]; fileToChar(xmlFileName, buf, BUFSIZE); rapidxml::xml_document<> doc; doc.parse<0>(buf); rapidxml::xml_node<> *root = doc.first_node(); // Get the kernel file name. std::string kernelFileName(root->first_node("kernelFileName")->value()); // Get the input size. size_t inSize = getSizeT(root, "inSize"); // Get the queue barrier. queueBarrier = getSizeT(root, "queueBarrier"); initOpenCL(isQueueInOrder, inSize); //// Initialize the OpenCL. //if (xclbinFile == "NONE") { // initOpenCL(kernelFileName, isQueueInOrder, inSize); //} //else { // initOpenCL(xclbinFile, isQueueInOrder, inSize); //} // For every layer. bool isFront = true; for (rapidxml::xml_node<> *layer = root->first_node("layer"); layer; layer = layer->next_sibling("layer")) { Flag flag = INNER; if (isFront) { flag |= FRONT; isFront = false; } if (!(layer->next_sibling())) { flag |= BACK; } layers.push_back(createLayer(layer, xclbinFile != "NONE", flag)); } delete[] buf; } ~CNN() { for (int i = 0; i < layers.size(); ++i) { delete layers[i]; } //clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context); } // Forward with CPU. unsigned long long forwardCPU(const vec &in) { unsigned long long totalTime = layers[0]->forwardCPU(in); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCPU(layers[i - 1]->out); } return totalTime; } // Forward with OpenCL. unsigned long long forwardCL(const vec &in) { // Prepare the input cl_mem. cl_int err; err = clEnqueueWriteBuffer(queue, clIn, CL_TRUE, 0, in.size() * sizeof(cl_float), (void *)&in[0], 0, NULL, NULL); handleError(err, "Failed copy input buffer. "); // Enqueue the first kernel. unsigned long long totalTime = layers[0]->forwardCL(queue); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCL(queue); } // Get the result to the last layer's out vec. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_TRUE, 0, getOutSize() * sizeof(cl_float), &(layers[layers.size() - 1]->out[0]), 0, NULL, NULL); return totalTime; } // Forward more than one input with in order command queue. std::vector<cl_event> forwardCLBatch(const vec &in, vec &out, size_t n, double *averageTime) { // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // Reserve the event buffer. // One event for each layer plus two events for IO. std::vector<cl_event> events(n * eventSize); // For OpenCL error. cl_int err; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], i == 0 ? 0 : 1, i == 0 ? NULL : &events[(i - 1) * eventSize], &events[i * eventSize]); handleError(err, "Failed copy input buffer. "); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, 1, &events[i * eventSize + l], &events[i * eventSize + l + 1]); handleError(err, "Failed enqueuing kernel. "); // Wait for this layer. // err = clWaitForEvents(1, &events[i * eventSize + l + 1]); // handleError(err, "Failed waiting for event. "); } // Get the output. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], 1, &events[i * eventSize + layers.size()], &events[i * eventSize + layers.size() + 1]); handleError(err, "Failed enqueuing reading buffer. "); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Average time: " << *averageTime << "s" << std::endl; return events; } // Forward with pipelined command queue. std::vector<cl_event> forwardCLPipeline(const vec &in, vec &out, size_t n, double *averageTime) { // Check if the command queue supports out of order queue. if (isQueueInOrder) { std::cout << "Warning: using an in order command queue for pipeline cnn!" << std::endl; } // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } // Initialize the event pool. EventPool events(layers.size() + 2, n); clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // For OpenCL error. cl_int err; // Temporary holder for returned event. cl_event event; uint32_t len; cl_event *eventList; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. eventList = events.getDependentEventList(0, i, &len); err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], len, eventList, &event); handleError(err, "Failed copy input buffer. "); events.pushEvent(0, i, event); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { eventList = events.getDependentEventList(l + 1, i, &len); err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, len, eventList, &event); handleError(err, "Failed enqueuing kernel. "); events.pushEvent(l + 1, i, event); } // Get the output. eventList = events.getDependentEventList(layers.size() + 1, i, &len); err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], len, eventList, &event); handleError(err, "Failed enqueuing reading buffer. "); events.pushEvent(layers.size() + 1, i, event); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Pipelined average time: " << *averageTime << "s" << std::endl; return events.sort(); } // For OpenCL. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; //cl_program program; cl_mem clIn; size_t queueBarrier; bool isQueueInOrder; std::vector<Layer *> layers; size_t getInSize() const { return layers[0]->iWidth * layers[0]->iHeight * layers[0]->iDepth; } size_t getOutSize() const { size_t last = layers.size() - 1; return layers[last]->out.size(); } const vec &getOut() const { return layers[layers.size() - 1]->out; } private: void initOpenCL(/*const std::string &kernelFileName*//*, bool isBinary, */bool isQueueInOrder, size_t inSize) { cl_int err; // Choose the first platform. err = clGetPlatformIDs(1, &platform, NULL); // Choose the first device. err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL); printDeviceInfo(std::cout, device); cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; context = clCreateContext( properties, 1, &device, NULL, NULL, &err); handleError(err, "Failed creating context. "); clRetainContext(context); queue = clCreateCommandQueue( context, device, CL_QUEUE_PROFILING_ENABLE | (isQueueInOrder ? 0 : CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE), &err); handleError(err, "Failed creating command queue. "); clRetainCommandQueue(queue); /*if (isBinary) { program = buildProgramFromBinary(kernelFileName.c_str(), context, device); } else { program = buildProgramFromSource(kernelFileName.c_str(), context, device); } err = clRetainProgram(program); handleError(err, "Failed retaining program. ");*/ clIn = clCreateBuffer( context, CL_MEM_READ_ONLY, inSize * sizeof(cl_float), NULL, &err); handleError(err, "Failed creating clIn"); err = clRetainMemObject(clIn); handleError(err, "Failed retaining clIn"); } // Create a layer. Layer *createLayer(rapidxml::xml_node<> *root, bool isBinary, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.oWidth = getSizeT(root, "oWidth"); params.oHeight = getSizeT(root, "oHeight"); params.oDepth = getSizeT(root, "oDepth"); params.oWidthTile = getSizeT(root, "oWidthTile"); params.oHeightTile = getSizeT(root, "oHeightTile"); params.oDepthTile = getSizeT(root, "oDepthTile"); params.iDepthTile = getSizeT(root, "iDepthTile"); params.kernelSize = getSizeT(root, "kernelSize"); // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); // Create the offset vector. cnn::vec offset; getAllItem(root->first_node("offset"), offset); // Create the program. cl_program program; cl_int err; if (isBinary) { std::string xclbinFileName = getString(root, "xclbinFileName"); program = buildProgramFromBinary(xclbinFileName.c_str(), context, device); } else { std::string kernelFileName = getString(root, "kernelFileName"); program = buildProgramFromSource(kernelFileName.c_str(), context, device); } /*err = clRetainProgram(program); handleError(err, "Failed retaining program. ");*/ std::string type = getString(root, "type"); if (type == "conv") { return new cnn::ConvolutionLayer(params, weight, offset, context, program, clIn ); } else if (type == "pool") { return new cnn::MaxPoolLayer(params, weight, offset, context, program, clIn ); } else if (type == "full") { return new cnn::FullConnectLayer(params, weight, offset, context, program, clIn ); } else if (type == "rbf") { return new cnn::RBFLayer(params, weight, offset, context, program, clIn ); } else { std::cerr << "createLayer: Unsupported layer: " << type << std::endl; exit(-1); } } }; } #endif <|endoftext|>
<commit_before>#ifndef _sql_string_hpp__ #define _sql_string_hpp__ // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // 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. // // 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 "__configure__.hpp" #include "types.hpp" #include <algorithm> #include <ostream> #include <string> namespace sql { /*! * @brief Replacement for std::string which does not allow to write * directly into it's buffer because it wishes to support optional * copy-on-write semantics. */ template<typename Char> class basic_string { /* nested types. */ public: typedef Char char_type; typedef size_t size_type; typedef char_type * iterator; typedef const char_type * const_iterator; private: // To make this template class somewhat readable. typedef basic_string<Char> self_type; /* data. */ private: size_type myCapacity; char_type * myData; /* construction. */ public: /*! * @brief Creates a copy of the given string. * * @note Although this is a convenient way to convert ASCII strings * to other types of characters, this will not account for multi * byte character sets, such as UTF-8. * * @param value Pointer to the first character in the null * terminated string. */ basic_string ( const char * value = "" ) : myCapacity(0), myData(0) { const char *const termination = endof(value); self_type buffer(static_cast<size_type>(termination-value)); std::copy(value,termination,buffer.begin()); buffer.swap(*this); } /*! * @brief Creates a copy of the given string. */ basic_string ( const char_type * value ) : myCapacity(0), myData(0) { const char_type *const termination = endof(value); self_type buffer(static_cast<size_type>(termination-value)); std::copy(value,termination,buffer.begin()); buffer.swap(*this); } /*! * @brief Allocates the buffer for a string with at least * \c capacity, but with no characters (\c size() returns 0). */ explicit basic_string ( size_type capacity ) : myCapacity(capacity), myData(new char_type[myCapacity+1]) { myData[myCapacity] = myData[0] = '\0'; } basic_string ( const self_type& other ) : myCapacity(0), myData(0) { self_type buffer(other.capacity()); std::copy(other.begin(),other.end(),buffer.begin()); buffer.swap(*this); } template<typename Traits> basic_string ( const std::basic_string<Char, Traits>& other ) : myCapacity(0), myData(0) { self_type buffer(other.capacity()); std::copy(other.begin(),other.end(),buffer.begin()); buffer.swap(*this); } basic_string ( const std::string& other ) : myCapacity(0), myData(0) { self_type buffer(other.capacity()); std::copy(other.begin(),other.end(),buffer.begin()); buffer.swap(*this); } /*! * @brief Frees up all acquired resources (memory). */ ~basic_string () { delete [] myData; } /* class methods. */ private: // Returns the first null character. template<typename T> static T * endof ( T * current ) { if ( current != 0 ) { while ( *current ) { ++current; } } return (current); } /* methods. */ public: /*! * @brief Truncates the string to 0 characters. Does not deallocate * the buffer. */ void clear () throw() { if ( myData != 0 ) { myData[0] = '\0'; } } /*! * @brief Returns the length of the string, based on where it finds * the first null character. * * Although this is not constant time, it accounts for greater * flexibility (in particular, allowing you to write directly to the * buffer). */ size_type length () const throw() { return (end()-begin()); } /*! * @brief Returns the total size of the buffer. */ size_type capacity () const throw() { return (myCapacity); } /*! * @brief Returns a pointer to the first character in the buffer. * * As this is a write-buffer, this returns a null pointer if no * buffer was allocated (like if default constructed). * * @note Do NOT deallocate this value, or else! */ char_type * data () throw() { return (myData); } /*! * @brief Returns a pointer to the first character in the buffer. * * This is a read only buffer, so if you request this operation on * a const string, it will return a buffer with only a null * character. */ const char_type * data () const throw() { static const char_type empty[] = { static_cast<char_type>(0) }; return ((myData != 0)? myData : empty); } /*! * @brief Returns an iterator to the first element. */ iterator begin () throw() { return (data()); } /*! * @brief Returns an iterator to the first element. */ const_iterator begin () const throw() { return (data()); } /*! * @brief Returns an iterator to one-past-the-last element. */ iterator end () throw() { return (endof(myData)); } /*! * @brief Returns an iterator to one-past-the-last element. */ const_iterator end () const throw() { return (endof(myData)); } /*! * @brief Ensures that the capacity is at least \c minimum. */ void reserve ( size_type minimum ) { if ((minimum+1) > myCapacity ) { self_type other(minimum); std::copy(begin(),end(),other.begin()); other.swap(*this); } } /*! * @brief Constant time exchange of buffers. */ void swap ( self_type& other ) throw() { std::swap(myData,other.myData); std::swap(myCapacity,other.myCapacity); } /* operators. */ public: self_type& operator= ( const self_type& other ) { self_type copy(other); copy.swap(*this); return (*this); } self_type& operator= ( const char_type * value ) { const char_type * last = endof(value); reserve(last-value); std::copy(value,last+1,end()); return (*this); } self_type& operator= ( const char * value ) { const char * last = endof(value); reserve(last-value); std::copy(value,last+1,end()); return (*this); } self_type& operator+= ( const self_type& suffix ) { reserve(length()+suffix.length()); std::copy(suffix.begin(),suffix.end()+1,end()); return (*this); } self_type& operator+= ( const char_type * suffix ) { const_iterator last = endof(suffix); reserve(length()+(last-suffix)); std::copy(suffix,last+1,end()); return (*this); } }; typedef basic_string<character> string; typedef basic_string<wcharacter> wstring; template<typename Char> inline void swap ( basic_string<Char>& lhs, basic_string<Char>& rhs ) { lhs.swap(rhs); } inline std::ostream& operator<< ( std::ostream& out, const string& value ) { return (out << reinterpret_cast<const char*>(value.data())); } inline std::wostream& operator<< ( std::wostream& out, const wstring& value ) { return (out << reinterpret_cast<const wchar_t*>(value.data())); } } #endif /* _sql_string_hpp__ */ <commit_msg>Fixes std::string-based constructor.<commit_after>#ifndef _sql_string_hpp__ #define _sql_string_hpp__ // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // 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. // // 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 "__configure__.hpp" #include "types.hpp" #include <algorithm> #include <ostream> #include <string> namespace sql { template<typename C> struct char_traits; template<> struct char_traits<character> { typedef char std_char; }; template<> struct char_traits<wcharacter> { typedef wchar_t std_char; }; /*! * @brief Replacement for std::string which does not allow to write * directly into it's buffer because it wishes to support optional * copy-on-write semantics. */ template<typename Char> class basic_string { /* nested types. */ public: typedef Char char_type; typedef size_t size_type; typedef char_type * iterator; typedef const char_type * const_iterator; typedef typename char_traits<char_type>::std_char std_char_type; typedef std::basic_string<std_char_type> std_string_type; private: // To make this template class somewhat readable. typedef basic_string<Char> self_type; /* data. */ private: size_type myCapacity; char_type * myData; /* construction. */ public: /*! * @brief Creates a copy of the given string. * * @note Although this is a convenient way to convert ASCII strings * to other types of characters, this will not account for multi * byte character sets, such as UTF-8. * * @param value Pointer to the first character in the null * terminated string. */ basic_string ( const char * value = "" ) : myCapacity(0), myData(0) { const char *const termination = endof(value); self_type buffer(static_cast<size_type>(termination-value)); std::copy(value,termination,buffer.begin()); buffer.swap(*this); } /*! * @brief Creates a copy of the given string. */ basic_string ( const char_type * value ) : myCapacity(0), myData(0) { const char_type *const termination = endof(value); self_type buffer(static_cast<size_type>(termination-value)); std::copy(value,termination,buffer.begin()); buffer.swap(*this); } /*! * @brief Allocates the buffer for a string with at least * \c capacity, but with no characters (\c size() returns 0). */ explicit basic_string ( size_type capacity ) : myCapacity(capacity), myData(new char_type[myCapacity+1]) { myData[myCapacity] = myData[0] = '\0'; } basic_string ( const self_type& other ) : myCapacity(0), myData(0) { self_type buffer(other.capacity()); std::copy(other.begin(),other.end(),buffer.begin()); buffer.swap(*this); } template<typename Traits> basic_string ( const std::basic_string<Char, Traits>& other ) : myCapacity(0), myData(0) { self_type buffer(other.capacity()); std::copy(other.begin(),other.end(),buffer.begin()); buffer.swap(*this); } basic_string ( const std_string_type& other ) : myCapacity(0), myData(0) { self_type buffer(other.capacity()); std::copy(other.begin(),other.end(),buffer.begin()); buffer.swap(*this); } /*! * @brief Frees up all acquired resources (memory). */ ~basic_string () { delete [] myData; } /* class methods. */ private: // Returns the first null character. template<typename T> static T * endof ( T * current ) { if ( current != 0 ) { while ( *current ) { ++current; } } return (current); } /* methods. */ public: /*! * @brief Truncates the string to 0 characters. Does not deallocate * the buffer. */ void clear () throw() { if ( myData != 0 ) { myData[0] = '\0'; } } /*! * @brief Returns the length of the string, based on where it finds * the first null character. * * Although this is not constant time, it accounts for greater * flexibility (in particular, allowing you to write directly to the * buffer). */ size_type length () const throw() { return (end()-begin()); } /*! * @brief Returns the total size of the buffer. */ size_type capacity () const throw() { return (myCapacity); } /*! * @brief Returns a pointer to the first character in the buffer. * * As this is a write-buffer, this returns a null pointer if no * buffer was allocated (like if default constructed). * * @note Do NOT deallocate this value, or else! */ char_type * data () throw() { return (myData); } /*! * @brief Returns a pointer to the first character in the buffer. * * This is a read only buffer, so if you request this operation on * a const string, it will return a buffer with only a null * character. */ const char_type * data () const throw() { static const char_type empty[] = { static_cast<char_type>(0) }; return ((myData != 0)? myData : empty); } /*! * @brief Returns an iterator to the first element. */ iterator begin () throw() { return (data()); } /*! * @brief Returns an iterator to the first element. */ const_iterator begin () const throw() { return (data()); } /*! * @brief Returns an iterator to one-past-the-last element. */ iterator end () throw() { return (endof(myData)); } /*! * @brief Returns an iterator to one-past-the-last element. */ const_iterator end () const throw() { return (endof(myData)); } /*! * @brief Ensures that the capacity is at least \c minimum. */ void reserve ( size_type minimum ) { if ((minimum+1) > myCapacity ) { self_type other(minimum); std::copy(begin(),end(),other.begin()); other.swap(*this); } } /*! * @brief Constant time exchange of buffers. */ void swap ( self_type& other ) throw() { std::swap(myData,other.myData); std::swap(myCapacity,other.myCapacity); } /* operators. */ public: self_type& operator= ( const self_type& other ) { self_type copy(other); copy.swap(*this); return (*this); } self_type& operator= ( const char_type * value ) { const char_type * last = endof(value); reserve(last-value); std::copy(value,last+1,end()); return (*this); } self_type& operator= ( const char * value ) { const char * last = endof(value); reserve(last-value); std::copy(value,last+1,end()); return (*this); } self_type& operator+= ( const self_type& suffix ) { reserve(length()+suffix.length()); std::copy(suffix.begin(),suffix.end()+1,end()); return (*this); } self_type& operator+= ( const char_type * suffix ) { const_iterator last = endof(suffix); reserve(length()+(last-suffix)); std::copy(suffix,last+1,end()); return (*this); } }; typedef basic_string<character> string; typedef basic_string<wcharacter> wstring; template<typename Char> inline void swap ( basic_string<Char>& lhs, basic_string<Char>& rhs ) { lhs.swap(rhs); } inline std::ostream& operator<< ( std::ostream& out, const string& value ) { return (out << reinterpret_cast<const char*>(value.data())); } inline std::wostream& operator<< ( std::wostream& out, const wstring& value ) { return (out << reinterpret_cast<const wchar_t*>(value.data())); } } #endif /* _sql_string_hpp__ */ <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <cstddef> #include <cstdint> #include <string> #include "caf/fwd.hpp" namespace caf { /// PEC stands for "Parser Error Code". This enum contains error codes used by /// various CAF parsers. enum class pec : uint8_t { /// Not-an-error. success = 0, /// Parser succeeded but found trailing character(s). trailing_character = 1, /// Parser stopped after reaching the end while still expecting input. unexpected_eof, /// Parser stopped after reading an unexpected character. unexpected_character, /// Parsed integer exceeds the number of available bits of a `timespan`. timespan_overflow, /// Tried constructing a `timespan` with from a floating point number. fractional_timespan = 5, /// Too many characters for an atom. too_many_characters, /// Unrecognized character after escaping `\`. illegal_escape_sequence, /// Misplaced newline, e.g., inside a string. unexpected_newline, /// Parsed positive integer exceeds the number of available bits. integer_overflow, /// Parsed negative integer exceeds the number of available bits. integer_underflow = 10, /// Exponent of parsed double is less than the minimum supported exponent. exponent_underflow, /// Exponent of parsed double is greater than the maximum supported exponent. exponent_overflow, /// Parsed type does not match the expected type. type_mismatch, /// Stopped at an unrecognized option name. not_an_option, /// Stopped at an unparseable argument. illegal_argument = 15, /// Stopped because an argument was omitted. missing_argument, /// Stopped because the key of a category was taken. illegal_category, /// Stopped at an unexpected field name while reading a user-defined type. invalid_field_name, /// Stopped at a repeated field name while reading a user-defined type. repeated_field_name, /// Stopped while reading a user-defined type with one or more missing /// mandatory fields. missing_field, }; /// Returns an error object from given error code. error make_error(pec code); /// Returns an error object from given error code with additional context /// information for where the parser stopped in the input. error make_error(pec code, int32_t line, int32_t column); /// Returns an error object from given error code with additional context /// information for where the parser stopped in the argument. error make_error(pec code, string_view argument); } // namespace caf <commit_msg>Add missing function declaration, close #940<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <cstddef> #include <cstdint> #include <string> #include "caf/fwd.hpp" namespace caf { /// PEC stands for "Parser Error Code". This enum contains error codes used by /// various CAF parsers. enum class pec : uint8_t { /// Not-an-error. success = 0, /// Parser succeeded but found trailing character(s). trailing_character = 1, /// Parser stopped after reaching the end while still expecting input. unexpected_eof, /// Parser stopped after reading an unexpected character. unexpected_character, /// Parsed integer exceeds the number of available bits of a `timespan`. timespan_overflow, /// Tried constructing a `timespan` with from a floating point number. fractional_timespan = 5, /// Too many characters for an atom. too_many_characters, /// Unrecognized character after escaping `\`. illegal_escape_sequence, /// Misplaced newline, e.g., inside a string. unexpected_newline, /// Parsed positive integer exceeds the number of available bits. integer_overflow, /// Parsed negative integer exceeds the number of available bits. integer_underflow = 10, /// Exponent of parsed double is less than the minimum supported exponent. exponent_underflow, /// Exponent of parsed double is greater than the maximum supported exponent. exponent_overflow, /// Parsed type does not match the expected type. type_mismatch, /// Stopped at an unrecognized option name. not_an_option, /// Stopped at an unparseable argument. illegal_argument = 15, /// Stopped because an argument was omitted. missing_argument, /// Stopped because the key of a category was taken. illegal_category, /// Stopped at an unexpected field name while reading a user-defined type. invalid_field_name, /// Stopped at a repeated field name while reading a user-defined type. repeated_field_name, /// Stopped while reading a user-defined type with one or more missing /// mandatory fields. missing_field, }; /// @relates pec std::string to_string(pec); /// Returns an error object from given error code. error make_error(pec code); /// Returns an error object from given error code with additional context /// information for where the parser stopped in the input. error make_error(pec code, int32_t line, int32_t column); /// Returns an error object from given error code with additional context /// information for where the parser stopped in the argument. error make_error(pec code, string_view argument); } // namespace caf <|endoftext|>
<commit_before>/* This file is part of libkdepim. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <qstring.h> #include <kstandarddirs.h> #include <kglobal.h> #include <kconfig.h> #include <klocale.h> #include <kdebug.h> #include "kpimprefs.h" KPimPrefs::KPimPrefs( const QString &name ) : KConfigSkeleton( name ) { } KPimPrefs::~KPimPrefs() { } void KPimPrefs::usrSetDefaults() { setCategoryDefaults(); } void KPimPrefs::usrReadConfig() { kdDebug(5300) << "KPimPrefs::usrReadConfig()" << endl; config()->setGroup("General"); mCustomCategories = config()->readListEntry( "Custom Categories" ); if ( mCustomCategories.isEmpty() ) setCategoryDefaults(); mCustomCategories.sort(); } const QString KPimPrefs::timezone() { QString zone = ""; // Read TimeZoneId from korganizerrc. KConfig korgcfg( locate( "config", "korganizerrc" ) ); korgcfg.setGroup( "Time & Date" ); QString tz( korgcfg.readEntry( "TimeZoneId" ) ); if ( !tz.isEmpty() ) { zone = tz; kdDebug(5300) << "timezone from korganizerrc is " << zone << endl; } // If timezone not found in KOrg, use the system's default timezone. if ( zone.isEmpty() ) { char zonefilebuf[ PATH_MAX ]; int len = readlink( "/etc/localtime", zonefilebuf, PATH_MAX ); if ( len > 0 && len < PATH_MAX ) { zone = QString::fromLocal8Bit( zonefilebuf, len ); zone = zone.mid( zone.find( "zoneinfo/" ) + 9 ); kdDebug(5300) << "system timezone from /etc/localtime is " << zone << endl; } else { tzset(); zone = tzname[ 0 ]; kdDebug(5300) << "system timezone from tzset() is " << zone << endl; } } return( zone ); } QDateTime KPimPrefs::utcToLocalTime( const QDateTime &dt, const QString &timeZoneId ) { // kdDebug() << "--- UTC: " << dt.toString() << endl; QCString origTz = getenv("TZ"); setenv( "TZ", "UTC", 1 ); time_t utcTime = dt.toTime_t(); setenv( "TZ", timeZoneId.local8Bit(), 1 ); struct tm *local = localtime( &utcTime ); if ( origTz.isNull() ) { unsetenv( "TZ" ); } else { setenv( "TZ", origTz, 1 ); } tzset(); QDateTime result( QDate( local->tm_year + 1900, local->tm_mon + 1, local->tm_mday ), QTime( local->tm_hour, local->tm_min, local->tm_sec ) ); // kdDebug() << "--- LOCAL: " << result.toString() << endl; return result; } QDateTime KPimPrefs::localTimeToUtc( const QDateTime &dt, const QString &timeZoneId ) { // kdDebug() << "--- LOCAL: " << dt.toString() << endl; QCString origTz = getenv("TZ"); setenv( "TZ", timeZoneId.local8Bit(), 1 ); time_t localTime = dt.toTime_t(); setenv( "TZ", "UTC", 1 ); struct tm *utc = gmtime( &localTime ); if ( origTz.isNull() ) { unsetenv( "TZ" ); } else { setenv( "TZ", origTz, 1 ); } tzset(); QDateTime result( QDate( utc->tm_year + 1900, utc->tm_mon + 1, utc->tm_mday ), QTime( utc->tm_hour, utc->tm_min, utc->tm_sec ) ); // kdDebug() << "--- UTC: " << result.toString() << endl; return result; } void KPimPrefs::usrWriteConfig() { config()->setGroup( "General" ); config()->writeEntry( "Custom Categories", mCustomCategories ); } <commit_msg>Handle dates before 1970 in timezone conversion<commit_after>/* This file is part of libkdepim. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <qstring.h> #include <kstandarddirs.h> #include <kglobal.h> #include <kconfig.h> #include <klocale.h> #include <kdebug.h> #include "kpimprefs.h" KPimPrefs::KPimPrefs( const QString &name ) : KConfigSkeleton( name ) { } KPimPrefs::~KPimPrefs() { } void KPimPrefs::usrSetDefaults() { setCategoryDefaults(); } void KPimPrefs::usrReadConfig() { kdDebug(5300) << "KPimPrefs::usrReadConfig()" << endl; config()->setGroup("General"); mCustomCategories = config()->readListEntry( "Custom Categories" ); if ( mCustomCategories.isEmpty() ) setCategoryDefaults(); mCustomCategories.sort(); } const QString KPimPrefs::timezone() { QString zone = ""; // Read TimeZoneId from korganizerrc. KConfig korgcfg( locate( "config", "korganizerrc" ) ); korgcfg.setGroup( "Time & Date" ); QString tz( korgcfg.readEntry( "TimeZoneId" ) ); if ( !tz.isEmpty() ) { zone = tz; kdDebug(5300) << "timezone from korganizerrc is " << zone << endl; } // If timezone not found in KOrg, use the system's default timezone. if ( zone.isEmpty() ) { char zonefilebuf[ PATH_MAX ]; int len = readlink( "/etc/localtime", zonefilebuf, PATH_MAX ); if ( len > 0 && len < PATH_MAX ) { zone = QString::fromLocal8Bit( zonefilebuf, len ); zone = zone.mid( zone.find( "zoneinfo/" ) + 9 ); kdDebug(5300) << "system timezone from /etc/localtime is " << zone << endl; } else { tzset(); zone = tzname[ 0 ]; kdDebug(5300) << "system timezone from tzset() is " << zone << endl; } } return( zone ); } QDateTime KPimPrefs::utcToLocalTime( const QDateTime &_dt, const QString &timeZoneId ) { QDateTime dt(_dt); // kdDebug() << "--- UTC: " << dt.toString() << endl; int yearCorrection = 0; // The timezone conversion only works for dates > 1970 // For dates < 1970 we adjust the date to be in 1970, // do the correction there and then re-adjust back. // Actually, we use 1971 to prevent errors around // January 1, 1970 int year = dt.date().year(); if (year < 1971) { yearCorrection = 1971 - year; dt = dt.addYears(yearCorrection); // kdDebug() << "--- Adjusted UTC: " << dt.toString() << endl; } QCString origTz = getenv("TZ"); setenv( "TZ", "UTC", 1 ); time_t utcTime = dt.toTime_t(); setenv( "TZ", timeZoneId.local8Bit(), 1 ); struct tm *local = localtime( &utcTime ); if ( origTz.isNull() ) { unsetenv( "TZ" ); } else { setenv( "TZ", origTz, 1 ); } tzset(); QDateTime result( QDate( local->tm_year + 1900 - yearCorrection, local->tm_mon + 1, local->tm_mday ), QTime( local->tm_hour, local->tm_min, local->tm_sec ) ); // kdDebug() << "--- LOCAL: " << result.toString() << endl; return result; } QDateTime KPimPrefs::localTimeToUtc( const QDateTime &_dt, const QString &timeZoneId ) { QDateTime dt(_dt); // kdDebug() << "--- LOCAL: " << dt.toString() << endl; int yearCorrection = 0; // The timezone conversion only works for dates > 1970 // For dates < 1970 we adjust the date to be in 1970, // do the correction there and then re-adjust back. // Actually, we use 1971 to prevent errors around // January 1, 1970 int year = dt.date().year(); if (year < 1971) { yearCorrection = 1971 - year; dt = dt.addYears(yearCorrection); // kdDebug() << "--- Adjusted LOCAL: " << dt.toString() << endl; } QCString origTz = getenv("TZ"); setenv( "TZ", timeZoneId.local8Bit(), 1 ); time_t localTime = dt.toTime_t(); setenv( "TZ", "UTC", 1 ); struct tm *utc = gmtime( &localTime ); if ( origTz.isNull() ) { unsetenv( "TZ" ); } else { setenv( "TZ", origTz, 1 ); } tzset(); QDateTime result( QDate( utc->tm_year + 1900 - yearCorrection, utc->tm_mon + 1, utc->tm_mday ), QTime( utc->tm_hour, utc->tm_min, utc->tm_sec ) ); // kdDebug() << "--- UTC: " << result.toString() << endl; return result; } void KPimPrefs::usrWriteConfig() { config()->setGroup( "General" ); config()->writeEntry( "Custom Categories", mCustomCategories ); } <|endoftext|>
<commit_before>#include "student.hpp" using namespace std; void Student::init(string n, int s, int g, string m) { name = n; startingYear = s; graduationYear = g; addMajors(m); } Student::Student() { init("", 2000, 2004, ""); } Student::Student(string n, string s, string e, string m) { int startYear = stringToInt(s), endYear = stringToInt(e); init(n, startYear, endYear, m); } Student::Student(string fn) { string yearS, yearE; string contentsOfFile = getFileContents(fn); vector<string> lines = split(contentsOfFile, '\n'); string previousHeading; for (vector<string>::iterator i = lines.begin(); i != lines.end(); ++i) { string str = *i; if (previousHeading.empty()) previousHeading = "# NAME"; if (str[0] == '#') { std::transform(str.begin(), str.end(), str.begin(), ::toupper); previousHeading = str; continue; } else if (str != "") { if (str.substr(0, 2) == "//") { // it's a comment } else if (previousHeading == "# NAME") name = str; else if (previousHeading == "# MAJORS") addMajor(Major(str)); else if (previousHeading == "# CONCENTRATIONS") addConcentration(Concentration(str)); else if (previousHeading == "# COURSES") addCourse(Course(str)); else if (previousHeading == "# LABS") addCourse(Course(str)); } } } void Student::addMajor(const Major& m) { majors.push_back(m); } void Student::addMajors(string str) { vector<string> record = split(str, ','); for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) addMajor(Major(*i)); } void Student::addConcentration(const Concentration& m) { concentrations.push_back(m); } void Student::addConcentrations(string str) { vector<string> record = split(str, ','); for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) addConcentration(Concentration(*i)); } void Student::addCourse(const Course& c) { courses.push_back(c); } void Student::addCourses(string str) { vector<string> record = split(str, ','); for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) addCourse(Course(*i)); } bool Student::hasTakenCourse(string str) { bool userHasTaken = false; const Course checkAgainst = getCourse(str); for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i) if (*i == checkAgainst) userHasTaken = true; return userHasTaken; } ostream& Student::getData(ostream &os) { os << name << ", "; if (majors.size()) { os << "you are majoring in "; for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){ if (majors.size() == 1) { os << *i << " "; } else if (majors.size() == 2) { os << *i; if (i != majors.end()-1) os << " and "; else os << " "; } else { if (i != majors.end()-1) os << *i << ", "; else os << "and " << *i << ", "; } } } if (concentrations.size()) { os << "with concentrations in "; for (vector<Concentration>::iterator i = concentrations.begin(); i != concentrations.end(); ++i) { if (concentrations.size() == 1) { os << *i << " "; } else if (concentrations.size() == 2) { os << *i; if (i != concentrations.end()-1) os << " and "; else os << " "; } else { if (i != concentrations.end()-1) os << *i << ", "; else os << "and " << *i << ", "; } } } if (!majors.size()) os << "you are taking: " << endl; else os << "while taking:" << endl; for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i) { os << *i << endl; } // TODO: don't cout an extra line at the end of the output. for (vector<Major>::iterator m = majors.begin(); m != majors.end(); ++m) { for (vector<MajorRequirement>::iterator req = m->requirements.begin(); req != m->requirements.end(); ++req) cout << *req << endl; for (vector<SpecialRequirement>::iterator set = m->specialRequirements.begin(); set != m->specialRequirements.end(); ++set) for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) cout << *req << endl; } for (vector<Concentration>::iterator conc = concentrations.begin(); conc != concentrations.end(); ++conc) { for (vector<MajorRequirement>::iterator req = conc->requirements.begin(); req != conc->requirements.end(); ++req) cout << *req << endl; for (vector<SpecialRequirement>::iterator set = conc->specialRequirements.begin(); set != conc->specialRequirements.end(); ++set) for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) cout << *req << endl; } return os; } void Student::updateStanding() { for (vector<Major>::iterator m = majors.begin(); m != majors.end(); ++m) { for (vector<Course>::iterator c = courses.begin(); c != courses.end(); ++c) { for (vector<MajorRequirement>::iterator req = m->requirements.begin(); req != m->requirements.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } for (vector<SpecialRequirement>::iterator set = m->specialRequirements.begin(); set != m->specialRequirements.end(); ++set) { for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } } } } for (vector<Concentration>::iterator conc = concentrations.begin(); conc != concentrations.end(); ++conc) { for (vector<Course>::iterator c = courses.begin(); c != courses.end(); ++c) { for (vector<MajorRequirement>::iterator req = conc->requirements.begin(); req != conc->requirements.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } for (vector<SpecialRequirement>::iterator set = conc->specialRequirements.begin(); set != conc->specialRequirements.end(); ++set) { for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } } } } } void Student::display() { cout << *this << endl; } ostream& operator<<(ostream& os, Student& item) { return item.getData(os); } <commit_msg>Add an extra line between courses and requirements<commit_after>#include "student.hpp" using namespace std; void Student::init(string n, int s, int g, string m) { name = n; startingYear = s; graduationYear = g; addMajors(m); } Student::Student() { init("", 2000, 2004, ""); } Student::Student(string n, string s, string e, string m) { int startYear = stringToInt(s), endYear = stringToInt(e); init(n, startYear, endYear, m); } Student::Student(string fn) { string yearS, yearE; string contentsOfFile = getFileContents(fn); vector<string> lines = split(contentsOfFile, '\n'); string previousHeading; for (vector<string>::iterator i = lines.begin(); i != lines.end(); ++i) { string str = *i; if (previousHeading.empty()) previousHeading = "# NAME"; if (str[0] == '#') { std::transform(str.begin(), str.end(), str.begin(), ::toupper); previousHeading = str; continue; } else if (str != "") { if (str.substr(0, 2) == "//") { // it's a comment } else if (previousHeading == "# NAME") name = str; else if (previousHeading == "# MAJORS") addMajor(Major(str)); else if (previousHeading == "# CONCENTRATIONS") addConcentration(Concentration(str)); else if (previousHeading == "# COURSES") addCourse(Course(str)); else if (previousHeading == "# LABS") addCourse(Course(str)); } } } void Student::addMajor(const Major& m) { majors.push_back(m); } void Student::addMajors(string str) { vector<string> record = split(str, ','); for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) addMajor(Major(*i)); } void Student::addConcentration(const Concentration& m) { concentrations.push_back(m); } void Student::addConcentrations(string str) { vector<string> record = split(str, ','); for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) addConcentration(Concentration(*i)); } void Student::addCourse(const Course& c) { courses.push_back(c); } void Student::addCourses(string str) { vector<string> record = split(str, ','); for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) addCourse(Course(*i)); } bool Student::hasTakenCourse(string str) { bool userHasTaken = false; const Course checkAgainst = getCourse(str); for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i) if (*i == checkAgainst) userHasTaken = true; return userHasTaken; } ostream& Student::getData(ostream &os) { os << name << ", "; if (majors.size()) { os << "you are majoring in "; for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){ if (majors.size() == 1) { os << *i << " "; } else if (majors.size() == 2) { os << *i; if (i != majors.end()-1) os << " and "; else os << " "; } else { if (i != majors.end()-1) os << *i << ", "; else os << "and " << *i << ", "; } } } if (concentrations.size()) { os << "with concentrations in "; for (vector<Concentration>::iterator i = concentrations.begin(); i != concentrations.end(); ++i) { if (concentrations.size() == 1) { os << *i << " "; } else if (concentrations.size() == 2) { os << *i; if (i != concentrations.end()-1) os << " and "; else os << " "; } else { if (i != concentrations.end()-1) os << *i << ", "; else os << "and " << *i << ", "; } } } if (!majors.size()) os << "you are taking: " << endl; else os << "while taking:" << endl; for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i) { os << *i << endl; } os << endl; // TODO: don't cout an extra line at the end of the output. for (vector<Major>::iterator m = majors.begin(); m != majors.end(); ++m) { for (vector<MajorRequirement>::iterator req = m->requirements.begin(); req != m->requirements.end(); ++req) cout << *req << endl; for (vector<SpecialRequirement>::iterator set = m->specialRequirements.begin(); set != m->specialRequirements.end(); ++set) for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) cout << *req << endl; } for (vector<Concentration>::iterator conc = concentrations.begin(); conc != concentrations.end(); ++conc) { for (vector<MajorRequirement>::iterator req = conc->requirements.begin(); req != conc->requirements.end(); ++req) cout << *req << endl; for (vector<SpecialRequirement>::iterator set = conc->specialRequirements.begin(); set != conc->specialRequirements.end(); ++set) for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) cout << *req << endl; } return os; } void Student::updateStanding() { for (vector<Major>::iterator m = majors.begin(); m != majors.end(); ++m) { for (vector<Course>::iterator c = courses.begin(); c != courses.end(); ++c) { for (vector<MajorRequirement>::iterator req = m->requirements.begin(); req != m->requirements.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } for (vector<SpecialRequirement>::iterator set = m->specialRequirements.begin(); set != m->specialRequirements.end(); ++set) { for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } } } } for (vector<Concentration>::iterator conc = concentrations.begin(); conc != concentrations.end(); ++conc) { for (vector<Course>::iterator c = courses.begin(); c != courses.end(); ++c) { for (vector<MajorRequirement>::iterator req = conc->requirements.begin(); req != conc->requirements.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } for (vector<SpecialRequirement>::iterator set = conc->specialRequirements.begin(); set != conc->specialRequirements.end(); ++set) { for (vector<MajorRequirement>::iterator req = set->validSets.begin(); req != set->validSets.end(); ++req) { if (req->checkCourseValidity(c->getID())) { req->incrementHas(); } } } } } } void Student::display() { cout << *this << endl; } ostream& operator<<(ostream& os, Student& item) { return item.getData(os); } <|endoftext|>
<commit_before>#include "../src/kseq.h" #include "../src/fastseq.h" #include "../src/gason.h" #include "../src/jsonutil.h" #include "../src/knhx.h" #include "../src/logger.h" #include "../src/logsumexp.h" #include "../src/vguard.h" #include "../src/optparser.h" #include "../src/recon.h" // GNU --version #define HISTORIAN_PROGNAME "historian" #define HISTORIAN_VERSION "0.1" struct ProgUsage : OptParser { ProgUsage (int argc, char** argv); }; ProgUsage::ProgUsage (int argc, char** argv) : OptParser (argc, argv, HISTORIAN_PROGNAME, "{recon[struct],count,fit,help,version} [options]") { text = briefText + "\n" + "EXAMPLES\n" + "\n" + "Reconstruction:\n" + " " + prog + " recon seqs.fa [-tree tree.nh] -output fasta >reconstruction.fa\n" + " " + prog + " recon -guide guide.fa [-tree tree.nh] >reconstruction.stk\n" + " " + prog + " recon guide.stk >reconstruction.stk\n" + " " + prog + " recon data.nex -output nexus >reconstruction.nex\n" + "\n" + "Event counting:\n" + " " + prog + " count seqs.fa [-tree tree.nh] [-model model.json] >counts.json\n" + " " + prog + " count -guide guide.fa [-tree tree.nh] >counts.json\n" + " " + prog + " count -recon reconstruction.fa -tree tree.nh >counts.json\n" + "\n" + "Model fitting:\n" + " " + prog + " fit seqs.fa >newmodel.json\n" + " " + prog + " fit -counts counts.json >newmodel.json\n" + "\n" + "Commands can be abbreviated to single letters, like so:\n" + " " + prog + " r seqs.fa >reconstruction.stk\n" + " " + prog + " c seqs.fa >counts.json\n" + " " + prog + " f -counts counts.json >model.json\n" + "(etc.)\n" + "\n" + "OPTIONS\n" + "\n" + "Reconstruction file I/O options:\n" + " -auto <file> Auto-detect file format and guess its purpose\n" + " -model <file> Specify substitution & indel model (JSON)\n" + " -seqs <file> Specify unaligned sequences (FASTA)\n" + " -guide <file> Specify guide alignment (gapped FASTA)\n" + " -tree <file> Specify phylogeny (New Hampshire)\n" + " -nexus <file>, -stockholm <file>\n" + " Specify phylogeny & guide alignment together\n" + "\n" + " -saveguide <f> Save guide alignment to file\n" + " (guide tree too, if output format allows)\n" + " -output (nexus|fasta|stockholm)\n" + " Specify output format (default is Stockholm)\n" + "\n" + "Reconstruction algorithm options:\n" + "\n" + "The reconstruction algorithm iterates through the guide tree in postorder,\n" + "aligning each sibling pair and reconstructing a profile of their parent.\n" + "The dynamic programming is constrained to a band around a guide alignment,\n" + "and the reconstructed parent profile is a weighted finite-state transducer\n" + "sampled from the posterior distribution implied by the children. The band\n" + "size, posterior probability threshold for inclusion in the parent profile,\n" + "and number of states in the parent profile can all be tweaked to trade off\n" + "sensitivity vs performance.\n" + "\n" + " -band <n> Size of band around guide alignment (default " + to_string(DefaultMaxDistanceFromGuide) + ")\n" + " -noband Unlimit band, ignore guide alignment\n" + " -minpost <p> Posterior prob. threshold for profile states (default " + TOSTRING(DefaultProfilePostProb) + ")\n" // Uncomment to show help for obsolescent random-sampling profile option: // + " -samples <n> Sample profile states randomly\n" + " -states <n> Limit max number of states per profile\n" + "\n" + " -ancseq Predict ancestral sequences (default is to leave them as " + Alignment::wildcardChar + "'s)\n" + " -ancprob Report posterior probabilities for ancestral residues\n" + "\n" // Uncomment to show help for obsolescent random-sampling profile option: // + "Note -minpost and -samples select different profile construction strategies.\n" // + " -minpost (the default) deterministically includes all states above a given\n" // + " posterior probability threshold, along with paths required to reach them.\n" // + " -samples randomly samples state paths from the posterior distribution.\n" // + "Both strategies are subject to the state limit imposed by -states.\n" // + "\n" + "Guide alignment & tree estimation options:\n" + "\n" + "The guide aligner builds a maximal spanning tree of pairwise alignments.\n" + "It can be accelerated in two ways: (1) by using a sparse random forest\n" + "instead of a fully connected all-vs-all pairwise comparison; and (2) by\n" + "confining the pairwise DP matrix to cells around a subset of diagonals\n" + "that contain above a threshold number of k-mer matches. To turn on the\n" + "former optimization, use -rndspan; the latter is turned on by default for\n" + "sequences whose full DP matrix would not otherwise fit in memory (the\n" + "memory threshold can be set with -kmatchmb). It can be disabled with\n" + "-kmatchoff, or enabled (for a particular k-mer threshold) with -kmatchn.\n" + "\n" + " -rndspan Use a sparse random spanning graph, not all-vs-all pairs\n" + " -kmatchn <n> Threshold# of kmer matches to seed a diagonal\n" + " (default sets this as low as available memory will allow)\n" + " -kmatch <k> Length of kmers for pre-filtering heuristic (default " + to_string(DEFAULT_KMER_LENGTH) + ")\n" + " -kmatchband <n> Size of DP band around kmer-matching diagonals (default " + to_string(DEFAULT_BAND_SIZE) + ")\n" + " -kmatchmb <M> Set kmer threshold to use M megabytes of memory\n" // + " -kmatchmax Set kmer threshold to use all available memory (default)\n" + " -kmatchoff No kmer threshold, do full DP\n" + "\n" + " -upgma Use UPGMA, not neighbor-joining, to estimate tree\n" + "\n" + "Model-fitting and event-counting options:\n" + "\n" + "By default, the reconstruction algorithm will interpret any supplied alignment\n" + "as a guide alignment, i.e. a hint, even if it contains a full ancestral sequence\n" + "reconstruction. To insist that the alignment be interpreted as a reconstruction,\n" + "precede it with -recon, -nexusrecon or -stockrecon (depending on the format).\n" + "\n" + " -recon <file>, -nexusrecon <file>, -stockrecon <file>\n" + " Use precomputed reconstruction (FASTA/NEXUS/Stockholm)\n" + " -mininc <n> EM convergence threshold as relative log-likelihood increase\n" + " (default is " + TOSTRING(DefaultMinEMImprovement) + ")\n" + " -maxiter <n> Max number of EM iterations (default " + to_string(DefaultMaxEMIterations) + ")\n" + " -nolaplace Do not add Laplace +1 pseudocounts during model-fitting\n" + " -fixsubrates Do not estimate substitution rates or initial composition\n" + " -fixgaprates Do not estimate indel rates or length distributions\n" + "\n" + "General options:\n" + " -verbose, -vv, -vvv, -v4, -v5, etc.\n" // uncomment to document debug logging: // + " -log <function_name>\n" + " Various levels of logging (-nocolor for monochrome)\n" + " -V, --version Print GNU-style version info\n" + " -h, --help Print help message\n" + " -seed <n> Seed random number generator (" + DPMatrix::random_engine_name() + "; default seed " + to_string(DPMatrix::random_engine::default_seed) + ")\n" + "\n" + "REFERENCES\n" + "\n" + "The reconstruction method uses phylogenetic transducers, as described in:\n" + " Westesson, Lunter, Paten & Holmes (2012). Accurate Reconstruction of\n" + " Insertion-Deletion Histories by Statistical Phylogenetics.\n" + " PLoS One, DOI: 10.1371/journal.pone.0034572\n" + " http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0034572\n" + "\n" + "A longer, tutorial-style introduction is available here:\n" + " Westesson, Lunter, Paten & Holmes (2012).\n" + " Phylogenetic Automata, Pruning, and Multiple Alignment.\n" + " http://arxiv.org/abs/1103.4347\n" + "\n" + "Model-fitting uses the following phylogenetic EM algorithm:\n" + " Holmes & Rubin (2002). An Expectation Maximization Algorithm\n" + " for Training Hidden Substitution Models.\n" + " Journal of Molecular Biology, 317(5).\n" + "\n"; } int main (int argc, char** argv) { ProgUsage usage (argc, argv); Reconstructor recon; const string command = usage.getCommand(); deque<string>& argvec (usage.argvec); auto reconstruct = [&]() -> void { recon.reconstructRoot = true; recon.accumulateSubstCounts = false; recon.accumulateIndelCounts = false; usage.implicitSwitches.push_back (string ("-auto")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseReconArgs (argvec) || usage.parseUnknown()) { } recon.loadModel(); recon.loadSeqs(); recon.reconstructAll(); recon.writeRecon (cout); }; if (command == "reconstruct" || command == "recon" || command == "r") { reconstruct(); } else if (command == "count" || command == "c") { recon.reconstructRoot = false; recon.accumulateSubstCounts = true; recon.accumulateIndelCounts = true; usage.implicitSwitches.push_back (string ("-auto")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseFitArgs (argvec) || usage.parseUnknown()) { } recon.loadModel(); recon.loadSeqs(); recon.loadRecon(); recon.loadCounts(); recon.countAll(); recon.writeCounts (cout); } else if (command == "sum" || command == "s") { recon.useLaplacePseudocounts = false; usage.implicitSwitches.push_back (string ("-counts")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseSumArgs (argvec) || usage.parseUnknown()) { } recon.loadCounts(); recon.writeCounts (cout); } else if (command == "fit" || command == "f") { recon.reconstructRoot = false; recon.accumulateSubstCounts = true; recon.accumulateIndelCounts = true; usage.implicitSwitches.push_back (string ("-auto")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseFitArgs (argvec) || usage.parseUnknown()) { } recon.loadModel(); recon.loadSeqs(); recon.loadRecon(); recon.loadCounts(); recon.fit(); recon.writeModel (cout); } else if (!usage.parseUnknownCommand (command, HISTORIAN_VERSION, false)) { // default: reconstruct argvec.push_front (command); reconstruct(); } return EXIT_SUCCESS; } <commit_msg>Fixed count args<commit_after>#include "../src/kseq.h" #include "../src/fastseq.h" #include "../src/gason.h" #include "../src/jsonutil.h" #include "../src/knhx.h" #include "../src/logger.h" #include "../src/logsumexp.h" #include "../src/vguard.h" #include "../src/optparser.h" #include "../src/recon.h" // GNU --version #define HISTORIAN_PROGNAME "historian" #define HISTORIAN_VERSION "0.1" struct ProgUsage : OptParser { ProgUsage (int argc, char** argv); }; ProgUsage::ProgUsage (int argc, char** argv) : OptParser (argc, argv, HISTORIAN_PROGNAME, "{recon[struct],count,fit,help,version} [options]") { text = briefText + "\n" + "EXAMPLES\n" + "\n" + "Reconstruction:\n" + " " + prog + " recon seqs.fa [-tree tree.nh] -output fasta >reconstruction.fa\n" + " " + prog + " recon -guide guide.fa [-tree tree.nh] >reconstruction.stk\n" + " " + prog + " recon guide.stk >reconstruction.stk\n" + " " + prog + " recon data.nex -output nexus >reconstruction.nex\n" + "\n" + "Event counting:\n" + " " + prog + " count seqs.fa [-tree tree.nh] [-model model.json] >counts.json\n" + " " + prog + " count -guide guide.fa [-tree tree.nh] >counts.json\n" + " " + prog + " count -recon reconstruction.fa -tree tree.nh >counts.json\n" + "\n" + "Model fitting:\n" + " " + prog + " fit seqs.fa >newmodel.json\n" + " " + prog + " fit -counts counts.json >newmodel.json\n" + "\n" + "Commands can be abbreviated to single letters, like so:\n" + " " + prog + " r seqs.fa >reconstruction.stk\n" + " " + prog + " c seqs.fa >counts.json\n" + " " + prog + " f -counts counts.json >model.json\n" + "(etc.)\n" + "\n" + "OPTIONS\n" + "\n" + "Reconstruction file I/O options:\n" + " -auto <file> Auto-detect file format and guess its purpose\n" + " -model <file> Specify substitution & indel model (JSON)\n" + " -seqs <file> Specify unaligned sequences (FASTA)\n" + " -guide <file> Specify guide alignment (gapped FASTA)\n" + " -tree <file> Specify phylogeny (New Hampshire)\n" + " -nexus <file>, -stockholm <file>\n" + " Specify phylogeny & guide alignment together\n" + "\n" + " -saveguide <f> Save guide alignment to file\n" + " (guide tree too, if output format allows)\n" + " -output (nexus|fasta|stockholm)\n" + " Specify output format (default is Stockholm)\n" + "\n" + "Reconstruction algorithm options:\n" + "\n" + "The reconstruction algorithm iterates through the guide tree in postorder,\n" + "aligning each sibling pair and reconstructing a profile of their parent.\n" + "The dynamic programming is constrained to a band around a guide alignment,\n" + "and the reconstructed parent profile is a weighted finite-state transducer\n" + "sampled from the posterior distribution implied by the children. The band\n" + "size, posterior probability threshold for inclusion in the parent profile,\n" + "and number of states in the parent profile can all be tweaked to trade off\n" + "sensitivity vs performance.\n" + "\n" + " -band <n> Size of band around guide alignment (default " + to_string(DefaultMaxDistanceFromGuide) + ")\n" + " -noband Unlimit band, ignore guide alignment\n" + " -minpost <p> Posterior prob. threshold for profile states (default " + TOSTRING(DefaultProfilePostProb) + ")\n" // Uncomment to show help for obsolescent random-sampling profile option: // + " -samples <n> Sample profile states randomly\n" + " -states <n> Limit max number of states per profile\n" + "\n" + " -ancseq Predict ancestral sequences (default is to leave them as " + Alignment::wildcardChar + "'s)\n" + " -ancprob Report posterior probabilities for ancestral residues\n" + "\n" // Uncomment to show help for obsolescent random-sampling profile option: // + "Note -minpost and -samples select different profile construction strategies.\n" // + " -minpost (the default) deterministically includes all states above a given\n" // + " posterior probability threshold, along with paths required to reach them.\n" // + " -samples randomly samples state paths from the posterior distribution.\n" // + "Both strategies are subject to the state limit imposed by -states.\n" // + "\n" + "Guide alignment & tree estimation options:\n" + "\n" + "The guide aligner builds a maximal spanning tree of pairwise alignments.\n" + "It can be accelerated in two ways: (1) by using a sparse random forest\n" + "instead of a fully connected all-vs-all pairwise comparison; and (2) by\n" + "confining the pairwise DP matrix to cells around a subset of diagonals\n" + "that contain above a threshold number of k-mer matches. To turn on the\n" + "former optimization, use -rndspan; the latter is turned on by default for\n" + "sequences whose full DP matrix would not otherwise fit in memory (the\n" + "memory threshold can be set with -kmatchmb). It can be disabled with\n" + "-kmatchoff, or enabled (for a particular k-mer threshold) with -kmatchn.\n" + "\n" + " -rndspan Use a sparse random spanning graph, not all-vs-all pairs\n" + " -kmatchn <n> Threshold# of kmer matches to seed a diagonal\n" + " (default sets this as low as available memory will allow)\n" + " -kmatch <k> Length of kmers for pre-filtering heuristic (default " + to_string(DEFAULT_KMER_LENGTH) + ")\n" + " -kmatchband <n> Size of DP band around kmer-matching diagonals (default " + to_string(DEFAULT_BAND_SIZE) + ")\n" + " -kmatchmb <M> Set kmer threshold to use M megabytes of memory\n" // + " -kmatchmax Set kmer threshold to use all available memory (default)\n" + " -kmatchoff No kmer threshold, do full DP\n" + "\n" + " -upgma Use UPGMA, not neighbor-joining, to estimate tree\n" + "\n" + "Model-fitting and event-counting options:\n" + "\n" + "By default, the reconstruction algorithm will interpret any supplied alignment\n" + "as a guide alignment, i.e. a hint, even if it contains a full ancestral sequence\n" + "reconstruction. To insist that the alignment be interpreted as a reconstruction,\n" + "precede it with -recon, -nexusrecon or -stockrecon (depending on the format).\n" + "\n" + " -recon <file>, -nexusrecon <file>, -stockrecon <file>\n" + " Use precomputed reconstruction (FASTA/NEXUS/Stockholm)\n" + " -mininc <n> EM convergence threshold as relative log-likelihood increase\n" + " (default is " + TOSTRING(DefaultMinEMImprovement) + ")\n" + " -maxiter <n> Max number of EM iterations (default " + to_string(DefaultMaxEMIterations) + ")\n" + " -nolaplace Do not add Laplace +1 pseudocounts during model-fitting\n" + " -fixsubrates Do not estimate substitution rates or initial composition\n" + " -fixgaprates Do not estimate indel rates or length distributions\n" + "\n" + "General options:\n" + " -verbose, -vv, -vvv, -v4, -v5, etc.\n" // uncomment to document debug logging: // + " -log <function_name>\n" + " Various levels of logging (-nocolor for monochrome)\n" + " -V, --version Print GNU-style version info\n" + " -h, --help Print help message\n" + " -seed <n> Seed random number generator (" + DPMatrix::random_engine_name() + "; default seed " + to_string(DPMatrix::random_engine::default_seed) + ")\n" + "\n" + "REFERENCES\n" + "\n" + "The reconstruction method uses phylogenetic transducers, as described in:\n" + " Westesson, Lunter, Paten & Holmes (2012). Accurate Reconstruction of\n" + " Insertion-Deletion Histories by Statistical Phylogenetics.\n" + " PLoS One, DOI: 10.1371/journal.pone.0034572\n" + " http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0034572\n" + "\n" + "A longer, tutorial-style introduction is available here:\n" + " Westesson, Lunter, Paten & Holmes (2012).\n" + " Phylogenetic Automata, Pruning, and Multiple Alignment.\n" + " http://arxiv.org/abs/1103.4347\n" + "\n" + "Model-fitting uses the following phylogenetic EM algorithm:\n" + " Holmes & Rubin (2002). An Expectation Maximization Algorithm\n" + " for Training Hidden Substitution Models.\n" + " Journal of Molecular Biology, 317(5).\n" + "\n"; } int main (int argc, char** argv) { ProgUsage usage (argc, argv); Reconstructor recon; const string command = usage.getCommand(); deque<string>& argvec (usage.argvec); auto reconstruct = [&]() -> void { recon.reconstructRoot = true; recon.accumulateSubstCounts = false; recon.accumulateIndelCounts = false; usage.implicitSwitches.push_back (string ("-auto")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseReconArgs (argvec) || usage.parseUnknown()) { } recon.loadModel(); recon.loadSeqs(); recon.reconstructAll(); recon.writeRecon (cout); }; if (command == "reconstruct" || command == "recon" || command == "r") { reconstruct(); } else if (command == "count" || command == "c") { recon.reconstructRoot = false; recon.accumulateSubstCounts = true; recon.accumulateIndelCounts = true; usage.implicitSwitches.push_back (string ("-auto")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseCountArgs (argvec) || usage.parseUnknown()) { } recon.loadModel(); recon.loadSeqs(); recon.loadRecon(); recon.loadCounts(); recon.countAll(); recon.writeCounts (cout); } else if (command == "sum" || command == "s") { recon.useLaplacePseudocounts = false; usage.implicitSwitches.push_back (string ("-counts")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseSumArgs (argvec) || usage.parseUnknown()) { } recon.loadCounts(); recon.writeCounts (cout); } else if (command == "fit" || command == "f") { recon.reconstructRoot = false; recon.accumulateSubstCounts = true; recon.accumulateIndelCounts = true; usage.implicitSwitches.push_back (string ("-auto")); usage.unlimitImplicitSwitches = true; while (logger.parseLogArgs (argvec) || recon.parseFitArgs (argvec) || usage.parseUnknown()) { } recon.loadModel(); recon.loadSeqs(); recon.loadRecon(); recon.loadCounts(); recon.fit(); recon.writeModel (cout); } else if (!usage.parseUnknownCommand (command, HISTORIAN_VERSION, false)) { // default: reconstruct argvec.push_front (command); reconstruct(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright 2016-2017 deepstreamHub GmbH * * 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 <cstdio> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstring> #include <numeric> #include <random> #include <vector> #include <message.hpp> #include <parser.hpp> extern "C" { #include <lexer.h> } // Remarks: // - Do not use BOOST_CHECK_EQUAL() to compare const char* variables as // Boost.Test attempts to be smart by calling std::strcmp() // [with Boost 1.53, see boost/test/impl/test_tools.ipp:383, equal_impl()]. // In this file, const char* variables do not always reference null-terminated // strings, e.g., when using std::vector<char*>::data(). If this happens, // Valgrind may detect invalid reads. namespace deepstream { namespace parser { BOOST_AUTO_TEST_CASE(empty_string) { deepstream_parser_state state("", 0); int token = state.handle_token(TOKEN_EOF, "\0", 1); BOOST_CHECK_EQUAL( token, TOKEN_EOF ); BOOST_CHECK( state.tokenizing_header_ ); BOOST_CHECK_EQUAL( state.offset_, 1 ); BOOST_CHECK( state.messages_.empty() ); BOOST_CHECK( state.errors_.empty() ); } BOOST_AUTO_TEST_CASE(simple) { const auto input = Message::from_human_readable("A|A+"); const auto copy(input); const char* matches[] = { &input[0], &input[3], "" }; std::size_t sizes[] = { 3, 1, 1 }; const deepstream_token tokens[] = { TOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { bool tokenizing_header = state.tokenizing_header_; BOOST_CHECK( (i==0||i==2) ? tokenizing_header : !tokenizing_header ); int ret = state.handle_token(tokens[i], matches[i], sizes[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), 1 ); BOOST_CHECK( state.errors_.empty() ); std::size_t offset = std::accumulate( sizes, sizes+i+1, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); } Message& msg = state.messages_.front(); BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.offset_, 0 ); BOOST_CHECK_EQUAL( msg.size_, input.size() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg.action(), Action::REQUEST ); BOOST_CHECK( msg.is_ack() ); BOOST_CHECK( msg.arguments_.empty() ); } BOOST_AUTO_TEST_CASE(concatenated_messages) { const char STRING[] = "E|L|listen+E|S|event+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token tokens[] = { TOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); const std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 }; const char* matches[num_tokens] = { &input[ 0], &input[3], &input[10], &input[11], &input[14], &input[20], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { BOOST_CHECK( (i==0||i==3||i==6) ? state.tokenizing_header_ : !state.tokenizing_header_ ); std::size_t offset = std::accumulate( matchlens, matchlens+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(tokens[i], matches[i], matchlens[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 ); BOOST_CHECK( state.errors_.empty() ); BOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] ); } BOOST_CHECK( state.tokenizing_header_ ); for(const Message& msg : state.messages_) { BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT ); BOOST_CHECK( !msg.is_ack() ); BOOST_CHECK_EQUAL( msg.arguments_.size(), 1 ); } BOOST_CHECK_EQUAL( state.messages_.size(), 2 ); const Message& msg_f = state.messages_.front(); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 11 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN ); const Location& arg_f = msg_f.arguments_.front(); BOOST_CHECK_EQUAL( arg_f.offset_, 4 ); BOOST_CHECK_EQUAL( arg_f.size_, 6 ); BOOST_CHECK( !strncmp(&input[arg_f.offset_], "listen", arg_f.size_) ); const Message& msg_b = state.messages_.back(); BOOST_CHECK_EQUAL( msg_b.offset(), 11 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE ); const Location& arg_b = msg_b.arguments_.front(); BOOST_CHECK_EQUAL( arg_b.offset_, 15 ); BOOST_CHECK_EQUAL( arg_b.size_, 5 ); BOOST_CHECK( !strncmp(&input[arg_b.offset_], "event", arg_b.size_) ); } BOOST_AUTO_TEST_CASE(invalid_number_of_arguments) { const char STRING[] = "E|A|L|l+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token TOKENS[] = { TOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); const std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 }; const char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < NUM_TOKENS; ++i) { bool tokenizing_header = state.tokenizing_header_; BOOST_CHECK( (i==0||i==3) ? tokenizing_header : !tokenizing_header ); std::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]); BOOST_CHECK_EQUAL( ret, TOKENS[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 ); BOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 ); BOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] ); } const Error& e = state.errors_.front(); BOOST_CHECK_EQUAL( e.location_.offset_, 0 ); BOOST_CHECK_EQUAL( e.location_.size_, 8 ); BOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS ); } // lexer, parser integration tests BOOST_AUTO_TEST_CASE(simple_integration) { const char raw[] = "A|A+ERROR+++E|A|L|p|m+"; const std::vector<char> input = Message::from_human_readable(raw); std::vector<char> lexer_input( input.size()+2 ); std::copy( input.cbegin(), input.cend(), lexer_input.begin() ); yyscan_t scanner; int ret = yylex_init(&scanner); BOOST_REQUIRE_EQUAL(ret, 0); YY_BUFFER_STATE buffer = \ yy_scan_buffer( lexer_input.data(), lexer_input.size(), scanner ); yy_switch_to_buffer(buffer, scanner); State parser( input.data(), input.size() ); yyset_extra(&parser, scanner); for( int ret = TOKEN_UNKNOWN; ret != TOKEN_EOF; ret = yylex(scanner) ); BOOST_CHECK( parser.buffer_ == input.data() ); BOOST_CHECK_EQUAL( parser.buffer_size_, input.size() ); BOOST_CHECK( parser.tokenizing_header_ ); BOOST_CHECK_EQUAL( parser.offset_, parser.buffer_size_ + 1 ); BOOST_CHECK_EQUAL( parser.messages_.size(), 2 ); BOOST_CHECK_EQUAL( parser.errors_.size(), 1 ); const Message& msg_f = parser.messages_.front(); BOOST_CHECK( msg_f.base() == input.data() ); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 4 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg_f.action(), Action::REQUEST ); BOOST_CHECK( msg_f.is_ack() ); BOOST_CHECK( msg_f.arguments().empty() ); const Message& msg_b = parser.messages_.back(); BOOST_CHECK( msg_b.base() == input.data() ); BOOST_CHECK_EQUAL( msg_b.offset(), 12 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::LISTEN ); BOOST_CHECK( msg_b.is_ack() ); BOOST_CHECK_EQUAL( msg_b.arguments().size(), 2 ); const Error& error = parser.errors_.front(); BOOST_CHECK_EQUAL( error.tag(), Error::UNEXPECTED_TOKEN ); } } } <commit_msg>Test: fix memory leak<commit_after>/* * Copyright 2016-2017 deepstreamHub GmbH * * 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 <cstdio> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstring> #include <numeric> #include <random> #include <vector> #include <message.hpp> #include <parser.hpp> #include <scope_guard.hpp> extern "C" { #include <lexer.h> } // Remarks: // - Do not use BOOST_CHECK_EQUAL() to compare const char* variables as // Boost.Test attempts to be smart by calling std::strcmp() // [with Boost 1.53, see boost/test/impl/test_tools.ipp:383, equal_impl()]. // In this file, const char* variables do not always reference null-terminated // strings, e.g., when using std::vector<char*>::data(). If this happens, // Valgrind may detect invalid reads. namespace deepstream { namespace parser { BOOST_AUTO_TEST_CASE(empty_string) { deepstream_parser_state state("", 0); int token = state.handle_token(TOKEN_EOF, "\0", 1); BOOST_CHECK_EQUAL( token, TOKEN_EOF ); BOOST_CHECK( state.tokenizing_header_ ); BOOST_CHECK_EQUAL( state.offset_, 1 ); BOOST_CHECK( state.messages_.empty() ); BOOST_CHECK( state.errors_.empty() ); } BOOST_AUTO_TEST_CASE(simple) { const auto input = Message::from_human_readable("A|A+"); const auto copy(input); const char* matches[] = { &input[0], &input[3], "" }; std::size_t sizes[] = { 3, 1, 1 }; const deepstream_token tokens[] = { TOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { bool tokenizing_header = state.tokenizing_header_; BOOST_CHECK( (i==0||i==2) ? tokenizing_header : !tokenizing_header ); int ret = state.handle_token(tokens[i], matches[i], sizes[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), 1 ); BOOST_CHECK( state.errors_.empty() ); std::size_t offset = std::accumulate( sizes, sizes+i+1, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); } Message& msg = state.messages_.front(); BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.offset_, 0 ); BOOST_CHECK_EQUAL( msg.size_, input.size() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg.action(), Action::REQUEST ); BOOST_CHECK( msg.is_ack() ); BOOST_CHECK( msg.arguments_.empty() ); } BOOST_AUTO_TEST_CASE(concatenated_messages) { const char STRING[] = "E|L|listen+E|S|event+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token tokens[] = { TOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); const std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 }; const char* matches[num_tokens] = { &input[ 0], &input[3], &input[10], &input[11], &input[14], &input[20], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { BOOST_CHECK( (i==0||i==3||i==6) ? state.tokenizing_header_ : !state.tokenizing_header_ ); std::size_t offset = std::accumulate( matchlens, matchlens+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(tokens[i], matches[i], matchlens[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 ); BOOST_CHECK( state.errors_.empty() ); BOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] ); } BOOST_CHECK( state.tokenizing_header_ ); for(const Message& msg : state.messages_) { BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT ); BOOST_CHECK( !msg.is_ack() ); BOOST_CHECK_EQUAL( msg.arguments_.size(), 1 ); } BOOST_CHECK_EQUAL( state.messages_.size(), 2 ); const Message& msg_f = state.messages_.front(); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 11 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN ); const Location& arg_f = msg_f.arguments_.front(); BOOST_CHECK_EQUAL( arg_f.offset_, 4 ); BOOST_CHECK_EQUAL( arg_f.size_, 6 ); BOOST_CHECK( !strncmp(&input[arg_f.offset_], "listen", arg_f.size_) ); const Message& msg_b = state.messages_.back(); BOOST_CHECK_EQUAL( msg_b.offset(), 11 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE ); const Location& arg_b = msg_b.arguments_.front(); BOOST_CHECK_EQUAL( arg_b.offset_, 15 ); BOOST_CHECK_EQUAL( arg_b.size_, 5 ); BOOST_CHECK( !strncmp(&input[arg_b.offset_], "event", arg_b.size_) ); } BOOST_AUTO_TEST_CASE(invalid_number_of_arguments) { const char STRING[] = "E|A|L|l+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token TOKENS[] = { TOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); const std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 }; const char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < NUM_TOKENS; ++i) { bool tokenizing_header = state.tokenizing_header_; BOOST_CHECK( (i==0||i==3) ? tokenizing_header : !tokenizing_header ); std::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]); BOOST_CHECK_EQUAL( ret, TOKENS[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 ); BOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 ); BOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] ); } const Error& e = state.errors_.front(); BOOST_CHECK_EQUAL( e.location_.offset_, 0 ); BOOST_CHECK_EQUAL( e.location_.size_, 8 ); BOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS ); } // lexer, parser integration tests BOOST_AUTO_TEST_CASE(simple_integration) { const char raw[] = "A|A+ERROR+++E|A|L|p|m+"; const std::vector<char> input = Message::from_human_readable(raw); std::vector<char> lexer_input( input.size()+2 ); std::copy( input.cbegin(), input.cend(), lexer_input.begin() ); yyscan_t scanner; int ret = yylex_init(&scanner); BOOST_REQUIRE_EQUAL(ret, 0); DEEPSTREAM_ON_EXIT( [&scanner] () { yylex_destroy(scanner); } ); YY_BUFFER_STATE buffer = \ yy_scan_buffer( lexer_input.data(), lexer_input.size(), scanner ); yy_switch_to_buffer(buffer, scanner); State parser( input.data(), input.size() ); yyset_extra(&parser, scanner); for( int ret = TOKEN_UNKNOWN; ret != TOKEN_EOF; ret = yylex(scanner) ); BOOST_CHECK( parser.buffer_ == input.data() ); BOOST_CHECK_EQUAL( parser.buffer_size_, input.size() ); BOOST_CHECK( parser.tokenizing_header_ ); BOOST_CHECK_EQUAL( parser.offset_, parser.buffer_size_ + 1 ); BOOST_CHECK_EQUAL( parser.messages_.size(), 2 ); BOOST_CHECK_EQUAL( parser.errors_.size(), 1 ); const Message& msg_f = parser.messages_.front(); BOOST_CHECK( msg_f.base() == input.data() ); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 4 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg_f.action(), Action::REQUEST ); BOOST_CHECK( msg_f.is_ack() ); BOOST_CHECK( msg_f.arguments().empty() ); const Message& msg_b = parser.messages_.back(); BOOST_CHECK( msg_b.base() == input.data() ); BOOST_CHECK_EQUAL( msg_b.offset(), 12 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::LISTEN ); BOOST_CHECK( msg_b.is_ack() ); BOOST_CHECK_EQUAL( msg_b.arguments().size(), 2 ); const Error& error = parser.errors_.front(); BOOST_CHECK_EQUAL( error.tag(), Error::UNEXPECTED_TOKEN ); } } } <|endoftext|>
<commit_before>#include <CQRealSpin.h> #include <QLineEdit> //#include <iostream> //#include <cassert> CQRealSpin:: CQRealSpin(QWidget *parent, double value) : QDoubleSpinBox(parent) { init(value); } CQRealSpin:: CQRealSpin(double value) : QDoubleSpinBox(0) { init(value); } void CQRealSpin:: init(double value) { setObjectName("realSpin"); setRange(-1E6, 1E6); setValue(value); connect(lineEdit(), SIGNAL(cursorPositionChanged(int,int)), this, SLOT(updateStep())); updateStep(); } void CQRealSpin:: updateStep() { int pos = lineEdit()->cursorPosition(); double s = posToStep(pos); if (fabs(step() - s) >= 1E-6) { step_ = s; emit stepChanged(step()); } } double CQRealSpin:: posToStep(int pos) const { bool negative = isNegative(); int dotPos = this->dotPos(); //--- // if no dot then power is length - pos if (dotPos < 0) { if (! negative) { if (pos < 1) pos = 1; } else { if (pos < 2) pos = 2; } int d = text().length() - pos; return pow(10, d); } //--- // dot on right (1) if (pos == dotPos) return 1; //--- // dot on left (0.1) if (pos == dotPos + 1) return 0.1; if (! negative) { if (pos < 1) pos = 1; } else { if (pos < 2) pos = 2; } if (pos > dotPos) --pos; return pow(10, dotPos - pos); } void CQRealSpin:: stepBy(int n) { double v = value(); double s = step(); int pos = lineEdit()->cursorPosition(); int dotPos = this->dotPos(); bool negative = isNegative(); if (! negative) { if (pos < 1) pos = 1; } else { if (pos < 2) pos = 2; } setValue(v + n*s); int dotPos1 = this->dotPos(); int pos1 = dotPos1 - dotPos + pos; if (pos1 != pos) lineEdit()->setCursorPosition(pos1); updateStep(); } bool CQRealSpin:: isNegative() const { const QString &text = lineEdit()->text(); return (text.length() && text[0] == '-'); } int CQRealSpin:: dotPos() const { const QString &text = lineEdit()->text(); for (int i = 0; i < text.length(); ++i) if (text[i] == '.') return i; return -1; } <commit_msg>new files<commit_after>#include <CQRealSpin.h> #include <QLineEdit> //#include <iostream> //#include <cassert> #include <cmath> CQRealSpin:: CQRealSpin(QWidget *parent, double value) : QDoubleSpinBox(parent) { init(value); } CQRealSpin:: CQRealSpin(double value) : QDoubleSpinBox(0) { init(value); } void CQRealSpin:: init(double value) { setObjectName("realSpin"); setRange(-1E6, 1E6); setValue(value); connect(lineEdit(), SIGNAL(cursorPositionChanged(int,int)), this, SLOT(updateStep())); updateStep(); } void CQRealSpin:: updateStep() { int pos = lineEdit()->cursorPosition(); double s = posToStep(pos); if (fabs(step() - s) >= 1E-6) { step_ = s; emit stepChanged(step()); } } double CQRealSpin:: posToStep(int pos) const { bool negative = isNegative(); int dotPos = this->dotPos(); //--- // if no dot then power is length - pos if (dotPos < 0) { if (! negative) { if (pos < 1) pos = 1; } else { if (pos < 2) pos = 2; } int d = text().length() - pos; return pow(10, d); } //--- // dot on right (1) if (pos == dotPos) return 1; //--- // dot on left (0.1) if (pos == dotPos + 1) return 0.1; if (! negative) { if (pos < 1) pos = 1; } else { if (pos < 2) pos = 2; } if (pos > dotPos) --pos; return pow(10, dotPos - pos); } void CQRealSpin:: stepBy(int n) { double v = value(); double s = step(); int pos = lineEdit()->cursorPosition(); int dotPos = this->dotPos(); bool negative = isNegative(); if (! negative) { if (pos < 1) pos = 1; } else { if (pos < 2) pos = 2; } setValue(v + n*s); int dotPos1 = this->dotPos(); int pos1 = dotPos1 - dotPos + pos; if (pos1 != pos) lineEdit()->setCursorPosition(pos1); updateStep(); } bool CQRealSpin:: isNegative() const { const QString &text = lineEdit()->text(); return (text.length() && text[0] == '-'); } int CQRealSpin:: dotPos() const { const QString &text = lineEdit()->text(); for (int i = 0; i < text.length(); ++i) if (text[i] == '.') return i; return -1; } <|endoftext|>
<commit_before>/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact license@matroska.org if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id$ \author Steve Lhomme <robux4 @ users.sf.net> \author Julien Coloos <suiryc @ users.sf.net> */ #include <cassert> #include <string> #include "ebml/EbmlBinary.h" #include "ebml/StdIOCallback.h" START_LIBEBML_NAMESPACE EbmlBinary::EbmlBinary() :EbmlElement(0, false), Data(nullptr) {} EbmlBinary::EbmlBinary(const EbmlBinary & ElementToClone) :EbmlElement(ElementToClone) { if (ElementToClone.Data == nullptr) Data = nullptr; else { Data = static_cast<binary *>(malloc(GetSize() * sizeof(binary))); assert(Data != nullptr); memcpy(Data, ElementToClone.Data, GetSize()); } } EbmlBinary::~EbmlBinary() { if(Data) free(Data); } EbmlBinary::operator const binary &() const {return *Data;} filepos_t EbmlBinary::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */) { output.writeFully(Data,GetSize()); return GetSize(); } /*! \note no Default binary value handled */ uint64 EbmlBinary::UpdateSize(bool /* bWithDefault */, bool /* bForceRender */) { return GetSize(); } filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully) { if (Data != nullptr) free(Data); if (ReadFully == SCOPE_NO_DATA) { Data = nullptr; return GetSize(); } if (!GetSize()) { SetValueIsSet(); Data = nullptr; return 0; } Data = static_cast<binary *>(malloc(GetSize())); if (Data == nullptr) throw CRTError(std::string("Error allocating data")); SetValueIsSet(); return input.read(Data, GetSize()); } bool EbmlBinary::operator==(const EbmlBinary & ElementToCompare) const { return ((GetSize() == ElementToCompare.GetSize()) && (GetSize() == 0 || !memcmp(Data, ElementToCompare.Data, GetSize()))); } END_LIBEBML_NAMESPACE <commit_msg>EbmlBinary: don't write in unallocated memory<commit_after>/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact license@matroska.org if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id$ \author Steve Lhomme <robux4 @ users.sf.net> \author Julien Coloos <suiryc @ users.sf.net> */ #include <cassert> #include <string> #include "ebml/EbmlBinary.h" #include "ebml/StdIOCallback.h" START_LIBEBML_NAMESPACE EbmlBinary::EbmlBinary() :EbmlElement(0, false), Data(nullptr) {} EbmlBinary::EbmlBinary(const EbmlBinary & ElementToClone) :EbmlElement(ElementToClone) { if (ElementToClone.Data == nullptr) Data = nullptr; else { Data = static_cast<binary *>(malloc(GetSize())); if(Data != nullptr) memcpy(Data, ElementToClone.Data, GetSize()); } } EbmlBinary::~EbmlBinary() { if(Data) free(Data); } EbmlBinary::operator const binary &() const {return *Data;} filepos_t EbmlBinary::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */) { output.writeFully(Data,GetSize()); return GetSize(); } /*! \note no Default binary value handled */ uint64 EbmlBinary::UpdateSize(bool /* bWithDefault */, bool /* bForceRender */) { return GetSize(); } filepos_t EbmlBinary::ReadData(IOCallback & input, ScopeMode ReadFully) { if (Data != nullptr) free(Data); if (ReadFully == SCOPE_NO_DATA) { Data = nullptr; return GetSize(); } if (!GetSize()) { SetValueIsSet(); Data = nullptr; return 0; } Data = static_cast<binary *>(malloc(GetSize())); if (Data == nullptr) throw CRTError(std::string("Error allocating data")); SetValueIsSet(); return input.read(Data, GetSize()); } bool EbmlBinary::operator==(const EbmlBinary & ElementToCompare) const { return ((GetSize() == ElementToCompare.GetSize()) && (GetSize() == 0 || !memcmp(Data, ElementToCompare.Data, GetSize()))); } END_LIBEBML_NAMESPACE <|endoftext|>
<commit_before>#include "EventTypes.h" BOOST_CLASS_EXPORT(MyoSim::onPairEvent); BOOST_CLASS_EXPORT(MyoSim::onUnpairEvent); BOOST_CLASS_EXPORT(MyoSim::onConnectEvent); BOOST_CLASS_EXPORT(MyoSim::onDisconnectEvent); BOOST_CLASS_EXPORT(MyoSim::onArmSyncEvent); BOOST_CLASS_EXPORT(MyoSim::onArmUnsyncEvent); BOOST_CLASS_EXPORT(MyoSim::onUnlockEvent); BOOST_CLASS_EXPORT(MyoSim::onLockEvent); BOOST_CLASS_EXPORT(MyoSim::onPoseEvent); BOOST_CLASS_EXPORT(MyoSim::onOrientationDataEvent); BOOST_CLASS_EXPORT(MyoSim::onAccelerometerDataEvent); BOOST_CLASS_EXPORT(MyoSim::onGyroscopeDataEvent); BOOST_CLASS_EXPORT(MyoSim::onRssiEvent); BOOST_CLASS_EXPORT(MyoSim::onEmgDataEvent); <commit_msg>Add boost::archive includes<commit_after>#include "EventTypes.h" #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> BOOST_CLASS_EXPORT(MyoSim::onPairEvent); BOOST_CLASS_EXPORT(MyoSim::onUnpairEvent); BOOST_CLASS_EXPORT(MyoSim::onConnectEvent); BOOST_CLASS_EXPORT(MyoSim::onDisconnectEvent); BOOST_CLASS_EXPORT(MyoSim::onArmSyncEvent); BOOST_CLASS_EXPORT(MyoSim::onArmUnsyncEvent); BOOST_CLASS_EXPORT(MyoSim::onUnlockEvent); BOOST_CLASS_EXPORT(MyoSim::onLockEvent); BOOST_CLASS_EXPORT(MyoSim::onPoseEvent); BOOST_CLASS_EXPORT(MyoSim::onOrientationDataEvent); BOOST_CLASS_EXPORT(MyoSim::onAccelerometerDataEvent); BOOST_CLASS_EXPORT(MyoSim::onGyroscopeDataEvent); BOOST_CLASS_EXPORT(MyoSim::onRssiEvent); BOOST_CLASS_EXPORT(MyoSim::onEmgDataEvent); <|endoftext|>
<commit_before>// Button.cc for FbTk - fluxbox toolkit // Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // 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. // $Id: Button.cc,v 1.13 2003/09/08 15:37:37 fluxgen Exp $ #include "Button.hh" #include "Command.hh" #include "EventManager.hh" #include "App.hh" namespace FbTk { Button::Button(int screen_num, int x, int y, unsigned int width, unsigned int height): FbWindow(screen_num, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), screen_num)), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, *this); } Button::Button(const FbWindow &parent, int x, int y, unsigned int width, unsigned int height): FbWindow(parent, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), screenNumber())), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, *this); } Button::~Button() { FbTk::EventManager::instance()->remove(*this); } void Button::setOnClick(RefCount<Command> &cmd, int button) { // we only handle buttons 1 to 5 if (button > 5 || button == 0) return; //set on click command for the button m_onclick[button - 1] = cmd; } void Button::setPixmap(Pixmap pm) { m_foreground_pm = pm; } void Button::setPressedPixmap(Pixmap pm) { m_pressed_pm = pm; } void Button::setBackgroundColor(const Color &color) { m_background_color = color; FbTk::FbWindow::setBackgroundColor(color); } void Button::setBackgroundPixmap(Pixmap pm) { m_background_pm = pm; FbTk::FbWindow::setBackgroundPixmap(pm); } void Button::buttonPressEvent(XButtonEvent &event) { if (m_pressed_pm != 0) FbWindow::setBackgroundPixmap(m_pressed_pm); m_pressed = true; clear(); FbWindow::updateTransparent(); } void Button::buttonReleaseEvent(XButtonEvent &event) { m_pressed = false; if (m_background_pm) FbWindow::setBackgroundPixmap(m_background_pm); else FbWindow::setBackgroundColor(m_background_color); clear(); // clear background if (m_foreground_pm) { // draw foreground pixmap Display *disp = App::instance()->display(); if (m_gc == 0) // get default gc if we dont have one m_gc = DefaultGC(disp, screenNumber()); XCopyArea(disp, m_foreground_pm, window(), m_gc, 0, 0, width(), height(), 0, 0); } FbWindow::updateTransparent(); // finaly, execute command (this must be done last since this object might be deleted by the command) if (event.button > 0 && event.button <= 5 && event.x > 0 && event.x < width() && event.y > 0 && event.y < height() && m_onclick[event.button -1].get() != 0) m_onclick[event.button - 1]->execute(); } void Button::exposeEvent(XExposeEvent &event) { if (m_background_pm) FbWindow::setBackgroundPixmap(m_background_pm); else FbWindow::setBackgroundColor(m_background_color); clear(); FbWindow::updateTransparent(event.x, event.y, event.width, event.height); } }; // end namespace FbTk <commit_msg>fixed expose event<commit_after>// Button.cc for FbTk - fluxbox toolkit // Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // 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. // $Id: Button.cc,v 1.14 2003/09/10 11:19:39 fluxgen Exp $ #include "Button.hh" #include "Command.hh" #include "EventManager.hh" #include "App.hh" namespace FbTk { Button::Button(int screen_num, int x, int y, unsigned int width, unsigned int height): FbWindow(screen_num, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), screen_num)), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, *this); } Button::Button(const FbWindow &parent, int x, int y, unsigned int width, unsigned int height): FbWindow(parent, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), screenNumber())), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, *this); } Button::~Button() { FbTk::EventManager::instance()->remove(*this); } void Button::setOnClick(RefCount<Command> &cmd, int button) { // we only handle buttons 1 to 5 if (button > 5 || button == 0) return; //set on click command for the button m_onclick[button - 1] = cmd; } void Button::setPixmap(Pixmap pm) { m_foreground_pm = pm; } void Button::setPressedPixmap(Pixmap pm) { m_pressed_pm = pm; } void Button::setBackgroundColor(const Color &color) { m_background_color = color; FbTk::FbWindow::setBackgroundColor(color); } void Button::setBackgroundPixmap(Pixmap pm) { m_background_pm = pm; FbTk::FbWindow::setBackgroundPixmap(pm); } void Button::buttonPressEvent(XButtonEvent &event) { if (m_pressed_pm != 0) FbWindow::setBackgroundPixmap(m_pressed_pm); m_pressed = true; clear(); FbWindow::updateTransparent(); } void Button::buttonReleaseEvent(XButtonEvent &event) { m_pressed = false; if (m_background_pm) FbWindow::setBackgroundPixmap(m_background_pm); else FbWindow::setBackgroundColor(m_background_color); clear(); // clear background if (m_foreground_pm) { // draw foreground pixmap Display *disp = App::instance()->display(); if (m_gc == 0) // get default gc if we dont have one m_gc = DefaultGC(disp, screenNumber()); XCopyArea(disp, m_foreground_pm, window(), m_gc, 0, 0, width(), height(), 0, 0); } FbWindow::updateTransparent(); // finaly, execute command (this must be done last since this object might be deleted by the command) if (event.button > 0 && event.button <= 5 && event.x > 0 && event.x < width() && event.y > 0 && event.y < height() && m_onclick[event.button -1].get() != 0) m_onclick[event.button - 1]->execute(); } void Button::exposeEvent(XExposeEvent &event) { if (m_background_pm) FbWindow::setBackgroundPixmap(m_background_pm); else FbWindow::setBackgroundColor(m_background_color); clear(); FbWindow::updateTransparent(); } }; // end namespace FbTk <|endoftext|>
<commit_before>#include <cstdlib> #include <time.h> #include "Move.h" #include "MoveManager.h" #include "json/json.h" #include "schema.h" #include "../Validator/ObjectRequirement.h" #include "../Validator/ArrayRequirement.h" #include "../Simulation/SimException.h" #include "../Worlds/WorldManager.h" #include "FlipSpinMove.h" #include "TranslateMove.h" #include "TranslatePrimitiveMove.h" #include "DirectorRotateMove.h" #include "ParticleSwapMove.h" #include "RandomIdentityMove.h" #include "RotateMove.h" #include "SpeciesSwapMove.h" #include "VolumeSwapMove.h" #include "VolumeScaleMove.h" #include "InsertParticleMove.h" #include "DeleteParticleMove.h" #include "AnnealChargeMove.h" #include "AcidTitrationMove.h" #include "AcidReactionMove.h" using namespace Json; namespace SAPHRON { Move* Move::BuildMove(const Json::Value &json, SAPHRON::MoveManager *mm, WorldManager* wm) { return BuildMove(json, mm, wm, "#/moves"); } Move* Move::BuildMove(const Value &json, MoveManager *mm, WorldManager* wm, const std::string& path) { ObjectRequirement validator; Value schema; Reader reader; Move* move = nullptr; // Get move type. std::string type = json.get("type", "none").asString(); if(type == "AcidReaction") { reader.parse(JsonSchema::AcidReactionMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); std::vector<std::string> reactants; for(auto& s : json["swap"]) reactants.push_back(s.asString()); std::vector<std::string> products; for(auto& s : json["products"]) products.push_back(s.asString()); auto pKo = json.get("pKo", 0.0).asDouble(); auto scount = json["stash_count"].asInt(); auto prefac = json.get("op_prefactor", true).asBool(); auto* m = new AcidReactionMove(reactants,products,*wm, scount, pKo, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "AcidTitrate") { reader.parse(JsonSchema::AcidTitrationMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto protoncharge = json.get("proton_charge", 1.0).asDouble(); auto mu = json.get("mu", 0.0).asDouble(); auto prefac = json.get("op_prefactor", true).asBool(); auto* m = new AcidTitrationMove(species, protoncharge, mu, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "AnnealCharge") { reader.parse(JsonSchema::AnnealChargeMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); move = new AnnealChargeMove(species, seed); } else if(type == "DeleteParticle") { reader.parse(JsonSchema::DeleteParticleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); auto prefac = json.get("op_prefactor", true).asBool(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto* m = new DeleteParticleMove(species, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "DirectorRotate") { reader.parse(JsonSchema::DirectorRotateMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new DirectorRotateMove(seed); } else if(type == "FlipSpin") { reader.parse(JsonSchema::FlipSpinMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new FlipSpinMove(seed); } else if(type == "InsertParticle") { reader.parse(JsonSchema::InsertParticleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); auto seed = json.get("seed", rand()).asInt(); auto scount = json["stash_count"].asInt(); auto prefac = json.get("op_prefactor", true).asBool(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto* m = new InsertParticleMove(species, *wm, scount, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "ParticleSwap") { reader.parse(JsonSchema::ParticleSwapMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new ParticleSwapMove(seed); } else if(type == "RandomIdentity") { reader.parse(JsonSchema::RandomIdentityMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); std::vector<std::string> identities; for(auto& i : json["identities"]) identities.push_back(i.asString()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new RandomIdentityMove(identities, seed); } else if(type == "Rotate") { reader.parse(JsonSchema::RotateMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); double dmax = json["maxangle"].asDouble(); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new RotateMove(dmax, seed); } else if(type == "SpeciesSwap") { reader.parse(JsonSchema::SpeciesSwapMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); bool deepcopy = json.get("deep_copy", false).asBool(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); move = new SpeciesSwapMove(species,deepcopy,seed); } else if(type == "Translate") { reader.parse(JsonSchema::TranslateMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); if(json["dx"].isObject()) { std::map<std::string, double> dx; for(auto& s : json["dx"].getMemberNames()) dx[s] = json["dx"][s].asDouble(); auto expl = json.get("explicit_draw", false).asBool(); move = new TranslateMove(dx, expl, seed); } else { auto dx = json["dx"].asDouble(); move = new TranslateMove(dx, seed); } } else if(type == "TranslatePrimitive") { reader.parse(JsonSchema::TranslatePrimitiveMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); if(json["dx"].isObject()) { std::map<std::string, double> dx; for(auto& s : json["dx"].getMemberNames()) dx[s] = json["dx"][s].asDouble(); auto expl = json.get("explicit_draw", false).asBool(); move = new TranslatePrimitiveMove(dx, expl, seed); } else { auto dx = json["dx"].asDouble(); move = new TranslatePrimitiveMove(dx, seed); } } else if(type == "VolumeScale") { reader.parse(JsonSchema::VolumeScaleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); auto dv = json["dv"].asDouble(); auto Pextern = json["Pextern"].asDouble(); srand(time(NULL)); auto seed = json.get("seed", rand()).asInt(); move = new VolumeScaleMove(Pextern, dv, seed); } else if(type == "VolumeSwap") { reader.parse(JsonSchema::VolumeSwapMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); double dv = json["dv"].asDouble(); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new VolumeSwapMove(dv, seed); } else { throw BuildException({path + ": Unknown move type specified."}); } // Add to appropriate species pair. try{ int weight = json.get("weight", 1).asUInt(); mm->AddMove(move, weight); } catch(std::exception& e) { delete move; throw BuildException({ e.what() }); } return move; } void Move::BuildMoves(const Json::Value &json, SAPHRON::MoveManager *mm, WorldManager* wm, MoveList &mvlist) { ArrayRequirement validator; Value schema; Reader reader; reader.parse(JsonSchema::Moves, schema); validator.Parse(schema, "#/moves"); // Validate high level schema. validator.Validate(json, "#/moves"); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); // Loop through moves. int i = 0; for(auto& m : json) { mvlist.push_back(BuildMove(m, mm, wm, "#/moves/" + std::to_string(i))); ++i; } } }<commit_msg>Update move builder for widom, insert, and delete particle moves<commit_after>#include <cstdlib> #include <time.h> #include "Move.h" #include "MoveManager.h" #include "json/json.h" #include "schema.h" #include "../Validator/ObjectRequirement.h" #include "../Validator/ArrayRequirement.h" #include "../Simulation/SimException.h" #include "../Worlds/WorldManager.h" #include "FlipSpinMove.h" #include "TranslateMove.h" #include "TranslatePrimitiveMove.h" #include "DirectorRotateMove.h" #include "ParticleSwapMove.h" #include "RandomIdentityMove.h" #include "RotateMove.h" #include "SpeciesSwapMove.h" #include "VolumeSwapMove.h" #include "VolumeScaleMove.h" #include "InsertParticleMove.h" #include "DeleteParticleMove.h" #include "AnnealChargeMove.h" #include "AcidTitrationMove.h" #include "AcidReactionMove.h" #include "WidomInsertionMove.h" using namespace Json; namespace SAPHRON { Move* Move::BuildMove(const Json::Value &json, SAPHRON::MoveManager *mm, WorldManager* wm) { return BuildMove(json, mm, wm, "#/moves"); } Move* Move::BuildMove(const Value &json, MoveManager *mm, WorldManager* wm, const std::string& path) { ObjectRequirement validator; Value schema; Reader reader; Move* move = nullptr; // Get move type. std::string type = json.get("type", "none").asString(); if(type == "AcidReaction") { reader.parse(JsonSchema::AcidReactionMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); std::vector<std::string> reactants; for(auto& s : json["swap"]) reactants.push_back(s.asString()); std::vector<std::string> products; for(auto& s : json["products"]) products.push_back(s.asString()); auto pKo = json.get("pKo", 0.0).asDouble(); auto scount = json["stash_count"].asInt(); auto prefac = json.get("op_prefactor", true).asBool(); auto* m = new AcidReactionMove(reactants,products,*wm, scount, pKo, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "AcidTitrate") { reader.parse(JsonSchema::AcidTitrationMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto protoncharge = json.get("proton_charge", 1.0).asDouble(); auto mu = json.get("mu", 0.0).asDouble(); auto prefac = json.get("op_prefactor", true).asBool(); auto* m = new AcidTitrationMove(species, protoncharge, mu, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "AnnealCharge") { reader.parse(JsonSchema::AnnealChargeMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); move = new AnnealChargeMove(species, seed); } else if(type == "DeleteParticle") { reader.parse(JsonSchema::DeleteParticleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); auto prefac = json.get("op_prefactor", true).asBool(); auto multi_d = json.get("multi_delete", false).asBool(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto* m = new DeleteParticleMove(species, multi_delete, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "DirectorRotate") { reader.parse(JsonSchema::DirectorRotateMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new DirectorRotateMove(seed); } else if(type == "FlipSpin") { reader.parse(JsonSchema::FlipSpinMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new FlipSpinMove(seed); } else if(type == "InsertParticle") { reader.parse(JsonSchema::InsertParticleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); auto seed = json.get("seed", rand()).asInt(); auto scount = json["stash_count"].asInt(); auto prefac = json.get("op_prefactor", true).asBool(); auto multi_i = json.get("multi_insertion", false).asBool(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto* m = new InsertParticleMove(species, *wm, scount, multi_i, seed); m->SetOrderParameterPrefactor(prefac); move = static_cast<Move*>(m); } else if(type == "ParticleSwap") { reader.parse(JsonSchema::ParticleSwapMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new ParticleSwapMove(seed); } else if(type == "RandomIdentity") { reader.parse(JsonSchema::RandomIdentityMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); std::vector<std::string> identities; for(auto& i : json["identities"]) identities.push_back(i.asString()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new RandomIdentityMove(identities, seed); } else if(type == "Rotate") { reader.parse(JsonSchema::RotateMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); double dmax = json["maxangle"].asDouble(); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new RotateMove(dmax, seed); } else if(type == "SpeciesSwap") { reader.parse(JsonSchema::SpeciesSwapMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); bool deepcopy = json.get("deep_copy", false).asBool(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); move = new SpeciesSwapMove(species,deepcopy,seed); } else if(type == "Translate") { reader.parse(JsonSchema::TranslateMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); if(json["dx"].isObject()) { std::map<std::string, double> dx; for(auto& s : json["dx"].getMemberNames()) dx[s] = json["dx"][s].asDouble(); auto expl = json.get("explicit_draw", false).asBool(); move = new TranslateMove(dx, expl, seed); } else { auto dx = json["dx"].asDouble(); move = new TranslateMove(dx, seed); } } else if(type == "TranslatePrimitive") { reader.parse(JsonSchema::TranslatePrimitiveMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); if(json["dx"].isObject()) { std::map<std::string, double> dx; for(auto& s : json["dx"].getMemberNames()) dx[s] = json["dx"][s].asDouble(); auto expl = json.get("explicit_draw", false).asBool(); move = new TranslatePrimitiveMove(dx, expl, seed); } else { auto dx = json["dx"].asDouble(); move = new TranslatePrimitiveMove(dx, seed); } } else if(type == "VolumeScale") { reader.parse(JsonSchema::VolumeScaleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); auto dv = json["dv"].asDouble(); auto Pextern = json["Pextern"].asDouble(); srand(time(NULL)); auto seed = json.get("seed", rand()).asInt(); move = new VolumeScaleMove(Pextern, dv, seed); } else if(type == "VolumeSwap") { reader.parse(JsonSchema::VolumeSwapMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); double dv = json["dv"].asDouble(); srand(time(NULL)); int seed = json.get("seed", rand()).asInt(); move = new VolumeSwapMove(dv, seed); } else if(type == "WidomInsertion") { reader.parse(JsonSchema::InsertParticleMove, schema); validator.Parse(schema, path); // Validate inputs. validator.Validate(json, path); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); srand(time(NULL)); auto seed = json.get("seed", rand()).asInt(); std::vector<std::string> species; for(auto& s : json["species"]) species.push_back(s.asString()); auto* m = new WidomInsertionMove(species, *wm, seed); } else { throw BuildException({path + ": Unknown move type specified."}); } // Add to appropriate species pair. try{ int weight = json.get("weight", 1).asUInt(); mm->AddMove(move, weight); } catch(std::exception& e) { delete move; throw BuildException({ e.what() }); } return move; } void Move::BuildMoves(const Json::Value &json, SAPHRON::MoveManager *mm, WorldManager* wm, MoveList &mvlist) { ArrayRequirement validator; Value schema; Reader reader; reader.parse(JsonSchema::Moves, schema); validator.Parse(schema, "#/moves"); // Validate high level schema. validator.Validate(json, "#/moves"); if(validator.HasErrors()) throw BuildException(validator.GetErrors()); // Loop through moves. int i = 0; for(auto& m : json) { mvlist.push_back(BuildMove(m, mm, wm, "#/moves/" + std::to_string(i))); ++i; } } }<|endoftext|>
<commit_before>#include <iostream> #include <math.h> #include "../include/PSATsolver.hpp" #include "../include/CVC4solver.hpp" #include "../include/Parser.hpp" using namespace std; using namespace arma; void PSATsolver::solve(char* inputPath, bool v) { Parser problem(inputPath); solve(problem.getN(), problem.getProbs(), problem.getClauses(), v); } void PSATsolver::solve(int n, vector<double> prob, vector<vector<int>> clauses, bool v) { vector<double> cleaned; vector<int> extra; cleaned.push_back(1); for(int i = 0; i < prob.size(); i++) if(prob[i] == -1) extra.push_back(i); else cleaned.push_back(prob[i]); mat c = ones<mat>(n,1); mat B = eye<mat>(n,n); mat p = vectorToMat(cleaned); mat pi = p; mat z = c.t()*pi; if(v) { cout << "c:\n" << c << "\n"; cout << "B:\n" << B << "\n"; cout << "p:\n" << p << "\n"; cout << "pi:\n" << pi << "\n"; cout << "c*pi:" << z(0,0) << "\n"; } int count = 0; double min = 1; while(z(0,0) > 0.00000001) { vector<double> coeffs = matToVector(c.t()*B.i()); if(v) cout << z << "\n"; vector<int> sol = CVC4Solver::solve(coeffs, extra, clauses, n-1); if(sol[0] == 0) { cout << "Unsat" << "\n"; if(v) cout << count << " iterações\n"; return; } mat teste = (c.t()*B.i())*vectorToMat(sol); if (teste(0,0) < min) min = teste(0,0); if(v) cout << "min: " << min << "\n"; pivoting(B, pi, c, vectorToMat(sol), p, v); z = c.t()*pi; count++; } mat onlyones = ones<mat>(n,1); if(v) { cout << "c:\n" << c << "\n"; cout << "p:\n" << p << "\n"; cout << "c*pi:\n" << z(0,0) << "\n"; cout << "tem que ser 1: " << onlyones.t()*pi << "\n"; cout << "tem que ser p:\n" << B*pi << "\n"; cout << count << " iterações\n"; } cout << "B:\n" << B << "\n"; cout << "pi:\n" << pi << "\n"; } vector<double> PSATsolver::matToVector(mat A) { vector<double> v; for(int i = 0; i < A.n_cols; i++) { int temp; if(A(0,i) >= 0) temp = A(0,i)*100000; else temp = ceil(A(0,i)*100000); v.push_back(temp/10000000.0); } return v; } mat PSATsolver::vectorToMat(vector<int>& v) { mat A(v.size(), 1); for(int i = 0; i < A.n_rows; i++) { A(i,0) = v[i]; } return A; } mat PSATsolver::vectorToMat(vector<double>& v) { mat A(v.size(), 1); for(int i = 0; i < A.n_rows; i++) { A(i,0) = v[i]; } return A; } void PSATsolver::pivoting(mat& B, mat& pi, mat& c, mat Aj, mat p, bool v) { double min = 2; int minIndex = -1; mat Xj = B.i()*Aj; for(int i = 0; i < Xj.n_rows; i++) { if(Xj(i,0) > 0.000001 && pi(i,0)/Xj(i,0) < min) { min = pi(i,0)/Xj(i,0); minIndex = i; } } B.insert_cols(minIndex, Aj); B.shed_col(minIndex+1); c(minIndex,0) = 0; if(v) cout << "B:\n" << B << "\n"; if(arma::rank(B) < B.n_cols) { cout << "Caso degenerado" << "\n"; exit(-1); } pi = B.i()*p; } <commit_msg>Now the solve function returns the information<commit_after>#include <iostream> #include <math.h> #include <sys/times.h> #include "../include/PSATsolver.hpp" #include "../include/CVC4solver.hpp" #include "../include/Parser.hpp" using namespace std; using namespace arma; int PSATsolver::solve(int**& m, vector<double>& prob, double* time, char* inputPath, bool v) { Parser problem(inputPath); prob = problem.getProbs(); return solve(m, prob, time, problem.getClauses(), v); } int PSATsolver::solve(int**& m, vector<double>& prob, double* time, vector<vector<int>> clauses, bool v) { struct tms tmsstart, tmsend; clock_t start, end; if ((start = times(&tmsstart)) == -1) cout << "times error" << endl; vector<double> cleaned; vector<int> extra; cleaned.push_back(1); for(int i = 0; i < prob.size(); i++) if(prob[i] == -1) extra.push_back(i); else cleaned.push_back(prob[i]); int n = cleaned.size(); mat c = ones<mat>(n,1); mat B = eye<mat>(n,n); mat p = vectorToMat(cleaned); mat pi = p; mat z = c.t()*pi; if(v) { cout << "c:\n" << c << "\n"; cout << "B:\n" << B << "\n"; cout << "p:\n" << p << "\n"; cout << "pi:\n" << pi << "\n"; cout << "c*pi:" << z(0,0) << "\n"; } int count = 0; double min = 1; while(z(0,0) > 0.00000001) { vector<double> coeffs = matToVector(c.t()*B.i()); if(v) cout << z << "\n"; vector<int> sol = CVC4Solver::solve(coeffs, extra, clauses, n-1); if(sol[0] == 0) { cout << "Unsat" << "\n"; if(v) cout << count << " iterações\n"; return 0; } mat teste = (c.t()*B.i())*vectorToMat(sol); if (teste(0,0) < min) min = teste(0,0); if(v) cout << "min: " << min << "\n"; pivoting(B, pi, c, vectorToMat(sol), p, v); z = c.t()*pi; count++; } mat onlyones = ones<mat>(n,1); if(v) { cout << "c:\n" << c << "\n"; cout << "p:\n" << p << "\n"; cout << "c*pi:\n" << z(0,0) << "\n"; cout << "tem que ser 1: " << onlyones.t()*pi << "\n"; cout << "tem que ser p:\n" << B*pi << "\n"; cout << count << " iterações\n"; cout << "B:\n" << B << "\n"; cout << "pi:\n" << pi << "\n"; } int** matrix = makeMatrix(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) matrix[i][j] = B(i,j); m = matrix; if ((end = times(&tmsend)) == -1) cout << "times error" << endl; static long clktck = 0; if ((clktck = sysconf(_SC_CLK_TCK)) < 0) cout << "sysconf error" << endl; *time = ((tmsend.tms_utime - tmsstart.tms_utime) / (double) clktck); return n; } vector<double> PSATsolver::matToVector(mat A) { vector<double> v; for(int i = 0; i < A.n_cols; i++) { int temp; if(A(0,i) >= 0) temp = A(0,i)*100000; else temp = ceil(A(0,i)*100000); v.push_back(temp/10000000.0); } return v; } mat PSATsolver::vectorToMat(vector<int>& v) { mat A(v.size(), 1); for(int i = 0; i < A.n_rows; i++) { A(i,0) = v[i]; } return A; } mat PSATsolver::vectorToMat(vector<double>& v) { mat A(v.size(), 1); for(int i = 0; i < A.n_rows; i++) { A(i,0) = v[i]; } return A; } int** PSATsolver::makeMatrix(int n) { int** matrix = (int**) malloc((sizeof (int*)) * n); for(int i = 0; i < n; i ++) matrix[i] = (int*) malloc((sizeof (int)) * n); return matrix; } void PSATsolver::pivoting(mat& B, mat& pi, mat& c, mat Aj, mat p, bool v) { double min = 2; int minIndex = -1; mat Xj = B.i()*Aj; for(int i = 0; i < Xj.n_rows; i++) { if(Xj(i,0) > 0.000001 && pi(i,0)/Xj(i,0) < min) { min = pi(i,0)/Xj(i,0); minIndex = i; } } B.insert_cols(minIndex, Aj); B.shed_col(minIndex+1); c(minIndex,0) = 0; if(v) cout << "B:\n" << B << "\n"; if(arma::rank(B) < B.n_cols) { cout << "Caso degenerado" << "\n"; exit(-1); } pi = B.i()*p; } <|endoftext|>
<commit_before>/* Copyright (C) 2010 Collabora Multimedia. @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "query.h" #include "element.h" #include "../QGlib/error.h" #include "../QGlib/string_p.h" #include <QtCore/QUrl> #include <QtCore/QDebug> #include <gst/gst.h> namespace QGst { QString Query::typeName() const { return QString::fromUtf8(GST_QUERY_TYPE_NAME(object<GstQuery>())); } QueryType Query::type() const { return static_cast<QueryType>(GST_QUERY_TYPE(object<GstQuery>())); } const StructurePtr Query::internalStructure() { const GstStructure *structure = gst_query_get_structure(object<GstQuery>()); return SharedStructure::fromMiniObject(const_cast<GstStructure *>(structure), MiniObjectPtr(this)); } //******************************************************** PositionQueryPtr PositionQuery::create(Format format) { return PositionQueryPtr::wrap(gst_query_new_position(static_cast<GstFormat>(format)), false); } Format PositionQuery::format() const { GstFormat f; gst_query_parse_position(object<GstQuery>(), &f, NULL); return static_cast<Format>(f); } qint64 PositionQuery::position() const { gint64 p; gst_query_parse_position(object<GstQuery>(), NULL, &p); return p; } void PositionQuery::setValues(Format format, qint64 position) { gst_query_set_position(object<GstQuery>(), static_cast<GstFormat>(format), position); } //******************************************************** DurationQueryPtr DurationQuery::create(Format format) { return DurationQueryPtr::wrap(gst_query_new_duration(static_cast<GstFormat>(format)), false); } Format DurationQuery::format() const { GstFormat f; gst_query_parse_duration(object<GstQuery>(), &f, NULL); return static_cast<Format>(f); } qint64 DurationQuery::duration() const { gint64 d; gst_query_parse_duration(object<GstQuery>(), NULL, &d); return d; } void DurationQuery::setValues(Format format, qint64 duration) { gst_query_set_duration(object<GstQuery>(), static_cast<GstFormat>(format), duration); } //******************************************************** LatencyQueryPtr LatencyQuery::create() { return LatencyQueryPtr::wrap(gst_query_new_latency(), false); } bool LatencyQuery::hasLive() const { gboolean l; gst_query_parse_latency(object<GstQuery>(), &l, NULL, NULL); return l; } ClockTime LatencyQuery::minimumLatency() const { GstClockTime c; gst_query_parse_latency(object<GstQuery>(), NULL, &c, NULL); return c; } ClockTime LatencyQuery::maximumLatency() const { GstClockTime c; gst_query_parse_latency(object<GstQuery>(), NULL, NULL, &c); return c; } void LatencyQuery::setValues(bool live, ClockTime minimumLatency, ClockTime maximumLatency) { gst_query_set_latency(object<GstQuery>(), live, minimumLatency, maximumLatency); } //******************************************************** SeekingQueryPtr SeekingQuery::create(Format format) { return SeekingQueryPtr::wrap(gst_query_new_seeking(static_cast<GstFormat>(format)), false); } Format SeekingQuery::format() const { GstFormat f; gst_query_parse_seeking(object<GstQuery>(), &f, NULL, NULL, NULL); return static_cast<Format>(f); } bool SeekingQuery::seekable() const { gboolean s; gst_query_parse_seeking(object<GstQuery>(), NULL, &s, NULL, NULL); return s; } qint64 SeekingQuery::segmentStart() const { gint64 s; gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, &s, NULL); return s; } qint64 SeekingQuery::segmentEnd() const { gint64 s; gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, NULL, &s); return s; } void SeekingQuery::setValues(Format format, bool seekable, qint64 segmentStart, qint64 segmentEnd) { gst_query_set_seeking(object<GstQuery>(), static_cast<GstFormat>(format), seekable, segmentStart, segmentEnd); } //******************************************************** SegmentQueryPtr SegmentQuery::create(Format format) { return SegmentQueryPtr::wrap(gst_query_new_segment(static_cast<GstFormat>(format)), false); } double SegmentQuery::rate() const { gdouble r; gst_query_parse_segment(object<GstQuery>(), &r, NULL, NULL, NULL); return r; } Format SegmentQuery::format() const { GstFormat f; gst_query_parse_segment(object<GstQuery>(), NULL, &f, NULL, NULL); return static_cast<Format>(f); } qint64 SegmentQuery::startValue() const { gint64 s; gst_query_parse_segment(object<GstQuery>(), NULL, NULL, &s, NULL); return s; } qint64 SegmentQuery::stopValue() const { gint64 s; gst_query_parse_segment(object<GstQuery>(), NULL, NULL, NULL, &s); return s; } void SegmentQuery::setValues(Format format, double rate, qint64 startValue, qint64 stopValue) { gst_query_set_segment(object<GstQuery>(), rate, static_cast<GstFormat>(format), startValue, stopValue); } //******************************************************** ConvertQueryPtr ConvertQuery::create(Format sourceFormat, qint64 value, Format destinationFormat) { return ConvertQueryPtr::wrap(gst_query_new_convert(static_cast<GstFormat>(sourceFormat), value, static_cast<GstFormat>(destinationFormat)), false); } Format ConvertQuery::sourceFormat() const { GstFormat f; gst_query_parse_convert(object<GstQuery>(), &f, NULL, NULL, NULL); return static_cast<Format>(f); } qint64 ConvertQuery::sourceValue() const { gint64 v; gst_query_parse_convert(object<GstQuery>(), NULL, &v, NULL, NULL); return v; } Format ConvertQuery::destinationFormat() const { GstFormat f; gst_query_parse_convert(object<GstQuery>(), NULL, NULL, &f, NULL); return static_cast<Format>(f); } qint64 ConvertQuery::destinationValue() const { gint64 v; gst_query_parse_convert(object<GstQuery>(), NULL, NULL, NULL, &v); return v; } void ConvertQuery::setValues(Format sourceFormat, qint64 sourceValue, Format destinationFormat, qint64 destinationValue) { gst_query_set_convert(object<GstQuery>(), static_cast<GstFormat>(sourceFormat), sourceValue, static_cast<GstFormat>(destinationFormat), destinationValue); } //******************************************************** FormatsQueryPtr FormatsQuery::create() { return FormatsQueryPtr::wrap(gst_query_new_formats(), false); } QList<Format> FormatsQuery::formats() const { guint cnt; QList<Format> formats; gst_query_parse_formats_length(object<GstQuery>(), &cnt); GstFormat f; for (uint i=0; i<cnt; i++) { gst_query_parse_formats_nth(object<GstQuery>(), i, &f); formats << static_cast<Format>(f); } return formats; } void FormatsQuery::setFormats(const QList<Format> & formats) { int cnt = formats.count(); if (cnt==0) return; GstFormat *f = new GstFormat[cnt]; for (int i=0; i<cnt; i++) { f[i] = static_cast<GstFormat>(formats.at(i)); } gst_query_set_formatsv(object<GstQuery>(), cnt, f); delete [] f; } //******************************************************** BufferingQueryPtr BufferingQuery::create(Format format) { return BufferingQueryPtr::wrap(gst_query_new_buffering(static_cast<GstFormat>(format)), false); } bool BufferingQuery::isBusy() const { gboolean b; gst_query_parse_buffering_percent(object<GstQuery>(), &b, NULL); return b; } int BufferingQuery::percent() const { gint p; gst_query_parse_buffering_percent(object<GstQuery>(), NULL, &p); return p; } void BufferingQuery::setBufferingPercent(bool busy, int percent) { gst_query_set_buffering_percent(object<GstQuery>(), busy, percent); } BufferingMode BufferingQuery::mode() const { GstBufferingMode m; gst_query_parse_buffering_stats(object<GstQuery>(), &m, NULL, NULL, NULL); return static_cast<BufferingMode>(m); } int BufferingQuery::averageIn() const { gint a; gst_query_parse_buffering_stats(object<GstQuery>(), NULL, &a, NULL, NULL); return a; } int BufferingQuery::averageOut() const { gint a; gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, &a, NULL); return a; } qint64 BufferingQuery::bufferingLeft() const { gint64 l; gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, NULL, &l); return l; } ; void BufferingQuery::setBufferingStats(BufferingMode mode, int averageIn, int averageOut, qint64 bufferingLeft) { gst_query_set_buffering_stats(object<GstQuery>(), static_cast<GstBufferingMode>(mode), averageIn, averageOut, bufferingLeft); } Format BufferingQuery::rangeFormat() const { GstFormat f; gst_query_parse_buffering_range(object<GstQuery>(), &f, NULL, NULL, NULL); return static_cast<Format>(f); } qint64 BufferingQuery::rangeStart() const { gint64 r; gst_query_parse_buffering_range(object<GstQuery>(), NULL, &r, NULL, NULL); return r; } qint64 BufferingQuery::rangeStop() const { gint64 r; gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, &r, NULL); return r; } qint64 BufferingQuery::estimatedTotal() const { gint64 r; gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, NULL, &r); return r; } void BufferingQuery::setBufferingRange(Format rangeFormat, qint64 rangeStart, qint64 rangeStop, qint64 estimatedTotal) { gst_query_set_buffering_range(object<GstQuery>(), static_cast<GstFormat>(rangeFormat), rangeStart, rangeStop, estimatedTotal); } //******************************************************** UriQueryPtr UriQuery::create() { return UriQueryPtr::wrap(gst_query_new_uri(), false); } QUrl UriQuery::uri() const { gchar *uri; gst_query_parse_uri(object<GstQuery>(), &uri); return QUrl::fromPercentEncoding(uri); } void UriQuery::setUri(const QUrl & uri) { gst_query_set_uri(object<GstQuery>(), uri.toEncoded()); } } //namespace QGst <commit_msg>src/QGst/query.cpp rename functions<commit_after>/* Copyright (C) 2010 Collabora Multimedia. @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "query.h" #include "element.h" #include "../QGlib/error.h" #include "../QGlib/string_p.h" #include <QtCore/QUrl> #include <QtCore/QDebug> #include <gst/gst.h> namespace QGst { QString Query::typeName() const { return QString::fromUtf8(GST_QUERY_TYPE_NAME(object<GstQuery>())); } QueryType Query::type() const { return static_cast<QueryType>(GST_QUERY_TYPE(object<GstQuery>())); } const StructurePtr Query::internalStructure() { const GstStructure *structure = gst_query_get_structure(object<GstQuery>()); return SharedStructure::fromMiniObject(const_cast<GstStructure *>(structure), MiniObjectPtr(this)); } //******************************************************** PositionQueryPtr PositionQuery::create(Format format) { return PositionQueryPtr::wrap(gst_query_new_position(static_cast<GstFormat>(format)), false); } Format PositionQuery::format() const { GstFormat f; gst_query_parse_position(object<GstQuery>(), &f, NULL); return static_cast<Format>(f); } qint64 PositionQuery::position() const { gint64 p; gst_query_parse_position(object<GstQuery>(), NULL, &p); return p; } void PositionQuery::setValues(Format format, qint64 position) { gst_query_set_position(object<GstQuery>(), static_cast<GstFormat>(format), position); } //******************************************************** DurationQueryPtr DurationQuery::create(Format format) { return DurationQueryPtr::wrap(gst_query_new_duration(static_cast<GstFormat>(format)), false); } Format DurationQuery::format() const { GstFormat f; gst_query_parse_duration(object<GstQuery>(), &f, NULL); return static_cast<Format>(f); } qint64 DurationQuery::duration() const { gint64 d; gst_query_parse_duration(object<GstQuery>(), NULL, &d); return d; } void DurationQuery::setValues(Format format, qint64 duration) { gst_query_set_duration(object<GstQuery>(), static_cast<GstFormat>(format), duration); } //******************************************************** LatencyQueryPtr LatencyQuery::create() { return LatencyQueryPtr::wrap(gst_query_new_latency(), false); } bool LatencyQuery::hasLive() const { gboolean l; gst_query_parse_latency(object<GstQuery>(), &l, NULL, NULL); return l; } ClockTime LatencyQuery::minimumLatency() const { GstClockTime c; gst_query_parse_latency(object<GstQuery>(), NULL, &c, NULL); return c; } ClockTime LatencyQuery::maximumLatency() const { GstClockTime c; gst_query_parse_latency(object<GstQuery>(), NULL, NULL, &c); return c; } void LatencyQuery::setValues(bool live, ClockTime minimumLatency, ClockTime maximumLatency) { gst_query_set_latency(object<GstQuery>(), live, minimumLatency, maximumLatency); } //******************************************************** SeekingQueryPtr SeekingQuery::create(Format format) { return SeekingQueryPtr::wrap(gst_query_new_seeking(static_cast<GstFormat>(format)), false); } Format SeekingQuery::format() const { GstFormat f; gst_query_parse_seeking(object<GstQuery>(), &f, NULL, NULL, NULL); return static_cast<Format>(f); } bool SeekingQuery::seekable() const { gboolean s; gst_query_parse_seeking(object<GstQuery>(), NULL, &s, NULL, NULL); return s; } qint64 SeekingQuery::segmentStart() const { gint64 s; gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, &s, NULL); return s; } qint64 SeekingQuery::segmentEnd() const { gint64 s; gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, NULL, &s); return s; } void SeekingQuery::setValues(Format format, bool seekable, qint64 segmentStart, qint64 segmentEnd) { gst_query_set_seeking(object<GstQuery>(), static_cast<GstFormat>(format), seekable, segmentStart, segmentEnd); } //******************************************************** SegmentQueryPtr SegmentQuery::create(Format format) { return SegmentQueryPtr::wrap(gst_query_new_segment(static_cast<GstFormat>(format)), false); } double SegmentQuery::rate() const { gdouble r; gst_query_parse_segment(object<GstQuery>(), &r, NULL, NULL, NULL); return r; } Format SegmentQuery::format() const { GstFormat f; gst_query_parse_segment(object<GstQuery>(), NULL, &f, NULL, NULL); return static_cast<Format>(f); } qint64 SegmentQuery::startValue() const { gint64 s; gst_query_parse_segment(object<GstQuery>(), NULL, NULL, &s, NULL); return s; } qint64 SegmentQuery::stopValue() const { gint64 s; gst_query_parse_segment(object<GstQuery>(), NULL, NULL, NULL, &s); return s; } void SegmentQuery::setValues(Format format, double rate, qint64 startValue, qint64 stopValue) { gst_query_set_segment(object<GstQuery>(), rate, static_cast<GstFormat>(format), startValue, stopValue); } //******************************************************** ConvertQueryPtr ConvertQuery::create(Format sourceFormat, qint64 value, Format destinationFormat) { return ConvertQueryPtr::wrap(gst_query_new_convert(static_cast<GstFormat>(sourceFormat), value, static_cast<GstFormat>(destinationFormat)), false); } Format ConvertQuery::sourceFormat() const { GstFormat f; gst_query_parse_convert(object<GstQuery>(), &f, NULL, NULL, NULL); return static_cast<Format>(f); } qint64 ConvertQuery::sourceValue() const { gint64 v; gst_query_parse_convert(object<GstQuery>(), NULL, &v, NULL, NULL); return v; } Format ConvertQuery::destinationFormat() const { GstFormat f; gst_query_parse_convert(object<GstQuery>(), NULL, NULL, &f, NULL); return static_cast<Format>(f); } qint64 ConvertQuery::destinationValue() const { gint64 v; gst_query_parse_convert(object<GstQuery>(), NULL, NULL, NULL, &v); return v; } void ConvertQuery::setValues(Format sourceFormat, qint64 sourceValue, Format destinationFormat, qint64 destinationValue) { gst_query_set_convert(object<GstQuery>(), static_cast<GstFormat>(sourceFormat), sourceValue, static_cast<GstFormat>(destinationFormat), destinationValue); } //******************************************************** FormatsQueryPtr FormatsQuery::create() { return FormatsQueryPtr::wrap(gst_query_new_formats(), false); } QList<Format> FormatsQuery::formats() const { guint cnt; QList<Format> formats; gst_query_parse_n_formats(object<GstQuery>(), &cnt); GstFormat f; for (uint i=0; i<cnt; i++) { gst_query_parse_nth_format(object<GstQuery>(), i, &f); formats << static_cast<Format>(f); } return formats; } void FormatsQuery::setFormats(const QList<Format> & formats) { int cnt = formats.count(); if (cnt==0) return; GstFormat *f = new GstFormat[cnt]; for (int i=0; i<cnt; i++) { f[i] = static_cast<GstFormat>(formats.at(i)); } gst_query_set_formatsv(object<GstQuery>(), cnt, f); delete [] f; } //******************************************************** BufferingQueryPtr BufferingQuery::create(Format format) { return BufferingQueryPtr::wrap(gst_query_new_buffering(static_cast<GstFormat>(format)), false); } bool BufferingQuery::isBusy() const { gboolean b; gst_query_parse_buffering_percent(object<GstQuery>(), &b, NULL); return b; } int BufferingQuery::percent() const { gint p; gst_query_parse_buffering_percent(object<GstQuery>(), NULL, &p); return p; } void BufferingQuery::setBufferingPercent(bool busy, int percent) { gst_query_set_buffering_percent(object<GstQuery>(), busy, percent); } BufferingMode BufferingQuery::mode() const { GstBufferingMode m; gst_query_parse_buffering_stats(object<GstQuery>(), &m, NULL, NULL, NULL); return static_cast<BufferingMode>(m); } int BufferingQuery::averageIn() const { gint a; gst_query_parse_buffering_stats(object<GstQuery>(), NULL, &a, NULL, NULL); return a; } int BufferingQuery::averageOut() const { gint a; gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, &a, NULL); return a; } qint64 BufferingQuery::bufferingLeft() const { gint64 l; gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, NULL, &l); return l; } ; void BufferingQuery::setBufferingStats(BufferingMode mode, int averageIn, int averageOut, qint64 bufferingLeft) { gst_query_set_buffering_stats(object<GstQuery>(), static_cast<GstBufferingMode>(mode), averageIn, averageOut, bufferingLeft); } Format BufferingQuery::rangeFormat() const { GstFormat f; gst_query_parse_buffering_range(object<GstQuery>(), &f, NULL, NULL, NULL); return static_cast<Format>(f); } qint64 BufferingQuery::rangeStart() const { gint64 r; gst_query_parse_buffering_range(object<GstQuery>(), NULL, &r, NULL, NULL); return r; } qint64 BufferingQuery::rangeStop() const { gint64 r; gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, &r, NULL); return r; } qint64 BufferingQuery::estimatedTotal() const { gint64 r; gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, NULL, &r); return r; } void BufferingQuery::setBufferingRange(Format rangeFormat, qint64 rangeStart, qint64 rangeStop, qint64 estimatedTotal) { gst_query_set_buffering_range(object<GstQuery>(), static_cast<GstFormat>(rangeFormat), rangeStart, rangeStop, estimatedTotal); } //******************************************************** UriQueryPtr UriQuery::create() { return UriQueryPtr::wrap(gst_query_new_uri(), false); } QUrl UriQuery::uri() const { gchar *uri; gst_query_parse_uri(object<GstQuery>(), &uri); return QUrl::fromPercentEncoding(uri); } void UriQuery::setUri(const QUrl & uri) { gst_query_set_uri(object<GstQuery>(), uri.toEncoded()); } } //namespace QGst <|endoftext|>
<commit_before> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <libclientserver.h> ServerUnix::ServerUnix(const std::string &path) { Init(); m_path = path; } ServerUnix::ServerUnix(const std::string &path, mode_t perms) { Init(); m_path = path; m_perms = perms; } ServerUnix::~ServerUnix() { if (IsRunning()) abort(); //Attempted to remove an active server } void ServerUnix::Init() { m_backlog = 32; m_perms = S_IRUSR | S_IWUSR; m_fd = -1; m_quit = true; } void ServerUnix::Start(ServerManager *Manager) { struct sockaddr_un addr; size_t addr_len = sizeof(addr); unlink(m_path.c_str()); m_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (m_fd < 0) { std::string err = strerror(errno); //Logger("ServerUnix::Start() -> socket: %s", strerror(errno)); throw(err); } memset(&addr, addr_len, 0); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", m_path.c_str()); if(bind(m_fd, (struct sockaddr *) &addr, addr_len) < 0) { std::string err = strerror(errno); //Logger("ServerUnix::Start() -> bind: %s", strerror(errno)); if (close(m_fd) < 0) abort(); throw(err); } if (chmod(m_path.c_str(), m_perms) < 0) { std::string err = strerror(errno); throw(err); } if(listen(m_fd, m_backlog) < 0) { std::string err = strerror(errno); //Logger("ServerUnix::Start() -> listen: %s", strerror(errno)); if (close(m_fd) < 0) abort(); throw(err); } m_manager = Manager; m_quit = false; Thread::Start(); } void ServerUnix::Stop() { m_quit = true; m_manager = NULL; Thread::Stop(); } void ServerUnix::Run() { while(m_quit == false) { fd_set fds; struct sockaddr_un addr; struct timeval tv; socklen_t addr_len = sizeof(addr); tv.tv_sec = 1; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(m_fd, &fds); int ret = select(m_fd + 1, &fds, NULL, NULL, &tv); if (ret < 0) { switch(errno) { case EINTR: case ETIMEDOUT: continue; break; default: abort(); } } if (FD_ISSET(m_fd, &fds)) { int fd = accept(m_fd, (struct sockaddr *) &addr, &addr_len); if (fd < 0) continue; m_manager->RaisePreNewConnection(); ServerUnixConnection *Connection = new ServerUnixConnection(m_manager, this, fd); Connection->Start(); } } if (close(m_fd) < 0) abort(); } <commit_msg>Added a FIXME<commit_after> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <libclientserver.h> ServerUnix::ServerUnix(const std::string &path) { Init(); m_path = path; } ServerUnix::ServerUnix(const std::string &path, mode_t perms) { Init(); m_path = path; m_perms = perms; } ServerUnix::~ServerUnix() { if (IsRunning()) abort(); //Attempted to remove an active server } void ServerUnix::Init() { m_backlog = 32; m_perms = S_IRUSR | S_IWUSR; m_fd = -1; m_quit = true; } void ServerUnix::Start(ServerManager *Manager) { struct sockaddr_un addr; size_t addr_len = sizeof(addr); unlink(m_path.c_str()); m_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (m_fd < 0) { std::string err = strerror(errno); //Logger("ServerUnix::Start() -> socket: %s", strerror(errno)); throw(err); } memset(&addr, addr_len, 0); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", m_path.c_str()); if(bind(m_fd, (struct sockaddr *) &addr, addr_len) < 0) { std::string err = strerror(errno); //Logger("ServerUnix::Start() -> bind: %s", strerror(errno)); if (close(m_fd) < 0) abort(); throw(err); } if (chmod(m_path.c_str(), m_perms) < 0) { std::string err = strerror(errno); throw(err); } if(listen(m_fd, m_backlog) < 0) { std::string err = strerror(errno); //Logger("ServerUnix::Start() -> listen: %s", strerror(errno)); if (close(m_fd) < 0) abort(); throw(err); } m_manager = Manager; m_quit = false; Thread::Start(); } void ServerUnix::Stop() { m_quit = true; m_manager = NULL; Thread::Stop(); } void ServerUnix::Run() { while(m_quit == false) { fd_set fds; struct sockaddr_un addr; struct timeval tv; socklen_t addr_len = sizeof(addr); tv.tv_sec = 1; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(m_fd, &fds); int ret = select(m_fd + 1, &fds, NULL, NULL, &tv); if (ret < 0) { switch(errno) { case EINTR: case ETIMEDOUT: continue; break; default: abort(); } } if (FD_ISSET(m_fd, &fds)) { int fd = accept(m_fd, (struct sockaddr *) &addr, &addr_len); if (fd < 0) continue; //FIXME: Find a way to turn off SIGPIPE on fd m_manager->RaisePreNewConnection(); ServerUnixConnection *Connection = new ServerUnixConnection(m_manager, this, fd); Connection->Start(); } } if (close(m_fd) < 0) abort(); } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] 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 "ShareLogger.h" #include "Common.h" #include "Stratum.h" #include "Utils.h" #include "utilities_js.hpp" #include <algorithm> #include <string> #include <boost/algorithm/string.hpp> #include <boost/thread.hpp> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <chainparams.h> #include "BitcoinUtils.h" ////////////////////////////// ShareLogWriter /////////////////////////////// ShareLogWriter::ShareLogWriter(const char *chainType, const char *kafkaBrokers, const string &dataDir, const string &kafkaGroupID, const char *shareLogTopic) :running_(true), dataDir_(dataDir), chainType_(chainType), hlConsumer_(kafkaBrokers, shareLogTopic, 0/* patition */, kafkaGroupID) { } ShareLogWriter::~ShareLogWriter() { // close file handlers for (auto & itr : fileHandlers_) { LOG(INFO) << "fclose file handler, date: " << date("%F", itr.first); fclose(itr.second); } fileHandlers_.clear(); } void ShareLogWriter::stop() { if (!running_) return; running_ = false; } FILE* ShareLogWriter::getFileHandler(uint32_t ts) { if (fileHandlers_.find(ts) != fileHandlers_.end()) { return fileHandlers_[ts]; } const string filePath = getStatsFilePath(chainType_.c_str(), dataDir_, ts); LOG(INFO) << "fopen: " << filePath; FILE *f = fopen(filePath.c_str(), "ab"); // append mode, bin file if (f == nullptr) { LOG(FATAL) << "fopen file fail: " << filePath; return nullptr; } fileHandlers_[ts] = f; return f; } void ShareLogWriter::consumeShareLog(rd_kafka_message_t *rkmessage) { // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly return; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; } return; } if (rkmessage->len != sizeof(Share)) { LOG(ERROR) << "sharelog message size(" << rkmessage->len << ") is not: " << sizeof(Share); return; } shares_.push_back(Share()); Share *share = &(*shares_.rbegin()); memcpy((uint8_t *)share, (const uint8_t *)rkmessage->payload, rkmessage->len); if (!share->isValid()) { LOG(ERROR) << "invalid share: " << share->toString(); shares_.pop_back(); return; } } void ShareLogWriter::tryCloseOldHanders() { while (fileHandlers_.size() > 3) { // Maps (and sets) are sorted, so the first element is the smallest, // and the last element is the largest. auto itr = fileHandlers_.begin(); LOG(INFO) << "fclose file handler, date: " << date("%F", itr->first); fclose(itr->second); fileHandlers_.erase(itr); } } bool ShareLogWriter::flushToDisk() { std::set<FILE*> usedHandlers; for (const auto& share : shares_) { const uint32_t ts = share.timestamp_ - (share.timestamp_ % 86400); FILE *f = getFileHandler(ts); if (f == nullptr) return false; usedHandlers.insert(f); fwrite((uint8_t *)&share, sizeof(Share), 1, f); } shares_.clear(); for (auto & f : usedHandlers) { fflush(f); } // should call this after write data tryCloseOldHanders(); return true; } void ShareLogWriter::run() { time_t lastFlushTime = time(nullptr); const int32_t kFlushDiskInterval = 2; const int32_t kTimeoutMs = 1000; if (!hlConsumer_.setup()) { LOG(ERROR) << "setup sharelog consumer fail"; return; } while (running_) { // // flush data to disk // if (shares_.size() > 0 && time(nullptr) > kFlushDiskInterval + lastFlushTime) { flushToDisk(); lastFlushTime = time(nullptr); } // // consume message // rd_kafka_message_t *rkmessage; rkmessage = hlConsumer_.consumer(kTimeoutMs); // timeout, most of time it's not nullptr and set an error: // rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF if (rkmessage == nullptr) { continue; } // consume share log consumeShareLog(rkmessage); rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ } // flush left shares if (shares_.size() > 0) flushToDisk(); } <commit_msg>sharelogger: add some logs for debug.<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] 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 "ShareLogger.h" #include "Common.h" #include "Stratum.h" #include "Utils.h" #include "utilities_js.hpp" #include <algorithm> #include <string> #include <boost/algorithm/string.hpp> #include <boost/thread.hpp> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <chainparams.h> #include "BitcoinUtils.h" ////////////////////////////// ShareLogWriter /////////////////////////////// ShareLogWriter::ShareLogWriter(const char *chainType, const char *kafkaBrokers, const string &dataDir, const string &kafkaGroupID, const char *shareLogTopic) :running_(true), dataDir_(dataDir), chainType_(chainType), hlConsumer_(kafkaBrokers, shareLogTopic, 0/* patition */, kafkaGroupID) { } ShareLogWriter::~ShareLogWriter() { // close file handlers for (auto & itr : fileHandlers_) { LOG(INFO) << "fclose file handler, date: " << date("%F", itr.first); fclose(itr.second); } fileHandlers_.clear(); } void ShareLogWriter::stop() { if (!running_) return; running_ = false; } FILE* ShareLogWriter::getFileHandler(uint32_t ts) { if (fileHandlers_.find(ts) != fileHandlers_.end()) { return fileHandlers_[ts]; } const string filePath = getStatsFilePath(chainType_.c_str(), dataDir_, ts); LOG(INFO) << "fopen: " << filePath; FILE *f = fopen(filePath.c_str(), "ab"); // append mode, bin file if (f == nullptr) { LOG(FATAL) << "fopen file fail: " << filePath; return nullptr; } fileHandlers_[ts] = f; return f; } void ShareLogWriter::consumeShareLog(rd_kafka_message_t *rkmessage) { // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly return; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; } return; } if (rkmessage->len != sizeof(Share)) { LOG(ERROR) << "sharelog message size(" << rkmessage->len << ") is not: " << sizeof(Share); return; } shares_.push_back(Share()); Share *share = &(*shares_.rbegin()); memcpy((uint8_t *)share, (const uint8_t *)rkmessage->payload, rkmessage->len); DLOG(INFO) << share->toString(); if (!share->isValid()) { LOG(ERROR) << "invalid share: " << share->toString(); shares_.pop_back(); return; } } void ShareLogWriter::tryCloseOldHanders() { while (fileHandlers_.size() > 3) { // Maps (and sets) are sorted, so the first element is the smallest, // and the last element is the largest. auto itr = fileHandlers_.begin(); LOG(INFO) << "fclose file handler, date: " << date("%F", itr->first); fclose(itr->second); fileHandlers_.erase(itr); } } bool ShareLogWriter::flushToDisk() { std::set<FILE*> usedHandlers; for (const auto& share : shares_) { const uint32_t ts = share.timestamp_ - (share.timestamp_ % 86400); FILE *f = getFileHandler(ts); if (f == nullptr) return false; usedHandlers.insert(f); fwrite((uint8_t *)&share, sizeof(Share), 1, f); } shares_.clear(); for (auto & f : usedHandlers) { fflush(f); } // should call this after write data tryCloseOldHanders(); return true; } void ShareLogWriter::run() { time_t lastFlushTime = time(nullptr); const int32_t kFlushDiskInterval = 2; const int32_t kTimeoutMs = 1000; LOG(INFO) << "setup sharelog consumer..."; if (!hlConsumer_.setup()) { LOG(ERROR) << "setup sharelog consumer fail"; return; } LOG(INFO) << "waiting sharelog messages..."; while (running_) { // // flush data to disk // if (shares_.size() > 0 && time(nullptr) > kFlushDiskInterval + lastFlushTime) { flushToDisk(); lastFlushTime = time(nullptr); } // // consume message // rd_kafka_message_t *rkmessage; rkmessage = hlConsumer_.consumer(kTimeoutMs); // timeout, most of time it's not nullptr and set an error: // rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF if (rkmessage == nullptr) { continue; } DLOG(INFO) << "a new message, size: " << rkmessage->len; // consume share log consumeShareLog(rkmessage); rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ } // flush left shares if (shares_.size() > 0) flushToDisk(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Matt Fichman * * 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, APEXPRESS 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. */ namespace coro { void Socket::connect(SocketAddr const& addr) { // Windows asynchronous connect // Initialize a bunch of Windows-specific crap needed to load a pointer to // the ConnectEx function... // Get a pointer to the ConnectEx() function. Sigh. Windows. This // function never blocks, however, so we don't have to worry about I/O // completion ports. DWORD code = SIO_GET_EXTENSION_FUNCTION_POINTER; GUID guid = WSAID_CONNECTEX; LPFN_CONNECTEX ConnectEx = 0; DWORD bytes = 0; DWORD len = sizeof(ConnectEx); WSAIoctl(sd_, code, &guid, sizeof(guid), &ConnectEx, len, &bytes, 0, 0); // To use ConnectEx, bind() must be called first to assign a port number to // the socket. struct sockaddr_in sin{0}; sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = 0; if (::bind(sd_, (struct sockaddr*)&sin, sizeof(sin)) != 0) { throw SystemError(); } // Initialize the OVERLAPPED structure that contains the user I/O data used // to resume the coroutine when ConnectEx completes. Overlapped op{0}; OVERLAPPED* evt = &op.overlapped; op.coroutine = current().get(); // Now call ConnectEx to begin connecting the socket. The call will return // immediately, allowing this function to yield to the I/O manager. sin = addr.sockaddr(); if (!ConnectEx(sd_, (struct sockaddr*)&sin, sizeof(sin), 0, 0, 0, evt)) { if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { throw SystemError(op.error); } // The following setsockopt() call is needed when calling ConectEx. From // the MSDN documentation: // // When the ConnectEx function returns TRUE, the socket s is in the default // state for a connected socket. The socket s does not enable previously // set properties or options until SO_UPDATE_CONNECT_CONTEXT is set on the // socket. Use the setsockopt function to set the SO_UPDATE_CONNECT_CONTEXT // option. if (::setsockopt(sd_, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0)) { throw SystemError(); } } Ptr<Socket> Socket::accept() { // Waits for a client to connect, then returns a pointer to the established // connection. The code below is a bit tricky, because Windows expects the // call to accept() to happen before the I/O event can be triggered. For // Unix systems, the wait happens first, and then accept() is used to // receive the incoming socket afterwards. // Create a new socket for AcceptEx to use when a peer connects. SOCKET ls = sd_; SOCKET sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sd < 0) { throw SystemError(); } // Get a pointer to the AcceptEx() function. DWORD code = SIO_GET_EXTENSION_FUNCTION_POINTER; GUID guid = WSAID_ACCEPTEX; LPFN_ACCEPTEX AcceptEx = 0; DWORD bytes = 0; DWORD len = sizeof(AcceptEx); WSAIoctl(sd, code, &guid, sizeof(guid), &AcceptEx, len, &bytes, 0, 0); // Initialize the OVERLAPPED structure that contains the user I/O data used // to resume the coroutine when AcceptEx completes. Overlapped op{0}; op.coroutine = current().get(); OVERLAPPED* evt = &op.overlapped; // Now call ConnectEx to begin accepting peer connections. The call will // return immediately, allowing this function to yield to the I/O manager. char buffer[(sizeof(struct sockaddr_in)+16)*2]; // Windows BS, apparently DWORD socklen = sizeof(struct sockaddr_in)+16; // Ditto DWORD read = 0; if (!AcceptEx(ls, sd, buffer, 0, socklen, socklen, &read, evt)) { if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { throw SystemError(op.error); } // The following setsockopt() call is needed when calling AcceptEx. From // the MSDN documentation: // // When the AcceptEx function returns, the socket sAcceptSocket is in the // default state for a connected socket. The socket sAcceptSocket does not // inherit the properties of the socket associated with sListenSocket // parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket. Use the // setsockopt function to set the SO_UPDATE_ACCEPT_CONTEXT option, // specifying sAcceptSocket as the socket handle and sListenSocket as the // option value. char const* opt = (char const*)&ls; size_t optlen = sizeof(ls); if (::setsockopt(sd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, opt, optlen)) { throw SystemError(); } return Ptr<Socket>(new Socket(sd, "")); } ssize_t Socket::read(char* buf, size_t len, int flags) { // Read from the socket asynchronously. Returns the # of bytes read. WSABUF wsabuf = { len, buf }; Overlapped op{0}; op.coroutine = current().get(); OVERLAPPED* evt = &op.overlapped; DWORD flg = flags; if(WSARecv(sd_, &wsabuf, 1, NULL, &flg, evt, NULL)) { if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { throw SystemError(op.error); } assert(op.bytes >= 0); return op.bytes; } ssize_t Socket::write(char const* buf, size_t len, int flags) { // Write to the socket asynchronously. Returns the # of bytes written. WSABUF wsabuf = { len, (LPSTR)buf }; Overlapped op{0}; op.coroutine = current().get(); OVERLAPPED* evt = &op.overlapped; if(WSASend(sd_, &wsabuf, 1, NULL, flags, evt, NULL)) { if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { throw SystemError(op.error); } assert(op.bytes >= 0); return op.bytes; } } <commit_msg>Better socket error handling<commit_after>/* * Copyright (c) 2013 Matt Fichman * * 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, APEXPRESS 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. */ namespace coro { void Socket::connect(SocketAddr const& addr) { // Windows asynchronous connect // Initialize a bunch of Windows-specific crap needed to load a pointer to // the ConnectEx function... // Get a pointer to the ConnectEx() function. Sigh. Windows. This // function never blocks, however, so we don't have to worry about I/O // completion ports. DWORD code = SIO_GET_EXTENSION_FUNCTION_POINTER; GUID guid = WSAID_CONNECTEX; LPFN_CONNECTEX ConnectEx = 0; DWORD bytes = 0; DWORD len = sizeof(ConnectEx); WSAIoctl(sd_, code, &guid, sizeof(guid), &ConnectEx, len, &bytes, 0, 0); // To use ConnectEx, bind() must be called first to assign a port number to // the socket. struct sockaddr_in sin{0}; sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = 0; if (::bind(sd_, (struct sockaddr*)&sin, sizeof(sin)) != 0) { throw SystemError(); } // Initialize the OVERLAPPED structure that contains the user I/O data used // to resume the coroutine when ConnectEx completes. Overlapped op{0}; OVERLAPPED* evt = &op.overlapped; op.coroutine = current().get(); // Now call ConnectEx to begin connecting the socket. The call will return // immediately, allowing this function to yield to the I/O manager. sin = addr.sockaddr(); if (!ConnectEx(sd_, (struct sockaddr*)&sin, sizeof(sin), 0, 0, 0, evt)) { if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { throw SystemError(op.error); } // The following setsockopt() call is needed when calling ConectEx. From // the MSDN documentation: // // When the ConnectEx function returns TRUE, the socket s is in the default // state for a connected socket. The socket s does not enable previously // set properties or options until SO_UPDATE_CONNECT_CONTEXT is set on the // socket. Use the setsockopt function to set the SO_UPDATE_CONNECT_CONTEXT // option. if (::setsockopt(sd_, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0)) { throw SystemError(); } } Ptr<Socket> Socket::accept() { // Waits for a client to connect, then returns a pointer to the established // connection. The code below is a bit tricky, because Windows expects the // call to accept() to happen before the I/O event can be triggered. For // Unix systems, the wait happens first, and then accept() is used to // receive the incoming socket afterwards. // Create a new socket for AcceptEx to use when a peer connects. SOCKET ls = sd_; SOCKET sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sd < 0) { throw SystemError(); } // Get a pointer to the AcceptEx() function. DWORD code = SIO_GET_EXTENSION_FUNCTION_POINTER; GUID guid = WSAID_ACCEPTEX; LPFN_ACCEPTEX AcceptEx = 0; DWORD bytes = 0; DWORD len = sizeof(AcceptEx); WSAIoctl(sd, code, &guid, sizeof(guid), &AcceptEx, len, &bytes, 0, 0); // Initialize the OVERLAPPED structure that contains the user I/O data used // to resume the coroutine when AcceptEx completes. Overlapped op{0}; op.coroutine = current().get(); OVERLAPPED* evt = &op.overlapped; // Now call ConnectEx to begin accepting peer connections. The call will // return immediately, allowing this function to yield to the I/O manager. char buffer[(sizeof(struct sockaddr_in)+16)*2]; // Windows BS, apparently DWORD socklen = sizeof(struct sockaddr_in)+16; // Ditto DWORD read = 0; if (!AcceptEx(ls, sd, buffer, 0, socklen, socklen, &read, evt)) { if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { throw SystemError(op.error); } // The following setsockopt() call is needed when calling AcceptEx. From // the MSDN documentation: // // When the AcceptEx function returns, the socket sAcceptSocket is in the // default state for a connected socket. The socket sAcceptSocket does not // inherit the properties of the socket associated with sListenSocket // parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket. Use the // setsockopt function to set the SO_UPDATE_ACCEPT_CONTEXT option, // specifying sAcceptSocket as the socket handle and sListenSocket as the // option value. char const* opt = (char const*)&ls; size_t optlen = sizeof(ls); if (::setsockopt(sd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, opt, optlen)) { throw SystemError(); } return Ptr<Socket>(new Socket(sd, "")); } bool isSocketCloseError(DWORD error) { // Returns true if the given error code should be converted to a socket close // exception. switch (error) { case ERROR_NETNAME_DELETED: case ERROR_CONNECTION_ABORTED: case WSAENETRESET: case WSAECONNABORTED: case WSAECONNRESET: return true; default: return false; } } ssize_t Socket::read(char* buf, size_t len, int flags) { // Read from the socket asynchronously. Returns the # of bytes read. WSABUF wsabuf = { len, buf }; Overlapped op{0}; op.coroutine = current().get(); OVERLAPPED* evt = &op.overlapped; DWORD flg = flags; if (sd_ == -1) { throw SocketCloseException(); // Socket closed locally } if(WSARecv(sd_, &wsabuf, 1, NULL, &flg, evt, NULL)) { if (isSocketCloseError(GetLastError())) { throw SocketCloseException(); // Socket closed remotely } else if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { if (isSocketCloseError(op.error)) { throw SocketCloseException(); // Socket closed remotely during read } else { throw SystemError(op.error); } } assert(op.bytes >= 0); return op.bytes; } ssize_t Socket::write(char const* buf, size_t len, int flags) { // Write to the socket asynchronously. Returns the # of bytes written. WSABUF wsabuf = { len, (LPSTR)buf }; Overlapped op{0}; op.coroutine = current().get(); OVERLAPPED* evt = &op.overlapped; if (sd_ == -1) { throw SocketCloseException(); // Socket closed locally } if(WSASend(sd_, &wsabuf, 1, NULL, flags, evt, NULL)) { if (isSocketCloseError(GetLastError())) { throw SocketCloseException(); // Socket closed remotely } else if (ERROR_IO_PENDING != GetLastError()) { throw SystemError(); } } current()->block(); if (ERROR_SUCCESS != op.error) { if (isSocketCloseError(op.error)) { throw SocketCloseException(); // Socket closed remotely during write } else { throw SystemError(op.error); } } assert(op.bytes >= 0); return op.bytes; } } <|endoftext|>
<commit_before>//--------------------------------------------------------------- SudokuGrid.cpp #include <boost/lexical_cast.hpp> #include <numeric> #include <string> #include <stdexcept> #include "SetOperations.h" #include "SudokuGrid.h" using namespace std; const SudokuGrid::set_t SudokuGrid::EMPTY; const SudokuGrid::set_t SudokuGrid::U(makeRange(1, SudokuGrid::ORDER2 + 1)); ostream& operator<<(ostream& os, const SudokuGrid& Sdkg) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if ((col != 0) && (col % SudokuGrid::ORDER == 0)) { os << "|"; } if (!Sdkg.cellIsSolved(row, col)) { os << " . "; } else { os << " " << Sdkg._cell[row][col] << " "; } } os << endl; if ((row != SudokuGrid::ORDER2 - 1) && (row % SudokuGrid::ORDER == (SudokuGrid::ORDER - 1))) { // @TODO Remove magic number os << string(29, '-') << endl; } } os << endl; return os; } std::istream& operator>>(std::istream& is, SudokuGrid& sdkg) { int value = 0; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { is >> value; if (!sdkg.add(value, row, col)) { cerr << "ERROR for " << value << " in [" << row << "][" << col << "]" << endl; } } } return is; } void writeLatex(std::ostream& os, const SudokuGrid& sdkg) { os << "\n\\begin{sudoku}\n"; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (!sdkg.cellIsSolved(row, col)) { os << "| "; } else { os << "|" << sdkg._cell[row][col]; } } os << "|.\n"; } os << "\\end{sudoku}\n\n"; } SudokuGrid::SudokuGrid() : _numberOfCellsSolved(0) , _isSolvable(true) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { fill(_cell[row], _cell[row] + SudokuGrid::ORDER, 0); fill(_candidates[row], _candidates[row] + SudokuGrid::ORDER, U); } fill(_columnSet, _columnSet + SudokuGrid::ORDER2, U); fill(_rowSet, _rowSet + SudokuGrid::ORDER2, U); for (int row = 0; row < SudokuGrid::ORDER; ++row) { fill(_blockSet[row], _blockSet[row] + SudokuGrid::ORDER, U); } mapPointerArraysToCandidates(); } SudokuGrid::SudokuGrid(const SudokuGrid& Sdkg) : _numberOfCellsSolved(Sdkg._numberOfCellsSolved) , _isSolvable(Sdkg._isSolvable) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int column = 0; column < SudokuGrid::ORDER2; ++column) { _cell[row][column] = Sdkg._cell[row][column]; _candidates[row][column] = Sdkg._candidates[row][column]; } } copy(Sdkg._columnSet, Sdkg._columnSet + SudokuGrid::ORDER2, _columnSet); copy(Sdkg._rowSet, Sdkg._rowSet + SudokuGrid::ORDER2, _rowSet); for (int row = 0; row < SudokuGrid::ORDER; ++row) { copy(Sdkg._blockSet[row], Sdkg._blockSet[row] + SudokuGrid::ORDER, _blockSet[row]); } mapPointerArraysToCandidates(); } SudokuGrid& SudokuGrid::operator=(const SudokuGrid& sdkg) { if (this != &sdkg) { _numberOfCellsSolved = sdkg._numberOfCellsSolved; _isSolvable = sdkg._isSolvable; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int column = 0; column < SudokuGrid::ORDER2; ++column) { _cell[row][column] = sdkg._cell[row][column]; _candidates[row][column] = sdkg._candidates[row][column]; } } copy(sdkg._columnSet, sdkg._columnSet + SudokuGrid::ORDER2, _columnSet); copy(sdkg._rowSet, sdkg._rowSet + SudokuGrid::ORDER2, _rowSet); for (int row = 0; row < SudokuGrid::ORDER; ++row) { for (int column = 0; column < SudokuGrid::ORDER; ++column) { _blockSet[row][column] = sdkg._blockSet[row][column]; } } mapPointerArraysToCandidates(); } return *this; } bool SudokuGrid::add(unsigned short value, int row, int column) { bool isAdded = false; if (isAnElementOf(value, SudokuGrid::U)) { //cout << "-- Add: " << Value << " in [" << Row << "][" << Column << "]" << endl; if (isAnElementOf(value, _columnSet[column]) && isAnElementOf(value, _rowSet[row]) && isAnElementOf(value, _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER])) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER].erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; isAdded = true; ++_numberOfCellsSolved; } else { throw std::logic_error("-- Sudoku elements must be in the range " "[0," + boost::lexical_cast<std::string>(int(SudokuGrid::ORDER2)) + "]"); } } else { if (value != 0) { throw std::logic_error("-- Sudoku element: " + boost::lexical_cast<std::string>(value) + " must be in the range " "[0," + boost::lexical_cast<std::string>(int(SudokuGrid::ORDER2)) + "]"); } _cell[row][column] = 0; isAdded = true; } return isAdded; } void SudokuGrid::unsafeAdd(unsigned short value, int row, int column) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER].erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; if (value != 0) { ++_numberOfCellsSolved; } } //-------------------------------------------------------------------------------------------------- void SudokuGrid::calculateAllCellCandidates() { for (int row = 0; row < SudokuGrid::ORDER2 && _isSolvable; ++row) { for (int col = 0; col < SudokuGrid::ORDER2 && _isSolvable; ++col) { if (!cellIsSolved(row, col)) { _candidates[row][col] = calculateCellCandidates(row, col); if (_candidates[row][col].empty()) { _isSolvable = false; } } } } } std::set<unsigned short> SudokuGrid::calculateCellCandidates(int row, int column) const { return _columnSet[column] * _rowSet[row] * _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER]; } void SudokuGrid::mapPointerArraysToCandidates() { for (int i = 0; i < SudokuGrid::ORDER2; ++i) { for (int j = 0; j < SudokuGrid::ORDER2; ++j) { pRow[i][j] = &_candidates[i][j]; pColumn[i][j] = &_candidates[j][i]; } } for (int blockIndex = 0; blockIndex < SudokuGrid::ORDER2; ++blockIndex) { int index = 0; int starti = SudokuGrid::ORDER * (blockIndex / SudokuGrid::ORDER); int startj = SudokuGrid::ORDER * (blockIndex % SudokuGrid::ORDER); for (int i = starti; i < starti + SudokuGrid::ORDER; ++i) { for (int j = startj; j < startj + SudokuGrid::ORDER; ++j) { pBlock[blockIndex][index++] = &_candidates[i][j]; } } } } //----------------------------------------------------------- eof SudokuGrid.cpp <commit_msg>Removed BOOST code<commit_after>//--------------------------------------------------------------- SudokuGrid.cpp #include "SetOperations.h" #include "SudokuGrid.h" #include <numeric> #include <string> #include <stdexcept> using namespace std; const SudokuGrid::set_t SudokuGrid::EMPTY; const SudokuGrid::set_t SudokuGrid::U(makeRange(1, SudokuGrid::ORDER2 + 1)); ostream& operator<<(ostream& os, const SudokuGrid& Sdkg) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if ((col != 0) && (col % SudokuGrid::ORDER == 0)) { os << "|"; } if (!Sdkg.cellIsSolved(row, col)) { os << " . "; } else { os << " " << Sdkg._cell[row][col] << " "; } } os << endl; if ((row != SudokuGrid::ORDER2 - 1) && (row % SudokuGrid::ORDER == (SudokuGrid::ORDER - 1))) { // @TODO Remove magic number os << string(29, '-') << endl; } } os << endl; return os; } std::istream& operator>>(std::istream& is, SudokuGrid& sdkg) { int value = 0; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { is >> value; if (!sdkg.add(value, row, col)) { cerr << "ERROR for " << value << " in [" << row << "][" << col << "]" << endl; } } } return is; } void writeLatex(std::ostream& os, const SudokuGrid& sdkg) { os << "\n\\begin{sudoku}\n"; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int col = 0; col < SudokuGrid::ORDER2; ++col) { if (!sdkg.cellIsSolved(row, col)) { os << "| "; } else { os << "|" << sdkg._cell[row][col]; } } os << "|.\n"; } os << "\\end{sudoku}\n\n"; } SudokuGrid::SudokuGrid() : _numberOfCellsSolved(0) , _isSolvable(true) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { fill(_cell[row], _cell[row] + SudokuGrid::ORDER, 0); fill(_candidates[row], _candidates[row] + SudokuGrid::ORDER, U); } fill(_columnSet, _columnSet + SudokuGrid::ORDER2, U); fill(_rowSet, _rowSet + SudokuGrid::ORDER2, U); for (int row = 0; row < SudokuGrid::ORDER; ++row) { fill(_blockSet[row], _blockSet[row] + SudokuGrid::ORDER, U); } mapPointerArraysToCandidates(); } SudokuGrid::SudokuGrid(const SudokuGrid& Sdkg) : _numberOfCellsSolved(Sdkg._numberOfCellsSolved) , _isSolvable(Sdkg._isSolvable) { for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int column = 0; column < SudokuGrid::ORDER2; ++column) { _cell[row][column] = Sdkg._cell[row][column]; _candidates[row][column] = Sdkg._candidates[row][column]; } } copy(Sdkg._columnSet, Sdkg._columnSet + SudokuGrid::ORDER2, _columnSet); copy(Sdkg._rowSet, Sdkg._rowSet + SudokuGrid::ORDER2, _rowSet); for (int row = 0; row < SudokuGrid::ORDER; ++row) { copy(Sdkg._blockSet[row], Sdkg._blockSet[row] + SudokuGrid::ORDER, _blockSet[row]); } mapPointerArraysToCandidates(); } SudokuGrid& SudokuGrid::operator=(const SudokuGrid& sdkg) { if (this != &sdkg) { _numberOfCellsSolved = sdkg._numberOfCellsSolved; _isSolvable = sdkg._isSolvable; for (int row = 0; row < SudokuGrid::ORDER2; ++row) { for (int column = 0; column < SudokuGrid::ORDER2; ++column) { _cell[row][column] = sdkg._cell[row][column]; _candidates[row][column] = sdkg._candidates[row][column]; } } copy(sdkg._columnSet, sdkg._columnSet + SudokuGrid::ORDER2, _columnSet); copy(sdkg._rowSet, sdkg._rowSet + SudokuGrid::ORDER2, _rowSet); for (int row = 0; row < SudokuGrid::ORDER; ++row) { for (int column = 0; column < SudokuGrid::ORDER; ++column) { _blockSet[row][column] = sdkg._blockSet[row][column]; } } mapPointerArraysToCandidates(); } return *this; } bool SudokuGrid::add(unsigned short value, int row, int column) { bool isAdded = false; if (isAnElementOf(value, SudokuGrid::U)) { //cout << "-- Add: " << Value << " in [" << Row << "][" << Column << "]" << endl; if (isAnElementOf(value, _columnSet[column]) && isAnElementOf(value, _rowSet[row]) && isAnElementOf(value, _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER])) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER].erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; isAdded = true; ++_numberOfCellsSolved; } else { throw std::logic_error("-- Sudoku elements must be in the range " "[0," + to_string(SudokuGrid::ORDER2) + "]"); } } else { if (value != 0) { throw std::logic_error("-- Sudoku element: " + to_string(value) + " must be in the range " "[0," + to_string(SudokuGrid::ORDER2) + "]"); } _cell[row][column] = 0; isAdded = true; } return isAdded; } void SudokuGrid::unsafeAdd(unsigned short value, int row, int column) { _columnSet[column].erase(value); _rowSet[row].erase(value); _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER].erase(value); _candidates[row][column] = SudokuGrid::EMPTY; _cell[row][column] = value; if (value != 0) { ++_numberOfCellsSolved; } } //-------------------------------------------------------------------------------------------------- void SudokuGrid::calculateAllCellCandidates() { for (int row = 0; row < SudokuGrid::ORDER2 && _isSolvable; ++row) { for (int col = 0; col < SudokuGrid::ORDER2 && _isSolvable; ++col) { if (!cellIsSolved(row, col)) { _candidates[row][col] = calculateCellCandidates(row, col); if (_candidates[row][col].empty()) { _isSolvable = false; } } } } } std::set<unsigned short> SudokuGrid::calculateCellCandidates(int row, int column) const { return _columnSet[column] * _rowSet[row] * _blockSet[row / SudokuGrid::ORDER][column / SudokuGrid::ORDER]; } void SudokuGrid::mapPointerArraysToCandidates() { for (int i = 0; i < SudokuGrid::ORDER2; ++i) { for (int j = 0; j < SudokuGrid::ORDER2; ++j) { pRow[i][j] = &_candidates[i][j]; pColumn[i][j] = &_candidates[j][i]; } } for (int blockIndex = 0; blockIndex < SudokuGrid::ORDER2; ++blockIndex) { int index = 0; int starti = SudokuGrid::ORDER * (blockIndex / SudokuGrid::ORDER); int startj = SudokuGrid::ORDER * (blockIndex % SudokuGrid::ORDER); for (int i = starti; i < starti + SudokuGrid::ORDER; ++i) { for (int j = startj; j < startj + SudokuGrid::ORDER; ++j) { pBlock[blockIndex][index++] = &_candidates[i][j]; } } } } //----------------------------------------------------------- eof SudokuGrid.cpp <|endoftext|>
<commit_before>#include "Tensor.hpp" #include <errors.hpp> #include <initializer_list> #include <array> extern "C" mlopenStatus_t mlopenCreateTensorDescriptor( mlopenTensorDescriptor_t *tensorDesc) { return mlopen::try_([&] { mlopen::deref(tensorDesc) = new mlopenTensorDescriptor(); }); } extern "C" mlopenStatus_t mlopenSet4dTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t dataType, int n, int c, int h, int w) { return mlopen::try_([&] { std::initializer_list<int> lens = {n, c, h, w}; mlopen::deref(tensorDesc) = mlopenTensorDescriptor(dataType, lens.begin(), 4); }); } extern "C" mlopenStatus_t mlopenGet4dTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t *dataType, int *n, int *c, int *h, int *w, int *nStride, int *cStride, int *hStride, int *wStride) { return mlopen::try_([&] { mlopen::deref(dataType) = tensorDesc->GetType(); std::tie(mlopen::deref(n), mlopen::deref(c), mlopen::deref(h), mlopen::deref(w)) = tie4(tensorDesc->GetLengths()); std::tie(mlopen::deref(nStride), mlopen::deref(cStride), mlopen::deref(hStride), mlopen::deref(wStride)) = tie4(tensorDesc->GetStrides()); }); } // Internal API // MD: This should not be reqired to be exported. Temporary hack MLOPEN_EXPORT mlopenStatus_t mlopenGet4dTensorDescriptorLengths( mlopenTensorDescriptor_t tensorDesc, int *n, int *c, int *h, int *w) { return mlopen::try_([&] { std::tie(mlopen::deref(n), mlopen::deref(c), mlopen::deref(h), mlopen::deref(w)) = tie4(tensorDesc->GetLengths()); }); } // Internal API MLOPEN_EXPORT mlopenStatus_t mlopenGet4dTensorDescriptorStrides( mlopenTensorDescriptor_t tensorDesc, int *nStride, int *cStride, int *hStride, int *wStride) { return mlopen::try_([&] { std::tie(mlopen::deref(nStride), mlopen::deref(cStride), mlopen::deref(hStride), mlopen::deref(wStride)) = tie4(tensorDesc->GetStrides()); }); } // Internal API mlopenStatus_t mlopenSetTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t dataType, int nbDims, int *dimsA, int *stridesA) { return mlopen::try_([&] { if (stridesA == nullptr) { mlopen::deref(tensorDesc) = mlopenTensorDescriptor(dataType, dimsA, nbDims); } else { mlopen::deref(tensorDesc) = mlopenTensorDescriptor(dataType, dimsA, stridesA, nbDims); } }); } // Internal API int mlopenGetTensorDescriptorElementSize(mlopenTensorDescriptor_t tensorDesc) { return tensorDesc->GetElementSize(); } extern "C" mlopenStatus_t mlopenGetTensorDescriptorSize(mlopenTensorDescriptor_t tensorDesc, int* size) { return mlopen::try_([&] { mlopen::deref(size) = tensorDesc->GetSize(); }); } extern "C" mlopenStatus_t mlopenGetTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t *dataType, int *dimsA, int *stridesA) { return mlopen::try_([&] { if (dataType != nullptr) { *dataType = tensorDesc->GetType(); } if (dimsA != nullptr) { std::copy(tensorDesc->GetLengths().begin(), tensorDesc->GetLengths().end(), dimsA); } if (stridesA != nullptr) { std::copy(tensorDesc->GetStrides().begin(), tensorDesc->GetStrides().end(), stridesA); } }); } extern "C" mlopenStatus_t mlopenDestroyTensorDescriptor(mlopenTensorDescriptor_t tensorDesc) { return mlopen::try_([&] { delete tensorDesc; }); } extern "C" mlopenStatus_t mlopenTransformTensor(mlopenHandle_t handle, const void *alpha, const mlopenTensorDescriptor_t xDesc, const void *x, const void *beta, const mlopenTensorDescriptor_t yDesc, void *y) { return mlopen::try_([&] { return yDesc->TransformTensor(handle, alpha, xDesc, DataCast(x), beta, DataCast(y)); }); } extern "C" mlopenStatus_t mlopenOpTensor(mlopenHandle_t handle, mlopenTensorOp_t tensorOp, const void *alpha1, const mlopenTensorDescriptor_t aDesc, const void *A, const void *alpha2, const mlopenTensorDescriptor_t bDesc, const void *B, const void *beta, const mlopenTensorDescriptor_t cDesc, void *C) { return mlopen::try_([&] { return cDesc->OpTensor(handle, tensorOp, alpha1, aDesc, DataCast(A), alpha2, bDesc, DataCast(B), beta, DataCast(C)); }); } extern "C" mlopenStatus_t mlopenSetTensor(mlopenHandle_t handle, const mlopenTensorDescriptor_t yDesc, void *y, const void *valuePtr) { return mlopen::try_([&] { return yDesc->SetTensor(handle, DataCast(y), valuePtr); }); } extern "C" mlopenStatus_t mlopenScaleTensor(mlopenHandle_t handle, const mlopenTensorDescriptor_t yDesc, void *y, const void *alpha) { return mlopen::try_([&] { return yDesc->ScaleTensor(handle, DataCast(y), alpha); }); } <commit_msg>Added extern C to SetForwardTensorDescriptor<commit_after>#include "Tensor.hpp" #include <errors.hpp> #include <initializer_list> #include <array> extern "C" mlopenStatus_t mlopenCreateTensorDescriptor( mlopenTensorDescriptor_t *tensorDesc) { return mlopen::try_([&] { mlopen::deref(tensorDesc) = new mlopenTensorDescriptor(); }); } extern "C" mlopenStatus_t mlopenSet4dTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t dataType, int n, int c, int h, int w) { return mlopen::try_([&] { std::initializer_list<int> lens = {n, c, h, w}; mlopen::deref(tensorDesc) = mlopenTensorDescriptor(dataType, lens.begin(), 4); }); } extern "C" mlopenStatus_t mlopenGet4dTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t *dataType, int *n, int *c, int *h, int *w, int *nStride, int *cStride, int *hStride, int *wStride) { return mlopen::try_([&] { mlopen::deref(dataType) = tensorDesc->GetType(); std::tie(mlopen::deref(n), mlopen::deref(c), mlopen::deref(h), mlopen::deref(w)) = tie4(tensorDesc->GetLengths()); std::tie(mlopen::deref(nStride), mlopen::deref(cStride), mlopen::deref(hStride), mlopen::deref(wStride)) = tie4(tensorDesc->GetStrides()); }); } // Internal API // MD: This should not be reqired to be exported. Temporary hack MLOPEN_EXPORT mlopenStatus_t mlopenGet4dTensorDescriptorLengths( mlopenTensorDescriptor_t tensorDesc, int *n, int *c, int *h, int *w) { return mlopen::try_([&] { std::tie(mlopen::deref(n), mlopen::deref(c), mlopen::deref(h), mlopen::deref(w)) = tie4(tensorDesc->GetLengths()); }); } // Internal API MLOPEN_EXPORT mlopenStatus_t mlopenGet4dTensorDescriptorStrides( mlopenTensorDescriptor_t tensorDesc, int *nStride, int *cStride, int *hStride, int *wStride) { return mlopen::try_([&] { std::tie(mlopen::deref(nStride), mlopen::deref(cStride), mlopen::deref(hStride), mlopen::deref(wStride)) = tie4(tensorDesc->GetStrides()); }); } extern "C" mlopenStatus_t mlopenSetTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t dataType, int nbDims, int *dimsA, int *stridesA) { return mlopen::try_([&] { if (stridesA == nullptr) { mlopen::deref(tensorDesc) = mlopenTensorDescriptor(dataType, dimsA, nbDims); } else { mlopen::deref(tensorDesc) = mlopenTensorDescriptor(dataType, dimsA, stridesA, nbDims); } }); } // Internal API int mlopenGetTensorDescriptorElementSize(mlopenTensorDescriptor_t tensorDesc) { return tensorDesc->GetElementSize(); } extern "C" mlopenStatus_t mlopenGetTensorDescriptorSize(mlopenTensorDescriptor_t tensorDesc, int* size) { return mlopen::try_([&] { mlopen::deref(size) = tensorDesc->GetSize(); }); } extern "C" mlopenStatus_t mlopenGetTensorDescriptor( mlopenTensorDescriptor_t tensorDesc, mlopenDataType_t *dataType, int *dimsA, int *stridesA) { return mlopen::try_([&] { if (dataType != nullptr) { *dataType = tensorDesc->GetType(); } if (dimsA != nullptr) { std::copy(tensorDesc->GetLengths().begin(), tensorDesc->GetLengths().end(), dimsA); } if (stridesA != nullptr) { std::copy(tensorDesc->GetStrides().begin(), tensorDesc->GetStrides().end(), stridesA); } }); } extern "C" mlopenStatus_t mlopenDestroyTensorDescriptor(mlopenTensorDescriptor_t tensorDesc) { return mlopen::try_([&] { delete tensorDesc; }); } extern "C" mlopenStatus_t mlopenTransformTensor(mlopenHandle_t handle, const void *alpha, const mlopenTensorDescriptor_t xDesc, const void *x, const void *beta, const mlopenTensorDescriptor_t yDesc, void *y) { return mlopen::try_([&] { return yDesc->TransformTensor(handle, alpha, xDesc, DataCast(x), beta, DataCast(y)); }); } extern "C" mlopenStatus_t mlopenOpTensor(mlopenHandle_t handle, mlopenTensorOp_t tensorOp, const void *alpha1, const mlopenTensorDescriptor_t aDesc, const void *A, const void *alpha2, const mlopenTensorDescriptor_t bDesc, const void *B, const void *beta, const mlopenTensorDescriptor_t cDesc, void *C) { return mlopen::try_([&] { return cDesc->OpTensor(handle, tensorOp, alpha1, aDesc, DataCast(A), alpha2, bDesc, DataCast(B), beta, DataCast(C)); }); } extern "C" mlopenStatus_t mlopenSetTensor(mlopenHandle_t handle, const mlopenTensorDescriptor_t yDesc, void *y, const void *valuePtr) { return mlopen::try_([&] { return yDesc->SetTensor(handle, DataCast(y), valuePtr); }); } extern "C" mlopenStatus_t mlopenScaleTensor(mlopenHandle_t handle, const mlopenTensorDescriptor_t yDesc, void *y, const void *alpha) { return mlopen::try_([&] { return yDesc->ScaleTensor(handle, DataCast(y), alpha); }); } <|endoftext|>
<commit_before>/*************************************************************************** * This file is part of libmygpo-qt * * Copyright (c) 2010 - 2011 Stefan Derkits <stefan@derkits.at> * * Copyright (c) 2010 - 2011 Christian Wagner <christian.wagner86@gmx.at> * * Copyright (c) 2010 - 2011 Felix Winter <ixos01@gmail.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * * USA * ***************************************************************************/ #include "UrlBuilder.h" #include "QString" #include <QLatin1String> using namespace mygpo; const QString UrlBuilder::s_server = QLatin1String( "gpodder.net" ); const QString UrlBuilder::s_api2 = QLatin1String( "/api/2" ); const QString UrlBuilder::s_api1 = QLatin1String( "/api/1" ); QString UrlBuilder::getToplistUrl( uint i, Format f ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return QLatin1String("http://") + s_server + QLatin1String( "/toplist/" ) + numString + UrlBuilder::getFormatExtension( f ); } QString UrlBuilder::getSuggestionsUrl( uint i, Format f ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return QLatin1String("http://") + s_server + QLatin1String( "/suggestions/" ) + numString + getFormatExtension( f ); } QString UrlBuilder::getPodcastSearchUrl( const QString& query, Format f ) { return QLatin1String("http://") + s_server + QLatin1String( "/search" ) + getFormatExtension( f ) + QLatin1String( "?q=" ) + query; } QString UrlBuilder::getTopTagsUrl( uint i ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/tags/" ) + numString + QLatin1String( ".json" ); } QString UrlBuilder::getPodcastsOfTagUrl( const QString& tag, uint i ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return s_server + s_api2 + QLatin1String( "/tag/" ) + tag + QLatin1String( "/" ) + numString + QLatin1String( ".json" ); } QString UrlBuilder::getPodcastDataUrl( const QString& url ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/data/podcast" ) + QLatin1String( ".json" ) + QLatin1String( "?url=" ) + url; } QString UrlBuilder::getEpisodeDataUrl( const QString& podcastUrl, const QString& episodeUrl ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/data/episode" ) + QLatin1String( ".json" ) + QLatin1String( "?podcast=" ) + podcastUrl + QLatin1String( "&url=" ) + episodeUrl; } QString UrlBuilder::getFavEpisodesUrl( const QString& username ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/favorites/" ) + username + QLatin1String( ".json" ); } QString UrlBuilder::getAddRemoveSubUrl( const QString& username, const QString& deviceId ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/subscriptions/" ) + username + QLatin1String( "/" ) + deviceId + QLatin1String( ".json" ); } QString UrlBuilder::getAccountSettingsUrl( const QString& username ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/account" ) + QLatin1String( ".json" ); } QString UrlBuilder::getDeviceSettingsUrl( const QString& username, const QString& deviceId ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/device" ) + QLatin1String( ".json" ) + QLatin1String( "?device=" ) + deviceId; } QString UrlBuilder::getPodcastSettingsUrl( const QString& username, const QString& podcastUrl ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/podcast" ) + QLatin1String( ".json" ) + QLatin1String( "?podcast=" ) + podcastUrl; } QString UrlBuilder::getEpisodeSettingsUrl( const QString& username, const QString& podcastUrl, const QString& episodeUrl ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/episode" ) + QLatin1String( ".json" ) + QLatin1String( "?podcast=" ) + podcastUrl + QLatin1String( "&episode=" ) + episodeUrl; } QString UrlBuilder::getDeviceListUrl( const QString& username ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/devices/" ) + username + QLatin1String( ".json" ) ; } QString UrlBuilder::getDeviceUpdatesUrl( const QString& username, const QString& deviceId, qulonglong timestamp ) { QString numString = QString::number( timestamp < 0 ? 0 : timestamp ); return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/updates/" ) + username + QLatin1String( "/" ) + deviceId + QLatin1String( ".json?since=" ) + numString; } QString UrlBuilder::getRenameDeviceUrl( const QString& username, const QString& deviceId ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/devices/" ) + username + QLatin1String( "/" ) + deviceId + QLatin1String( ".json" ); } QString UrlBuilder::getEpisodeActionsUrl( const QString& username ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json" ); } QString UrlBuilder::getEpisodeActionsUrlByPodcast( const QString& username, const QString& podcastUrl ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?podcast=" ) + podcastUrl; } QString UrlBuilder::getEpisodeActionsUrlByDevice( const QString& username, const QString& deviceId ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?device=" ) + deviceId; } QString UrlBuilder::getEpisodeActionsUrlByTimestamp( const QString& username, const qulonglong since ) { QString numString = QString::number( since ); return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?since=" ) + numString; } QString UrlBuilder::getEpisodeActionsUrlByPodcastAndTimestamp( const QString& username, const QString& podcastUrl, const qulonglong since ) { QString numString = QString::number( since ); return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?podcast=" ) + podcastUrl + QLatin1String( "&since=" ) + numString; } QString UrlBuilder::getEpisodeActionsUrlByDeviceAndTimestamp( const QString& username, const QString& deviceId, const qulonglong since ) { QString numString = QString::number( since ); return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?device=" ) + deviceId + QLatin1String( "&since=" ) + numString; } QString UrlBuilder::getEpisodeActionsUrlByPodcastAndAggregate( const QString& username, const QString& deviceId, const bool aggregated ) { QString agg; if( aggregated ) agg = QLatin1String( "true" ); else agg = QLatin1String( "false" ); return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?podcast=" ) + deviceId + QLatin1String( "&aggregated=" ) + agg; } QString UrlBuilder::getUploadEpisodeActionsUrl( const QString& username ) { return QLatin1String("http://") + s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json" ); } QString UrlBuilder::getFormatExtension( Format f ) { QString ret; switch( f ) { case JSON: ret = QString( QLatin1String( ".json" ) ); break; case OPML: ret = QString( QLatin1String( ".opml" ) ); break; case TEXT: ret = QString( QLatin1String( ".txt" ) ); break; } return ret; } <commit_msg>Fixed bug in podcastsOfaTag request and moved "http://" into server constant<commit_after>/*************************************************************************** * This file is part of libmygpo-qt * * Copyright (c) 2010 - 2011 Stefan Derkits <stefan@derkits.at> * * Copyright (c) 2010 - 2011 Christian Wagner <christian.wagner86@gmx.at> * * Copyright (c) 2010 - 2011 Felix Winter <ixos01@gmail.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * * USA * ***************************************************************************/ #include "UrlBuilder.h" #include "QString" #include <QLatin1String> using namespace mygpo; const QString UrlBuilder::s_server = QLatin1String( "http://gpodder.net" ); const QString UrlBuilder::s_api2 = QLatin1String( "/api/2" ); const QString UrlBuilder::s_api1 = QLatin1String( "/api/1" ); QString UrlBuilder::getToplistUrl( uint i, Format f ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return s_server + QLatin1String( "/toplist/" ) + numString + UrlBuilder::getFormatExtension( f ); } QString UrlBuilder::getSuggestionsUrl( uint i, Format f ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return s_server + QLatin1String( "/suggestions/" ) + numString + getFormatExtension( f ); } QString UrlBuilder::getPodcastSearchUrl( const QString& query, Format f ) { return s_server + QLatin1String( "/search" ) + getFormatExtension( f ) + QLatin1String( "?q=" ) + query; } QString UrlBuilder::getTopTagsUrl( uint i ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return s_server + s_api2 + QLatin1String( "/tags/" ) + numString + QLatin1String( ".json" ); } QString UrlBuilder::getPodcastsOfTagUrl( const QString& tag, uint i ) { QString numString = QString::number(( i == 0 ) ? 1 : i ); return s_server + s_api2 + QLatin1String( "/tag/" ) + tag + QLatin1String( "/" ) + numString + QLatin1String( ".json" ); } QString UrlBuilder::getPodcastDataUrl( const QString& url ) { return s_server + s_api2 + QLatin1String( "/data/podcast" ) + QLatin1String( ".json" ) + QLatin1String( "?url=" ) + url; } QString UrlBuilder::getEpisodeDataUrl( const QString& podcastUrl, const QString& episodeUrl ) { return s_server + s_api2 + QLatin1String( "/data/episode" ) + QLatin1String( ".json" ) + QLatin1String( "?podcast=" ) + podcastUrl + QLatin1String( "&url=" ) + episodeUrl; } QString UrlBuilder::getFavEpisodesUrl( const QString& username ) { return s_server + s_api2 + QLatin1String( "/favorites/" ) + username + QLatin1String( ".json" ); } QString UrlBuilder::getAddRemoveSubUrl( const QString& username, const QString& deviceId ) { return s_server + s_api2 + QLatin1String( "/subscriptions/" ) + username + QLatin1String( "/" ) + deviceId + QLatin1String( ".json" ); } QString UrlBuilder::getAccountSettingsUrl( const QString& username ) { return s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/account" ) + QLatin1String( ".json" ); } QString UrlBuilder::getDeviceSettingsUrl( const QString& username, const QString& deviceId ) { return s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/device" ) + QLatin1String( ".json" ) + QLatin1String( "?device=" ) + deviceId; } QString UrlBuilder::getPodcastSettingsUrl( const QString& username, const QString& podcastUrl ) { return s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/podcast" ) + QLatin1String( ".json" ) + QLatin1String( "?podcast=" ) + podcastUrl; } QString UrlBuilder::getEpisodeSettingsUrl( const QString& username, const QString& podcastUrl, const QString& episodeUrl ) { return s_server + s_api2 + QLatin1String( "/settings/" ) + username + QLatin1String( "/episode" ) + QLatin1String( ".json" ) + QLatin1String( "?podcast=" ) + podcastUrl + QLatin1String( "&episode=" ) + episodeUrl; } QString UrlBuilder::getDeviceListUrl( const QString& username ) { return s_server + s_api2 + QLatin1String( "/devices/" ) + username + QLatin1String( ".json" ) ; } QString UrlBuilder::getDeviceUpdatesUrl( const QString& username, const QString& deviceId, qulonglong timestamp ) { QString numString = QString::number( timestamp < 0 ? 0 : timestamp ); return s_server + s_api2 + QLatin1String( "/updates/" ) + username + QLatin1String( "/" ) + deviceId + QLatin1String( ".json?since=" ) + numString; } QString UrlBuilder::getRenameDeviceUrl( const QString& username, const QString& deviceId ) { return s_server + s_api2 + QLatin1String( "/devices/" ) + username + QLatin1String( "/" ) + deviceId + QLatin1String( ".json" ); } QString UrlBuilder::getEpisodeActionsUrl( const QString& username ) { return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json" ); } QString UrlBuilder::getEpisodeActionsUrlByPodcast( const QString& username, const QString& podcastUrl ) { return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?podcast=" ) + podcastUrl; } QString UrlBuilder::getEpisodeActionsUrlByDevice( const QString& username, const QString& deviceId ) { return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?device=" ) + deviceId; } QString UrlBuilder::getEpisodeActionsUrlByTimestamp( const QString& username, const qulonglong since ) { QString numString = QString::number( since ); return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?since=" ) + numString; } QString UrlBuilder::getEpisodeActionsUrlByPodcastAndTimestamp( const QString& username, const QString& podcastUrl, const qulonglong since ) { QString numString = QString::number( since ); return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?podcast=" ) + podcastUrl + QLatin1String( "&since=" ) + numString; } QString UrlBuilder::getEpisodeActionsUrlByDeviceAndTimestamp( const QString& username, const QString& deviceId, const qulonglong since ) { QString numString = QString::number( since ); return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?device=" ) + deviceId + QLatin1String( "&since=" ) + numString; } QString UrlBuilder::getEpisodeActionsUrlByPodcastAndAggregate( const QString& username, const QString& deviceId, const bool aggregated ) { QString agg; if( aggregated ) agg = QLatin1String( "true" ); else agg = QLatin1String( "false" ); return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json?podcast=" ) + deviceId + QLatin1String( "&aggregated=" ) + agg; } QString UrlBuilder::getUploadEpisodeActionsUrl( const QString& username ) { return s_server + s_api2 + QLatin1String( "/episodes/" ) + username + QLatin1String( ".json" ); } QString UrlBuilder::getFormatExtension( Format f ) { QString ret; switch( f ) { case JSON: ret = QString( QLatin1String( ".json" ) ); break; case OPML: ret = QString( QLatin1String( ".opml" ) ); break; case TEXT: ret = QString( QLatin1String( ".txt" ) ); break; } return ret; } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "adapter.hh" #include "log.hh" #include "conf.hh" #include "helper.hh" #include <dlfcn.h> #include <string.h> namespace { Adapter* creator_func(Log& l, std::string params = "") { Adapter* a; std::string adapter_name,adapter_param,adapter_filename; std::string s(unescape_string(strdup(params.c_str()))); split(s, adapter_name, adapter_param); split(adapter_name,adapter_name,adapter_filename,","); a = AdapterFactory::create(l, adapter_name, adapter_param); if (!a) { void* handle=load_lib(adapter_name,adapter_filename); if (handle) { a = AdapterFactory::create(l, adapter_name, adapter_param); } else { std::string d("dummy"); std::string em(""); a = AdapterFactory::create(l, d, em); a->status = false; a->errormsg = std::string("lib:Can't load adapter ") + params; } } return a; } static AdapterFactory::Register me("lib", creator_func); } <commit_msg>adapter lib: fix memory leak<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "adapter.hh" #include "log.hh" #include "conf.hh" #include "helper.hh" #include <dlfcn.h> #include <string.h> namespace { Adapter* creator_func(Log& l, std::string params = "") { Adapter* a; std::string adapter_name,adapter_param,adapter_filename; char* stmp=strdup(params.c_str()); std::string s(unescape_string(stmp)); free(stmp); split(s, adapter_name, adapter_param); split(adapter_name,adapter_name,adapter_filename,","); a = AdapterFactory::create(l, adapter_name, adapter_param); if (!a) { void* handle=load_lib(adapter_name,adapter_filename); if (handle) { a = AdapterFactory::create(l, adapter_name, adapter_param); } else { std::string d("dummy"); std::string em(""); a = AdapterFactory::create(l, d, em); a->status = false; a->errormsg = std::string("lib:Can't load adapter ") + params; } } return a; } static AdapterFactory::Register me("lib", creator_func); } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. */ #ifndef __SOCKET_HH__ #define __SOCKET_HH__ class ListenSocket { protected: static bool listeningDisabled; static bool anyListening; static bool bindToLoopback; public: static void disableAll(); static bool allDisabled(); static void loopbackOnly(); protected: bool listening; int fd; /* * cleanup resets the static variables back to their default values. */ static void cleanup(); public: ListenSocket(); virtual ~ListenSocket(); virtual int accept(bool nodelay = false); virtual bool listen(int port, bool reuse = true); int getfd() const { return fd; } bool islistening() const { return listening; } }; #endif //__SOCKET_HH__ <commit_msg>base: Tag API methods in socket.hh<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. */ #ifndef __SOCKET_HH__ #define __SOCKET_HH__ class ListenSocket { protected: /** * The following variables are only used by socket unit tests: * listeningDisabled, anyListening, bindToLoopback. */ static bool listeningDisabled; static bool anyListening; static bool bindToLoopback; public: static void disableAll(); static bool allDisabled(); static void loopbackOnly(); protected: bool listening; int fd; /* * cleanup resets the static variables back to their default values. */ static void cleanup(); public: /** * @ingroup api_socket * @{ */ ListenSocket(); virtual ~ListenSocket(); virtual int accept(bool nodelay = false); virtual bool listen(int port, bool reuse = true); int getfd() const { return fd; } bool islistening() const { return listening; } /** @} */ // end of api_socket }; #endif //__SOCKET_HH__ <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Nicholas Campbell <nicholas.j.campbell@gmail.com> * 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. Neither the name of the <ORGANIZATION> 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 * 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 <node.h> #include <node_version.h> #include <string> #include <cstring> #include <vector> #include <openssl/rand.h> #include <openssl/crypto.h> #include "node_blf.h" //pulled from node commit - 97cada0 #ifdef _WIN32 # include <windows.h> #else # include <pthread.h> #endif #define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4))) using namespace v8; using namespace node; #ifdef _WIN32 static HANDLE* locks; static void crypto_lock_init(void) { int i, n; n = CRYPTO_num_locks(); locks = new HANDLE[n]; for (i = 0; i < n; i++) if (!(locks[i] = CreateMutex(NULL, FALSE, NULL))) abort(); } static void crypto_lock_cb(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) WaitForSingleObject(locks[n], INFINITE); else ReleaseMutex(locks[n]); } static unsigned long crypto_id_cb(void) { return (unsigned long) GetCurrentThreadId(); } #else /* !_WIN32 */ static pthread_rwlock_t* locks; static void crypto_lock_init(void) { const int n = CRYPTO_num_locks(); locks = new pthread_rwlock_t[n]; for (int i = 0; i < n; i++) if (pthread_rwlock_init(locks + i, NULL)) abort(); } static void crypto_lock_cb(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) { if (mode & CRYPTO_READ) pthread_rwlock_rdlock(locks + n); if (mode & CRYPTO_WRITE) pthread_rwlock_wrlock(locks + n); } else { pthread_rwlock_unlock(locks + n); } } static unsigned long crypto_id_cb(void) { return (unsigned long) pthread_self(); } #endif /* !_WIN32 */ namespace { struct baton_base { v8::Persistent<v8::Function> callback; std::string error; virtual ~baton_base() { callback.Dispose(); } }; struct salt_baton : baton_base { std::string salt; int rand_len; ssize_t rounds; }; struct encrypt_baton : baton_base { std::string salt; std::string input; std::string output; }; struct compare_baton : baton_base { std::string input; std::string encrypted; bool result; }; int GetSeed(uint8_t* seed, int size) { // try to get good random bytes first if (RAND_bytes((unsigned char *)seed, size) > 0) { return 1; } return RAND_pseudo_bytes(seed, size); } bool ValidateSalt(const char* salt) { if (!salt || *salt != '$') { return false; } // discard $ salt++; if (*salt > BCRYPT_VERSION) { return false; } if (salt[1] != '$') { switch (salt[1]) { case 'a': salt++; break; default: return false; } } // discard version + $ salt += 2; if (salt[2] != '$') { return false; } int n = atoi(salt); if (n > 31 || n < 0) { return false; } if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) { return false; } salt += 3; if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) { return false; } return true; } /* SALT GENERATION */ void GenSaltAsync(uv_work_t* req) { salt_baton* baton = static_cast<salt_baton*>(req->data); std::vector<uint8_t> seed(baton->rand_len); switch(GetSeed(&seed[0], baton->rand_len)) { case -1: baton->error = "Rand operation not supported."; case 0: baton->error = "Rand operation did not generate a cryptographically sound seed."; } char salt[_SALT_LEN]; bcrypt_gensalt(baton->rounds, &seed[0], salt); baton->salt = std::string(salt); } void GenSaltAsyncAfter(uv_work_t* req) { HandleScope scope; salt_baton* baton = static_cast<salt_baton*>(req->data); delete req; Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = Exception::Error(String::New(baton->error.c_str())); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = Encode(baton->salt.c_str(), baton->salt.size(), BINARY); } TryCatch try_catch; // don't quite see the necessity of this baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); delete baton; } Handle<Value> GenerateSalt(const Arguments &args) { HandleScope scope; const ssize_t rounds = args[0]->Int32Value(); const int rand_len = args[1]->Int32Value(); Local<Function> callback = Local<Function>::Cast(args[2]); salt_baton* baton = new salt_baton(); baton->callback = Persistent<Function>::New(callback); baton->rand_len = rand_len; baton->rounds = rounds; uv_work_t* req = new uv_work_t; req->data = baton; uv_queue_work(uv_default_loop(), req, GenSaltAsync, (uv_after_work_cb)GenSaltAsyncAfter); return Undefined(); } Handle<Value> GenerateSaltSync(const Arguments& args) { HandleScope scope; const ssize_t rounds = args[0]->Int32Value(); const int size = args[1]->Int32Value(); std::vector<uint8_t> seed(size); switch(GetSeed(&seed[0], size)) { case -1: return ThrowException(Exception::Error(String::New("Rand operation not supported."))); case 0: return ThrowException(Exception::Error(String::New("Rand operation did not generate a cryptographically sound seed."))); } char salt[_SALT_LEN]; bcrypt_gensalt(rounds, &seed[0], salt); return scope.Close(Encode(salt, strlen(salt), BINARY)); } /* ENCRYPT DATA - USED TO BE HASHPW */ void EncryptAsync(uv_work_t* req) { encrypt_baton* baton = static_cast<encrypt_baton*>(req->data); if (!(ValidateSalt(baton->salt.c_str()))) { baton->error = "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"; } char bcrypted[_PASSWORD_LEN]; bcrypt(baton->input.c_str(), baton->salt.c_str(), bcrypted); baton->output = std::string(bcrypted); } void EncryptAsyncAfter(uv_work_t* req) { HandleScope scope; encrypt_baton* baton = static_cast<encrypt_baton*>(req->data); delete req; Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = Exception::Error(String::New(baton->error.c_str())); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = Encode(baton->output.c_str(), baton->output.size(), BINARY); } TryCatch try_catch; // don't quite see the necessity of this baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); delete baton; } Handle<Value> Encrypt(const Arguments& args) { HandleScope scope; String::Utf8Value data(args[0]->ToString()); String::Utf8Value salt(args[1]->ToString()); Local<Function> callback = Local<Function>::Cast(args[2]); encrypt_baton* baton = new encrypt_baton(); baton->callback = Persistent<Function>::New(callback); baton->input = std::string(*data); baton->salt = std::string(*salt); uv_work_t* req = new uv_work_t; req->data = baton; uv_queue_work(uv_default_loop(), req, EncryptAsync, (uv_after_work_cb)EncryptAsyncAfter); return Undefined(); } Handle<Value> EncryptSync(const Arguments& args) { HandleScope scope; String::Utf8Value data(args[0]->ToString()); String::Utf8Value salt(args[1]->ToString()); if (!(ValidateSalt(*salt))) { return ThrowException(Exception::Error(String::New("Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"))); } char bcrypted[_PASSWORD_LEN]; bcrypt(*data, *salt, bcrypted); return scope.Close(Encode(bcrypted, strlen(bcrypted), BINARY)); } /* COMPARATOR */ bool CompareStrings(const char* s1, const char* s2) { bool eq = true; int s1_len = strlen(s1); int s2_len = strlen(s2); if (s1_len != s2_len) { return false; } const int max_len = (s2_len < s1_len) ? s1_len : s2_len; // to prevent timing attacks, should check entire string // don't exit after found to be false for (int i = 0; i < max_len; ++i) { if (s1_len >= i && s2_len >= i && s1[i] != s2[i]) { eq = false; } } return eq; } void CompareAsync(uv_work_t* req) { compare_baton* baton = static_cast<compare_baton*>(req->data); char bcrypted[_PASSWORD_LEN]; if (ValidateSalt(baton->encrypted.c_str())) { bcrypt(baton->input.c_str(), baton->encrypted.c_str(), bcrypted); baton->result = CompareStrings(bcrypted, baton->encrypted.c_str()); } } void CompareAsyncAfter(uv_work_t* req) { HandleScope scope; compare_baton* baton = static_cast<compare_baton*>(req->data); delete req; Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = Exception::Error(String::New(baton->error.c_str())); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = Boolean::New(baton->result); } TryCatch try_catch; // don't quite see the necessity of this baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); // done with the baton // free the memory and callback delete baton; } Handle<Value> Compare(const Arguments& args) { HandleScope scope; String::Utf8Value input(args[0]->ToString()); String::Utf8Value encrypted(args[1]->ToString()); Local<Function> callback = Local<Function>::Cast(args[2]); compare_baton* baton = new compare_baton(); baton->callback = Persistent<Function>::New(callback); baton->input = std::string(*input); baton->encrypted = std::string(*encrypted); uv_work_t* req = new uv_work_t; req->data = baton; uv_queue_work(uv_default_loop(), req, CompareAsync, (uv_after_work_cb)CompareAsyncAfter); return Undefined(); } Handle<Value> CompareSync(const Arguments& args) { HandleScope scope; String::Utf8Value pw(args[0]->ToString()); String::Utf8Value hash(args[1]->ToString()); char bcrypted[_PASSWORD_LEN]; if (ValidateSalt(*hash)) { bcrypt(*pw, *hash, bcrypted); return Boolean::New(CompareStrings(bcrypted, *hash)); } else { return Boolean::New(false); } } Handle<Value> GetRounds(const Arguments& args) { HandleScope scope; String::Utf8Value hash(args[0]->ToString()); u_int32_t rounds; if (!(rounds = bcrypt_get_rounds(*hash))) { return ThrowException(Exception::Error(String::New("invalid hash provided"))); } return Integer::New(rounds); } } // anonymous namespace // bind the bcrypt module extern "C" void init(Handle<Object> target) { HandleScope scope; crypto_lock_init(); CRYPTO_set_locking_callback(crypto_lock_cb); CRYPTO_set_id_callback(crypto_id_cb); NODE_SET_METHOD(target, "gen_salt_sync", GenerateSaltSync); NODE_SET_METHOD(target, "encrypt_sync", EncryptSync); NODE_SET_METHOD(target, "compare_sync", CompareSync); NODE_SET_METHOD(target, "get_rounds", GetRounds); NODE_SET_METHOD(target, "gen_salt", GenerateSalt); NODE_SET_METHOD(target, "encrypt", Encrypt); NODE_SET_METHOD(target, "compare", Compare); }; NODE_MODULE(bcrypt_lib, init); <commit_msg>Revert small change.<commit_after>/* * Copyright (c) 2010, Nicholas Campbell <nicholas.j.campbell@gmail.com> * 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. Neither the name of the <ORGANIZATION> 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 * 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 <node.h> #include <node_version.h> #include <string> #include <cstring> #include <vector> #include <openssl/rand.h> #include <openssl/crypto.h> #include "node_blf.h" //pulled from node commit - 97cada0 #ifdef _WIN32 # include <windows.h> #else # include <pthread.h> #endif #define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4))) using namespace v8; using namespace node; #ifdef _WIN32 static HANDLE* locks; static void crypto_lock_init(void) { int i, n; n = CRYPTO_num_locks(); locks = new HANDLE[n]; for (i = 0; i < n; i++) if (!(locks[i] = CreateMutex(NULL, FALSE, NULL))) abort(); } static void crypto_lock_cb(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) WaitForSingleObject(locks[n], INFINITE); else ReleaseMutex(locks[n]); } static unsigned long crypto_id_cb(void) { return (unsigned long) GetCurrentThreadId(); } #else /* !_WIN32 */ static pthread_rwlock_t* locks; static void crypto_lock_init(void) { const int n = CRYPTO_num_locks(); locks = new pthread_rwlock_t[n]; for (int i = 0; i < n; i++) if (pthread_rwlock_init(locks + i, NULL)) abort(); } static void crypto_lock_cb(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) { if (mode & CRYPTO_READ) pthread_rwlock_rdlock(locks + n); if (mode & CRYPTO_WRITE) pthread_rwlock_wrlock(locks + n); } else { pthread_rwlock_unlock(locks + n); } } static unsigned long crypto_id_cb(void) { return (unsigned long) pthread_self(); } #endif /* !_WIN32 */ namespace { struct baton_base { v8::Persistent<v8::Function> callback; std::string error; virtual ~baton_base() { callback.Dispose(); } }; struct salt_baton : baton_base { std::string salt; int rand_len; ssize_t rounds; }; struct encrypt_baton : baton_base { std::string salt; std::string input; std::string output; }; struct compare_baton : baton_base { std::string input; std::string encrypted; bool result; }; int GetSeed(uint8_t* seed, int size) { // try to get good random bytes first if (RAND_bytes((unsigned char *)seed, size) > 0) { return 1; } return RAND_pseudo_bytes(seed, size); } bool ValidateSalt(const char* salt) { if (!salt || *salt != '$') { return false; } // discard $ salt++; if (*salt > BCRYPT_VERSION) { return false; } if (salt[1] != '$') { switch (salt[1]) { case 'a': salt++; break; default: return false; } } // discard version + $ salt += 2; if (salt[2] != '$') { return false; } int n = atoi(salt); if (n > 31 || n < 0) { return false; } if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) { return false; } salt += 3; if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) { return false; } return true; } /* SALT GENERATION */ void GenSaltAsync(uv_work_t* req) { salt_baton* baton = static_cast<salt_baton*>(req->data); std::vector<uint8_t> seed(baton->rand_len); switch(GetSeed(&seed[0], baton->rand_len)) { case -1: baton->error = "Rand operation not supported."; case 0: baton->error = "Rand operation did not generate a cryptographically sound seed."; } char salt[_SALT_LEN]; bcrypt_gensalt(baton->rounds, &seed[0], salt); baton->salt = std::string(salt); } void GenSaltAsyncAfter(uv_work_t* req) { HandleScope scope; salt_baton* baton = static_cast<salt_baton*>(req->data); delete req; Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = Exception::Error(String::New(baton->error.c_str())); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = Encode(baton->salt.c_str(), baton->salt.size(), BINARY); } TryCatch try_catch; // don't quite see the necessity of this baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); delete baton; } Handle<Value> GenerateSalt(const Arguments &args) { HandleScope scope; const ssize_t rounds = args[0]->Int32Value(); const int rand_len = args[1]->Int32Value(); Local<Function> callback = Local<Function>::Cast(args[2]); salt_baton* baton = new salt_baton(); baton->callback = Persistent<Function>::New(callback); baton->rand_len = rand_len; baton->rounds = rounds; uv_work_t* req = new uv_work_t; req->data = baton; uv_queue_work(uv_default_loop(), req, GenSaltAsync, (uv_after_work_cb)GenSaltAsyncAfter); return Undefined(); } Handle<Value> GenerateSaltSync(const Arguments& args) { HandleScope scope; const ssize_t rounds = args[0]->Int32Value(); const int size = args[1]->Int32Value(); std::vector<uint8_t> seed(size); switch(GetSeed(&seed[0], size)) { case -1: return ThrowException(Exception::Error(String::New("Rand operation not supported."))); case 0: return ThrowException(Exception::Error(String::New("Rand operation did not generate a cryptographically sound seed."))); } char salt[_SALT_LEN]; bcrypt_gensalt(rounds, &seed[0], salt); return scope.Close(Encode(salt, strlen(salt), BINARY)); } /* ENCRYPT DATA - USED TO BE HASHPW */ void EncryptAsync(uv_work_t* req) { encrypt_baton* baton = static_cast<encrypt_baton*>(req->data); if (!(ValidateSalt(baton->salt.c_str()))) { baton->error = "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"; } char bcrypted[_PASSWORD_LEN]; bcrypt(baton->input.c_str(), baton->salt.c_str(), bcrypted); baton->output = std::string(bcrypted); } void EncryptAsyncAfter(uv_work_t* req) { HandleScope scope; encrypt_baton* baton = static_cast<encrypt_baton*>(req->data); delete req; Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = Exception::Error(String::New(baton->error.c_str())); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = Encode(baton->output.c_str(), baton->output.size(), BINARY); } TryCatch try_catch; // don't quite see the necessity of this baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); delete baton; } Handle<Value> Encrypt(const Arguments& args) { HandleScope scope; String::Utf8Value data(args[0]->ToString()); String::Utf8Value salt(args[1]->ToString()); Local<Function> callback = Local<Function>::Cast(args[2]); encrypt_baton* baton = new encrypt_baton(); baton->callback = Persistent<Function>::New(callback); baton->input = std::string(*data); baton->salt = std::string(*salt); uv_work_t* req = new uv_work_t; req->data = baton; uv_queue_work(uv_default_loop(), req, EncryptAsync, (uv_after_work_cb)EncryptAsyncAfter); return Undefined(); } Handle<Value> EncryptSync(const Arguments& args) { HandleScope scope; String::Utf8Value data(args[0]->ToString()); String::Utf8Value salt(args[1]->ToString()); if (!(ValidateSalt(*salt))) { return ThrowException(Exception::Error(String::New("Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue"))); } char bcrypted[_PASSWORD_LEN]; bcrypt(*data, *salt, bcrypted); return scope.Close(Encode(bcrypted, strlen(bcrypted), BINARY)); } /* COMPARATOR */ bool CompareStrings(const char* s1, const char* s2) { bool eq = true; int s1_len = strlen(s1); int s2_len = strlen(s2); if (s1_len != s2_len) { eq = false; } const int max_len = (s2_len < s1_len) ? s1_len : s2_len; // to prevent timing attacks, should check entire string // don't exit after found to be false for (int i = 0; i < max_len; ++i) { if (s1_len >= i && s2_len >= i && s1[i] != s2[i]) { eq = false; } } return eq; } void CompareAsync(uv_work_t* req) { compare_baton* baton = static_cast<compare_baton*>(req->data); char bcrypted[_PASSWORD_LEN]; if (ValidateSalt(baton->encrypted.c_str())) { bcrypt(baton->input.c_str(), baton->encrypted.c_str(), bcrypted); baton->result = CompareStrings(bcrypted, baton->encrypted.c_str()); } } void CompareAsyncAfter(uv_work_t* req) { HandleScope scope; compare_baton* baton = static_cast<compare_baton*>(req->data); delete req; Handle<Value> argv[2]; if (!baton->error.empty()) { argv[0] = Exception::Error(String::New(baton->error.c_str())); argv[1] = Undefined(); } else { argv[0] = Undefined(); argv[1] = Boolean::New(baton->result); } TryCatch try_catch; // don't quite see the necessity of this baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) FatalException(try_catch); // done with the baton // free the memory and callback delete baton; } Handle<Value> Compare(const Arguments& args) { HandleScope scope; String::Utf8Value input(args[0]->ToString()); String::Utf8Value encrypted(args[1]->ToString()); Local<Function> callback = Local<Function>::Cast(args[2]); compare_baton* baton = new compare_baton(); baton->callback = Persistent<Function>::New(callback); baton->input = std::string(*input); baton->encrypted = std::string(*encrypted); uv_work_t* req = new uv_work_t; req->data = baton; uv_queue_work(uv_default_loop(), req, CompareAsync, (uv_after_work_cb)CompareAsyncAfter); return Undefined(); } Handle<Value> CompareSync(const Arguments& args) { HandleScope scope; String::Utf8Value pw(args[0]->ToString()); String::Utf8Value hash(args[1]->ToString()); char bcrypted[_PASSWORD_LEN]; if (ValidateSalt(*hash)) { bcrypt(*pw, *hash, bcrypted); return Boolean::New(CompareStrings(bcrypted, *hash)); } else { return Boolean::New(false); } } Handle<Value> GetRounds(const Arguments& args) { HandleScope scope; String::Utf8Value hash(args[0]->ToString()); u_int32_t rounds; if (!(rounds = bcrypt_get_rounds(*hash))) { return ThrowException(Exception::Error(String::New("invalid hash provided"))); } return Integer::New(rounds); } } // anonymous namespace // bind the bcrypt module extern "C" void init(Handle<Object> target) { HandleScope scope; crypto_lock_init(); CRYPTO_set_locking_callback(crypto_lock_cb); CRYPTO_set_id_callback(crypto_id_cb); NODE_SET_METHOD(target, "gen_salt_sync", GenerateSaltSync); NODE_SET_METHOD(target, "encrypt_sync", EncryptSync); NODE_SET_METHOD(target, "compare_sync", CompareSync); NODE_SET_METHOD(target, "get_rounds", GetRounds); NODE_SET_METHOD(target, "gen_salt", GenerateSalt); NODE_SET_METHOD(target, "encrypt", Encrypt); NODE_SET_METHOD(target, "compare", Compare); }; NODE_MODULE(bcrypt_lib, init); <|endoftext|>
<commit_before>/// /// @file calculator.hpp /// @brief calculator::eval(const std::string&) evaluates an integer /// arithmetic expression and returns the result. If an error /// occurs a calculator::error exception is thrown. /// <https://github.com/kimwalisch/calculator> /// @author Kim Walisch, <kim.walisch@gmail.com> /// @copyright Copyright (C) 2013 Kim Walisch /// @date November 8, 2013 /// @license BSD 2-Clause, http://opensource.org/licenses/BSD-2-Clause /// @version 1.0 patched: `^' is raise to power instead of XOR. /// /// == Supported operators == /// /// OPERATOR NAME ASSOCIATIVITY PRECEDENCE /// /// | Bitwise Inclusive OR Left 4 /// & Bitwise AND Left 6 /// << Shift Left Left 9 /// >> Shift Right Left 9 /// + Addition Left 10 /// - Subtraction Left 10 /// * Multiplication Left 20 /// / Division Left 20 /// % Modulo Left 20 /// ^, ** Raise to power Right 30 /// e, E Scientific notation Right 40 /// ~ Unary complement Left 99 /// /// The operator precedence has been set according to (uses the C and /// C++ operator precedence): http://en.wikipedia.org/wiki/Order_of_operations /// Operators with higher precedence are evaluated before operators /// with relatively lower precedence. Unary operators are set to have /// the highest precedence, this is not strictly correct for the power /// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell, /// Microsoft Excel, GNU bc, ...) use the same convention. /// /// == Examples of valid expressions == /// /// "65536 >> 15" = 2 /// "2**16" = 65536 /// "(0 + 0xDf234 - 1000)*3/2%999" = 828 /// "-(2**2**2**2)" = -65536 /// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817 /// "(2**16) + (1 << 16) >> 0X5" = 4096 /// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221 /// /// == About the algorithm used == /// /// calculator::eval(std::string&) relies on the ExpressionParser /// class which is a simple C++ operator precedence parser with infix /// notation for integer arithmetic expressions. /// ExpressionParser has its roots in a JavaScript parser published /// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961 /// The same author has also published an article about his operator /// precedence algorithm at PerlMonks: /// http://www.perlmonks.org/?node_id=554516 /// #ifndef CALCULATOR_HPP #define CALCULATOR_HPP #include <stdexcept> #include <string> #include <sstream> #include <stack> #include <cstddef> #include <cctype> namespace calculator { /// calculator::eval() throws a calculator::error if it fails /// to evaluate the expression string. /// class error : public std::runtime_error { public: error(const std::string& expr, const std::string& message) : std::runtime_error(message), expr_(expr) { } #if __cplusplus >= 201103L ~error() { } #else ~error() throw() { } #endif std::string expression() const { return expr_; } private: std::string expr_; }; template <typename T> class ExpressionParser { public: /// Evaluate an integer arithmetic expression and return its result. /// @throw error if parsing fails. /// T eval(const std::string& expr) { T result = 0; index_ = 0; expr_ = expr; try { result = parseExpr(); if (!isEnd()) unexpected(); } catch (const calculator::error& e) { while(!stack_.empty()) stack_.pop(); throw e; } return result; } /// Get the integer value of a character. T eval(char c) { std::string expr(1, c); return eval(expr); } private: enum { OPERATOR_NULL, OPERATOR_BITWISE_OR, /// | OPERATOR_BITWISE_XOR, /// ^ OPERATOR_BITWISE_AND, /// & OPERATOR_BITWISE_SHL, /// << OPERATOR_BITWISE_SHR, /// >> OPERATOR_ADDITION, /// + OPERATOR_SUBTRACTION, /// - OPERATOR_MULTIPLICATION, /// * OPERATOR_DIVISION, /// / OPERATOR_MODULO, /// % OPERATOR_POWER, /// ** OPERATOR_EXPONENT /// e, E }; struct Operator { /// Operator, one of the OPERATOR_* enum definitions int op; int precedence; /// 'L' = left or 'R' = right int associativity; Operator(int opr, int precedence, int associativity) : op(opr), precedence(precedence), associativity(associativity) { } }; struct OperatorValue { Operator op; T value; OperatorValue(const Operator& opr, T value) : op(opr), value(value) { } int getPrecedence() const { return op.precedence; } bool isNull() const { return op.op == OPERATOR_NULL; } }; /// Expression string std::string expr_; /// Current expression index, incremented whilst parsing std::size_t index_; /// The current operator and its left value /// are pushed onto the stack if the operator on /// top of the stack has lower precedence. std::stack<OperatorValue> stack_; /// Exponentiation by squaring, x^n. static T pow(T x, T n) { T res = 1; while (n != 0) { if (n % 2 != 0) { res *= x; n -= 1; } x *= x; n /= 2; } return res; } T checkZero(T value) const { if (value == 0) { std::string divOperators("/%"); std::size_t division = expr_.find_last_of(divOperators, index_ - 2); std::ostringstream msg; msg << "Parser error: division by 0"; if (division != std::string::npos) msg << " (error token is \"" << expr_.substr(division, expr_.size() - division) << "\")"; throw calculator::error(expr_, msg.str()); } return value; } T calculate(T v1, T v2, const Operator& op) const { switch (op.op) { case OPERATOR_BITWISE_OR: return v1 | v2; case OPERATOR_BITWISE_XOR: return v1 ^ v2; case OPERATOR_BITWISE_AND: return v1 & v2; case OPERATOR_BITWISE_SHL: return v1 << v2; case OPERATOR_BITWISE_SHR: return v1 >> v2; case OPERATOR_ADDITION: return v1 + v2; case OPERATOR_SUBTRACTION: return v1 - v2; case OPERATOR_MULTIPLICATION: return v1 * v2; case OPERATOR_DIVISION: return v1 / checkZero(v2); case OPERATOR_MODULO: return v1 % checkZero(v2); case OPERATOR_POWER: return pow(v1, v2); case OPERATOR_EXPONENT: return v1 * pow(10, v2); default: return 0; } } bool isEnd() const { return index_ >= expr_.size(); } /// Returns the character at the current expression index or /// 0 if the end of the expression is reached. /// char getCharacter() const { if (!isEnd()) return expr_[index_]; return 0; } /// Parse str at the current expression index. /// @throw error if parsing fails. /// void expect(const std::string& str) { if (expr_.compare(index_, str.size(), str) != 0) unexpected(); index_ += str.size(); } void unexpected() const { std::ostringstream msg; msg << "Syntax error: unexpected token \"" << expr_.substr(index_, expr_.size() - index_) << "\" at index " << index_; throw calculator::error(expr_, msg.str()); } /// Eat all white space characters at the /// current expression index. /// void eatSpaces() { while (std::isspace(getCharacter()) != 0) index_++; } /// Parse a binary operator at the current expression index. /// @return Operator with precedence and associativity. /// Operator parseOp() { eatSpaces(); switch (getCharacter()) { case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L'); case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L'); case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L'); case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L'); case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L'); case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L'); case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L'); case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L'); case '*': index_++; if (getCharacter() != '*') return Operator(OPERATOR_MULTIPLICATION, 20, 'L'); case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R'); case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); default : return Operator(OPERATOR_NULL, 0, 'L'); } } static T toInteger(char c) { if (c >= '0' && c <= '9') return c -'0'; if (c >= 'a' && c <= 'f') return c -'a' + 0xa; if (c >= 'A' && c <= 'F') return c -'A' + 0xa; T noDigit = 0xf + 1; return noDigit; } T getInteger() const { return toInteger(getCharacter()); } T parseDecimal() { T value = 0; for (T d; (d = getInteger()) <= 9; index_++) value = value * 10 + d; return value; } T parseHex() { index_ = index_ + 2; T value = 0; for (T h; (h = getInteger()) <= 0xf; index_++) value = value * 0x10 + h; return value; } bool isHex() const { if (index_ + 2 < expr_.size()) { char x = expr_[index_ + 1]; char h = expr_[index_ + 2]; return (std::tolower(x) == 'x' && toInteger(h) <= 0xf); } return false; } /// Parse an integer value at the current expression index. /// The unary `+', `-' and `~' operators and opening /// parentheses `(' cause recursion. /// T parseValue() { T val = 0; eatSpaces(); switch (getCharacter()) { case '0': if (isHex()) { val = parseHex(); break; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': val = parseDecimal(); break; case '(': index_++; val = parseExpr(); eatSpaces(); if (getCharacter() != ')') { if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: `)' expected at end of expression"); } index_++; break; case '~': index_++; val = ~parseValue(); break; case '+': index_++; val = parseValue(); break; case '-': index_++; val = parseValue() * static_cast<T>(-1); break; default : if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: value expected at end of expression"); } return val; } /// Parse all operations of the current parenthesis /// level and the levels above, when done /// return the result (value). /// T parseExpr() { stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0)); // first parse value on the left T value = parseValue(); while (!stack_.empty()) { // parse an operator (+, -, *, ...) Operator op(parseOp()); while (op.precedence < stack_.top().getPrecedence() || ( op.precedence == stack_.top().getPrecedence() && op.associativity == 'L')) { // end reached if (stack_.top().isNull()) { stack_.pop(); return value; } // do the calculation ("reduce"), producing a new value value = calculate(stack_.top().value, value, stack_.top().op); stack_.pop(); } // store on stack_ and continue parsing ("shift") stack_.push(OperatorValue(op, value)); // parse value on the right value = parseValue(); } return 0; } }; template <typename T> inline T eval(const std::string& expression) { ExpressionParser<T> parser; return parser.eval(expression); } template <typename T> inline T eval(char c) { ExpressionParser<T> parser; return parser.eval(c); } inline int eval(const std::string& expression) { return eval<int>(expression); } inline int eval(char c) { return eval<int>(c); } } // namespace calculator #endif <commit_msg>Silence warning<commit_after>/// /// @file calculator.hpp /// @brief calculator::eval(const std::string&) evaluates an integer /// arithmetic expression and returns the result. If an error /// occurs a calculator::error exception is thrown. /// <https://github.com/kimwalisch/calculator> /// @author Kim Walisch, <kim.walisch@gmail.com> /// @copyright Copyright (C) 2013 Kim Walisch /// @date November 8, 2013 /// @license BSD 2-Clause, http://opensource.org/licenses/BSD-2-Clause /// @version 1.0 patched: `^' is raise to power instead of XOR. /// /// == Supported operators == /// /// OPERATOR NAME ASSOCIATIVITY PRECEDENCE /// /// | Bitwise Inclusive OR Left 4 /// & Bitwise AND Left 6 /// << Shift Left Left 9 /// >> Shift Right Left 9 /// + Addition Left 10 /// - Subtraction Left 10 /// * Multiplication Left 20 /// / Division Left 20 /// % Modulo Left 20 /// ^, ** Raise to power Right 30 /// e, E Scientific notation Right 40 /// ~ Unary complement Left 99 /// /// The operator precedence has been set according to (uses the C and /// C++ operator precedence): http://en.wikipedia.org/wiki/Order_of_operations /// Operators with higher precedence are evaluated before operators /// with relatively lower precedence. Unary operators are set to have /// the highest precedence, this is not strictly correct for the power /// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell, /// Microsoft Excel, GNU bc, ...) use the same convention. /// /// == Examples of valid expressions == /// /// "65536 >> 15" = 2 /// "2**16" = 65536 /// "(0 + 0xDf234 - 1000)*3/2%999" = 828 /// "-(2**2**2**2)" = -65536 /// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817 /// "(2**16) + (1 << 16) >> 0X5" = 4096 /// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221 /// /// == About the algorithm used == /// /// calculator::eval(std::string&) relies on the ExpressionParser /// class which is a simple C++ operator precedence parser with infix /// notation for integer arithmetic expressions. /// ExpressionParser has its roots in a JavaScript parser published /// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961 /// The same author has also published an article about his operator /// precedence algorithm at PerlMonks: /// http://www.perlmonks.org/?node_id=554516 /// #ifndef CALCULATOR_HPP #define CALCULATOR_HPP #include <stdexcept> #include <string> #include <sstream> #include <stack> #include <cstddef> #include <cctype> namespace calculator { /// calculator::eval() throws a calculator::error if it fails /// to evaluate the expression string. /// class error : public std::runtime_error { public: error(const std::string& expr, const std::string& message) : std::runtime_error(message), expr_(expr) { } #if __cplusplus >= 201103L ~error() { } #else ~error() throw() { } #endif std::string expression() const { return expr_; } private: std::string expr_; }; template <typename T> class ExpressionParser { public: /// Evaluate an integer arithmetic expression and return its result. /// @throw error if parsing fails. /// T eval(const std::string& expr) { T result = 0; index_ = 0; expr_ = expr; try { result = parseExpr(); if (!isEnd()) unexpected(); } catch (const calculator::error&) { while(!stack_.empty()) stack_.pop(); throw; } return result; } /// Get the integer value of a character. T eval(char c) { std::string expr(1, c); return eval(expr); } private: enum { OPERATOR_NULL, OPERATOR_BITWISE_OR, /// | OPERATOR_BITWISE_XOR, /// ^ OPERATOR_BITWISE_AND, /// & OPERATOR_BITWISE_SHL, /// << OPERATOR_BITWISE_SHR, /// >> OPERATOR_ADDITION, /// + OPERATOR_SUBTRACTION, /// - OPERATOR_MULTIPLICATION, /// * OPERATOR_DIVISION, /// / OPERATOR_MODULO, /// % OPERATOR_POWER, /// ** OPERATOR_EXPONENT /// e, E }; struct Operator { /// Operator, one of the OPERATOR_* enum definitions int op; int precedence; /// 'L' = left or 'R' = right int associativity; Operator(int opr, int precedence, int associativity) : op(opr), precedence(precedence), associativity(associativity) { } }; struct OperatorValue { Operator op; T value; OperatorValue(const Operator& opr, T value) : op(opr), value(value) { } int getPrecedence() const { return op.precedence; } bool isNull() const { return op.op == OPERATOR_NULL; } }; /// Expression string std::string expr_; /// Current expression index, incremented whilst parsing std::size_t index_; /// The current operator and its left value /// are pushed onto the stack if the operator on /// top of the stack has lower precedence. std::stack<OperatorValue> stack_; /// Exponentiation by squaring, x^n. static T pow(T x, T n) { T res = 1; while (n != 0) { if (n % 2 != 0) { res *= x; n -= 1; } x *= x; n /= 2; } return res; } T checkZero(T value) const { if (value == 0) { std::string divOperators("/%"); std::size_t division = expr_.find_last_of(divOperators, index_ - 2); std::ostringstream msg; msg << "Parser error: division by 0"; if (division != std::string::npos) msg << " (error token is \"" << expr_.substr(division, expr_.size() - division) << "\")"; throw calculator::error(expr_, msg.str()); } return value; } T calculate(T v1, T v2, const Operator& op) const { switch (op.op) { case OPERATOR_BITWISE_OR: return v1 | v2; case OPERATOR_BITWISE_XOR: return v1 ^ v2; case OPERATOR_BITWISE_AND: return v1 & v2; case OPERATOR_BITWISE_SHL: return v1 << v2; case OPERATOR_BITWISE_SHR: return v1 >> v2; case OPERATOR_ADDITION: return v1 + v2; case OPERATOR_SUBTRACTION: return v1 - v2; case OPERATOR_MULTIPLICATION: return v1 * v2; case OPERATOR_DIVISION: return v1 / checkZero(v2); case OPERATOR_MODULO: return v1 % checkZero(v2); case OPERATOR_POWER: return pow(v1, v2); case OPERATOR_EXPONENT: return v1 * pow(10, v2); default: return 0; } } bool isEnd() const { return index_ >= expr_.size(); } /// Returns the character at the current expression index or /// 0 if the end of the expression is reached. /// char getCharacter() const { if (!isEnd()) return expr_[index_]; return 0; } /// Parse str at the current expression index. /// @throw error if parsing fails. /// void expect(const std::string& str) { if (expr_.compare(index_, str.size(), str) != 0) unexpected(); index_ += str.size(); } void unexpected() const { std::ostringstream msg; msg << "Syntax error: unexpected token \"" << expr_.substr(index_, expr_.size() - index_) << "\" at index " << index_; throw calculator::error(expr_, msg.str()); } /// Eat all white space characters at the /// current expression index. /// void eatSpaces() { while (std::isspace(getCharacter()) != 0) index_++; } /// Parse a binary operator at the current expression index. /// @return Operator with precedence and associativity. /// Operator parseOp() { eatSpaces(); switch (getCharacter()) { case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L'); case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L'); case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L'); case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L'); case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L'); case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L'); case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L'); case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L'); case '*': index_++; if (getCharacter() != '*') return Operator(OPERATOR_MULTIPLICATION, 20, 'L'); case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R'); case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); default : return Operator(OPERATOR_NULL, 0, 'L'); } } static T toInteger(char c) { if (c >= '0' && c <= '9') return c -'0'; if (c >= 'a' && c <= 'f') return c -'a' + 0xa; if (c >= 'A' && c <= 'F') return c -'A' + 0xa; T noDigit = 0xf + 1; return noDigit; } T getInteger() const { return toInteger(getCharacter()); } T parseDecimal() { T value = 0; for (T d; (d = getInteger()) <= 9; index_++) value = value * 10 + d; return value; } T parseHex() { index_ = index_ + 2; T value = 0; for (T h; (h = getInteger()) <= 0xf; index_++) value = value * 0x10 + h; return value; } bool isHex() const { if (index_ + 2 < expr_.size()) { char x = expr_[index_ + 1]; char h = expr_[index_ + 2]; return (std::tolower(x) == 'x' && toInteger(h) <= 0xf); } return false; } /// Parse an integer value at the current expression index. /// The unary `+', `-' and `~' operators and opening /// parentheses `(' cause recursion. /// T parseValue() { T val = 0; eatSpaces(); switch (getCharacter()) { case '0': if (isHex()) { val = parseHex(); break; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': val = parseDecimal(); break; case '(': index_++; val = parseExpr(); eatSpaces(); if (getCharacter() != ')') { if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: `)' expected at end of expression"); } index_++; break; case '~': index_++; val = ~parseValue(); break; case '+': index_++; val = parseValue(); break; case '-': index_++; val = parseValue() * static_cast<T>(-1); break; default : if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: value expected at end of expression"); } return val; } /// Parse all operations of the current parenthesis /// level and the levels above, when done /// return the result (value). /// T parseExpr() { stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0)); // first parse value on the left T value = parseValue(); while (!stack_.empty()) { // parse an operator (+, -, *, ...) Operator op(parseOp()); while (op.precedence < stack_.top().getPrecedence() || ( op.precedence == stack_.top().getPrecedence() && op.associativity == 'L')) { // end reached if (stack_.top().isNull()) { stack_.pop(); return value; } // do the calculation ("reduce"), producing a new value value = calculate(stack_.top().value, value, stack_.top().op); stack_.pop(); } // store on stack_ and continue parsing ("shift") stack_.push(OperatorValue(op, value)); // parse value on the right value = parseValue(); } return 0; } }; template <typename T> inline T eval(const std::string& expression) { ExpressionParser<T> parser; return parser.eval(expression); } template <typename T> inline T eval(char c) { ExpressionParser<T> parser; return parser.eval(c); } inline int eval(const std::string& expression) { return eval<int>(expression); } inline int eval(char c) { return eval<int>(c); } } // namespace calculator #endif <|endoftext|>
<commit_before>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * 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 <assert.h> #include <sys/socket.h> #include <unistd.h> #include "xapiand.h" #include "utils.h" #include "client_base.h" const int WRITE_QUEUE_SIZE = -1; BaseClient::BaseClient(XapiandServer *server_, ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_) : server(server_), iterator(server->attach_client(this)), io_read(*loop), io_write(*loop), async_write(*loop), closed(false), sock(sock_), database_pool(database_pool_), thread_pool(thread_pool_), write_queue(WRITE_QUEUE_SIZE) { inc_ref(); pthread_mutexattr_init(&qmtx_attr); pthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qmtx, &qmtx_attr); pthread_mutex_lock(&XapiandServer::static_mutex); int total_clients = ++XapiandServer::total_clients; pthread_mutex_unlock(&XapiandServer::static_mutex); async_write.set<BaseClient, &BaseClient::async_write_cb>(this); async_write.start(); io_read.set<BaseClient, &BaseClient::io_cb>(this); io_read.start(sock, ev::READ); io_write.set<BaseClient, &BaseClient::io_cb>(this); io_write.set(sock, ev::WRITE); LOG_OBJ(this, "CREATED CLIENT! (%d clients)\n", total_clients); } BaseClient::~BaseClient() { destroy(); while(!write_queue.empty()) { Buffer *buffer; if (write_queue.pop(buffer, 0)) { delete buffer; } } server->detach_client(this); pthread_mutex_lock(&XapiandServer::static_mutex); int total_clients = --XapiandServer::total_clients; pthread_mutex_unlock(&XapiandServer::static_mutex); pthread_mutex_destroy(&qmtx); pthread_mutexattr_destroy(&qmtx_attr); LOG_OBJ(this, "DELETED CLIENT! (%d clients left)\n", total_clients); assert(total_clients >= 0); } void BaseClient::destroy() { close(); pthread_mutex_lock(&qmtx); if (sock == -1) { pthread_mutex_unlock(&qmtx); return; } // Stop and free watcher if client socket is closing io_read.stop(); io_write.stop(); ::close(sock); sock = -1; pthread_mutex_unlock(&qmtx); write_queue.clear(); LOG_OBJ(this, "DESTROYED CLIENT!\n"); } void BaseClient::close() { if (closed) { return; } closed = true; LOG_OBJ(this, "CLOSED CLIENT!\n"); } void BaseClient::io_update() { if (sock != -1) { if (write_queue.empty()) { if (closed) { destroy(); } else { io_write.stop(); } } else { io_write.start(); } } if (sock == -1) { rel_ref(); } } void BaseClient::io_cb(ev::io &watcher, int revents) { if (revents & EV_ERROR) { LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno)); destroy(); return; } LOG_EV(this, "%s (sock=%d) %x\n", (revents & EV_WRITE & EV_READ) ? "IO_CB" : (revents & EV_WRITE) ? "WRITE_CB" : (revents & EV_READ) ? "READ_CB" : "IO_CB", sock, revents); if (sock == -1) { return; } assert(sock == watcher.fd); if (sock != -1 && revents & EV_WRITE) { write_cb(); } if (sock != -1 && revents & EV_READ) { read_cb(); } io_update(); } void BaseClient::write_cb() { if (!write_queue.empty()) { Buffer* buffer = write_queue.front(); size_t buf_size = buffer->nbytes(); const char * buf = buffer->dpos(); LOG_CONN_WIRE(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str()); ssize_t written = ::write(sock, buf, buf_size); if (written < 0) { if (errno != EAGAIN) { LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno)); destroy(); } } else if (written == 0) { // nothing written? } else { buffer->pos += written; if (buffer->nbytes() == 0) { if(write_queue.pop(buffer)) { delete buffer; } } } } } void BaseClient::read_cb() { char buf[1024]; ssize_t received = ::read(sock, buf, sizeof(buf)); if (received < 0) { if (errno != EAGAIN) { LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno)); destroy(); } } else if (received == 0) { // The peer has closed its half side of the connection. LOG_CONN(this, "Received EOF (sock=%d)!\n", sock); destroy(); } else { LOG_CONN_WIRE(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str()); on_read(buf, received); } } void BaseClient::async_write_cb(ev::async &watcher, int revents) { io_update(); } bool BaseClient::write(const char *buf, size_t buf_size) { LOG_CONN_WIRE(this, "(sock=%d) <ENQUEUE> '%s'\n", sock, repr(buf, buf_size).c_str()); Buffer *buffer = new Buffer('\0', buf, buf_size); write_queue.push(buffer); if (sock == -1) { return false; } async_write.send(); return true; } void BaseClient::shutdown() { if (server->manager->shutdown_now) { LOG_EV(this, "Signaled destroy!!\n"); destroy(); rel_ref(); } } <commit_msg>Avoid using invalid socket<commit_after>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * 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 <assert.h> #include <sys/socket.h> #include <unistd.h> #include "xapiand.h" #include "utils.h" #include "client_base.h" const int WRITE_QUEUE_SIZE = -1; BaseClient::BaseClient(XapiandServer *server_, ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_) : server(server_), iterator(server->attach_client(this)), io_read(*loop), io_write(*loop), async_write(*loop), closed(false), sock(sock_), database_pool(database_pool_), thread_pool(thread_pool_), write_queue(WRITE_QUEUE_SIZE) { inc_ref(); pthread_mutexattr_init(&qmtx_attr); pthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qmtx, &qmtx_attr); pthread_mutex_lock(&XapiandServer::static_mutex); int total_clients = ++XapiandServer::total_clients; pthread_mutex_unlock(&XapiandServer::static_mutex); async_write.set<BaseClient, &BaseClient::async_write_cb>(this); async_write.start(); io_read.set<BaseClient, &BaseClient::io_cb>(this); io_read.start(sock, ev::READ); io_write.set<BaseClient, &BaseClient::io_cb>(this); io_write.set(sock, ev::WRITE); LOG_OBJ(this, "CREATED CLIENT! (%d clients)\n", total_clients); } BaseClient::~BaseClient() { destroy(); while(!write_queue.empty()) { Buffer *buffer; if (write_queue.pop(buffer, 0)) { delete buffer; } } server->detach_client(this); pthread_mutex_lock(&XapiandServer::static_mutex); int total_clients = --XapiandServer::total_clients; pthread_mutex_unlock(&XapiandServer::static_mutex); pthread_mutex_destroy(&qmtx); pthread_mutexattr_destroy(&qmtx_attr); LOG_OBJ(this, "DELETED CLIENT! (%d clients left)\n", total_clients); assert(total_clients >= 0); } void BaseClient::destroy() { close(); pthread_mutex_lock(&qmtx); if (sock == -1) { pthread_mutex_unlock(&qmtx); return; } // Stop and free watcher if client socket is closing io_read.stop(); io_write.stop(); ::close(sock); sock = -1; pthread_mutex_unlock(&qmtx); write_queue.clear(); LOG_OBJ(this, "DESTROYED CLIENT!\n"); } void BaseClient::close() { if (closed) { return; } closed = true; LOG_OBJ(this, "CLOSED CLIENT!\n"); } void BaseClient::io_update() { if (sock != -1) { if (write_queue.empty()) { if (closed) { destroy(); } else { io_write.stop(); } } else { io_write.start(); } } if (sock == -1) { rel_ref(); } } void BaseClient::io_cb(ev::io &watcher, int revents) { if (revents & EV_ERROR) { LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno)); destroy(); return; } LOG_EV(this, "%s (sock=%d) %x\n", (revents & EV_WRITE & EV_READ) ? "IO_CB" : (revents & EV_WRITE) ? "WRITE_CB" : (revents & EV_READ) ? "READ_CB" : "IO_CB", sock, revents); if (sock == -1) { return; } assert(sock == watcher.fd); if (sock != -1 && revents & EV_WRITE) { write_cb(); } if (sock != -1 && revents & EV_READ) { read_cb(); } io_update(); } void BaseClient::write_cb() { if (sock != -1 && !write_queue.empty()) { Buffer* buffer = write_queue.front(); size_t buf_size = buffer->nbytes(); const char * buf = buffer->dpos(); LOG_CONN_WIRE(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str()); ssize_t written = ::write(sock, buf, buf_size); if (written < 0) { if (errno != EAGAIN) { LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno)); destroy(); } } else if (written == 0) { // nothing written? } else { buffer->pos += written; if (buffer->nbytes() == 0) { if(write_queue.pop(buffer)) { delete buffer; } } } } } void BaseClient::read_cb() { if (sock != -1) { char buf[1024]; ssize_t received = ::read(sock, buf, sizeof(buf)); if (received < 0) { if (errno != EAGAIN) { LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno)); destroy(); } } else if (received == 0) { // The peer has closed its half side of the connection. LOG_CONN(this, "Received EOF (sock=%d)!\n", sock); destroy(); } else { LOG_CONN_WIRE(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str()); on_read(buf, received); } } } void BaseClient::async_write_cb(ev::async &watcher, int revents) { io_update(); } bool BaseClient::write(const char *buf, size_t buf_size) { LOG_CONN_WIRE(this, "(sock=%d) <ENQUEUE> '%s'\n", sock, repr(buf, buf_size).c_str()); Buffer *buffer = new Buffer('\0', buf, buf_size); write_queue.push(buffer); if (sock == -1) { return false; } async_write.send(); return true; } void BaseClient::shutdown() { if (server->manager->shutdown_now) { LOG_EV(this, "Signaled destroy!!\n"); destroy(); rel_ref(); } } <|endoftext|>
<commit_before>#include "jewel.h" #include <SDL2/SDL_image.h> #include "graphics/Renderer.h" #include "util/Log.h" #include "util/Point.h" namespace bejeweled { namespace { int dx[7] = {3,0,1,2,0,1,2}; int dy[7] = {3,0,0,0,1,1,1}; } Jewel::Jewel() : type_(JewelType::kNull), position_(util::Point(0,0)), texture_(nullptr), spritesheet_location_(0,0,0,0) {} Jewel::Jewel(graphics::Renderer &renderer, JewelType type, util::Point position) : type_(type), position_(position), texture_(nullptr) { LogSDL(texture_ = graphics::Texture(IMG_LoadTexture(renderer, "resources/sprites/sprites.bmp"))); int x, y; auto aux = static_cast<int>(type_); x = dx[aux]; y = dy[aux]; //spritesheet_location_ = util::Point(x * 32, y * 32) + Size(); spritesheet_location_ = Size() + util::Point(x * 32, y * 32); } void Jewel::Render(graphics::Renderer &renderer) { if (type_ != JewelType::kNull) renderer.RenderCopy(texture_, spritesheet_location_, Size() + position_); } util::Rectangle Jewel::Size() { static auto size = util::Rectangle{32, 32}; return size; } } // namespace bejeweled <commit_msg>Fix init of spritesheet_location on jewel<commit_after>#include "jewel.h" #include <SDL2/SDL_image.h> #include "graphics/Renderer.h" #include "util/Log.h" #include "util/Point.h" namespace bejeweled { namespace { int dx[7] = {3,0,1,2,0,1,2}; int dy[7] = {3,0,0,0,1,1,1}; } Jewel::Jewel() : type_(JewelType::kNull), position_(util::Point(0,0)), texture_(nullptr) {} Jewel::Jewel(graphics::Renderer &renderer, JewelType type, util::Point position) : type_(type), position_(position), texture_(nullptr) { LogSDL(texture_ = graphics::Texture(IMG_LoadTexture(renderer, "resources/sprites/sprites.bmp"))); int x, y; auto aux = static_cast<int>(type_); x = dx[aux]; y = dy[aux]; //spritesheet_location_ = util::Point(x * 32, y * 32) + Size(); spritesheet_location_ = Size() + util::Point(x * 32, y * 32); } void Jewel::Render(graphics::Renderer &renderer) { if (type_ != JewelType::kNull) renderer.RenderCopy(texture_, spritesheet_location_, Size() + position_); } util::Rectangle Jewel::Size() { static auto size = util::Rectangle{32, 32}; return size; } } // namespace bejeweled <|endoftext|>
<commit_before>/* * QML Material - An application framework implementing Material Design. * * Copyright (C) 2016 Michael Spencer <sonrisesoftware@gmail.com> * * 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 "units.h" #include <QGuiApplication> #include <QQuickItem> #if defined(Q_OS_ANDROID) #include <QtAndroidExtras> #endif #define DEFAULT_DPI 72 UnitsAttached::UnitsAttached(QObject *attachee) : QObject(attachee), m_screen(nullptr), m_window(nullptr), m_multiplier(1), m_dpi(0) { m_attachee = qobject_cast<QQuickItem *>(attachee); if (m_attachee) { if (m_attachee->window()) // It might not be assigned to a window yet windowChanged(m_attachee->window()); } else { QQuickWindow *window = qobject_cast<QQuickWindow *>(attachee); if (window) windowChanged(window); } if (!m_screen) screenChanged(QGuiApplication::primaryScreen()); } void UnitsAttached::windowChanged(QQuickWindow *window) { if (m_window) disconnect(m_window, &QQuickWindow::screenChanged, this, &UnitsAttached::screenChanged); m_window = window; screenChanged(window ? window->screen() : nullptr); if (window) connect(window, &QQuickWindow::screenChanged, this, &UnitsAttached::screenChanged); } void UnitsAttached::screenChanged(QScreen *screen) { if (screen != m_screen) { QScreen *oldScreen = m_screen; m_screen = screen; if (oldScreen) oldScreen->disconnect(this); if (oldScreen == nullptr || screen == nullptr || screen->physicalDotsPerInch() != oldScreen->physicalDotsPerInch() || screen->logicalDotsPerInch() != oldScreen->logicalDotsPerInch() || screen->devicePixelRatio() != oldScreen->devicePixelRatio()) { updateDPI(); emit dpChanged(); } } } int UnitsAttached::dp() const { #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) return m_multiplier; #else auto dp = dpi() / 160; return dp > 0 ? dp * m_multiplier : m_multiplier; #endif } int UnitsAttached::dpi() const { return m_dpi; } qreal UnitsAttached::multiplier() const { return m_multiplier; } void UnitsAttached::setMultiplier(qreal multiplier) { if (m_multiplier != multiplier) { m_multiplier = multiplier; emit multiplierChanged(); } } void UnitsAttached::updateDPI() { if (m_screen == nullptr) { m_dpi = DEFAULT_DPI; return; } #if defined(Q_OS_IOS) // iOS integration of scaling (retina, non-retina, 4K) does itself. m_dpi = m_screen->physicalDotsPerInch(); #elif defined(Q_OS_ANDROID) // https://bugreports.qt-project.org/browse/QTBUG-35701 // recalculate dpi for Android QAndroidJniEnvironment env; QAndroidJniObject activity = QtAndroid::androidActivity(); QAndroidJniObject resources = activity.callObjectMethod("getResources", "()Landroid/content/res/Resources;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); m_dpi = DEFAULT_DPI; return; } QAndroidJniObject displayMetrics = resources.callObjectMethod("getDisplayMetrics", "()Landroid/util/DisplayMetrics;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); m_dpi = DEFAULT_DPI; return; } m_dpi = displayMetrics.getField<int>("densityDpi"); #else // standard dpi m_dpi = m_screen->logicalDotsPerInch() * m_screen->devicePixelRatio(); #endif } <commit_msg>fix(units): Fix initialization order of two fields<commit_after>/* * QML Material - An application framework implementing Material Design. * * Copyright (C) 2016 Michael Spencer <sonrisesoftware@gmail.com> * * 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 "units.h" #include <QGuiApplication> #include <QQuickItem> #if defined(Q_OS_ANDROID) #include <QtAndroidExtras> #endif #define DEFAULT_DPI 72 UnitsAttached::UnitsAttached(QObject *attachee) : QObject(attachee), m_screen(nullptr), m_window(nullptr), m_dpi(0), m_multiplier(1) { m_attachee = qobject_cast<QQuickItem *>(attachee); if (m_attachee) { if (m_attachee->window()) // It might not be assigned to a window yet windowChanged(m_attachee->window()); } else { QQuickWindow *window = qobject_cast<QQuickWindow *>(attachee); if (window) windowChanged(window); } if (!m_screen) screenChanged(QGuiApplication::primaryScreen()); } void UnitsAttached::windowChanged(QQuickWindow *window) { if (m_window) disconnect(m_window, &QQuickWindow::screenChanged, this, &UnitsAttached::screenChanged); m_window = window; screenChanged(window ? window->screen() : nullptr); if (window) connect(window, &QQuickWindow::screenChanged, this, &UnitsAttached::screenChanged); } void UnitsAttached::screenChanged(QScreen *screen) { if (screen != m_screen) { QScreen *oldScreen = m_screen; m_screen = screen; if (oldScreen) oldScreen->disconnect(this); if (oldScreen == nullptr || screen == nullptr || screen->physicalDotsPerInch() != oldScreen->physicalDotsPerInch() || screen->logicalDotsPerInch() != oldScreen->logicalDotsPerInch() || screen->devicePixelRatio() != oldScreen->devicePixelRatio()) { updateDPI(); emit dpChanged(); } } } int UnitsAttached::dp() const { #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) return m_multiplier; #else auto dp = dpi() / 160; return dp > 0 ? dp * m_multiplier : m_multiplier; #endif } int UnitsAttached::dpi() const { return m_dpi; } qreal UnitsAttached::multiplier() const { return m_multiplier; } void UnitsAttached::setMultiplier(qreal multiplier) { if (m_multiplier != multiplier) { m_multiplier = multiplier; emit multiplierChanged(); } } void UnitsAttached::updateDPI() { if (m_screen == nullptr) { m_dpi = DEFAULT_DPI; return; } #if defined(Q_OS_IOS) // iOS integration of scaling (retina, non-retina, 4K) does itself. m_dpi = m_screen->physicalDotsPerInch(); #elif defined(Q_OS_ANDROID) // https://bugreports.qt-project.org/browse/QTBUG-35701 // recalculate dpi for Android QAndroidJniEnvironment env; QAndroidJniObject activity = QtAndroid::androidActivity(); QAndroidJniObject resources = activity.callObjectMethod("getResources", "()Landroid/content/res/Resources;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); m_dpi = DEFAULT_DPI; return; } QAndroidJniObject displayMetrics = resources.callObjectMethod("getDisplayMetrics", "()Landroid/util/DisplayMetrics;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); m_dpi = DEFAULT_DPI; return; } m_dpi = displayMetrics.getField<int>("densityDpi"); #else // standard dpi m_dpi = m_screen->logicalDotsPerInch() * m_screen->devicePixelRatio(); #endif } <|endoftext|>
<commit_before>#include "Token/Token.h" #include "Generator/Generator.h" #include <cstring> #include <cstdlib> #include <unistd.h> #include <sys/stat.h> #include <getopt.h> #include <cstdio> const int MAX_LIBS = 100; const int MAX_INPUT_FILES = 100; using namespace dale; int appears_to_be_lib(char *str) { int len = strlen(str); if (len >= 2) { char *end = str + (len - 2); if ((!strcmp(end, ".o")) || (!strcmp(end, ".a"))) { return 1; } } return 0; } int main(int argc, char **argv) { const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR"; int opt; char optc; char *input_files[MAX_INPUT_FILES]; char *input_link_files[MAX_INPUT_FILES]; const char *compile_libs[MAX_LIBS]; const char *run_libs[MAX_LIBS]; char *include_paths[MAX_LIBS]; char *run_paths[MAX_LIBS]; char *bitcode_paths[MAX_LIBS]; char *static_modules[MAX_LIBS]; char *cto_modules[MAX_LIBS]; char *output_path_arg = NULL; char *module_paths[MAX_LIBS]; int no_linking = 0; int produce = ASM; int produce_set = 0; int optlevel = 0; int cto_module_count = 0; int static_module_count = 0; int compile_lib_count = 0; int input_link_file_count = 0; int run_lib_count = 0; int include_path_count = 0; int run_path_count = 0; int input_file_count = 0; int j = 0; int debug = 0; char output_path[256] = ""; int no_dale_stdlib = 0; int no_stdlib = 0; int bitcode_path_count = 0; int remove_macros = 0; int no_common = 0; char *module_name = NULL; int no_strip = 0; int static_mods_all = 0; int found_sm = 0; int found_ctom = 0; int enable_cto = 0; int module_path_count = 0; if (argc < 2) { fprintf(stderr, "dalec: no input files.\n"); exit(1); } static struct option long_options[] = { { "no-dale-stdlib", no_argument, &no_dale_stdlib, 1 }, { "no-common", no_argument, &no_common, 1 }, { "no-stdlib", no_argument, &no_stdlib, 1 }, { "no-strip", no_argument, &no_strip, 1 }, { "static-modules", no_argument, &static_mods_all, 1 }, { "static-module", required_argument, &found_sm, 1 }, { "cto-module", required_argument, &found_ctom, 1 }, { "enable-cto", no_argument, &enable_cto, 1 }, { 0, 0, 0, 0 } }; int option_index = 0; int forced_remove_macros = 0; while ((opt = getopt_long(argc, argv, options, long_options, &option_index)) != -1) { optc = (char) opt; if (optc == 'o') { if (output_path_arg) { fprintf(stderr, "dalec: an output path has already " "been specified.\n"); exit(1); } output_path_arg = optarg; } else if (optc == 'd') { debug = 1; } else if (optc == 'O') { optlevel = (optarg[0] - '0'); if ((optlevel < 0) || (optlevel > 4)) { fprintf(stderr, "dalec: invalid optimisation level.\n"); exit(1); } } else if (optc == 's') { char *type = optarg; if (!strcmp(type, "as")) { produce = ASM; } else if (!strcmp(type, "ir")) { produce = IR; } else if (!strcmp(type, "bc")) { produce = BitCode; } else { fprintf(stderr, "dalec: unrecognised output " "option: %s\n", type); exit(1); } produce_set = 1; } else if (optc == 'I') { if (include_path_count == MAX_LIBS) { fprintf(stderr, "dalec: hit include path limit (change " "the limit in dale-to-bc.\n"); exit(1); } include_paths[include_path_count++] = optarg; } else if (optc == 'a') { if (compile_lib_count == MAX_LIBS) { fprintf(stderr, "dalec: hit library limit (change " "the limit in dale-to-bc.\n"); exit(1); } compile_libs[compile_lib_count++] = optarg; } else if (optc == 'L') { if (run_path_count == MAX_LIBS) { fprintf(stderr, "dalec: hit run-include path limit (change " "the limit in dale-to-bc.\n"); exit(1); } run_paths[run_path_count++] = optarg; } else if (optc == 'l') { if (run_lib_count == MAX_LIBS) { fprintf(stderr, "dalec: hit run-library limit (change " "the limit in dale-to-bc.\n"); exit(1); } run_libs[run_lib_count++] = optarg; } else if (optc == 'b') { if (run_lib_count == MAX_LIBS) { fprintf(stderr, "dalec: hit bitcode path limit (change " "the limit in dale-to-bc.\n"); exit(1); } bitcode_paths[bitcode_path_count++] = optarg; } else if (optc == 'M') { if (module_path_count == MAX_LIBS) { fprintf(stderr, "dalec: hit module path limit (change " "the limit in dale-to-bc.\n"); exit(1); } module_paths[module_path_count++] = optarg; } else if (optc == 'c') { no_linking = 1; } else if (optc == 'r') { remove_macros = 1; forced_remove_macros = 1; } else if (optc == 'R') { remove_macros = 0; forced_remove_macros = 1; } else if (optc == 'm') { module_name = optarg; } else if (found_sm == 1) { found_sm = 0; static_modules[static_module_count++] = optarg; } else if (found_ctom == 1) { found_sm = 0; cto_modules[cto_module_count++] = optarg; } } /* If the user wants an executable and has not specified either * way with respect to removing macros, then remove macros. */ if (!no_linking && !produce_set && !forced_remove_macros) { remove_macros = 1; } input_file_count = argc - optind; if (input_file_count > MAX_INPUT_FILES) { fprintf(stderr, "dalec: input file count (%d) exceeds the " "maximum number of input files that " "may be specified.\n", input_file_count); exit(1); } for (j = 0; j < input_file_count; ++j) { input_files[j] = argv[optind + j]; } /* Input files that end with .o or .a should go straight to the * linker. */ int actual_input_file_count = input_file_count; for (int k = 0; k < input_file_count; k++) { int len = strlen(input_files[k]); if (len >= 2) { if (appears_to_be_lib(input_files[k])) { input_link_files[input_link_file_count++] = input_files[k]; actual_input_file_count--; } } } if (actual_input_file_count < 1) { fprintf(stderr, "dalec: no input files.\n"); exit(1); } if (!no_linking) { if (output_path_arg) { strncpy(output_path, output_path_arg, 256); } else { if (produce == ASM) { sprintf(output_path, "a.out"); } else if (produce_set) { strncpy(output_path, input_files[0], 253); strcat(output_path, (produce == IR) ? ".ll" : (produce == ASM) ? ".s" : (produce == BitCode) ? ".bc" : ".unknown" ); } } } else { if (output_path_arg) { strncpy(output_path, output_path_arg, 256); } else { strncpy(output_path, input_files[0], 253); strcat(output_path, ".o"); } } char compile_lib_str[1024] = ""; for (int i = 0; i < compile_lib_count; ++i) { strcat(compile_lib_str, " -l "); strcat(compile_lib_str, compile_libs[i]); } char include_path_str[1024] = ""; for (int i = 0; i < include_path_count; ++i) { strcat(include_path_str, " -I "); strcat(include_path_str, include_paths[i]); } char run_path_str[1024] = ""; for (int i = 0; i < run_path_count; ++i) { strcat(run_path_str, " -L "); strcat(run_path_str, run_paths[i]); } char input_file_str[1024] = ""; for (int i = 0; i < input_file_count; ++i) { if (!appears_to_be_lib(input_files[i])) { strcat(input_file_str, " "); strcat(input_file_str, input_files[i]); } } std::vector<const char*> vinput_files; for (j = 0; j < input_file_count; ++j) { if (!appears_to_be_lib(argv[optind + j])) { vinput_files.push_back(argv[optind + j]); } } char input_link_file_str[1024] = ""; for (int i = 0; i < input_link_file_count; ++i) { strcat(input_link_file_str, " "); strcat(input_link_file_str, input_link_files[i]); } FILE *tempout = tmpfile(); if (!tempout) { perror("Unable to open temporary output file"); exit(1); } Generator *g = new Generator(); std::vector<const char*> compile_libs_sv; for (j = 0; j < compile_lib_count; ++j) { compile_libs_sv.push_back(compile_libs[j]); } std::vector<const char*> include_paths_sv; for (j = 0; j < include_path_count; ++j) { include_paths_sv.push_back(include_paths[j]); } std::vector<const char*> module_paths_sv; for (j = 0; j < module_path_count; ++j) { module_paths_sv.push_back(module_paths[j]); } std::vector<const char*> bc_files; for (j = 0; j < bitcode_path_count; ++j) { bc_files.push_back(bitcode_paths[j]); } std::vector<const char*> vstatic_modules; for (j = 0; j < static_module_count; ++j) { vstatic_modules.push_back(static_modules[j]); } std::vector<const char*> vcto_modules; for (j = 0; j < cto_module_count; ++j) { vcto_modules.push_back(cto_modules[j]); } std::vector<std::string> so_paths; //so_paths.push_back("/usr/local/lib/libffi.so"); int rest = g->run(&vinput_files, &bc_files, tempout, produce, optlevel, remove_macros, module_name, no_common, &so_paths, no_strip, static_mods_all, &vstatic_modules, &vcto_modules, enable_cto, debug, no_dale_stdlib, &compile_libs_sv, &include_paths_sv, &module_paths_sv); if (!rest) { exit(1); } delete g; char run_lib_str[1024] = ""; for (int i = 0; i < run_lib_count; ++i) { strcat(run_lib_str, " -l"); strcat(run_lib_str, run_libs[i]); } for (std::vector<std::string>::reverse_iterator b = so_paths.rbegin(), e = so_paths.rend(); b != e; ++b) { strcat(input_link_file_str, " "); strcat(input_link_file_str, (*b).c_str()); } char temp_output_path[256] = ""; strcpy(temp_output_path, output_path); if (!produce_set) { strcat(temp_output_path, ".s"); } if (!rest) { exit(1); } if (rest) { fflush(tempout); FILE *out = fopen(temp_output_path, "w"); fseek(tempout, 0, SEEK_SET); char buf[8192]; memset(buf, 0, 8192); size_t bytes; size_t wbytes; while ((bytes = fread(buf, (size_t) 1, (size_t) 8192, tempout))) { if (ferror(tempout)) { perror("Unable to read output file"); fclose(tempout); fclose(out); break; } wbytes = fwrite(buf, (size_t) 1, bytes, out); if (wbytes != bytes) { if (ferror(tempout)) { perror("Unable to copy file content"); break; } if (ferror(out)) { perror("Unable to copy file content"); break; } } if (bytes != 8192) { if (feof(tempout)) { break; } else { perror("Unable to copy file content"); break; } } memset(buf, 0, 8192); } fflush(tempout); fflush(out); fclose(tempout); fclose(out); } if (produce_set) { exit(0); } char final[8192] = ""; final[0] = '\0'; if (no_linking) { sprintf(final, "cc %s -c %s " "%s %s -o %s", (no_stdlib) ? "--nostdlib" : "", run_path_str, run_lib_str, temp_output_path, // not needed, obviously enough //input_link_file_str, output_path); int res = system(final); if (res) { perror("Unable to run cc"); fprintf(stderr, "dalec: cc failed: %d (%s)\n", res, final); exit(1); } } else { sprintf(final, "cc %s -Wl,--gc-sections %s " "%s %s %s -o %s", (no_stdlib) ? "--nostdlib" : "", run_path_str, temp_output_path, input_link_file_str, run_lib_str, output_path); int res = system(final); if (res) { perror("Unable to run cc"); fprintf(stderr, "dalec: cc failed: %d (%s)\n", res, final); exit(1); } } int rres = remove(temp_output_path); if (rres) { fprintf(stderr, "Internal error: unable to remove " "temporary file (%s).\n", temp_output_path); } return 0; } <commit_msg>[master] tidying<commit_after>#include "Token/Token.h" #include "Generator/Generator.h" #include <cstring> #include <cstdlib> #include <unistd.h> #include <sys/stat.h> #include <getopt.h> #include <cstdio> using namespace dale; int appears_to_be_lib(const char *str) { int len = strlen(str); if (len >= 2) { const char *end = str + (len - 2); if ((!strcmp(end, ".o")) || (!strcmp(end, ".a"))) { return 1; } } return 0; } int main(int argc, char **argv) { const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR"; int opt; char optc; std::vector<const char*> input_files; std::vector<const char*> input_link_files; std::vector<const char*> compile_libs; std::vector<const char*> run_libs; std::vector<const char*> include_paths; std::vector<const char*> run_paths; std::vector<const char*> bitcode_paths; std::vector<const char*> static_modules; std::vector<const char*> cto_modules; std::vector<const char*> module_paths; char *output_path_arg = NULL; int no_linking = 0; int produce = ASM; int produce_set = 0; int optlevel = 0; int input_file_count; int j = 0; int debug = 0; char output_path[256] = ""; int no_dale_stdlib = 0; int no_stdlib = 0; int remove_macros = 0; int no_common = 0; char *module_name = NULL; int no_strip = 0; int static_mods_all = 0; int found_sm = 0; int found_ctom = 0; int enable_cto = 0; if (argc < 2) { fprintf(stderr, "dalec: no input files.\n"); exit(1); } static struct option long_options[] = { { "no-dale-stdlib", no_argument, &no_dale_stdlib, 1 }, { "no-common", no_argument, &no_common, 1 }, { "no-stdlib", no_argument, &no_stdlib, 1 }, { "no-strip", no_argument, &no_strip, 1 }, { "static-modules", no_argument, &static_mods_all, 1 }, { "static-module", required_argument, &found_sm, 1 }, { "cto-module", required_argument, &found_ctom, 1 }, { "enable-cto", no_argument, &enable_cto, 1 }, { 0, 0, 0, 0 } }; int option_index = 0; int forced_remove_macros = 0; while ((opt = getopt_long(argc, argv, options, long_options, &option_index)) != -1) { optc = (char) opt; if (optc == 'o') { if (output_path_arg) { fprintf(stderr, "dalec: an output path has already " "been specified.\n"); exit(1); } output_path_arg = optarg; } else if (optc == 'd') { debug = 1; } else if (optc == 'O') { optlevel = (optarg[0] - '0'); if ((optlevel < 0) || (optlevel > 4)) { fprintf(stderr, "dalec: invalid optimisation level.\n"); exit(1); } } else if (optc == 's') { char *type = optarg; if (!strcmp(type, "as")) { produce = ASM; } else if (!strcmp(type, "ir")) { produce = IR; } else if (!strcmp(type, "bc")) { produce = BitCode; } else { fprintf(stderr, "dalec: unrecognised output " "option: %s\n", type); exit(1); } produce_set = 1; } else if (optc == 'I') { include_paths.push_back(optarg); } else if (optc == 'a') { compile_libs.push_back(optarg); } else if (optc == 'L') { run_paths.push_back(optarg); } else if (optc == 'l') { run_libs.push_back(optarg); } else if (optc == 'b') { bitcode_paths.push_back(optarg); } else if (optc == 'M') { module_paths.push_back(optarg); } else if (optc == 'c') { no_linking = 1; } else if (optc == 'r') { remove_macros = 1; forced_remove_macros = 1; } else if (optc == 'R') { remove_macros = 0; forced_remove_macros = 1; } else if (optc == 'm') { module_name = optarg; } else if (found_sm == 1) { found_sm = 0; static_modules.push_back(optarg); } else if (found_ctom == 1) { found_sm = 0; cto_modules.push_back(optarg); } } /* If the user wants an executable and has not specified either * way with respect to removing macros, then remove macros. */ if (!no_linking && !produce_set && !forced_remove_macros) { remove_macros = 1; } input_file_count = argc - optind; for (j = 0; j < input_file_count; ++j) { input_files.push_back(argv[optind + j]); } /* Input files that end with .o or .a should go straight to the * linker. */ int actual_input_file_count = input_file_count; for (int k = 0; k < input_file_count; k++) { int len = strlen(input_files[k]); if (len >= 2) { if (appears_to_be_lib(input_files[k])) { input_link_files.push_back(input_files[k]); actual_input_file_count--; } } } if (actual_input_file_count < 1) { fprintf(stderr, "dalec: no input files.\n"); exit(1); } if (!no_linking) { if (output_path_arg) { strncpy(output_path, output_path_arg, 256); } else { if (produce == ASM) { sprintf(output_path, "a.out"); } else if (produce_set) { strncpy(output_path, input_files[0], 253); strcat(output_path, (produce == IR) ? ".ll" : (produce == ASM) ? ".s" : (produce == BitCode) ? ".bc" : ".unknown" ); } } } else { if (output_path_arg) { strncpy(output_path, output_path_arg, 256); } else { strncpy(output_path, input_files[0], 253); strcat(output_path, ".o"); } } std::string compile_lib_str; for (std::vector<const char*>::iterator b = compile_libs.begin(), e = compile_libs.end(); b != e; ++b) { compile_lib_str.append(" -l "); compile_lib_str.append(*b); } std::string include_path_str; for (std::vector<const char*>::iterator b = include_paths.begin(), e = include_paths.end(); b != e; ++b) { include_path_str.append(" -I "); include_path_str.append(*b); } std::string run_path_str; for (std::vector<const char*>::iterator b = run_paths.begin(), e = run_paths.end(); b != e; ++b) { run_path_str.append(" -L "); run_path_str.append(*b); } std::string input_file_str; for (std::vector<const char*>::iterator b = input_files.begin(), e = input_files.end(); b != e; ++b) { if (!appears_to_be_lib(*b)) { input_file_str.append(" "); input_file_str.append(*b); } } std::vector<const char*> non_lib_input_files; for (std::vector<const char*>::iterator b = input_files.begin(), e = input_files.end(); b != e; ++b) { if (!appears_to_be_lib(*b)) { non_lib_input_files.push_back(*b); } } std::string input_link_file_str; for (std::vector<const char*>::iterator b = input_link_files.begin(), e = input_link_files.end(); b != e; ++b) { input_link_file_str.append(" "); input_link_file_str.append(*b); } FILE *tempout = tmpfile(); if (!tempout) { perror("Unable to open temporary output file"); exit(1); } Generator g; std::vector<std::string> so_paths; int rest = g.run(&non_lib_input_files, &bitcode_paths, tempout, produce, optlevel, remove_macros, module_name, no_common, &so_paths, no_strip, static_mods_all, &static_modules, &cto_modules, enable_cto, debug, no_dale_stdlib, &compile_libs, &include_paths, &module_paths); if (!rest) { exit(1); } std::string run_lib_str; for (std::vector<const char*>::iterator b = run_libs.begin(), e = run_libs.end(); b != e; ++b) { run_lib_str.append(" -l "); run_lib_str.append(*b); } for (std::vector<std::string>::reverse_iterator b = so_paths.rbegin(), e = so_paths.rend(); b != e; ++b) { input_link_file_str.append(" "); input_link_file_str.append((*b).c_str()); } char temp_output_path[256] = ""; strcpy(temp_output_path, output_path); if (!produce_set) { strcat(temp_output_path, ".s"); } if (!rest) { exit(1); } if (rest) { fflush(tempout); FILE *out = fopen(temp_output_path, "w"); fseek(tempout, 0, SEEK_SET); char buf[8192]; memset(buf, 0, 8192); size_t bytes; size_t wbytes; while ((bytes = fread(buf, (size_t) 1, (size_t) 8192, tempout))) { if (ferror(tempout)) { perror("Unable to read output file"); fclose(tempout); fclose(out); break; } wbytes = fwrite(buf, (size_t) 1, bytes, out); if (wbytes != bytes) { if (ferror(tempout)) { perror("Unable to copy file content"); break; } if (ferror(out)) { perror("Unable to copy file content"); break; } } if (bytes != 8192) { if (feof(tempout)) { break; } else { perror("Unable to copy file content"); break; } } memset(buf, 0, 8192); } fflush(tempout); fflush(out); fclose(tempout); fclose(out); } if (produce_set) { exit(0); } char final[8192] = ""; final[0] = '\0'; if (no_linking) { sprintf(final, "cc %s -c %s " "%s %s -o %s", (no_stdlib) ? "--nostdlib" : "", run_path_str.c_str(), run_lib_str.c_str(), temp_output_path, output_path); int res = system(final); if (res) { perror("Unable to run cc"); fprintf(stderr, "dalec: cc failed: %d (%s)\n", res, final); exit(1); } } else { sprintf(final, "cc %s -Wl,--gc-sections %s " "%s %s %s -o %s", (no_stdlib) ? "--nostdlib" : "", run_path_str.c_str(), temp_output_path, input_link_file_str.c_str(), run_lib_str.c_str(), output_path); int res = system(final); if (res) { perror("Unable to run cc"); fprintf(stderr, "dalec: cc failed: %d (%s)\n", res, final); exit(1); } } int rres = remove(temp_output_path); if (rres) { fprintf(stderr, "Internal error: unable to remove " "temporary file (%s).\n", temp_output_path); } return 0; } <|endoftext|>
<commit_before><commit_msg>bug fix. initialize all<commit_after><|endoftext|>
<commit_before><commit_msg>No need for a sub-stream; we reset m_SkipFlag.<commit_after><|endoftext|>
<commit_before><commit_msg>[PECOFF] Make ReaderCOFF more robust against planned identity_magic() changes.<commit_after><|endoftext|>
<commit_before><commit_msg>AMDGPU: Fix typo<commit_after><|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2010-2011 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <limits> #include <algorithm> using namespace Vc; template<typename V1, typename V2> void testNumber(double n) { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; // compare casts from T1 -> T2 with casts from V1 -> V2 const T1 n1 = static_cast<T1>(n); //std::cerr << "n1 = " << n1 << ", static_cast<T2>(n1) = " << static_cast<T2>(n1) << std::endl; COMPARE(static_cast<V2>(V1(n1)), V2(static_cast<T2>(n1))) << "\n n1: " << n1; } template<typename T> double maxHelper() { return static_cast<double>(std::numeric_limits<T>::max()); } template<> double maxHelper<int>() { const int intDigits = std::numeric_limits<int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((int(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<> double maxHelper<unsigned int>() { const int intDigits = std::numeric_limits<unsigned int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((unsigned(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<typename V1, typename V2> void testCast2() { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; const double max = std::min(maxHelper<T1>(), maxHelper<T2>()); const double min = std::max( std::numeric_limits<T1>::is_integer ? static_cast<double>(std::numeric_limits<T1>::min()) : static_cast<double>(-std::numeric_limits<T1>::max()), std::numeric_limits<T2>::is_integer ? static_cast<double>(std::numeric_limits<T2>::min()) : static_cast<double>(-std::numeric_limits<T2>::max()) ); testNumber<V1, V2>(0.); testNumber<V1, V2>(1.); testNumber<V1, V2>(2.); testNumber<V1, V2>(max); testNumber<V1, V2>(max / 4 + max / 2); testNumber<V1, V2>(max / 2); testNumber<V1, V2>(max / 4); testNumber<V1, V2>(min); } template<typename T> void testCast() { testCast2<typename T::V1, typename T::V2>(); } #define _CONCAT(A, B) A ## _ ## B #define CONCAT(A, B) _CONCAT(A, B) template<typename T1, typename T2> struct T2Helper { typedef T1 V1; typedef T2 V2; }; void testmain() { #define TEST(v1, v2) \ typedef T2Helper<v1, v2> CONCAT(v1, v2); \ runTest(testCast<CONCAT(v1, v2)>) TEST(float_v, float_v); TEST(float_v, int_v); TEST(float_v, uint_v); // needs special handling for different Size: //TEST(float_v, double_v); //TEST(float_v, short_v); //TEST(float_v, ushort_v); TEST(int_v, float_v); TEST(int_v, int_v); TEST(int_v, uint_v); TEST(uint_v, float_v); TEST(uint_v, int_v); TEST(uint_v, uint_v); TEST(ushort_v, short_v); TEST(ushort_v, ushort_v); TEST(short_v, short_v); TEST(short_v, ushort_v); #undef TEST } <commit_msg>test casts for -1: underflow for unsigned ints<commit_after>/* This file is part of the Vc library. Copyright (C) 2010-2011 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <limits> #include <algorithm> using namespace Vc; template<typename V1, typename V2> void testNumber(double n) { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; // compare casts from T1 -> T2 with casts from V1 -> V2 const T1 n1 = static_cast<T1>(n); //std::cerr << "n1 = " << n1 << ", static_cast<T2>(n1) = " << static_cast<T2>(n1) << std::endl; COMPARE(static_cast<V2>(V1(n1)), V2(static_cast<T2>(n1))) << "\n n1: " << n1; } template<typename T> double maxHelper() { return static_cast<double>(std::numeric_limits<T>::max()); } template<> double maxHelper<int>() { const int intDigits = std::numeric_limits<int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((int(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<> double maxHelper<unsigned int>() { const int intDigits = std::numeric_limits<unsigned int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((unsigned(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<typename V1, typename V2> void testCast2() { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; const double max = std::min(maxHelper<T1>(), maxHelper<T2>()); const double min = std::max( std::numeric_limits<T1>::is_integer ? static_cast<double>(std::numeric_limits<T1>::min()) : static_cast<double>(-std::numeric_limits<T1>::max()), std::numeric_limits<T2>::is_integer ? static_cast<double>(std::numeric_limits<T2>::min()) : static_cast<double>(-std::numeric_limits<T2>::max()) ); testNumber<V1, V2>(-1.); testNumber<V1, V2>(0.); testNumber<V1, V2>(1.); testNumber<V1, V2>(2.); testNumber<V1, V2>(max); testNumber<V1, V2>(max / 4 + max / 2); testNumber<V1, V2>(max / 2); testNumber<V1, V2>(max / 4); testNumber<V1, V2>(min); } template<typename T> void testCast() { testCast2<typename T::V1, typename T::V2>(); } #define _CONCAT(A, B) A ## _ ## B #define CONCAT(A, B) _CONCAT(A, B) template<typename T1, typename T2> struct T2Helper { typedef T1 V1; typedef T2 V2; }; void testmain() { #define TEST(v1, v2) \ typedef T2Helper<v1, v2> CONCAT(v1, v2); \ runTest(testCast<CONCAT(v1, v2)>) TEST(float_v, float_v); TEST(float_v, int_v); TEST(float_v, uint_v); // needs special handling for different Size: //TEST(float_v, double_v); //TEST(float_v, short_v); //TEST(float_v, ushort_v); TEST(int_v, float_v); TEST(int_v, int_v); TEST(int_v, uint_v); TEST(uint_v, float_v); TEST(uint_v, int_v); TEST(uint_v, uint_v); TEST(ushort_v, short_v); TEST(ushort_v, ushort_v); TEST(short_v, short_v); TEST(short_v, ushort_v); #undef TEST } <|endoftext|>
<commit_before>#ifndef MJOLNIR_READ_OBSERVER #define MJOLNIR_READ_OBSERVER #include <extlib/toml/toml.hpp> #include <mjolnir/core/Observer.hpp> #include <mjolnir/util/get_toml_value.hpp> #include <mjolnir/util/logger.hpp> namespace mjolnir { template<typename traitsT> Observer<traitsT> read_observer(const toml::Table& data) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_observer(), 0); const auto& files = get_toml_value<toml::Table>(data, "files", "<root>"); std::string path = get_toml_value<std::string>(files, "output_path", "[files]"); if(path.back() != '/') {path += '/';} //XXX assuming posix const std::string prefix = get_toml_value<std::string>( files, "output_prefix", "[files]"); MJOLNIR_LOG_INFO("path = ", path); MJOLNIR_LOG_INFO("prefix = ", prefix); return Observer<traitsT>(path + prefix); } } #endif// MJOLNIR_READ_OBSERVER <commit_msg>add LOG_NOTICE to read_observer<commit_after>#ifndef MJOLNIR_READ_OBSERVER #define MJOLNIR_READ_OBSERVER #include <extlib/toml/toml.hpp> #include <mjolnir/core/Observer.hpp> #include <mjolnir/util/get_toml_value.hpp> #include <mjolnir/util/logger.hpp> namespace mjolnir { template<typename traitsT> Observer<traitsT> read_observer(const toml::Table& data) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_observer(), 0); const auto& files = get_toml_value<toml::Table>(data, "files", "<root>"); std::string path_ = get_toml_value<std::string>(files, "output_path", "[files]"); if(path_.back() != '/') {path_ += '/';} //XXX assuming posix const auto path(path_); const std::string prefix = get_toml_value<std::string>( files, "output_prefix", "[files]"); MJOLNIR_LOG_INFO("path = ", path); MJOLNIR_LOG_INFO("prefix = ", prefix); MJOLNIR_LOG_NOTICE("output files are `", path, prefix, ".*`"); return Observer<traitsT>(path + prefix); } } #endif// MJOLNIR_READ_OBSERVER <|endoftext|>
<commit_before>/* Crystal Space Event Queue Copyright (C) 1998-2004 by Jorrit Tyberghein Written by Andrew Zabolotny <bit@eltech.ru>, Eric Sunshine, Jonathan Tarbox, Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/array.h" #include "csutil/csevent.h" #include "csutil/cseventq.h" #include "csutil/memfile.h" #include "csutil/util.h" #include "csutil/sysfunc.h" //--------------------------------------------------------------------------- SCF_IMPLEMENT_IBASE (csEvent) SCF_IMPLEMENTS_INTERFACE (iEvent) SCF_IMPLEMENTS_INTERFACE (csEvent) SCF_IMPLEMENT_IBASE_END CS_IMPLEMENT_STATIC_VAR(GetEventStrSet, csStringSet, ()) char const* csEvent::GetTypeName (csEventAttributeType t) { switch (t) { case csEventAttrInt: return "int"; case csEventAttrUInt: return "uint"; case csEventAttrFloat: return "double"; case csEventAttrDatabuffer: return "databuffer"; case csEventAttrEvent: return "event"; case csEventAttriBase: return "iBase"; default: break; } return "unknown"; } csStringID csEvent::GetKeyID (const char* key) { return GetEventStrSet()->Request (key); } const char* csEvent::GetKeyName (csStringID id) { return GetEventStrSet()->Request (id); } csEvent::csEvent () { SCF_CONSTRUCT_IBASE (0); count = 0; } csEvent::csEvent (csTicks iTime, int eType, int mx, int my, int mButton, int mModifiers) : attributes (53) { SCF_CONSTRUCT_IBASE (0); Time = iTime; Type = eType; Category = SubCategory = Flags = 0; Mouse.x = mx; Mouse.y = my; Mouse.Button = mButton; Mouse.Modifiers = mModifiers; count = 0; } csEvent::csEvent (csTicks iTime, int eType, int jn, int jx, int jy, int jButton, int jModifiers) : attributes (53) { SCF_CONSTRUCT_IBASE (0); Time = iTime; Type = eType; Category = SubCategory = Flags = 0; Joystick.number = jn; Joystick.x = jx; Joystick.y = jy; Joystick.Button = jButton; Joystick.Modifiers = jModifiers; count = 0; } csEvent::csEvent (csTicks iTime, int eType, int cCode, void *cInfo) : attributes (53) { SCF_CONSTRUCT_IBASE (0); Time = iTime; Type = eType; Category = SubCategory = Flags = 0; Command.Code = cCode; Command.Info = cInfo; if (eType == csevBroadcast) Flags = CSEF_BROADCAST; count = 0; } csEvent::csEvent (csEvent const& e) : iEvent(), attributes (53) { SCF_CONSTRUCT_IBASE (0); count = 0; Type = e.Type; Category = e.Category; SubCategory = e.SubCategory; Flags = e.Flags; Time = e.Time; attributes = e.attributes; if ((Type & CSMASK_Mouse) != 0) { Mouse.x = e.Mouse.x; Mouse.y = e.Mouse.y; Mouse.Button = e.Mouse.Button; Mouse.Modifiers = e.Mouse.Modifiers; } else if ((Type & CSMASK_Joystick) != 0) { Joystick.number = e.Joystick.number; Joystick.x = e.Joystick.x; Joystick.y = e.Joystick.y; Joystick.Button = e.Joystick.Button; Joystick.Modifiers = e.Joystick.Modifiers; } else { Command.Code = e.Command.Code; Command.Info = e.Command.Info; } } csEvent::~csEvent () { RemoveAll(); SCF_DESTRUCT_IBASE (); } bool csEvent::Add (const char *name, float v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrFloat); object->doubleVal = v; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, double v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrFloat); object->doubleVal = v; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, bool v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrInt); object->intVal = v ? 1 : 0; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, const char *v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrDatabuffer); object->dataSize = strlen(v); object->bufferVal = csStrNew(v); attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, const void *v, size_t size) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrDatabuffer); object->bufferVal = new char[size + 1]; memcpy (object->bufferVal, v, size); object->bufferVal[size] = 0; object->dataSize = size; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::CheckForLoops (iEvent* current, iEvent* e) { csRef<iEventAttributeIterator> iter (current->GetAttributeIterator()); while (iter->HasNext()) { const char* attr = iter->Next(); if (current->GetAttributeType (attr) == csEventAttrEvent) { csRef<iEvent> ev; if (current->Retrieve (attr, ev) != csEventErrNone) continue; if (ev == e) return false; return CheckForLoops(ev, e); } } return true; } bool csEvent::Add (const char *name, iEvent *v) { if (attributes.In (GetKeyID (name))) return false; if (this == v) return false; if (v && CheckForLoops(v, this)) { attribute* object = new attribute (csEventAttrEvent); (object->ibaseVal = (iBase*)v)->IncRef(); attributes.Put (GetKeyID (name), object); count++; return true; } return false; } bool csEvent::Add (const char *name, iBase* v) { if (attributes.In (GetKeyID (name))) return false; if (v) { attribute* object = new attribute (csEventAttriBase); (object->ibaseVal = v)->IncRef(); attributes.Put (GetKeyID (name), object); count++; return true; } return false; } csEventError csEvent::Retrieve (const char *name, float &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrFloat) { v = object->doubleVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, double &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrFloat) { v = object->doubleVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, const char *&v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrDatabuffer) { v = object->bufferVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, void const *&v, size_t &size) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrDatabuffer) { v = object->bufferVal; size = object->dataSize; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, bool &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrInt) { v = object->intVal != 0; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, csRef<iEvent> &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrEvent) { v = (iEvent*)object->ibaseVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, csRef<iBase> &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttriBase) { v = object->ibaseVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } bool csEvent::AttributeExists (const char* name) { return attributes.In (GetKeyID (name)); } csEventAttributeType csEvent::GetAttributeType (const char* name) { attribute* object = attributes.Get (GetKeyID (name), 0); if (object) { return object->type; } return csEventAttrUnknown; } bool csEvent::Remove(const char *name) { csStringID id = GetKeyID (name); if (!attributes.In (id)) return false; attribute* object = attributes.Get (id, 0); bool result = attributes.Delete (id, object); delete object; return result; } bool csEvent::RemoveAll() { csHash<attribute*, csStringID>::GlobalIterator iter ( attributes.GetIterator ()); while (iter.HasNext()) { csStringID name; attribute* object = iter.Next (name); delete object; } attributes.DeleteAll(); count = 0; return true; } csRef<iEventAttributeIterator> csEvent::GetAttributeIterator() { csHash<csEvent::attribute*, csStringID>::GlobalIterator attrIter ( attributes.GetIterator()); return csPtr<iEventAttributeIterator> (new csEventAttributeIterator ( attrIter)); } static void IndentLevel(int level) { for (int i = 0; i < level; i++) printf("\t"); } bool csEvent::Print (int level) { csHash<attribute*, csStringID>::GlobalIterator iter ( attributes.GetIterator ()); while (iter.HasNext()) { csStringID name; attribute* object = iter.Next (name); IndentLevel(level); csPrintf ("------\n"); IndentLevel(level); csPrintf ("Name: %s\n", GetKeyName (name)); IndentLevel(level); csPrintf (" Datatype: %s\n", GetTypeName(object->type)); if (object->type == csEventAttrEvent) { IndentLevel(level); csPrintf(" Sub-Event Contents:\n"); csRef<csEvent> csev = SCF_QUERY_INTERFACE (object->ibaseVal, csEvent); if (csev) csev->Print(level+1); else { IndentLevel(level+1); csPrintf(" (Not an event!):\n"); } } if (object->type == csEventAttrInt) { IndentLevel(level); csPrintf (" Value: %lld\n", object->intVal); } else if (object->type == csEventAttrUInt) { IndentLevel(level); csPrintf (" Value: %llu\n", (uint64)object->intVal); } else if (object->type == csEventAttrFloat) { IndentLevel(level); csPrintf (" Value: %f\n", object->doubleVal); } else if (object->type == csEventAttrDatabuffer) { IndentLevel(level); csPrintf(" Value: 0x%p\n", object->bufferVal); IndentLevel(level); csPrintf(" Length: %lu\n", (unsigned long)object->dataSize); } } return true; } csRef<iEvent> csEvent::CreateEvent() { return csPtr<iEvent>(new csEvent()); } //--------------------------------------------------------------------------- SCF_IMPLEMENT_IBASE (csEventAttributeIterator) SCF_IMPLEMENTS_INTERFACE (iEventAttributeIterator) SCF_IMPLEMENT_IBASE_END const char* csEventAttributeIterator::Next() { csStringID key; iterator.Next (key); return csEvent::GetKeyName (key); } //***************************************************************************** // csPoolEvent //***************************************************************************** csPoolEvent::csPoolEvent(csEventQueue *q) { pool = q; next = 0; } void csPoolEvent::DecRef() { if (scfRefCount == 1) { if (!pool.IsValid()) return; next = pool->EventPool; pool->EventPool = this; RemoveAll(); Type = 0; Category = 0; Flags = 0; Time = 0; SubCategory = 0; Command.Code = 0; Command.Info = 0; } else { scfRefCount--; } } csRef<iEvent> csPoolEvent::CreateEvent() { if (pool.IsValid()) return pool->CreateEvent(0); return superclass::CreateEvent(); } <commit_msg>fixed printf warning on 64bit archs<commit_after>/* Crystal Space Event Queue Copyright (C) 1998-2004 by Jorrit Tyberghein Written by Andrew Zabolotny <bit@eltech.ru>, Eric Sunshine, Jonathan Tarbox, Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/array.h" #include "csutil/csevent.h" #include "csutil/cseventq.h" #include "csutil/memfile.h" #include "csutil/util.h" #include "csutil/sysfunc.h" //--------------------------------------------------------------------------- SCF_IMPLEMENT_IBASE (csEvent) SCF_IMPLEMENTS_INTERFACE (iEvent) SCF_IMPLEMENTS_INTERFACE (csEvent) SCF_IMPLEMENT_IBASE_END CS_IMPLEMENT_STATIC_VAR(GetEventStrSet, csStringSet, ()) char const* csEvent::GetTypeName (csEventAttributeType t) { switch (t) { case csEventAttrInt: return "int"; case csEventAttrUInt: return "uint"; case csEventAttrFloat: return "double"; case csEventAttrDatabuffer: return "databuffer"; case csEventAttrEvent: return "event"; case csEventAttriBase: return "iBase"; default: break; } return "unknown"; } csStringID csEvent::GetKeyID (const char* key) { return GetEventStrSet()->Request (key); } const char* csEvent::GetKeyName (csStringID id) { return GetEventStrSet()->Request (id); } csEvent::csEvent () { SCF_CONSTRUCT_IBASE (0); count = 0; } csEvent::csEvent (csTicks iTime, int eType, int mx, int my, int mButton, int mModifiers) : attributes (53) { SCF_CONSTRUCT_IBASE (0); Time = iTime; Type = eType; Category = SubCategory = Flags = 0; Mouse.x = mx; Mouse.y = my; Mouse.Button = mButton; Mouse.Modifiers = mModifiers; count = 0; } csEvent::csEvent (csTicks iTime, int eType, int jn, int jx, int jy, int jButton, int jModifiers) : attributes (53) { SCF_CONSTRUCT_IBASE (0); Time = iTime; Type = eType; Category = SubCategory = Flags = 0; Joystick.number = jn; Joystick.x = jx; Joystick.y = jy; Joystick.Button = jButton; Joystick.Modifiers = jModifiers; count = 0; } csEvent::csEvent (csTicks iTime, int eType, int cCode, void *cInfo) : attributes (53) { SCF_CONSTRUCT_IBASE (0); Time = iTime; Type = eType; Category = SubCategory = Flags = 0; Command.Code = cCode; Command.Info = cInfo; if (eType == csevBroadcast) Flags = CSEF_BROADCAST; count = 0; } csEvent::csEvent (csEvent const& e) : iEvent(), attributes (53) { SCF_CONSTRUCT_IBASE (0); count = 0; Type = e.Type; Category = e.Category; SubCategory = e.SubCategory; Flags = e.Flags; Time = e.Time; attributes = e.attributes; if ((Type & CSMASK_Mouse) != 0) { Mouse.x = e.Mouse.x; Mouse.y = e.Mouse.y; Mouse.Button = e.Mouse.Button; Mouse.Modifiers = e.Mouse.Modifiers; } else if ((Type & CSMASK_Joystick) != 0) { Joystick.number = e.Joystick.number; Joystick.x = e.Joystick.x; Joystick.y = e.Joystick.y; Joystick.Button = e.Joystick.Button; Joystick.Modifiers = e.Joystick.Modifiers; } else { Command.Code = e.Command.Code; Command.Info = e.Command.Info; } } csEvent::~csEvent () { RemoveAll(); SCF_DESTRUCT_IBASE (); } bool csEvent::Add (const char *name, float v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrFloat); object->doubleVal = v; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, double v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrFloat); object->doubleVal = v; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, bool v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrInt); object->intVal = v ? 1 : 0; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, const char *v) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrDatabuffer); object->dataSize = strlen(v); object->bufferVal = csStrNew(v); attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::Add (const char *name, const void *v, size_t size) { if (attributes.In (GetKeyID (name))) return false; attribute* object = new attribute (csEventAttrDatabuffer); object->bufferVal = new char[size + 1]; memcpy (object->bufferVal, v, size); object->bufferVal[size] = 0; object->dataSize = size; attributes.Put (GetKeyID (name), object); count++; return true; } bool csEvent::CheckForLoops (iEvent* current, iEvent* e) { csRef<iEventAttributeIterator> iter (current->GetAttributeIterator()); while (iter->HasNext()) { const char* attr = iter->Next(); if (current->GetAttributeType (attr) == csEventAttrEvent) { csRef<iEvent> ev; if (current->Retrieve (attr, ev) != csEventErrNone) continue; if (ev == e) return false; return CheckForLoops(ev, e); } } return true; } bool csEvent::Add (const char *name, iEvent *v) { if (attributes.In (GetKeyID (name))) return false; if (this == v) return false; if (v && CheckForLoops(v, this)) { attribute* object = new attribute (csEventAttrEvent); (object->ibaseVal = (iBase*)v)->IncRef(); attributes.Put (GetKeyID (name), object); count++; return true; } return false; } bool csEvent::Add (const char *name, iBase* v) { if (attributes.In (GetKeyID (name))) return false; if (v) { attribute* object = new attribute (csEventAttriBase); (object->ibaseVal = v)->IncRef(); attributes.Put (GetKeyID (name), object); count++; return true; } return false; } csEventError csEvent::Retrieve (const char *name, float &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrFloat) { v = object->doubleVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, double &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrFloat) { v = object->doubleVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, const char *&v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrDatabuffer) { v = object->bufferVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, void const *&v, size_t &size) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrDatabuffer) { v = object->bufferVal; size = object->dataSize; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, bool &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrInt) { v = object->intVal != 0; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, csRef<iEvent> &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttrEvent) { v = (iEvent*)object->ibaseVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } csEventError csEvent::Retrieve (const char *name, csRef<iBase> &v) const { attribute* object = attributes.Get (GetKeyID (name), 0); if (!object) return csEventErrNotFound; if (object->type == csEventAttriBase) { v = object->ibaseVal; return csEventErrNone; } else { return InternalReportMismatch (object); } } bool csEvent::AttributeExists (const char* name) { return attributes.In (GetKeyID (name)); } csEventAttributeType csEvent::GetAttributeType (const char* name) { attribute* object = attributes.Get (GetKeyID (name), 0); if (object) { return object->type; } return csEventAttrUnknown; } bool csEvent::Remove(const char *name) { csStringID id = GetKeyID (name); if (!attributes.In (id)) return false; attribute* object = attributes.Get (id, 0); bool result = attributes.Delete (id, object); delete object; return result; } bool csEvent::RemoveAll() { csHash<attribute*, csStringID>::GlobalIterator iter ( attributes.GetIterator ()); while (iter.HasNext()) { csStringID name; attribute* object = iter.Next (name); delete object; } attributes.DeleteAll(); count = 0; return true; } csRef<iEventAttributeIterator> csEvent::GetAttributeIterator() { csHash<csEvent::attribute*, csStringID>::GlobalIterator attrIter ( attributes.GetIterator()); return csPtr<iEventAttributeIterator> (new csEventAttributeIterator ( attrIter)); } static void IndentLevel(int level) { for (int i = 0; i < level; i++) printf("\t"); } bool csEvent::Print (int level) { csHash<attribute*, csStringID>::GlobalIterator iter ( attributes.GetIterator ()); while (iter.HasNext()) { csStringID name; attribute* object = iter.Next (name); IndentLevel(level); csPrintf ("------\n"); IndentLevel(level); csPrintf ("Name: %s\n", GetKeyName (name)); IndentLevel(level); csPrintf (" Datatype: %s\n", GetTypeName(object->type)); if (object->type == csEventAttrEvent) { IndentLevel(level); csPrintf(" Sub-Event Contents:\n"); csRef<csEvent> csev = SCF_QUERY_INTERFACE (object->ibaseVal, csEvent); if (csev) csev->Print(level+1); else { IndentLevel(level+1); csPrintf(" (Not an event!):\n"); } } if (object->type == csEventAttrInt) { IndentLevel(level); #ifdef CS_COMPILER_GCC csPrintf (" Value: %lld\n", (long long int) object->intVal); #else csPrintf (" Value: %lu\n", (long) object->intVal); #endif } else if (object->type == csEventAttrUInt) { IndentLevel(level); #ifdef CS_COMPILER_GCC csPrintf (" Value: %llu\n", (unsigned long long int) object->intVal); #else csPrintf (" Value %ld\n", (unsigned long) object->intVal); #endif } else if (object->type == csEventAttrFloat) { IndentLevel(level); csPrintf (" Value: %f\n", object->doubleVal); } else if (object->type == csEventAttrDatabuffer) { IndentLevel(level); csPrintf(" Value: 0x%p\n", object->bufferVal); IndentLevel(level); csPrintf(" Length: %lu\n", (unsigned long)object->dataSize); } } return true; } csRef<iEvent> csEvent::CreateEvent() { return csPtr<iEvent>(new csEvent()); } //--------------------------------------------------------------------------- SCF_IMPLEMENT_IBASE (csEventAttributeIterator) SCF_IMPLEMENTS_INTERFACE (iEventAttributeIterator) SCF_IMPLEMENT_IBASE_END const char* csEventAttributeIterator::Next() { csStringID key; iterator.Next (key); return csEvent::GetKeyName (key); } //***************************************************************************** // csPoolEvent //***************************************************************************** csPoolEvent::csPoolEvent(csEventQueue *q) { pool = q; next = 0; } void csPoolEvent::DecRef() { if (scfRefCount == 1) { if (!pool.IsValid()) return; next = pool->EventPool; pool->EventPool = this; RemoveAll(); Type = 0; Category = 0; Flags = 0; Time = 0; SubCategory = 0; Command.Code = 0; Command.Info = 0; } else { scfRefCount--; } } csRef<iEvent> csPoolEvent::CreateEvent() { if (pool.IsValid()) return pool->CreateEvent(0); return superclass::CreateEvent(); } <|endoftext|>
<commit_before>/* Copyright (C) 1998-2003 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include "csutil/plugmgr.h" #include "csutil/util.h" #include "csutil/array.h" #include "iutil/comp.h" #include "iutil/objreg.h" #include "iutil/cmdline.h" #include "iutil/cfgmgr.h" #include "ivaria/reporter.h" //------------------------------------------------------ csPlugin class -----// csPluginManager::csPlugin::csPlugin (iComponent *obj, const char *classID) { Plugin = obj; ClassID = csStrNew (classID); } csPluginManager::csPlugin::~csPlugin () { //csPrintf ("DecRef %08p/'%s' ref=%d\n", Plugin, ClassID, Plugin->GetRefCount ()); fflush (stdout); delete [] ClassID; Plugin->DecRef (); } //------------------------------------------------------------------------ /** * Implementation of iPluginIterator. */ class csPluginIterator : public iPluginIterator { public: csArray<iBase*> pointers; size_t idx; public: csPluginIterator () { SCF_CONSTRUCT_IBASE (0); idx = 0; } virtual ~csPluginIterator () { SCF_DESTRUCT_IBASE (); } SCF_DECLARE_IBASE; virtual bool HasNext () { return idx < pointers.Length (); } virtual iBase* Next () { iBase* p = pointers[idx]; idx++; return p; } }; SCF_IMPLEMENT_IBASE (csPluginIterator) SCF_IMPLEMENTS_INTERFACE (iPluginIterator) SCF_IMPLEMENT_IBASE_END //------------------------------------------------------------------------ SCF_IMPLEMENT_IBASE (csPluginManager) SCF_IMPLEMENTS_INTERFACE (iPluginManager) SCF_IMPLEMENT_IBASE_END csPluginManager::csPluginManager (iObjectRegistry* object_reg) : Plugins (8, 8), OptionList (16, 16) { SCF_CONSTRUCT_IBASE (0); csPluginManager::object_reg = object_reg; // We need a recursive mutex. mutex = csMutex::Create (true); } csPluginManager::~csPluginManager () { Clear (); SCF_DESTRUCT_IBASE (); } void csPluginManager::Clear () { csScopedMutexLock lock (mutex); OptionList.DeleteAll (); // Free all plugins. for (size_t i = Plugins.Length() ; i > 0 ; i--) UnloadPlugin ((iComponent *)Plugins.Get(i - 1)->Plugin); } void csPluginManager::QueryOptions (iComponent *obj) { csRef<iCommandLineParser> CommandLine (CS_QUERY_REGISTRY (object_reg, iCommandLineParser)); csRef<iPluginConfig> Config (SCF_QUERY_INTERFACE (obj, iPluginConfig)); if (Config) { size_t on = OptionList.Length (); for (int i = 0 ; ; i++) { csOptionDescription option; if (!Config->GetOptionDescription (i, &option)) break; OptionList.Push (new csPluginOption (option.name, option.type, option.id, (option.type == CSVAR_BOOL) || (option.type == CSVAR_CMD), Config)); if (option.type == CSVAR_BOOL) { char buf[100]; strcpy (buf, "no"); strcpy (buf + 2, option.name); OptionList.Push (new csPluginOption (buf, option.type, option.id, false, Config)); } } // Parse the command line for plugin options and pass them to plugin for (; on < OptionList.Length (); on++) { csPluginOption *pio = (csPluginOption *)OptionList.Get (on); const char *val = CommandLine->GetOption (pio->Name); if (val) { csVariant optval; switch (pio->Type) { case CSVAR_CMD: optval.SetCommand (); break; case CSVAR_BOOL: optval.SetBool (pio->Value); break; case CSVAR_LONG: if (!val) continue; optval.SetLong (atol (val)); break; case CSVAR_FLOAT: if (!val) continue; optval.SetFloat (atof (val)); break; case CSVAR_STRING: if (!val) continue; optval.SetString (val); break; } pio->Config->SetOption (pio->ID, &optval); } } } } iBase *csPluginManager::LoadPlugin (const char *classID, const char *iInterface, int iVersion, bool init) { iComponent *p = 0; { // The reference must be held beyond the scope of this block. csRef<iComponent> dummy (SCF_CREATE_INSTANCE (classID, iComponent)); if (dummy) { p = dummy; p->IncRef(); } } if (!p) { csReport (object_reg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.pluginmgr.loadplugin", "WARNING: could not load plugin '%s'", classID); } else { csScopedMutexLock lock (mutex); size_t index = (size_t)-1; // See if the plugin is already in our plugin list. for (size_t i = 0 ; i < Plugins.Length () ; i++) { csPlugin* pl = Plugins.Get (i); if (pl->ClassID) if (pl->ClassID == classID || !strcmp (pl->ClassID, classID)) { index = i; break; } } bool added_here = false; if (index == (size_t)-1) { // The plugin wasn't in our plugin list yet. Add it here. index = Plugins.Push (new csPlugin (p, classID)); added_here = true; } if ((!init) || p->Initialize (object_reg)) { iBase *ret; if (iInterface) ret = (iBase *)p->QueryInterface ( iSCF::SCF->GetInterfaceID (iInterface), iVersion); else (ret = p)->IncRef(); if (ret) { if (!added_here) { // If we didn't add the plugin (i.e. this is not the first time // we called LoadPlugin() for this plugin) then we need to // DecRef() the component to avoid memory leaks. p->DecRef (); } if (init) QueryOptions (p); return ret; } else { if (!added_here) { // If we didn't add the plugin (i.e. this is not the first time // we called LoadPlugin() for this plugin) then we need to // DecRef() the component to avoid memory leaks. p->DecRef (); } } } csReport (object_reg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.pluginmgr.loadplugin", "WARNING: failed to initialize plugin '%s'", classID); // If we added this plugin in this call then we remove it here as well. if (added_here) Plugins.DeleteIndex (index); } return 0; } bool csPluginManager::RegisterPlugin (const char *classID, iComponent *obj) { csScopedMutexLock lock (mutex); size_t index = Plugins.Push (new csPlugin (obj, classID)); if (obj->Initialize (object_reg)) { QueryOptions (obj); obj->IncRef (); return true; } else { csReport (object_reg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.pluginmgr.registerplugin", "WARNING: failed to initialize plugin '%s'", classID); Plugins.DeleteIndex (index); return false; } } csPtr<iPluginIterator> csPluginManager::GetPlugins () { csScopedMutexLock lock (mutex); csPluginIterator* it = new csPluginIterator (); size_t i; for (i = 0 ; i < Plugins.Length () ; i++) { it->pointers.Push (Plugins.Get (i)->Plugin); } return csPtr<iPluginIterator> (it); } iBase *csPluginManager::QueryPlugin (const char *iInterface, int iVersion) { scfInterfaceID ifID = iSCF::SCF->GetInterfaceID (iInterface); csScopedMutexLock lock (mutex); for (size_t i = 0; i < Plugins.Length (); i++) { iBase *ret = (iBase *)Plugins.Get (i)->Plugin->QueryInterface (ifID, iVersion); if (ret) return ret; } return 0; } iBase *csPluginManager::QueryPlugin (const char* classID, const char *iInterface, int iVersion) { scfInterfaceID ifID = iSCF::SCF->GetInterfaceID (iInterface); csScopedMutexLock lock (mutex); for (size_t i = 0 ; i < Plugins.Length () ; i++) { csPlugin* pl = Plugins.Get (i); if (pl->ClassID) if (pl->ClassID == classID || !strcmp (pl->ClassID, classID)) { return (iBase*)Plugins.Get(i)->Plugin->QueryInterface(ifID,iVersion); } } return 0; } bool csPluginManager::UnloadPlugin (iComponent* obj) { csScopedMutexLock lock (mutex); size_t idx = Plugins.FindKey ( csArrayCmp<csPlugin*,iComponent*>(obj, csPluginsVector::CompareAddress)); csRef<iPluginConfig> config (SCF_QUERY_INTERFACE (obj, iPluginConfig)); if (config) { for (size_t i = OptionList.Length (); i > 0; i--) { csPluginOption *pio = (csPluginOption *)OptionList.Get (i - 1); if (pio->Config == config) OptionList.DeleteIndex (i - 1); } } object_reg->Unregister ((iBase *)obj, 0); return Plugins.DeleteIndex (idx); } <commit_msg>Reverted incorrect logic change introduced by last commit.<commit_after>/* Copyright (C) 1998-2003 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include "csutil/plugmgr.h" #include "csutil/util.h" #include "csutil/array.h" #include "iutil/comp.h" #include "iutil/objreg.h" #include "iutil/cmdline.h" #include "iutil/cfgmgr.h" #include "ivaria/reporter.h" //------------------------------------------------------ csPlugin class -----// csPluginManager::csPlugin::csPlugin (iComponent *obj, const char *classID) { Plugin = obj; ClassID = csStrNew (classID); } csPluginManager::csPlugin::~csPlugin () { //csPrintf ("DecRef %08p/'%s' ref=%d\n", Plugin, ClassID, Plugin->GetRefCount ()); fflush (stdout); delete [] ClassID; Plugin->DecRef (); } //------------------------------------------------------------------------ /** * Implementation of iPluginIterator. */ class csPluginIterator : public iPluginIterator { public: csArray<iBase*> pointers; size_t idx; public: csPluginIterator () { SCF_CONSTRUCT_IBASE (0); idx = 0; } virtual ~csPluginIterator () { SCF_DESTRUCT_IBASE (); } SCF_DECLARE_IBASE; virtual bool HasNext () { return idx < pointers.Length (); } virtual iBase* Next () { iBase* p = pointers[idx]; idx++; return p; } }; SCF_IMPLEMENT_IBASE (csPluginIterator) SCF_IMPLEMENTS_INTERFACE (iPluginIterator) SCF_IMPLEMENT_IBASE_END //------------------------------------------------------------------------ SCF_IMPLEMENT_IBASE (csPluginManager) SCF_IMPLEMENTS_INTERFACE (iPluginManager) SCF_IMPLEMENT_IBASE_END csPluginManager::csPluginManager (iObjectRegistry* object_reg) : Plugins (8, 8), OptionList (16, 16) { SCF_CONSTRUCT_IBASE (0); csPluginManager::object_reg = object_reg; // We need a recursive mutex. mutex = csMutex::Create (true); } csPluginManager::~csPluginManager () { Clear (); SCF_DESTRUCT_IBASE (); } void csPluginManager::Clear () { csScopedMutexLock lock (mutex); OptionList.DeleteAll (); // Free all plugins. for (size_t i = Plugins.Length() ; i > 0 ; i--) UnloadPlugin ((iComponent *)Plugins.Get(i - 1)->Plugin); } void csPluginManager::QueryOptions (iComponent *obj) { csRef<iCommandLineParser> CommandLine (CS_QUERY_REGISTRY (object_reg, iCommandLineParser)); csRef<iPluginConfig> Config (SCF_QUERY_INTERFACE (obj, iPluginConfig)); if (Config) { size_t on = OptionList.Length (); for (int i = 0 ; ; i++) { csOptionDescription option; if (!Config->GetOptionDescription (i, &option)) break; OptionList.Push (new csPluginOption (option.name, option.type, option.id, (option.type == CSVAR_BOOL) || (option.type == CSVAR_CMD), Config)); if (option.type == CSVAR_BOOL) { char buf[100]; strcpy (buf, "no"); strcpy (buf + 2, option.name); OptionList.Push (new csPluginOption (buf, option.type, option.id, false, Config)); } } // Parse the command line for plugin options and pass them to plugin for (; on < OptionList.Length (); on++) { csPluginOption *pio = (csPluginOption *)OptionList.Get (on); const char *val = CommandLine->GetOption (pio->Name); if (val) { csVariant optval; switch (pio->Type) { case CSVAR_CMD: optval.SetCommand (); break; case CSVAR_BOOL: optval.SetBool (pio->Value); break; case CSVAR_LONG: if (!val) continue; optval.SetLong (atol (val)); break; case CSVAR_FLOAT: if (!val) continue; optval.SetFloat (atof (val)); break; case CSVAR_STRING: if (!val) continue; optval.SetString (val); break; } pio->Config->SetOption (pio->ID, &optval); } } } } iBase *csPluginManager::LoadPlugin (const char *classID, const char *iInterface, int iVersion, bool init) { iComponent *p = 0; { // The reference must be held beyond the scope of this block. csRef<iComponent> dummy (SCF_CREATE_INSTANCE (classID, iComponent)); if (dummy) { p = dummy; p->IncRef(); } } if (!p) { csReport (object_reg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.pluginmgr.loadplugin", "WARNING: could not load plugin '%s'", classID); } else { csScopedMutexLock lock (mutex); size_t index = (size_t)-1; // See if the plugin is already in our plugin list. for (size_t i = 0 ; i < Plugins.Length () ; i++) { csPlugin* pl = Plugins.Get (i); if (pl->ClassID) if (pl->ClassID == classID || !strcmp (pl->ClassID, classID)) { index = i; break; } } bool added_here = false; if (index == (size_t)-1) { // The plugin wasn't in our plugin list yet. Add it here. index = Plugins.Push (new csPlugin (p, classID)); added_here = true; } if ((!init) || p->Initialize (object_reg)) { iBase *ret; if (iInterface) ret = (iBase *)p->QueryInterface ( iSCF::SCF->GetInterfaceID (iInterface), iVersion); else (ret = p)->IncRef(); if (ret) { if (!added_here) { // If we didn't add the plugin (i.e. this is not the first time // we called LoadPlugin() for this plugin) then we need to // DecRef() the component to avoid memory leaks. p->DecRef (); } if (init) QueryOptions (p); return ret; } else { if (!added_here) { // If we didn't add the plugin (i.e. this is not the first time // we called LoadPlugin() for this plugin) then we need to // DecRef() the component to avoid memory leaks. p->DecRef (); } } } csReport (object_reg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.pluginmgr.loadplugin", "WARNING: failed to initialize plugin '%s'", classID); // If we added this plugin in this call then we remove it here as well. if (added_here) Plugins.DeleteIndex (index); } return 0; } bool csPluginManager::RegisterPlugin (const char *classID, iComponent *obj) { csScopedMutexLock lock (mutex); size_t index = Plugins.Push (new csPlugin (obj, classID)); if (obj->Initialize (object_reg)) { QueryOptions (obj); obj->IncRef (); return true; } else { csReport (object_reg, CS_REPORTER_SEVERITY_WARNING, "crystalspace.pluginmgr.registerplugin", "WARNING: failed to initialize plugin '%s'", classID); Plugins.DeleteIndex (index); return false; } } csPtr<iPluginIterator> csPluginManager::GetPlugins () { csScopedMutexLock lock (mutex); csPluginIterator* it = new csPluginIterator (); size_t i; for (i = 0 ; i < Plugins.Length () ; i++) { it->pointers.Push (Plugins.Get (i)->Plugin); } return csPtr<iPluginIterator> (it); } iBase *csPluginManager::QueryPlugin (const char *iInterface, int iVersion) { scfInterfaceID ifID = iSCF::SCF->GetInterfaceID (iInterface); csScopedMutexLock lock (mutex); for (size_t i = 0; i < Plugins.Length (); i++) { iBase *ret = (iBase *)Plugins.Get (i)->Plugin->QueryInterface (ifID, iVersion); if (ret) return ret; } return 0; } iBase *csPluginManager::QueryPlugin (const char* classID, const char *iInterface, int iVersion) { scfInterfaceID ifID = iSCF::SCF->GetInterfaceID (iInterface); csScopedMutexLock lock (mutex); for (size_t i = 0 ; i < Plugins.Length () ; i++) { csPlugin* pl = Plugins.Get (i); if (pl->ClassID) if (pl->ClassID == classID || !strcmp (pl->ClassID, classID)) { return (iBase*)Plugins.Get(i)->Plugin->QueryInterface(ifID,iVersion); } } return 0; } bool csPluginManager::UnloadPlugin (iComponent* obj) { csScopedMutexLock lock (mutex); size_t idx = Plugins.FindKey ( csArrayCmp<csPlugin*,iComponent*>(obj, csPluginsVector::CompareAddress)); if (idx == csArrayItemNotFound) return false; csRef<iPluginConfig> config (SCF_QUERY_INTERFACE (obj, iPluginConfig)); if (config) { for (size_t i = OptionList.Length (); i > 0; i--) { csPluginOption *pio = (csPluginOption *)OptionList.Get (i - 1); if (pio->Config == config) OptionList.DeleteIndex (i - 1); } } object_reg->Unregister ((iBase *)obj, 0); return Plugins.DeleteIndex (idx); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #ifndef _Stroika_Foundation_Streams_InternallySyncrhonizedInputOutputStream_inl_ #define _Stroika_Foundation_Streams_InternallySyncrhonizedInputOutputStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika { namespace Foundation { namespace Streams { /* ******************************************************************************** * InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Rep_ *** ******************************************************************************** */ template <typename ELEMENT_TYPE, template <typename> typename BASE_CLASS, typename BASE_REP_TYPE> class InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Rep_ : public BASE_REP_TYPE { public: Rep_ (const typename BASE_CLASS<ELEMENT_TYPE>::Ptr& realInOut) : BASE_REP_TYPE () , fRealInOut_ (realInOut) { } Rep_ () = delete; Rep_ (const Rep_&) = delete; virtual bool IsSeekable () const override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.IsSeekable (); } virtual SeekOffsetType GetReadOffset () const override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.GetReadOffset (); } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.SeekRead (whence, offset); } virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.Read (intoStart, intoEnd); } virtual Memory::Optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.ReadNonBlocking (intoStart, intoEnd); } virtual SeekOffsetType GetWriteOffset () const override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.GetWriteOffset (); } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.SeekWrite (whence, offset); } virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override { lock_guard<mutex> critSec{fCriticalSection_}; fRealInOut_.Write (start, end); } virtual void Flush () override { lock_guard<mutex> critSec{fCriticalSection_}; fRealInOut_.Flush (); } private: mutable mutex fCriticalSection_; typename BASE_CLASS<ELEMENT_TYPE>::Ptr fRealInOut_; }; /* ******************************************************************************** * InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE> ******************************************************************************** */ template <typename ELEMENT_TYPE, template <typename> typename BASE_CLASS, typename BASE_REP_TYPE> inline auto InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::New (const typename BASE_CLASS<ELEMENT_TYPE>::Ptr& stream2Wrap) -> Ptr { return Ptr{make_shared<Rep_> (stream2Wrap)}; } /* ******************************************************************************** * InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr ******************************************************************************** */ template <typename ELEMENT_TYPE, template <typename> typename BASE_CLASS, typename BASE_REP_TYPE> inline InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from) : inherited (from) { } template <typename ELEMENT_TYPE, template <typename> typename BASE_CLASS, typename BASE_REP_TYPE> inline typename InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr& InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr::operator= (const InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>& rhs) { inherited::Ptr::operator= (rhs); return *this; } } } } #endif /*_Stroika_Foundation_Streams_InternallySyncrhonizedInputOutputStream_inl_*/ <commit_msg>use class for template template param for C++14 compat<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #ifndef _Stroika_Foundation_Streams_InternallySyncrhonizedInputOutputStream_inl_ #define _Stroika_Foundation_Streams_InternallySyncrhonizedInputOutputStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika { namespace Foundation { namespace Streams { /* ******************************************************************************** * InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Rep_ *** ******************************************************************************** */ template <typename ELEMENT_TYPE, template <typename> class BASE_CLASS, typename BASE_REP_TYPE> class InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Rep_ : public BASE_REP_TYPE { public: Rep_ (const typename BASE_CLASS<ELEMENT_TYPE>::Ptr& realInOut) : BASE_REP_TYPE () , fRealInOut_ (realInOut) { } Rep_ () = delete; Rep_ (const Rep_&) = delete; virtual bool IsSeekable () const override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.IsSeekable (); } virtual SeekOffsetType GetReadOffset () const override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.GetReadOffset (); } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.SeekRead (whence, offset); } virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.Read (intoStart, intoEnd); } virtual Memory::Optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.ReadNonBlocking (intoStart, intoEnd); } virtual SeekOffsetType GetWriteOffset () const override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.GetWriteOffset (); } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { lock_guard<mutex> critSec{fCriticalSection_}; return fRealInOut_.SeekWrite (whence, offset); } virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override { lock_guard<mutex> critSec{fCriticalSection_}; fRealInOut_.Write (start, end); } virtual void Flush () override { lock_guard<mutex> critSec{fCriticalSection_}; fRealInOut_.Flush (); } private: mutable mutex fCriticalSection_; typename BASE_CLASS<ELEMENT_TYPE>::Ptr fRealInOut_; }; /* ******************************************************************************** * InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE> ******************************************************************************** */ template <typename ELEMENT_TYPE, template <typename> class BASE_CLASS, typename BASE_REP_TYPE> inline auto InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::New (const typename BASE_CLASS<ELEMENT_TYPE>::Ptr& stream2Wrap) -> Ptr { return Ptr{make_shared<Rep_> (stream2Wrap)}; } /* ******************************************************************************** * InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr ******************************************************************************** */ template <typename ELEMENT_TYPE, template <typename> class BASE_CLASS, typename BASE_REP_TYPE> inline InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from) : inherited (from) { } template <typename ELEMENT_TYPE, template <typename> class BASE_CLASS, typename BASE_REP_TYPE> inline typename InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr& InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>::Ptr::operator= (const InternallySyncrhonizedInputOutputStream<ELEMENT_TYPE, BASE_CLASS, BASE_REP_TYPE>& rhs) { inherited::Ptr::operator= (rhs); return *this; } } } } #endif /*_Stroika_Foundation_Streams_InternallySyncrhonizedInputOutputStream_inl_*/ <|endoftext|>
<commit_before>// Copyright (c) 2017, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-pinocchio. // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>. #define BOOST_TEST_MODULE tframe #include <boost/test/unit_test.hpp> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/simple-device.hh> #include <hpp/pinocchio/humanoid-robot.hh> #include <hpp/pinocchio/urdf/util.hh> #include <hpp/pinocchio/liegroup-space.hh> #include <hpp/pinocchio/configuration.hh> static bool verbose = true; using namespace hpp::pinocchio; void displayAABB(const hpp::fcl::AABB& aabb) { std::cout << "Bounding box is\n" << aabb.min_.transpose() << '\n' << aabb.max_.transpose() << std::endl; } BOOST_AUTO_TEST_CASE (computeAABB) { DevicePtr_t robot = unittest::makeDevice(unittest::HumanoidSimple); BOOST_REQUIRE(robot); robot->rootJoint()->lowerBounds(vector3_t::Constant(-0)); robot->rootJoint()->upperBounds(vector3_t::Constant( 0)); hpp::fcl::AABB aabb0 = robot->computeAABB(); if (verbose) displayAABB(aabb0); robot->rootJoint()->lowerBounds(vector3_t(-1, -1, 0)); robot->rootJoint()->upperBounds(vector3_t( 1, 1, 0)); hpp::fcl::AABB aabb1 = robot->computeAABB(); if (verbose) displayAABB(aabb1); robot->rootJoint()->lowerBounds(vector3_t(-2, -2, 0)); robot->rootJoint()->upperBounds(vector3_t(-1, -1, 0)); hpp::fcl::AABB aabb2 = robot->computeAABB(); if (verbose) displayAABB(aabb2); } /* -------------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE (unit_test_device) { DevicePtr_t robot; LiegroupSpacePtr_t space; robot = unittest::makeDevice (unittest::HumanoidSimple); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "SE(3)*R^26"); space = LiegroupSpace::createCopy(robot->RnxSOnConfigSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "R^3*SO(3)*R^26"); robot->setDimensionExtraConfigSpace(3); BOOST_CHECK_EQUAL(robot->numberDof(), 32+3); BOOST_CHECK_EQUAL(robot->configSize(), 33+3); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "SE(3)*R^29"); robot = unittest::makeDevice (unittest::CarLike); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "SE(2)*R^2"); robot = unittest::makeDevice (unittest::ManipulatorArm2); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "R^19"); } // TODO When neutral configuration can be read from XML string, this test should be updated in order to // read a URDF and SRDF string rather than a file in a different package. BOOST_AUTO_TEST_CASE(load_neutral_configuration){ std::string robotName("romeo"); std::string packageName("romeo_description"); std::string rootJointType("freeflyer"); std::string modelName("romeo"); std::string urdfSuffix("_small"); std::string srdfSuffix(""); DevicePtr_t device = Device::create(robotName); urdf::loadRobotModel (device, rootJointType, packageName,modelName, urdfSuffix,srdfSuffix); BOOST_CHECK(device); BOOST_CHECK_EQUAL(device->neutralConfiguration().size(),device->configSize()); Eigen::VectorXd expected(device->configSize()); // values fond in the srdf file, if the file change this test need to be updated : expected << 0,0,0,0,0,0,1,0,0,-0.3490658,0.6981317,-0.3490658,0,0,0,-0.3490658,0.6981317,-0.3490658,0,0,1.5,0.6,-0.5,-1.05,-0.4,-0.3,-0.2,0,0,0,0,1.5,-0.6,0.5,1.05,-0.4,-0.3,-0.2; if(verbose) std::cout<<"neutral configuration after loading romeo : "<<displayConfig(device->neutralConfiguration())<<std::endl; BOOST_CHECK_MESSAGE(device->neutralConfiguration().isApprox(expected, 1e-12), "neutral configuration - wrong results"); } <commit_msg>Fix unit-test.<commit_after>// Copyright (c) 2017, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-pinocchio. // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>. #define BOOST_TEST_MODULE tframe #include <boost/test/unit_test.hpp> #include <pinocchio/multibody/model.hpp> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/simple-device.hh> #include <hpp/pinocchio/humanoid-robot.hh> #include <hpp/pinocchio/urdf/util.hh> #include <hpp/pinocchio/liegroup-space.hh> #include <hpp/pinocchio/configuration.hh> static bool verbose = true; using namespace hpp::pinocchio; void displayAABB(const hpp::fcl::AABB& aabb) { std::cout << "Bounding box is\n" << aabb.min_.transpose() << '\n' << aabb.max_.transpose() << std::endl; } BOOST_AUTO_TEST_CASE (computeAABB) { DevicePtr_t robot = unittest::makeDevice(unittest::HumanoidSimple); BOOST_REQUIRE(robot); robot->rootJoint()->lowerBounds(vector3_t::Constant(-0)); robot->rootJoint()->upperBounds(vector3_t::Constant( 0)); hpp::fcl::AABB aabb0 = robot->computeAABB(); if (verbose) displayAABB(aabb0); robot->rootJoint()->lowerBounds(vector3_t(-1, -1, 0)); robot->rootJoint()->upperBounds(vector3_t( 1, 1, 0)); hpp::fcl::AABB aabb1 = robot->computeAABB(); if (verbose) displayAABB(aabb1); robot->rootJoint()->lowerBounds(vector3_t(-2, -2, 0)); robot->rootJoint()->upperBounds(vector3_t(-1, -1, 0)); hpp::fcl::AABB aabb2 = robot->computeAABB(); if (verbose) displayAABB(aabb2); } /* -------------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE (unit_test_device) { DevicePtr_t robot; LiegroupSpacePtr_t space; robot = unittest::makeDevice (unittest::HumanoidSimple); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "SE(3)*R^26"); space = LiegroupSpace::createCopy(robot->RnxSOnConfigSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "R^3*SO(3)*R^26"); robot->setDimensionExtraConfigSpace(3); BOOST_CHECK_EQUAL(robot->numberDof(), 32+3); BOOST_CHECK_EQUAL(robot->configSize(), 33+3); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "SE(3)*R^29"); robot = unittest::makeDevice (unittest::CarLike); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "SE(2)*R^2"); robot = unittest::makeDevice (unittest::ManipulatorArm2); space = LiegroupSpace::createCopy(robot->configSpace()); space->mergeVectorSpaces(); BOOST_CHECK_EQUAL (space->name(), "R^19"); } BOOST_AUTO_TEST_CASE(load_neutral_configuration) { std::string urdf ( "<robot name='test'>" "<link name='base_link'/>" "<link name='link1'/>" "<joint name='joint1' type='revolute'>" " <parent link='base_link'/>" " <child link='link1'/>" " <limit effort='30' velocity='1.0' />" "</joint>" "</robot>"); std::string srdf ( "<robot name='test'>" "<group name='all'/>" "<group_state name='half_sitting' group='all'>" "<joint name='joint1' value='1.' />" "</group_state>" "</robot>"); DevicePtr_t device = Device::create("test"); urdf::loadModelFromString (device, 0, "", "anchor", urdf, srdf); BOOST_CHECK(device); BOOST_CHECK_EQUAL(device->neutralConfiguration().size(),device->configSize()); BOOST_CHECK_MESSAGE(device->neutralConfiguration().isZero(1e-12), "neutral configuration - wrong results"); /* // TODO When neutral configuration can be read from XML string, this test should be updated in order to // read a URDF and SRDF string rather than a file in a different package. Eigen::VectorXd expected(device->configSize()); expected.setOnes(); const Model& model = device->model(); Model::ConfigVectorMap::const_iterator half_sitting = model.referenceConfigurations.find ("half_sitting"); BOOST_REQUIRE(half_sitting != model.referenceConfigurations.end()); BOOST_CHECK_MESSAGE(half_sitting->second.isApprox (expected, 1e-12), "reference configuration - wrong results\ngot: " << half_sitting->second.transpose() << "\nexpected: " << expected.transpose()); */ } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk #include "QmitkTbssSkeletonizationView.h" #include <itkSkeletonizationFilter.h> #include <itkProjectionFilter.h> #include <itkDistanceMapFilter.h> #include <itkBinaryThresholdImageFilter.h> #include <itkImageFileReader.h> // mitk #include <mitkImagePixelReadAccessor.h> // Qt #include <QInputDialog> #include <QMessageBox> //vtk #include <vtkLinearTransform.h> #include <vtkMatrix4x4.h> // Boost #include <boost/lexical_cast.hpp> const std::string QmitkTbssSkeletonizationView::VIEW_ID = "org.mitk.views.tbssskeletonization"; using namespace berry; QmitkTbssSkeletonizationView::QmitkTbssSkeletonizationView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkTbssSkeletonizationView::~QmitkTbssSkeletonizationView() { } void QmitkTbssSkeletonizationView::OnSelectionChanged(std::vector<mitk::DataNode*> nodes) { //datamanager selection changed if (!this->IsActivated()) return; bool found3dImage = false; bool found4dImage = false; // iterate selection for ( int i=0; i<nodes.size(); i++ ) { // only look at interesting types from valid nodes mitk::BaseData* nodeData = nodes[i]->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast<mitk::Image*>(nodeData); if(img->GetDimension() == 3) { found3dImage = true; } else if(img->GetDimension() == 4) { found4dImage = true; } } } } this->m_Controls->m_Skeletonize->setEnabled(found3dImage); this->m_Controls->m_Project->setEnabled(found3dImage && found4dImage); this->m_Controls->m_OutputMask->setEnabled(found3dImage && found4dImage); this->m_Controls->m_OutputDistanceMap->setEnabled(found3dImage && found4dImage); } void QmitkTbssSkeletonizationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkTbssSkeletonizationViewControls; m_Controls->setupUi( parent ); this->CreateConnections(); } } void QmitkTbssSkeletonizationView::Activated() { QmitkFunctionality::Activated(); } void QmitkTbssSkeletonizationView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkTbssSkeletonizationView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_Skeletonize), SIGNAL(clicked()), this, SLOT(Skeletonize() )); connect( (QObject*)(m_Controls->m_Project), SIGNAL(clicked()), this, SLOT(Project() )); } } void QmitkTbssSkeletonizationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkTbssSkeletonizationView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkTbssSkeletonizationView::Skeletonize() { typedef itk::SkeletonizationFilter<FloatImageType, FloatImageType> SkeletonisationFilterType; SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New(); std::vector<mitk::DataNode*> nodes = this->GetDataManagerSelection(); mitk::Image::Pointer meanImage = mitk::Image::New(); std::string name = ""; for ( int i=0; i<nodes.size(); i++ ) { // process only on valid nodes mitk::BaseData* nodeData = nodes[i]->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast<mitk::Image*>(nodeData); if(img->GetDimension() == 3) { meanImage = img; name = nodes[i]->GetName(); } } } } // Calculate skeleton FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(meanImage, itkImg); skeletonizer->SetInput(itkImg); skeletonizer->Update(); FloatImageType::Pointer output = skeletonizer->GetOutput(); mitk::Image::Pointer mitkOutput = mitk::Image::New(); mitk::CastToMitkImage(output, mitkOutput); name += "_skeleton"; AddToDataStorage(mitkOutput, name); } void QmitkTbssSkeletonizationView::Project() { typedef itk::SkeletonizationFilter<FloatImageType, FloatImageType> SkeletonisationFilterType; typedef itk::ProjectionFilter ProjectionFilterType; typedef itk::DistanceMapFilter<FloatImageType, FloatImageType> DistanceMapFilterType; SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New(); std::vector<mitk::DataNode*> nodes = this->GetDataManagerSelection(); mitk::Image::Pointer meanImage = mitk::Image::New(); mitk::Image::Pointer subjects = mitk::Image::New(); for ( int i=0; i<nodes.size(); i++ ) { // process only on valid nodes mitk::BaseData* nodeData = nodes[i]->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast<mitk::Image*>(nodeData); if(img->GetDimension() == 3) { meanImage = img; } else if(img->GetDimension() == 4) { subjects = img; } } } } Float4DImageType::Pointer allFA = ConvertToItk(subjects); // Calculate skeleton FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(meanImage, itkImg); skeletonizer->SetInput(itkImg); skeletonizer->Update(); FloatImageType::Pointer output = skeletonizer->GetOutput(); mitk::Image::Pointer mitkOutput = mitk::Image::New(); mitk::CastToMitkImage(output, mitkOutput); AddToDataStorage(mitkOutput, "mean_FA_skeletonised"); // Retrieve direction image needed later by the projection filter DirectionImageType::Pointer directionImg = skeletonizer->GetVectorImage(); // Calculate distance image DistanceMapFilterType::Pointer distanceMapFilter = DistanceMapFilterType::New(); distanceMapFilter->SetInput(output); distanceMapFilter->Update(); FloatImageType::Pointer distanceMap = distanceMapFilter->GetOutput(); if(m_Controls->m_OutputDistanceMap->isChecked()) { mitk::Image::Pointer mitkDistance = mitk::Image::New(); mitk::CastToMitkImage(distanceMap, mitkDistance); AddToDataStorage(mitkDistance, "distance map"); } // Do projection // Ask a threshold to create a skeleton mask double threshold = -1.0; while(threshold == -1.0) { threshold = QInputDialog::getDouble(m_Controls->m_Skeletonize, tr("Specify the FA threshold"), tr("Threshold:"), QLineEdit::Normal, 0.2); if(threshold < 0.0 || threshold > 1.0) { QMessageBox msgBox; msgBox.setText("Please choose a value between 0 and 1"); msgBox.exec(); threshold = -1.0; } } typedef itk::BinaryThresholdImageFilter<FloatImageType, CharImageType> ThresholdFilterType; ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); thresholder->SetInput(output); thresholder->SetLowerThreshold(threshold); thresholder->SetUpperThreshold(std::numeric_limits<float>::max()); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(1); thresholder->Update(); CharImageType::Pointer thresholdedImg = thresholder->GetOutput(); if(m_Controls->m_OutputMask->isChecked()) { mitk::Image::Pointer mitkThresholded = mitk::Image::New(); mitk::CastToMitkImage(thresholdedImg, mitkThresholded); std::string maskName = "skeleton_mask_at_" + boost::lexical_cast<std::string>(threshold); AddToDataStorage(mitkThresholded, maskName); } typedef itk::ImageFileReader< CharImageType > CharReaderType; CharReaderType::Pointer reader = CharReaderType::New(); reader->SetFileName("/local/testing/LowerCingulum_1mm.nii.gz"); reader->Update(); CharImageType::Pointer cingulum = reader->GetOutput(); ProjectionFilterType::Pointer projectionFilter = ProjectionFilterType::New(); projectionFilter->SetDistanceMap(distanceMap); projectionFilter->SetDirections(directionImg); projectionFilter->SetAllFA(allFA); projectionFilter->SetTube(cingulum); projectionFilter->SetSkeleton(thresholdedImg); projectionFilter->Project(); Float4DImageType::Pointer projected = projectionFilter->GetProjections(); mitk::Image::Pointer mitkProjections = mitk::Image::New(); mitk::CastToMitkImage(projected, mitkProjections); AddToDataStorage(mitkProjections, "all_FA_projected"); } void QmitkTbssSkeletonizationView::AddToDataStorage(mitk::Image* img, std::string name) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "name", mitk::StringProperty::New(name) ); result->SetData( img ); // add new image to data storage and set as active to ease further processing GetDefaultDataStorage()->Add( result ); } Float4DImageType::Pointer QmitkTbssSkeletonizationView::ConvertToItk(mitk::Image::Pointer image) { Float4DImageType::Pointer output = Float4DImageType::New(); mitk::Geometry3D* geo = image->GetGeometry(); mitk::Vector3D mitkSpacing = geo->GetSpacing(); mitk::Point3D mitkOrigin = geo->GetOrigin(); Float4DImageType::SpacingType spacing; spacing[0] = mitkSpacing[0]; spacing[1] = mitkSpacing[1]; spacing[2] = mitkSpacing[2]; spacing[3] = 1.0; // todo: check if spacing has length 4 Float4DImageType::PointType origin; origin[0] = mitkOrigin[0]; origin[1] = mitkOrigin[1]; origin[2] = mitkOrigin[2]; origin[3] = 0; Float4DImageType::SizeType size; size[0] = image->GetDimension(0); size[1] = image->GetDimension(1); size[2] = image->GetDimension(2); size[3] = image->GetDimension(3); Float4DImageType::DirectionType dir; vtkLinearTransform* lin = geo->GetVtkTransform(); vtkMatrix4x4 *m = lin->GetMatrix(); dir.Fill(0.0); for(int x=0; x<3; x++) { for(int y=0; y<3; y++) { dir[x][y] = m->GetElement(x,y); } } dir[3][3] = 1; output->SetSpacing(spacing); output->SetOrigin(origin); output->SetRegions(size); output->SetDirection(dir); output->Allocate(); if(image->GetDimension() == 4) { int timesteps = image->GetDimension(3); try{ // REPLACE THIS METHODE()ConvertToItk) WITH mitk::CastToItk mitk::ImagePixelReadAccessor<float,4> imageAccessor(image); // iterate through the subjects and copy data to output for(int t=0; t<timesteps; t++) { for(int x=0; x<image->GetDimension(0); x++) { for(int y=0; y<image->GetDimension(1); y++) { for(int z=0; z<image->GetDimension(2); z++) { itk::Index<4> ix4; ix4[0] = x; ix4[1] = y; ix4[2] = z; ix4[3] = t; output->SetPixel(ix4, imageAccessor.GetPixelByIndex(ix4)); } } } } }catch(std::exception & e) { MITK_INFO << e.what(); } } return output; } <commit_msg>add ImageDataItemAccess<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk #include "QmitkTbssSkeletonizationView.h" #include <itkSkeletonizationFilter.h> #include <itkProjectionFilter.h> #include <itkDistanceMapFilter.h> #include <itkBinaryThresholdImageFilter.h> #include <itkImageFileReader.h> // mitk #include <mitkImagePixelReadAccessor.h> // Qt #include <QInputDialog> #include <QMessageBox> //vtk #include <vtkLinearTransform.h> #include <vtkMatrix4x4.h> // Boost #include <boost/lexical_cast.hpp> const std::string QmitkTbssSkeletonizationView::VIEW_ID = "org.mitk.views.tbssskeletonization"; using namespace berry; QmitkTbssSkeletonizationView::QmitkTbssSkeletonizationView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { } QmitkTbssSkeletonizationView::~QmitkTbssSkeletonizationView() { } void QmitkTbssSkeletonizationView::OnSelectionChanged(std::vector<mitk::DataNode*> nodes) { //datamanager selection changed if (!this->IsActivated()) return; bool found3dImage = false; bool found4dImage = false; // iterate selection for ( int i=0; i<nodes.size(); i++ ) { // only look at interesting types from valid nodes mitk::BaseData* nodeData = nodes[i]->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast<mitk::Image*>(nodeData); if(img->GetDimension() == 3) { found3dImage = true; } else if(img->GetDimension() == 4) { found4dImage = true; } } } } this->m_Controls->m_Skeletonize->setEnabled(found3dImage); this->m_Controls->m_Project->setEnabled(found3dImage && found4dImage); this->m_Controls->m_OutputMask->setEnabled(found3dImage && found4dImage); this->m_Controls->m_OutputDistanceMap->setEnabled(found3dImage && found4dImage); } void QmitkTbssSkeletonizationView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkTbssSkeletonizationViewControls; m_Controls->setupUi( parent ); this->CreateConnections(); } } void QmitkTbssSkeletonizationView::Activated() { QmitkFunctionality::Activated(); } void QmitkTbssSkeletonizationView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkTbssSkeletonizationView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_Skeletonize), SIGNAL(clicked()), this, SLOT(Skeletonize() )); connect( (QObject*)(m_Controls->m_Project), SIGNAL(clicked()), this, SLOT(Project() )); } } void QmitkTbssSkeletonizationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkTbssSkeletonizationView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkTbssSkeletonizationView::Skeletonize() { typedef itk::SkeletonizationFilter<FloatImageType, FloatImageType> SkeletonisationFilterType; SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New(); std::vector<mitk::DataNode*> nodes = this->GetDataManagerSelection(); mitk::Image::Pointer meanImage = mitk::Image::New(); std::string name = ""; for ( int i=0; i<nodes.size(); i++ ) { // process only on valid nodes mitk::BaseData* nodeData = nodes[i]->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast<mitk::Image*>(nodeData); if(img->GetDimension() == 3) { meanImage = img; name = nodes[i]->GetName(); } } } } // Calculate skeleton FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(meanImage, itkImg); skeletonizer->SetInput(itkImg); skeletonizer->Update(); FloatImageType::Pointer output = skeletonizer->GetOutput(); mitk::Image::Pointer mitkOutput = mitk::Image::New(); mitk::CastToMitkImage(output, mitkOutput); name += "_skeleton"; AddToDataStorage(mitkOutput, name); } void QmitkTbssSkeletonizationView::Project() { typedef itk::SkeletonizationFilter<FloatImageType, FloatImageType> SkeletonisationFilterType; typedef itk::ProjectionFilter ProjectionFilterType; typedef itk::DistanceMapFilter<FloatImageType, FloatImageType> DistanceMapFilterType; SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New(); std::vector<mitk::DataNode*> nodes = this->GetDataManagerSelection(); mitk::Image::Pointer meanImage = mitk::Image::New(); mitk::Image::Pointer subjects = mitk::Image::New(); for ( int i=0; i<nodes.size(); i++ ) { // process only on valid nodes mitk::BaseData* nodeData = nodes[i]->GetData(); if(nodeData) { if(QString("Image").compare(nodeData->GetNameOfClass())==0) { mitk::Image* img = static_cast<mitk::Image*>(nodeData); if(img->GetDimension() == 3) { meanImage = img; } else if(img->GetDimension() == 4) { subjects = img; } } } } Float4DImageType::Pointer allFA = ConvertToItk(subjects); // Calculate skeleton FloatImageType::Pointer itkImg = FloatImageType::New(); mitk::CastToItkImage(meanImage, itkImg); skeletonizer->SetInput(itkImg); skeletonizer->Update(); FloatImageType::Pointer output = skeletonizer->GetOutput(); mitk::Image::Pointer mitkOutput = mitk::Image::New(); mitk::CastToMitkImage(output, mitkOutput); AddToDataStorage(mitkOutput, "mean_FA_skeletonised"); // Retrieve direction image needed later by the projection filter DirectionImageType::Pointer directionImg = skeletonizer->GetVectorImage(); // Calculate distance image DistanceMapFilterType::Pointer distanceMapFilter = DistanceMapFilterType::New(); distanceMapFilter->SetInput(output); distanceMapFilter->Update(); FloatImageType::Pointer distanceMap = distanceMapFilter->GetOutput(); if(m_Controls->m_OutputDistanceMap->isChecked()) { mitk::Image::Pointer mitkDistance = mitk::Image::New(); mitk::CastToMitkImage(distanceMap, mitkDistance); AddToDataStorage(mitkDistance, "distance map"); } // Do projection // Ask a threshold to create a skeleton mask double threshold = -1.0; while(threshold == -1.0) { threshold = QInputDialog::getDouble(m_Controls->m_Skeletonize, tr("Specify the FA threshold"), tr("Threshold:"), QLineEdit::Normal, 0.2); if(threshold < 0.0 || threshold > 1.0) { QMessageBox msgBox; msgBox.setText("Please choose a value between 0 and 1"); msgBox.exec(); threshold = -1.0; } } typedef itk::BinaryThresholdImageFilter<FloatImageType, CharImageType> ThresholdFilterType; ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); thresholder->SetInput(output); thresholder->SetLowerThreshold(threshold); thresholder->SetUpperThreshold(std::numeric_limits<float>::max()); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(1); thresholder->Update(); CharImageType::Pointer thresholdedImg = thresholder->GetOutput(); if(m_Controls->m_OutputMask->isChecked()) { mitk::Image::Pointer mitkThresholded = mitk::Image::New(); mitk::CastToMitkImage(thresholdedImg, mitkThresholded); std::string maskName = "skeleton_mask_at_" + boost::lexical_cast<std::string>(threshold); AddToDataStorage(mitkThresholded, maskName); } typedef itk::ImageFileReader< CharImageType > CharReaderType; CharReaderType::Pointer reader = CharReaderType::New(); reader->SetFileName("/local/testing/LowerCingulum_1mm.nii.gz"); reader->Update(); CharImageType::Pointer cingulum = reader->GetOutput(); ProjectionFilterType::Pointer projectionFilter = ProjectionFilterType::New(); projectionFilter->SetDistanceMap(distanceMap); projectionFilter->SetDirections(directionImg); projectionFilter->SetAllFA(allFA); projectionFilter->SetTube(cingulum); projectionFilter->SetSkeleton(thresholdedImg); projectionFilter->Project(); Float4DImageType::Pointer projected = projectionFilter->GetProjections(); mitk::Image::Pointer mitkProjections = mitk::Image::New(); mitk::CastToMitkImage(projected, mitkProjections); AddToDataStorage(mitkProjections, "all_FA_projected"); } void QmitkTbssSkeletonizationView::AddToDataStorage(mitk::Image* img, std::string name) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "name", mitk::StringProperty::New(name) ); result->SetData( img ); // add new image to data storage and set as active to ease further processing GetDefaultDataStorage()->Add( result ); } Float4DImageType::Pointer QmitkTbssSkeletonizationView::ConvertToItk(mitk::Image::Pointer image) { Float4DImageType::Pointer output = Float4DImageType::New(); mitk::Geometry3D* geo = image->GetGeometry(); mitk::Vector3D mitkSpacing = geo->GetSpacing(); mitk::Point3D mitkOrigin = geo->GetOrigin(); Float4DImageType::SpacingType spacing; spacing[0] = mitkSpacing[0]; spacing[1] = mitkSpacing[1]; spacing[2] = mitkSpacing[2]; spacing[3] = 1.0; // todo: check if spacing has length 4 Float4DImageType::PointType origin; origin[0] = mitkOrigin[0]; origin[1] = mitkOrigin[1]; origin[2] = mitkOrigin[2]; origin[3] = 0; Float4DImageType::SizeType size; size[0] = image->GetDimension(0); size[1] = image->GetDimension(1); size[2] = image->GetDimension(2); size[3] = image->GetDimension(3); Float4DImageType::DirectionType dir; vtkLinearTransform* lin = geo->GetVtkTransform(); vtkMatrix4x4 *m = lin->GetMatrix(); dir.Fill(0.0); for(int x=0; x<3; x++) { for(int y=0; y<3; y++) { dir[x][y] = m->GetElement(x,y); } } dir[3][3] = 1; output->SetSpacing(spacing); output->SetOrigin(origin); output->SetRegions(size); output->SetDirection(dir); output->Allocate(); if(image->GetDimension() == 4) { int timesteps = image->GetDimension(3); try{ // REPLACE THIS METHODE()ConvertToItk) WITH mitk::CastToItk mitk::ImagePixelReadAccessor<float,4> imageAccessor(image, image->GetSliceData()); // iterate through the subjects and copy data to output for(int t=0; t<timesteps; t++) { for(int x=0; x<image->GetDimension(0); x++) { for(int y=0; y<image->GetDimension(1); y++) { for(int z=0; z<image->GetDimension(2); z++) { itk::Index<4> ix4; ix4[0] = x; ix4[1] = y; ix4[2] = z; ix4[3] = t; output->SetPixel(ix4, imageAccessor.GetPixelByIndex(ix4)); } } } } }catch(std::exception & e) { MITK_INFO << e.what(); } } return output; } <|endoftext|>
<commit_before>/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity abstract syntax tree. */ #include <libsolidity/interface/Utils.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/interface/Exceptions.h> #include <libsolidity/ast/AST_accept.h> #include <libdevcore/SHA3.h> #include <boost/algorithm/string.hpp> #include <algorithm> #include <functional> using namespace std; using namespace dev; using namespace dev::solidity; class IDDispenser { public: static size_t next() { return ++instance(); } static void reset() { instance() = 0; } private: static size_t& instance() { static IDDispenser dispenser; return dispenser.id; } size_t id = 0; }; ASTNode::ASTNode(SourceLocation const& _location): m_id(IDDispenser::next()), m_location(_location) { } ASTNode::~ASTNode() { delete m_annotation; } void ASTNode::resetID() { IDDispenser::reset(); } ASTAnnotation& ASTNode::annotation() const { if (!m_annotation) m_annotation = new ASTAnnotation(); return *m_annotation; } Error ASTNode::createTypeError(string const& _description) const { return Error(Error::Type::TypeError) << errinfo_sourceLocation(location()) << errinfo_comment(_description); } SourceUnitAnnotation& SourceUnit::annotation() const { if (!m_annotation) m_annotation = new SourceUnitAnnotation(); return static_cast<SourceUnitAnnotation&>(*m_annotation); } string Declaration::sourceUnitName() const { solAssert(!!m_scope, ""); ASTNode const* scope = m_scope; while (dynamic_cast<Declaration const*>(scope) && dynamic_cast<Declaration const*>(scope)->m_scope) scope = dynamic_cast<Declaration const*>(scope)->m_scope; return dynamic_cast<SourceUnit const&>(*scope).annotation().path; } ImportAnnotation& ImportDirective::annotation() const { if (!m_annotation) m_annotation = new ImportAnnotation(); return static_cast<ImportAnnotation&>(*m_annotation); } TypePointer ImportDirective::type() const { solAssert(!!annotation().sourceUnit, ""); return make_shared<ModuleType>(*annotation().sourceUnit); } map<FixedHash<4>, FunctionTypePointer> ContractDefinition::interfaceFunctions() const { auto exportedFunctionList = interfaceFunctionList(); map<FixedHash<4>, FunctionTypePointer> exportedFunctions; for (auto const& it: exportedFunctionList) exportedFunctions.insert(it); solAssert( exportedFunctionList.size() == exportedFunctions.size(), "Hash collision at Function Definition Hash calculation" ); return exportedFunctions; } FunctionDefinition const* ContractDefinition::constructor() const { for (FunctionDefinition const* f: definedFunctions()) if (f->isConstructor()) return f; return nullptr; } FunctionDefinition const* ContractDefinition::fallbackFunction() const { for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (FunctionDefinition const* f: contract->definedFunctions()) if (f->name().empty()) return f; return nullptr; } vector<EventDefinition const*> const& ContractDefinition::interfaceEvents() const { if (!m_interfaceEvents) { set<string> eventsSeen; m_interfaceEvents.reset(new vector<EventDefinition const*>()); for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (EventDefinition const* e: contract->events()) if (eventsSeen.count(e->name()) == 0) { eventsSeen.insert(e->name()); m_interfaceEvents->push_back(e); } } return *m_interfaceEvents; } vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::interfaceFunctionList() const { if (!m_interfaceFunctionList) { set<string> functionsSeen; set<string> signaturesSeen; m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>()); for (ContractDefinition const* contract: annotation().linearizedBaseContracts) { vector<FunctionTypePointer> functions; for (FunctionDefinition const* f: contract->definedFunctions()) if (f->isPartOfExternalInterface()) functions.push_back(make_shared<FunctionType>(*f, false)); for (VariableDeclaration const* v: contract->stateVariables()) if (v->isPartOfExternalInterface()) functions.push_back(make_shared<FunctionType>(*v)); for (FunctionTypePointer const& fun: functions) { if (!fun->interfaceFunctionType()) // Fails hopefully because we already registered the error continue; string functionSignature = fun->externalSignature(); if (signaturesSeen.count(functionSignature) == 0) { signaturesSeen.insert(functionSignature); FixedHash<4> hash(dev::keccak256(functionSignature)); m_interfaceFunctionList->push_back(make_pair(hash, fun)); } } } } return *m_interfaceFunctionList; } Json::Value const& ContractDefinition::devDocumentation() const { return m_devDocumentation; } Json::Value const& ContractDefinition::userDocumentation() const { return m_userDocumentation; } void ContractDefinition::setDevDocumentation(Json::Value const& _devDocumentation) { m_devDocumentation = _devDocumentation; } void ContractDefinition::setUserDocumentation(Json::Value const& _userDocumentation) { m_userDocumentation = _userDocumentation; } vector<Declaration const*> const& ContractDefinition::inheritableMembers() const { if (!m_inheritableMembers) { set<string> memberSeen; m_inheritableMembers.reset(new vector<Declaration const*>()); auto addInheritableMember = [&](Declaration const* _decl) { solAssert(_decl, "addInheritableMember got a nullpointer."); if (memberSeen.count(_decl->name()) == 0 && _decl->isVisibleInDerivedContracts()) { memberSeen.insert(_decl->name()); m_inheritableMembers->push_back(_decl); } }; for (FunctionDefinition const* f: definedFunctions()) addInheritableMember(f); for (VariableDeclaration const* v: stateVariables()) addInheritableMember(v); for (StructDefinition const* s: definedStructs()) addInheritableMember(s); for (EnumDefinition const* e: definedEnums()) addInheritableMember(e); for (EventDefinition const* e: events()) addInheritableMember(e); } return *m_inheritableMembers; } TypePointer ContractDefinition::type() const { return make_shared<TypeType>(make_shared<ContractType>(*this)); } ContractDefinitionAnnotation& ContractDefinition::annotation() const { if (!m_annotation) m_annotation = new ContractDefinitionAnnotation(); return static_cast<ContractDefinitionAnnotation&>(*m_annotation); } TypeNameAnnotation& TypeName::annotation() const { if (!m_annotation) m_annotation = new TypeNameAnnotation(); return static_cast<TypeNameAnnotation&>(*m_annotation); } TypePointer StructDefinition::type() const { return make_shared<TypeType>(make_shared<StructType>(*this)); } TypeDeclarationAnnotation& StructDefinition::annotation() const { if (!m_annotation) m_annotation = new TypeDeclarationAnnotation(); return static_cast<TypeDeclarationAnnotation&>(*m_annotation); } TypePointer EnumValue::type() const { auto parentDef = dynamic_cast<EnumDefinition const*>(scope()); solAssert(parentDef, "Enclosing Scope of EnumValue was not set"); return make_shared<EnumType>(*parentDef); } TypePointer EnumDefinition::type() const { return make_shared<TypeType>(make_shared<EnumType>(*this)); } TypeDeclarationAnnotation& EnumDefinition::annotation() const { if (!m_annotation) m_annotation = new TypeDeclarationAnnotation(); return static_cast<TypeDeclarationAnnotation&>(*m_annotation); } shared_ptr<FunctionType> FunctionDefinition::functionType(bool _internal) const { if (_internal) { switch (visibility()) { case Declaration::Visibility::Default: solAssert(false, "visibility() should not return Default"); case Declaration::Visibility::Private: case Declaration::Visibility::Internal: case Declaration::Visibility::Public: return make_shared<FunctionType>(*this, _internal); case Declaration::Visibility::External: return {}; default: solAssert(false, "visibility() should not return a Visibility"); } } else { switch (visibility()) { case Declaration::Visibility::Default: solAssert(false, "visibility() should not return Default"); case Declaration::Visibility::Private: case Declaration::Visibility::Internal: return {}; case Declaration::Visibility::Public: case Declaration::Visibility::External: return make_shared<FunctionType>(*this, _internal); default: solAssert(false, "visibility() should not return a Visibility"); } } // To make the compiler happy return {}; } TypePointer FunctionDefinition::type() const { return make_shared<FunctionType>(*this); } string FunctionDefinition::externalSignature() const { return FunctionType(*this).externalSignature(); } FunctionDefinitionAnnotation& FunctionDefinition::annotation() const { if (!m_annotation) m_annotation = new FunctionDefinitionAnnotation(); return static_cast<FunctionDefinitionAnnotation&>(*m_annotation); } TypePointer ModifierDefinition::type() const { return make_shared<ModifierType>(*this); } ModifierDefinitionAnnotation& ModifierDefinition::annotation() const { if (!m_annotation) m_annotation = new ModifierDefinitionAnnotation(); return static_cast<ModifierDefinitionAnnotation&>(*m_annotation); } TypePointer EventDefinition::type() const { return make_shared<FunctionType>(*this); } std::shared_ptr<FunctionType> EventDefinition::functionType(bool _internal) const { if (_internal) return make_shared<FunctionType>(*this); else return {}; } EventDefinitionAnnotation& EventDefinition::annotation() const { if (!m_annotation) m_annotation = new EventDefinitionAnnotation(); return static_cast<EventDefinitionAnnotation&>(*m_annotation); } UserDefinedTypeNameAnnotation& UserDefinedTypeName::annotation() const { if (!m_annotation) m_annotation = new UserDefinedTypeNameAnnotation(); return static_cast<UserDefinedTypeNameAnnotation&>(*m_annotation); } bool VariableDeclaration::isLValue() const { // External function parameters and constant declared variables are Read-Only return !isExternalCallableParameter() && !m_isConstant; } bool VariableDeclaration::isCallableParameter() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); if (!callable) return false; for (auto const& variable: callable->parameters()) if (variable.get() == this) return true; if (callable->returnParameterList()) for (auto const& variable: callable->returnParameterList()->parameters()) if (variable.get() == this) return true; return false; } bool VariableDeclaration::isExternalCallableParameter() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); if (!callable || callable->visibility() != Declaration::Visibility::External) return false; for (auto const& variable: callable->parameters()) if (variable.get() == this) return true; return false; } bool VariableDeclaration::canHaveAutoType() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); return (!!callable && !isCallableParameter()); } TypePointer VariableDeclaration::type() const { return annotation().type; } shared_ptr<FunctionType> VariableDeclaration::functionType(bool _internal) const { if (_internal) return {}; switch (visibility()) { case Declaration::Visibility::Default: solAssert(false, "visibility() should not return Default"); case Declaration::Visibility::Private: case Declaration::Visibility::Internal: return {}; case Declaration::Visibility::Public: case Declaration::Visibility::External: return make_shared<FunctionType>(*this); default: solAssert(false, "visibility() should not return a Visibility"); } // To make the compiler happy return {}; } VariableDeclarationAnnotation& VariableDeclaration::annotation() const { if (!m_annotation) m_annotation = new VariableDeclarationAnnotation(); return static_cast<VariableDeclarationAnnotation&>(*m_annotation); } StatementAnnotation& Statement::annotation() const { if (!m_annotation) m_annotation = new StatementAnnotation(); return static_cast<StatementAnnotation&>(*m_annotation); } InlineAssemblyAnnotation& InlineAssembly::annotation() const { if (!m_annotation) m_annotation = new InlineAssemblyAnnotation(); return static_cast<InlineAssemblyAnnotation&>(*m_annotation); } ReturnAnnotation& Return::annotation() const { if (!m_annotation) m_annotation = new ReturnAnnotation(); return static_cast<ReturnAnnotation&>(*m_annotation); } VariableDeclarationStatementAnnotation& VariableDeclarationStatement::annotation() const { if (!m_annotation) m_annotation = new VariableDeclarationStatementAnnotation(); return static_cast<VariableDeclarationStatementAnnotation&>(*m_annotation); } ExpressionAnnotation& Expression::annotation() const { if (!m_annotation) m_annotation = new ExpressionAnnotation(); return static_cast<ExpressionAnnotation&>(*m_annotation); } MemberAccessAnnotation& MemberAccess::annotation() const { if (!m_annotation) m_annotation = new MemberAccessAnnotation(); return static_cast<MemberAccessAnnotation&>(*m_annotation); } BinaryOperationAnnotation& BinaryOperation::annotation() const { if (!m_annotation) m_annotation = new BinaryOperationAnnotation(); return static_cast<BinaryOperationAnnotation&>(*m_annotation); } FunctionCallAnnotation& FunctionCall::annotation() const { if (!m_annotation) m_annotation = new FunctionCallAnnotation(); return static_cast<FunctionCallAnnotation&>(*m_annotation); } IdentifierAnnotation& Identifier::annotation() const { if (!m_annotation) m_annotation = new IdentifierAnnotation(); return static_cast<IdentifierAnnotation&>(*m_annotation); } bool Literal::looksLikeAddress() const { if (subDenomination() != SubDenomination::None) return false; string lit = value(); return lit.substr(0, 2) == "0x" && abs(int(lit.length()) - 42) <= 1; } bool Literal::passesAddressChecksum() const { string lit = value(); solAssert(lit.substr(0, 2) == "0x", "Expected hex prefix"); return dev::passesAddressChecksum(lit, true); } <commit_msg>Strict checking for AST annotation types.<commit_after>/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity abstract syntax tree. */ #include <libsolidity/interface/Utils.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/interface/Exceptions.h> #include <libsolidity/ast/AST_accept.h> #include <libdevcore/SHA3.h> #include <boost/algorithm/string.hpp> #include <algorithm> #include <functional> using namespace std; using namespace dev; using namespace dev::solidity; class IDDispenser { public: static size_t next() { return ++instance(); } static void reset() { instance() = 0; } private: static size_t& instance() { static IDDispenser dispenser; return dispenser.id; } size_t id = 0; }; ASTNode::ASTNode(SourceLocation const& _location): m_id(IDDispenser::next()), m_location(_location) { } ASTNode::~ASTNode() { delete m_annotation; } void ASTNode::resetID() { IDDispenser::reset(); } ASTAnnotation& ASTNode::annotation() const { if (!m_annotation) m_annotation = new ASTAnnotation(); return *m_annotation; } Error ASTNode::createTypeError(string const& _description) const { return Error(Error::Type::TypeError) << errinfo_sourceLocation(location()) << errinfo_comment(_description); } SourceUnitAnnotation& SourceUnit::annotation() const { if (!m_annotation) m_annotation = new SourceUnitAnnotation(); return dynamic_cast<SourceUnitAnnotation&>(*m_annotation); } string Declaration::sourceUnitName() const { solAssert(!!m_scope, ""); ASTNode const* scope = m_scope; while (dynamic_cast<Declaration const*>(scope) && dynamic_cast<Declaration const*>(scope)->m_scope) scope = dynamic_cast<Declaration const*>(scope)->m_scope; return dynamic_cast<SourceUnit const&>(*scope).annotation().path; } ImportAnnotation& ImportDirective::annotation() const { if (!m_annotation) m_annotation = new ImportAnnotation(); return dynamic_cast<ImportAnnotation&>(*m_annotation); } TypePointer ImportDirective::type() const { solAssert(!!annotation().sourceUnit, ""); return make_shared<ModuleType>(*annotation().sourceUnit); } map<FixedHash<4>, FunctionTypePointer> ContractDefinition::interfaceFunctions() const { auto exportedFunctionList = interfaceFunctionList(); map<FixedHash<4>, FunctionTypePointer> exportedFunctions; for (auto const& it: exportedFunctionList) exportedFunctions.insert(it); solAssert( exportedFunctionList.size() == exportedFunctions.size(), "Hash collision at Function Definition Hash calculation" ); return exportedFunctions; } FunctionDefinition const* ContractDefinition::constructor() const { for (FunctionDefinition const* f: definedFunctions()) if (f->isConstructor()) return f; return nullptr; } FunctionDefinition const* ContractDefinition::fallbackFunction() const { for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (FunctionDefinition const* f: contract->definedFunctions()) if (f->name().empty()) return f; return nullptr; } vector<EventDefinition const*> const& ContractDefinition::interfaceEvents() const { if (!m_interfaceEvents) { set<string> eventsSeen; m_interfaceEvents.reset(new vector<EventDefinition const*>()); for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (EventDefinition const* e: contract->events()) if (eventsSeen.count(e->name()) == 0) { eventsSeen.insert(e->name()); m_interfaceEvents->push_back(e); } } return *m_interfaceEvents; } vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::interfaceFunctionList() const { if (!m_interfaceFunctionList) { set<string> functionsSeen; set<string> signaturesSeen; m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>()); for (ContractDefinition const* contract: annotation().linearizedBaseContracts) { vector<FunctionTypePointer> functions; for (FunctionDefinition const* f: contract->definedFunctions()) if (f->isPartOfExternalInterface()) functions.push_back(make_shared<FunctionType>(*f, false)); for (VariableDeclaration const* v: contract->stateVariables()) if (v->isPartOfExternalInterface()) functions.push_back(make_shared<FunctionType>(*v)); for (FunctionTypePointer const& fun: functions) { if (!fun->interfaceFunctionType()) // Fails hopefully because we already registered the error continue; string functionSignature = fun->externalSignature(); if (signaturesSeen.count(functionSignature) == 0) { signaturesSeen.insert(functionSignature); FixedHash<4> hash(dev::keccak256(functionSignature)); m_interfaceFunctionList->push_back(make_pair(hash, fun)); } } } } return *m_interfaceFunctionList; } Json::Value const& ContractDefinition::devDocumentation() const { return m_devDocumentation; } Json::Value const& ContractDefinition::userDocumentation() const { return m_userDocumentation; } void ContractDefinition::setDevDocumentation(Json::Value const& _devDocumentation) { m_devDocumentation = _devDocumentation; } void ContractDefinition::setUserDocumentation(Json::Value const& _userDocumentation) { m_userDocumentation = _userDocumentation; } vector<Declaration const*> const& ContractDefinition::inheritableMembers() const { if (!m_inheritableMembers) { set<string> memberSeen; m_inheritableMembers.reset(new vector<Declaration const*>()); auto addInheritableMember = [&](Declaration const* _decl) { solAssert(_decl, "addInheritableMember got a nullpointer."); if (memberSeen.count(_decl->name()) == 0 && _decl->isVisibleInDerivedContracts()) { memberSeen.insert(_decl->name()); m_inheritableMembers->push_back(_decl); } }; for (FunctionDefinition const* f: definedFunctions()) addInheritableMember(f); for (VariableDeclaration const* v: stateVariables()) addInheritableMember(v); for (StructDefinition const* s: definedStructs()) addInheritableMember(s); for (EnumDefinition const* e: definedEnums()) addInheritableMember(e); for (EventDefinition const* e: events()) addInheritableMember(e); } return *m_inheritableMembers; } TypePointer ContractDefinition::type() const { return make_shared<TypeType>(make_shared<ContractType>(*this)); } ContractDefinitionAnnotation& ContractDefinition::annotation() const { if (!m_annotation) m_annotation = new ContractDefinitionAnnotation(); return dynamic_cast<ContractDefinitionAnnotation&>(*m_annotation); } TypeNameAnnotation& TypeName::annotation() const { if (!m_annotation) m_annotation = new TypeNameAnnotation(); return dynamic_cast<TypeNameAnnotation&>(*m_annotation); } TypePointer StructDefinition::type() const { return make_shared<TypeType>(make_shared<StructType>(*this)); } TypeDeclarationAnnotation& StructDefinition::annotation() const { if (!m_annotation) m_annotation = new TypeDeclarationAnnotation(); return dynamic_cast<TypeDeclarationAnnotation&>(*m_annotation); } TypePointer EnumValue::type() const { auto parentDef = dynamic_cast<EnumDefinition const*>(scope()); solAssert(parentDef, "Enclosing Scope of EnumValue was not set"); return make_shared<EnumType>(*parentDef); } TypePointer EnumDefinition::type() const { return make_shared<TypeType>(make_shared<EnumType>(*this)); } TypeDeclarationAnnotation& EnumDefinition::annotation() const { if (!m_annotation) m_annotation = new TypeDeclarationAnnotation(); return dynamic_cast<TypeDeclarationAnnotation&>(*m_annotation); } shared_ptr<FunctionType> FunctionDefinition::functionType(bool _internal) const { if (_internal) { switch (visibility()) { case Declaration::Visibility::Default: solAssert(false, "visibility() should not return Default"); case Declaration::Visibility::Private: case Declaration::Visibility::Internal: case Declaration::Visibility::Public: return make_shared<FunctionType>(*this, _internal); case Declaration::Visibility::External: return {}; default: solAssert(false, "visibility() should not return a Visibility"); } } else { switch (visibility()) { case Declaration::Visibility::Default: solAssert(false, "visibility() should not return Default"); case Declaration::Visibility::Private: case Declaration::Visibility::Internal: return {}; case Declaration::Visibility::Public: case Declaration::Visibility::External: return make_shared<FunctionType>(*this, _internal); default: solAssert(false, "visibility() should not return a Visibility"); } } // To make the compiler happy return {}; } TypePointer FunctionDefinition::type() const { return make_shared<FunctionType>(*this); } string FunctionDefinition::externalSignature() const { return FunctionType(*this).externalSignature(); } FunctionDefinitionAnnotation& FunctionDefinition::annotation() const { if (!m_annotation) m_annotation = new FunctionDefinitionAnnotation(); return dynamic_cast<FunctionDefinitionAnnotation&>(*m_annotation); } TypePointer ModifierDefinition::type() const { return make_shared<ModifierType>(*this); } ModifierDefinitionAnnotation& ModifierDefinition::annotation() const { if (!m_annotation) m_annotation = new ModifierDefinitionAnnotation(); return dynamic_cast<ModifierDefinitionAnnotation&>(*m_annotation); } TypePointer EventDefinition::type() const { return make_shared<FunctionType>(*this); } std::shared_ptr<FunctionType> EventDefinition::functionType(bool _internal) const { if (_internal) return make_shared<FunctionType>(*this); else return {}; } EventDefinitionAnnotation& EventDefinition::annotation() const { if (!m_annotation) m_annotation = new EventDefinitionAnnotation(); return dynamic_cast<EventDefinitionAnnotation&>(*m_annotation); } UserDefinedTypeNameAnnotation& UserDefinedTypeName::annotation() const { if (!m_annotation) m_annotation = new UserDefinedTypeNameAnnotation(); return dynamic_cast<UserDefinedTypeNameAnnotation&>(*m_annotation); } bool VariableDeclaration::isLValue() const { // External function parameters and constant declared variables are Read-Only return !isExternalCallableParameter() && !m_isConstant; } bool VariableDeclaration::isCallableParameter() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); if (!callable) return false; for (auto const& variable: callable->parameters()) if (variable.get() == this) return true; if (callable->returnParameterList()) for (auto const& variable: callable->returnParameterList()->parameters()) if (variable.get() == this) return true; return false; } bool VariableDeclaration::isExternalCallableParameter() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); if (!callable || callable->visibility() != Declaration::Visibility::External) return false; for (auto const& variable: callable->parameters()) if (variable.get() == this) return true; return false; } bool VariableDeclaration::canHaveAutoType() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); return (!!callable && !isCallableParameter()); } TypePointer VariableDeclaration::type() const { return annotation().type; } shared_ptr<FunctionType> VariableDeclaration::functionType(bool _internal) const { if (_internal) return {}; switch (visibility()) { case Declaration::Visibility::Default: solAssert(false, "visibility() should not return Default"); case Declaration::Visibility::Private: case Declaration::Visibility::Internal: return {}; case Declaration::Visibility::Public: case Declaration::Visibility::External: return make_shared<FunctionType>(*this); default: solAssert(false, "visibility() should not return a Visibility"); } // To make the compiler happy return {}; } VariableDeclarationAnnotation& VariableDeclaration::annotation() const { if (!m_annotation) m_annotation = new VariableDeclarationAnnotation(); return dynamic_cast<VariableDeclarationAnnotation&>(*m_annotation); } StatementAnnotation& Statement::annotation() const { if (!m_annotation) m_annotation = new StatementAnnotation(); return dynamic_cast<StatementAnnotation&>(*m_annotation); } InlineAssemblyAnnotation& InlineAssembly::annotation() const { if (!m_annotation) m_annotation = new InlineAssemblyAnnotation(); return dynamic_cast<InlineAssemblyAnnotation&>(*m_annotation); } ReturnAnnotation& Return::annotation() const { if (!m_annotation) m_annotation = new ReturnAnnotation(); return dynamic_cast<ReturnAnnotation&>(*m_annotation); } VariableDeclarationStatementAnnotation& VariableDeclarationStatement::annotation() const { if (!m_annotation) m_annotation = new VariableDeclarationStatementAnnotation(); return dynamic_cast<VariableDeclarationStatementAnnotation&>(*m_annotation); } ExpressionAnnotation& Expression::annotation() const { if (!m_annotation) m_annotation = new ExpressionAnnotation(); return dynamic_cast<ExpressionAnnotation&>(*m_annotation); } MemberAccessAnnotation& MemberAccess::annotation() const { if (!m_annotation) m_annotation = new MemberAccessAnnotation(); return dynamic_cast<MemberAccessAnnotation&>(*m_annotation); } BinaryOperationAnnotation& BinaryOperation::annotation() const { if (!m_annotation) m_annotation = new BinaryOperationAnnotation(); return dynamic_cast<BinaryOperationAnnotation&>(*m_annotation); } FunctionCallAnnotation& FunctionCall::annotation() const { if (!m_annotation) m_annotation = new FunctionCallAnnotation(); return dynamic_cast<FunctionCallAnnotation&>(*m_annotation); } IdentifierAnnotation& Identifier::annotation() const { if (!m_annotation) m_annotation = new IdentifierAnnotation(); return dynamic_cast<IdentifierAnnotation&>(*m_annotation); } bool Literal::looksLikeAddress() const { if (subDenomination() != SubDenomination::None) return false; string lit = value(); return lit.substr(0, 2) == "0x" && abs(int(lit.length()) - 42) <= 1; } bool Literal::passesAddressChecksum() const { string lit = value(); solAssert(lit.substr(0, 2) == "0x", "Expected hex prefix"); return dev::passesAddressChecksum(lit, true); } <|endoftext|>
<commit_before>#include <cpu/CPUDenseGraphBFSolver.h> #include <cpu/CPUDenseGraphAnnealer.h> #include <cpu/CPUBipartiteGraphBFSolver.h> #include <iostream> #include <chrono> #include <cuda_runtime.h> namespace sq = sqaod; #ifdef SQAOD_CUDA_ENABLED # include <cuda/CUDADenseGraphBFSolver.h> # include <cuda/CUDADenseGraphAnnealer.h> # include <cuda/CUDABipartiteGraphBFSolver.h> namespace sqcuda = sqaod_cuda; #endif template<class T> void showDuration(const T &duration) { std::cout << "elapsed time = " << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " msec." << std::endl; } template<class real> sq::MatrixType<real> symmetricMatrix(sq::SizeType dim) { sq::Random random; random.seed(0); sq::MatrixType<real> mat(dim, dim); for (sq::SizeType irow = 0; irow < dim; ++irow) { for (sq::SizeType icol = irow; icol < dim; ++icol) { mat(icol, irow) = mat(irow, icol) = random.random<real>() - 0.5f; } } return mat; } template<class real> sq::MatrixType<real> matrix(sq::Dim &dim) { sq::MatrixType<real> mat(dim.rows, dim.cols); for (sq::SizeType irow = 0; irow < dim.rows; ++irow) { for (sq::SizeType icol = 0; icol < dim.cols; ++icol) { mat(irow, icol) = sq::random.random<real>() - 0.5f; } } return mat; } template<class real> sq::VectorType<real> vector(sq::SizeType size) { sq::VectorType<real> vec(size); for (sq::SizeType idx = 0; idx < size; ++idx) { vec(idx) = sq::random.random<real>() - 0.5f; } return vec; } template<class real> void denseGraphBFSearch(int N) { sq::MatrixType<real> W = symmetricMatrix<real>(N); sq::CPUDenseGraphBFSolver<real> cpuSolver; cpuSolver.setProblem(W); cpuSolver.setTileSize(1 << std::min(N, 20)); auto start = std::chrono::system_clock::now(); cpuSolver.search(); auto end = std::chrono::system_clock::now(); std::cout << cpuSolver.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; device.initialize(); sqcuda::CUDADenseGraphBFSolver<real> cudaSolver(device); cudaSolver.setProblem(W); cudaSolver.setTileSize(1 << std::min(N, 18)); start = std::chrono::system_clock::now(); cudaSolver.search(); end = std::chrono::system_clock::now(); std::cout << cudaSolver.get_E().min() << std::endl; device.finalize(); showDuration(end - start); #endif } template<class real> void bipartiteGraphBFSearch(int N0, int N1) { sq::VectorType<real> b0 = vector<real>(N0); sq::VectorType<real> b1 = vector<real>(N1); sq::MatrixType<real> W = matrix<real>(sq::Dim(N1, N0)); sq::CPUBipartiteGraphBFSolver<real> cpuSolver; cpuSolver.setProblem(b0, b1, W); // cpuSolver.setTileSize(1 << std::min(N, 20)); auto start = std::chrono::system_clock::now(); cpuSolver.search(); auto end = std::chrono::system_clock::now(); std::cout << cpuSolver.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; // device.useManagedMemory(true); // device.enableLocalStore(false); device.initialize(); sqcuda::CUDABipartiteGraphBFSolver<real> cudaSolver(device); cudaSolver.setProblem(b0, b1, W); // cudaSolver.setTileSize(1 << std::min(N, 20)); start = std::chrono::system_clock::now(); cudaSolver.search(); end = std::chrono::system_clock::now(); std::cout << cudaSolver.get_E().min() << std::endl; device.finalize(); showDuration(end - start); #endif } template<class real, template<class real> class A> void anneal(A<real> &an, real Ginit, real Gfin, real kT, real tau) { an.initAnneal(); an.randomize_q(); real G = Ginit; while (Gfin < G) { an.annealOneStep(G, kT); G = G * tau; std::cerr << "."; } an.finAnneal(); std::cerr << std::endl; const sq::VectorType<real> &E = an.get_E(); std::cerr << "Energy : " << E.min() << std::endl; } template<class real> void denseGraphAnnealer(int N) { real Ginit = 5.; real Gfin = 0.01; real kT = 0.02; real tau = 0.99; sq::MatrixType<real> W = symmetricMatrix<real>(N); sq::CPUDenseGraphAnnealer<real> cpuAnnealer; cpuAnnealer.seed(0); cpuAnnealer.selectAlgorithm(sq::algoNaive); cpuAnnealer.setProblem(W); cpuAnnealer.setNumTrotters(N / 2); auto start = std::chrono::system_clock::now(); anneal(cpuAnnealer, Ginit, Gfin, kT, tau); auto end = std::chrono::system_clock::now(); std::cout << cpuAnnealer.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; device.initialize(); { sqcuda::CUDADenseGraphAnnealer<real> cudaAnnealer(device); cudaAnnealer.setProblem(W); cudaAnnealer.setNumTrotters(N / 2); cudaAnnealer.seed(1); auto start = std::chrono::system_clock::now(); anneal(cudaAnnealer, Ginit, Gfin, kT, tau); auto end = std::chrono::system_clock::now(); device.synchronize(); std::cout << cudaAnnealer.get_E().min() << std::endl; showDuration(end - start); } device.finalize(); #endif } int main() { sq::random.seed(0); int N = 24; denseGraphBFSearch<double>(N); denseGraphBFSearch<float>(N); N = 1024; denseGraphAnnealer<double>(N); denseGraphAnnealer<float>(N); int N0 = 14, N1 = 14; bipartiteGraphBFSearch<float>(N0, N1); bipartiteGraphBFSearch<double>(N0, N1); cudaDeviceReset(); } <commit_msg>bipartiteGraphAnnelear perf code added.<commit_after>#include <cpu/CPUDenseGraphBFSolver.h> #include <cpu/CPUDenseGraphAnnealer.h> #include <cpu/CPUBipartiteGraphBFSolver.h> #include <cpu/CPUBipartiteGraphAnnealer.h> #include <iostream> #include <chrono> #include <cuda_runtime.h> namespace sq = sqaod; #ifdef SQAOD_CUDA_ENABLED # include <cuda/CUDADenseGraphBFSolver.h> # include <cuda/CUDADenseGraphAnnealer.h> # include <cuda/CUDABipartiteGraphBFSolver.h> # include <cuda/CUDABipartiteGraphAnnealer.h> namespace sqcuda = sqaod_cuda; #endif template<class T> void showDuration(const T &duration) { std::cout << "elapsed time = " << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " msec." << std::endl; } template<class real> sq::MatrixType<real> symmetricMatrix(sq::SizeType dim) { sq::Random random; random.seed(0); sq::MatrixType<real> mat(dim, dim); for (sq::SizeType irow = 0; irow < dim; ++irow) { for (sq::SizeType icol = irow; icol < dim; ++icol) { mat(icol, irow) = mat(irow, icol) = random.random<real>() - 0.5f; } } return mat; } template<class real> sq::MatrixType<real> matrix(const sq::Dim &dim) { sq::MatrixType<real> mat(dim.rows, dim.cols); for (sq::SizeType irow = 0; irow < dim.rows; ++irow) { for (sq::SizeType icol = 0; icol < dim.cols; ++icol) { mat(irow, icol) = sq::random.random<real>() - 0.5f; } } return mat; } template<class real> sq::VectorType<real> vector(sq::SizeType size) { sq::VectorType<real> vec(size); for (sq::SizeType idx = 0; idx < size; ++idx) { vec(idx) = sq::random.random<real>() - 0.5f; } return vec; } template<class real> void denseGraphBFSearch(int N) { sq::MatrixType<real> W = symmetricMatrix<real>(N); sq::CPUDenseGraphBFSolver<real> cpuSolver; cpuSolver.setProblem(W); cpuSolver.setTileSize(1 << std::min(N, 20)); auto start = std::chrono::system_clock::now(); cpuSolver.search(); auto end = std::chrono::system_clock::now(); std::cout << cpuSolver.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; device.initialize(); sqcuda::CUDADenseGraphBFSolver<real> cudaSolver(device); cudaSolver.setProblem(W); cudaSolver.setTileSize(1 << std::min(N, 18)); start = std::chrono::system_clock::now(); cudaSolver.search(); end = std::chrono::system_clock::now(); std::cout << cudaSolver.get_E().min() << std::endl; device.finalize(); showDuration(end - start); #endif } template<class real> void bipartiteGraphBFSearch(int N0, int N1) { sq::VectorType<real> b0 = vector<real>(N0); sq::VectorType<real> b1 = vector<real>(N1); sq::MatrixType<real> W = matrix<real>(sq::Dim(N1, N0)); sq::CPUBipartiteGraphBFSolver<real> cpuSolver; cpuSolver.setProblem(b0, b1, W); // cpuSolver.setTileSize(1 << std::min(N, 20)); auto start = std::chrono::system_clock::now(); cpuSolver.search(); auto end = std::chrono::system_clock::now(); std::cout << cpuSolver.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; // device.useManagedMemory(true); // device.enableLocalStore(false); device.initialize(); sqcuda::CUDABipartiteGraphBFSolver<real> cudaSolver(device); cudaSolver.setProblem(b0, b1, W); // cudaSolver.setTileSize(1 << std::min(N, 20)); start = std::chrono::system_clock::now(); cudaSolver.search(); end = std::chrono::system_clock::now(); std::cout << cudaSolver.get_E().min() << std::endl; device.finalize(); showDuration(end - start); #endif } template<class real, template<class real> class A> void anneal(A<real> &an, real Ginit, real Gfin, real kT, real tau) { an.initAnneal(); an.randomize_q(); real G = Ginit; while (Gfin < G) { an.annealOneStep(G, kT); G = G * tau; std::cerr << "."; } an.finAnneal(); std::cerr << std::endl; const sq::VectorType<real> &E = an.get_E(); std::cerr << "Energy : " << E.min() << std::endl; } template<class real> void denseGraphAnnealer(int N) { real Ginit = 5.; real Gfin = 0.01; real kT = 0.02; real tau = 0.99; sq::MatrixType<real> W = symmetricMatrix<real>(N); sq::CPUDenseGraphAnnealer<real> cpuAnnealer; cpuAnnealer.seed(0); cpuAnnealer.selectAlgorithm(sq::algoNaive); cpuAnnealer.setProblem(W); cpuAnnealer.setNumTrotters(N / 2); auto start = std::chrono::system_clock::now(); anneal(cpuAnnealer, Ginit, Gfin, kT, tau); auto end = std::chrono::system_clock::now(); std::cout << cpuAnnealer.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; device.initialize(); { sqcuda::CUDADenseGraphAnnealer<real> cudaAnnealer(device); cudaAnnealer.setProblem(W); cudaAnnealer.setNumTrotters(N / 2); cudaAnnealer.seed(1); auto start = std::chrono::system_clock::now(); anneal(cudaAnnealer, Ginit, Gfin, kT, tau); auto end = std::chrono::system_clock::now(); device.synchronize(); std::cout << cudaAnnealer.get_E().min() << std::endl; showDuration(end - start); } device.finalize(); #endif } template<class real> void bipartiteGraphAnnealer(int N0, int N1) { real Ginit = 5.; real Gfin = 0.01; real kT = 0.02; real tau = 0.99; sq::VectorType<real> b0 = vector<real>(N0); sq::VectorType<real> b1 = vector<real>(N1); sq::MatrixType<real> W = matrix<real>(sq::Dim(N0, N1)); sq::CPUBipartiteGraphAnnealer<real> cpuAnnealer; cpuAnnealer.seed(0); // cpuAnnealer.selectAlgorithm(sq::algoNaive); cpuAnnealer.setProblem(b0, b1, W); cpuAnnealer.setNumTrotters((N0 + N1) / 2); auto start = std::chrono::system_clock::now(); anneal(cpuAnnealer, Ginit, Gfin, kT, tau); auto end = std::chrono::system_clock::now(); std::cout << cpuAnnealer.get_E().min() << std::endl; showDuration(end - start); #ifdef SQAOD_CUDA_ENABLED sqcuda::Device device; device.initialize(); { sqcuda::CUDABipartiteGraphAnnealer<real> cudaAnnealer(device); cudaAnnealer.setProblem(b0, b1, W); cudaAnnealer.setNumTrotters((N0 + N1) / 2); cudaAnnealer.seed(1); auto start = std::chrono::system_clock::now(); anneal(cudaAnnealer, Ginit, Gfin, kT, tau); auto end = std::chrono::system_clock::now(); device.synchronize(); std::cout << cudaAnnealer.get_E().min() << std::endl; showDuration(end - start); } device.finalize(); #endif } int main() { sq::random.seed(0); int N = 24; denseGraphBFSearch<double>(N); denseGraphBFSearch<float>(N); N = 1024; denseGraphAnnealer<double>(N); denseGraphAnnealer<float>(N); int N0 = 14, N1 = 14; bipartiteGraphBFSearch<float>(N0, N1); bipartiteGraphBFSearch<double>(N0, N1); bipartiteGraphAnnealer<float>(N0, N1); bipartiteGraphAnnealer<double>(N0, N1); cudaDeviceReset(); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <moe/moe.hpp> TEST_CASE( "Genetic Algorithm tests", "[genetic]" ) { auto dataset = moe::util::getAlphabet<char>(); dataset.push_back(' '); GeneticAlgorithm<char> ga( 200, dataset, 100 ); SECTION( "Getters tests" ) { SECTION( "Dataset check" ) { std::vector<char> model = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' '}; REQUIRE( ga.getDataset() == model ); } SECTION( "Default Crossover is OnePoint" ) { REQUIRE( ga.getCrossover() == moe::Crossover::OnePoint ); } SECTION( "Crossover & Mutation is enabled by default" ) { REQUIRE( ga.isCrossoverEnabled() ); REQUIRE( ga.isMutationEnabled() ); } SECTION( "random genotype should as long as m_fixedSize" ) { REQUIRE( ga.getRandomGenotype().size() == ga.getFixedSize() ); } } SECTION( "Should return an optimal solution" ) { std::vector<char> target = {'h','e','l','l','o',' ','w','o','r','l','d'}; ga.setFitnessFunction( [target](auto moe) -> double { std::vector<char> genotype = moe.genotype; int dSize = target.size() - genotype.size(); // get difference of number of characters unsigned int min = std::min(target.size(), genotype.size()); double error = std::abs(dSize) * 256; // add 256 error points for each extra or lack of char for(unsigned int i = 0; i < min; i++) error += std::abs( genotype[i] - target[i] ); // each difference of character is added to error score return 1/(error+1); }); ga.run( 1500 ); // converts std::vector<char> to std::string std::string genotype; for(char c : ga.getBestMoe().genotype) genotype += c; // CAPTURE( genotype ); CAPTURE( ga.getBestMoe().fitness ); REQUIRE( ga.getBestMoe().fitness <= 4 ); } } <commit_msg>Added Differential Evolution tests<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <moe/moe.hpp> TEST_CASE( "Genetic Algorithm tests", "[genetic_algorithm]" ) { auto dataset = moe::util::getAlphabet<char>(); dataset.push_back(' '); GeneticAlgorithm<char> ga( 200, dataset, 100 ); SECTION( "Getters tests" ) { SECTION( "Dataset check" ) { std::vector<char> model = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' '}; REQUIRE( ga.getDataset() == model ); } SECTION( "Default Crossover is OnePoint" ) { REQUIRE( ga.getCrossover() == moe::Crossover::OnePoint ); } SECTION( "Crossover & Mutation is enabled by default" ) { REQUIRE( ga.isCrossoverEnabled() ); REQUIRE( ga.isMutationEnabled() ); } SECTION( "random genotype should as long as m_fixedSize" ) { REQUIRE( ga.getRandomGenotype().size() == ga.getFixedSize() ); } } SECTION( "Should return an optimal solution" ) { std::vector<char> target = {'h','e','l','l','o',' ','w','o','r','l','d'}; ga.setFitnessFunction( [target](auto moe) -> double { std::vector<char> genotype = moe.genotype; int dSize = target.size() - genotype.size(); // get difference of number of characters unsigned int min = std::min(target.size(), genotype.size()); double error = std::abs(dSize) * 256; // add 256 error points for each extra or lack of char for(unsigned int i = 0; i < min; i++) error += std::abs( genotype[i] - target[i] ); // each difference of character is added to error score return 1/(error+1); }); ga.run( 1500 ); // converts std::vector<char> to std::string std::string genotype; for(char c : ga.getBestMoe().genotype) genotype += c; // CAPTURE( genotype ); CAPTURE( ga.getBestMoe().fitness ); REQUIRE( ga.getBestMoe().fitness <= 4 ); } } TEST_CASE( "Differential Evolution Tests", "[differential_evolution]" ) { DifferentialEvolution<int> de(20); long long n = 2261953600; de.setFitnessFunction( [n](auto moe) -> double { long long genotype = moe.genotype[0]; double error = std::abs(n - genotype*genotype); return 1/(error+1); }); SECTION( "Should return an optimal solution" ) { de.run(50); CAPTURE( de.getBestMoe().genotype[0] ); CAPTURE( de.getBestMoe().fitness ); REQUIRE( de.getBestMoe().fitness == Approx(1).margin(1)); } } <|endoftext|>
<commit_before>// mlsstr.cc see license.txt for copyright and terms of use // code for mlsstr.h // based on ccsstr.cc #include "mlsstr.h" // this module #include "xassert.h" // xassert #include "exc.h" // xformat #include "strutil.h" // string, replace #include <iostream.h> // cout #include <ctype.h> // isspace MLSubstrate::MLSubstrate(ReportError *err) : EmbeddedLang(err) { reset(); } void MLSubstrate::reset(int initNest) { state = ST_NORMAL; delims.empty(); comNesting = 0; prev = 0; text.setlength(0); } MLSubstrate::~MLSubstrate() {} void MLSubstrate::handle(char const *str, int len, char finalDelim) { text.append(str, len); for (; len>0; len--,str++) { process_char_again: switch (state) { case ST_NORMAL: switch (*str) { case '{': case '(': case '[': if (!inComment()) { delims.push(*str); } break; case '}': case ')': case ']': if (inComment()) { if (prev == '*' && *str == ')') { comNesting--; } } else if (nesting() == 0) { err->reportError(stringc << "unexpected closing delimiter `" << *str << "' -- probably due to missing `" << finalDelim << "'"); } else { char o = delims.top(); char c = *str; if (!(( o=='{' && c=='}' ) || ( o=='(' && c==')' ) || ( o=='[' && c==']' ))) { err->reportError(stringc << "opening delimiter `" << o << "' does not match closing delimiter `" << c << "'"); } delims.pop(); } break; case '\"': state = ST_STRING; break; case '\'': if (isalnum(prev) || prev=='_' || prev=='\'') { // this is a prime on a variable name; stay in normal mode } else { state = ST_APOSTROPHE1; } break; case '*': if (prev == '(') { if (comNesting == 0) { // undo 'delims.push()' from the '(' xassert(nesting() > 0); delims.pop(); } comNesting++; // if the next char is ')', i.e. input was "(*)", do // not allow it to use this '*' to finish the comment prev = 0; continue; } break; } break; case ST_APOSTROPHE1: // While the OCaml manual does not specify how to disambiguate // between character literals and type variables, the ocaml // lexer (parsing/lexer.mll) uses (approximately) the // following rules: // // - If the input is (apostrophe, char, apostrophe), it is // a character literal. // - If the input is (apostrophe, backslash), it is the start // of a a character literal. // - Any other occurrence of apostrophe starts a type variable. if (*str == '\\') { state = ST_CHAR; } else { state = ST_APOSTROPHE2; } break; case ST_APOSTROPHE2: if (*str == '\'') { state = ST_NORMAL; // finishes the character literal } else { // whole thing is a type variable; but if *str is something // like ')' then we need to consider its effects on nesting state = ST_NORMAL; goto process_char_again; } break; case ST_STRING: case ST_CHAR: if (prev != '\\') { if ((state == ST_STRING && *str == '\"') || (state == ST_CHAR && *str == '\'')) { state = ST_NORMAL; } else if (*str == '\n') { // actually, ocaml allows unescaped newlines in string literals //err->reportError("unterminated string or char literal"); } } else { prev = 0; // the backslash cancels any specialness of *str continue; } break; #if 0 // old case ST_COMMENT: if (prev == '(' && *str == '*') { comNesting++; prev = 0; // like above continue; } else if (prev == '*' && *str == ')') { xassert(comNesting >= 0); if (comNesting == 0) { // done with comment state = ST_NORMAL; } else { // decrease nesting comNesting--; } } break; #endif // 0 default: xfailure("unknown state"); } prev = *str; } } bool MLSubstrate::zeroNesting() const { return state == ST_NORMAL && nesting() == 0 && !inComment(); } string MLSubstrate::getFuncBody() const { return text; } // 4/29/04: I have no idea if this is right or not.. this is the // definition from ccsstr.cc. string MLSubstrate::getDeclName() const { // go with the rather inelegant heuristic that the word // just before the first '(' is the function's name char const *start = text.c_str(); char const *p = start; // find first '(' while (*p && *p!='(') { p++; } if (!*p) { xformat("missing '('"); } if (p == start) { xformat("missing name"); } // skip backward past any whitespace before the '(' p--; while (p>=start && isspace(*p)) { p--; } if (p<start) { xformat("missing name"); } char const *nameEnd = p+1; // char just past last // move backward through the name while (p>=start && (isalnum(*p) || *p=='_')) { p--; } p++; // move back to most recent legal char // done return substring(p, nameEnd-p); } // ------------------ test code ------------------- #ifdef TEST_MLSSTR #define ML MLSubstrate #define Test MLSubstrateTest // test code is put into a class just so that MLSubstrate // can grant it access to private fields class Test { public: void feed(ML &ml, char const *src, bool allowErrors = false); void silentFeed(ML &ml, char const *src); void test(char const *src, ML::State state, int nesting, int comNesting, char prev); void normal(char const *src, int nesting); void str(char const *src, int nesting, bool bs); void yes(char const *src); void no(char const *src); void name(char const *body, char const *n); void badname(char const *body); void bad(char const *body); int main(int argc, char *argv[]); }; #define min(a,b) ((a)<(b)?(a):(b)) void Test::feed(ML &ml, char const *src, bool allowErrors) { int origErrors = simpleReportError.errors; cout << "trying: " << src << endl; silentFeed(ml, src); if (!allowErrors && origErrors != simpleReportError.errors) { xfailure(stringc << "caused error: " << src); } } void Test::silentFeed(ML &ml, char const *src) { while (*src) { // feed it in 10 char increments, to test split processing too int len = min(strlen(src), 10); ml.handle(src, len, '}'); src += len; } } void Test::test(char const *src, ML::State state, int nesting, int comNesting, char prev) { ML ml; feed(ml, src); if (!( ml.state == state && ml.nesting() == nesting && ml.comNesting == comNesting && ml.prev == prev )) { xfailure(stringc << "failed on src: " << src); } } void Test::normal(char const *src, int nesting) { test(src, ML::ST_NORMAL, nesting, 0, src[strlen(src)-1]); } void Test::str(char const *src, int nesting, bool bs) { char prev = (bs? '\\' : src[strlen(src)-1]); test(src, ML::ST_STRING, nesting, 0, prev); // repeat the test with single-tick // // 2005-01-25: No, OCaml's character-literal rules do not treat // quote and apostrophe similarly. //string another = replace(src, "\"", "\'"); //test(another, ML::ST_CHAR, nesting, 0, prev); } void Test::yes(char const *src) { ML ml; feed(ml, src); xassert(ml.zeroNesting()); } void Test::no(char const *src) { ML ml; feed(ml, src); xassert(!ml.zeroNesting()); } void Test::name(char const *body, char const *n) { ML ml; feed(ml, body); xassert(ml.getDeclName().equals(n)); } void Test::badname(char const *body) { ML ml; feed(ml, body); try { ml.getDeclName(); xbase("got a name when it shoudn't have!"); } catch (...) {} } void Test::bad(char const *body) { int origErrors = simpleReportError.errors; ML ml; feed(ml, body, true /*allowErrors*/); if (origErrors == simpleReportError.errors) { xbase(stringc << "should have caused an error: " << body); } } int Test::main(int argc, char *argv[]) { if (argc >= 2) { // analyze the files passed as an argument, expecting them to be // complete caml source files, ending in normal mode with all // delimiters closed for (int i=1; i<argc; i++) { string text = readStringFromFile(argv[i]); ML ml; silentFeed(ml, text.c_str()); if (ml.state != ML::ST_NORMAL) { xbase(stringc << argv[i] << ": ended in state " << (int)ml.state); } if (ml.nesting() != 0) { xbase(stringc << argv[i] << ": ended with nesting " << ml.nesting()); } if (simpleReportError.errors != 0) { xbase(stringc << argv[i] << ": caused errors"); } cout << argv[i] << ": ok\n"; } return 0; } normal("int main()", 0); normal("int main() { hi", 1); normal("int main() { hi {", 2); normal("int main() { hi { foo[5", 3); normal("int main() { hi { foo[5] and ", 2); normal("int main() { hi { foo[5] and } bar ", 1); normal("int main() { hi { foo[5] and } bar } baz ", 0); normal("main() { printf(\"hello \\ world\"); ret", 1); normal("()[]{}([{}])", 0); normal("{ ()[]{}([{}]) } ", 0); normal("( ()[]{}([{}]) )", 0); normal("[ ()[]{}([{}]) ]", 0); normal("\"foo\" ()[]{}([{}])", 0); str("main() { printf(\"hello", 2, false); str("main() { printf(\"hello \\", 2, true); str("main() { printf(\"hello \\ world", 2, false); str("main() { printf(\"hello \\ world\", \"hi", 2, false); // escaped newline normal("main() { printf(\"hello \\\n world\"); }", 0); // newlines do not have to be escaped! normal("main() { printf(\"hello \n world\"); }", 0); test("\"a\" 'b' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" '\\n' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" '\\\\' (", ML::ST_NORMAL, 1, 0, '('); // here, the "'b" is to be treated as a type variable test("\"a\" 'b (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" ('b) (", ML::ST_NORMAL, 1, 0, '('); // and here it is a prime ending the name of a variable test("\"a\" b' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" (b') (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" let b=b' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" let b=b'' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" let b=b''' (", ML::ST_NORMAL, 1, 0, '('); // test comments, particularly testing test("(", ML::ST_NORMAL, 1, 0, '('); test("(*", ML::ST_NORMAL, 0, 1, 0); test("(*)", ML::ST_NORMAL, 0, 1, ')'); test("(*)(", ML::ST_NORMAL, 0, 1, '('); test("(*)(*", ML::ST_NORMAL, 0, 2, 0); test("(*)(*)", ML::ST_NORMAL, 0, 2, ')'); test("(*)(*)*", ML::ST_NORMAL, 0, 2, '*'); test("(*)(*)*)", ML::ST_NORMAL, 0, 1, ')'); test("(*)(*)*)*", ML::ST_NORMAL, 0, 1, '*'); test("(*)(*)*)*)", ML::ST_NORMAL, 0, 0, ')'); test("(*(*(*(*", ML::ST_NORMAL, 0, 4, 0); yes("main() {}"); yes("main() { printf(\"foo\", 3, 4 (*yep{*)); }"); yes("some (* junk {\n more*)"); yes("'\\''"); yes("\"\\\"\""); yes("[][][][][]"); yes("\"[[[\""); yes("*"); yes("(* [ / * [ *)"); yes("(* \"(*\" *)"); // quoted open-comment ignored no("\""); no("("); no(" ( (* ) *) "); name("int main()", "main"); name("int eval(Environment &env)", "eval"); name("man()", "man"); badname("("); badname(" ("); badname(" "); badname(""); bad(")"); badname("main"); cout << "\nmlsstr: all tests PASSED\n"; return 0; } int main(int argc, char *argv[]) { //xBase::logExceptions = false; try { Test t; return t.main(argc, argv); } catch (xBase &x) { cout << endl << x << endl; return 10; } } #endif // TEST_MLSSTR <commit_msg>tweak<commit_after>// mlsstr.cc see license.txt for copyright and terms of use // code for mlsstr.h // based on ccsstr.cc #include "mlsstr.h" // this module #include "xassert.h" // xassert #include "exc.h" // xformat #include "strutil.h" // string, replace #include <iostream.h> // cout #include <ctype.h> // isspace MLSubstrate::MLSubstrate(ReportError *err) : EmbeddedLang(err) { reset(); } void MLSubstrate::reset(int initNest) { state = ST_NORMAL; delims.empty(); comNesting = 0; prev = 0; text.setlength(0); } MLSubstrate::~MLSubstrate() {} void MLSubstrate::handle(char const *str, int len, char finalDelim) { text.append(str, len); for (; len>0; len--,str++) { process_char_again: switch (state) { case ST_NORMAL: switch (*str) { case '{': case '(': case '[': if (!inComment()) { delims.push(*str); } break; case '}': case ')': case ']': if (inComment()) { if (prev == '*' && *str == ')') { comNesting--; } } else if (nesting() == 0) { err->reportError(stringc << "unexpected closing delimiter `" << *str << "' -- probably due to missing `" << finalDelim << "'"); } else { char o = delims.top(); char c = *str; if (!(( o=='{' && c=='}' ) || ( o=='(' && c==')' ) || ( o=='[' && c==']' ))) { err->reportError(stringc << "opening delimiter `" << o << "' does not match closing delimiter `" << c << "'"); } delims.pop(); } break; case '\"': state = ST_STRING; break; case '\'': if (isalnum(prev) || prev=='_' || prev=='\'') { // this is a prime on a variable name; stay in normal mode } else { state = ST_APOSTROPHE1; } break; case '*': if (prev == '(') { if (comNesting == 0) { // undo 'delims.push()' from the '(' xassert(nesting() > 0); delims.pop(); } comNesting++; // if the next char is ')', i.e. input was "(*)", do // not allow it to use this '*' to finish the comment prev = 0; continue; } break; } break; case ST_APOSTROPHE1: // While the OCaml manual does not specify how to disambiguate // between character literals and type variables, the ocaml // lexer (parsing/lexer.mll) uses (approximately) the // following rules: // // - If the input is (apostrophe, char, apostrophe), it is // a character literal. // - If the input is (apostrophe, backslash), it is the start // of a a character literal. // - Any other occurrence of apostrophe starts a type variable. if (*str == '\\') { state = ST_CHAR; } else { state = ST_APOSTROPHE2; } break; case ST_APOSTROPHE2: if (*str == '\'') { state = ST_NORMAL; // finishes the character literal } else { // whole thing is a type variable; but if *str is something // like ')' then we need to consider its effects on nesting state = ST_NORMAL; goto process_char_again; } break; case ST_STRING: case ST_CHAR: if (prev != '\\') { if ((state == ST_STRING && *str == '\"') || (state == ST_CHAR && *str == '\'')) { state = ST_NORMAL; } else if (*str == '\n') { // actually, ocaml allows unescaped newlines in string literals //err->reportError("unterminated string or char literal"); } } else { prev = 0; // the backslash cancels any specialness of *str continue; } break; #if 0 // old case ST_COMMENT: if (prev == '(' && *str == '*') { comNesting++; prev = 0; // like above continue; } else if (prev == '*' && *str == ')') { xassert(comNesting >= 0); if (comNesting == 0) { // done with comment state = ST_NORMAL; } else { // decrease nesting comNesting--; } } break; #endif // 0 default: xfailure("unknown state"); } prev = *str; } } bool MLSubstrate::zeroNesting() const { return state == ST_NORMAL && nesting() == 0 && !inComment(); } string MLSubstrate::getFuncBody() const { return text; } // 4/29/04: I have no idea if this is right or not.. this is the // definition from ccsstr.cc. string MLSubstrate::getDeclName() const { // go with the rather inelegant heuristic that the word // just before the first '(' is the function's name char const *start = text.c_str(); char const *p = start; // find first '(' while (*p && *p!='(') { p++; } if (!*p) { xformat("missing '('"); } if (p == start) { xformat("missing name"); } // skip backward past any whitespace before the '(' p--; while (p>=start && isspace(*p)) { p--; } if (p<start) { xformat("missing name"); } char const *nameEnd = p+1; // char just past last // move backward through the name while (p>=start && (isalnum(*p) || *p=='_')) { p--; } p++; // move back to most recent legal char // done return substring(p, nameEnd-p); } // ------------------ test code ------------------- #ifdef TEST_MLSSTR #define ML MLSubstrate #define Test MLSubstrateTest // test code is put into a class just so that MLSubstrate // can grant it access to private fields class Test { public: void feed(ML &ml, char const *src, bool allowErrors = false); void silentFeed(ML &ml, char const *src); void test(char const *src, ML::State state, int nesting, int comNesting, char prev); void normal(char const *src, int nesting); void str(char const *src, int nesting, bool bs); void yes(char const *src); void no(char const *src); void name(char const *body, char const *n); void badname(char const *body); void bad(char const *body); int main(int argc, char *argv[]); }; #define min(a,b) ((a)<(b)?(a):(b)) void Test::feed(ML &ml, char const *src, bool allowErrors) { int origErrors = simpleReportError.errors; cout << "trying: " << src << endl; silentFeed(ml, src); if (!allowErrors && origErrors != simpleReportError.errors) { xfailure(stringc << "caused error: " << src); } } void Test::silentFeed(ML &ml, char const *src) { while (*src) { // feed it in 10 char increments, to test split processing too int len = min(strlen(src), 10); ml.handle(src, len, '}'); src += len; } } void Test::test(char const *src, ML::State state, int nesting, int comNesting, char prev) { ML ml; feed(ml, src); if (!( ml.state == state && ml.nesting() == nesting && ml.comNesting == comNesting && ml.prev == prev )) { xfailure(stringc << "failed on src: " << src); } } void Test::normal(char const *src, int nesting) { test(src, ML::ST_NORMAL, nesting, 0, src[strlen(src)-1]); } void Test::str(char const *src, int nesting, bool bs) { char prev = (bs? '\\' : src[strlen(src)-1]); test(src, ML::ST_STRING, nesting, 0, prev); // repeat the test with single-tick // // 2005-01-25: No, OCaml's character-literal rules do not treat // quote and apostrophe similarly. //string another = replace(src, "\"", "\'"); //test(another, ML::ST_CHAR, nesting, 0, prev); } void Test::yes(char const *src) { ML ml; feed(ml, src); xassert(ml.zeroNesting()); } void Test::no(char const *src) { ML ml; feed(ml, src); xassert(!ml.zeroNesting()); } void Test::name(char const *body, char const *n) { ML ml; feed(ml, body); xassert(ml.getDeclName().equals(n)); } void Test::badname(char const *body) { ML ml; feed(ml, body); try { ml.getDeclName(); xbase("got a name when it shoudn't have!"); } catch (...) {} } void Test::bad(char const *body) { int origErrors = simpleReportError.errors; ML ml; feed(ml, body, true /*allowErrors*/); if (origErrors == simpleReportError.errors) { xbase(stringc << "should have caused an error: " << body); } } int Test::main(int argc, char *argv[]) { if (argc >= 2) { // analyze the files passed as an argument, expecting them to be // complete caml source files, ending in normal mode with all // delimiters closed for (int i=1; i<argc; i++) { string text = readStringFromFile(argv[i]); ML ml; silentFeed(ml, text.c_str()); if (ml.state != ML::ST_NORMAL) { xbase(stringc << argv[i] << ": ended in state " << (int)ml.state); } if (ml.nesting() != 0) { xbase(stringc << argv[i] << ": ended with nesting " << ml.nesting()); } if (ml.inComment()) { xbase(stringc << argv[i] << ": ended in a comment"); } if (simpleReportError.errors != 0) { xbase(stringc << argv[i] << ": caused errors"); } cout << argv[i] << ": ok\n"; } return 0; } normal("int main()", 0); normal("int main() { hi", 1); normal("int main() { hi {", 2); normal("int main() { hi { foo[5", 3); normal("int main() { hi { foo[5] and ", 2); normal("int main() { hi { foo[5] and } bar ", 1); normal("int main() { hi { foo[5] and } bar } baz ", 0); normal("main() { printf(\"hello \\ world\"); ret", 1); normal("()[]{}([{}])", 0); normal("{ ()[]{}([{}]) } ", 0); normal("( ()[]{}([{}]) )", 0); normal("[ ()[]{}([{}]) ]", 0); normal("\"foo\" ()[]{}([{}])", 0); str("main() { printf(\"hello", 2, false); str("main() { printf(\"hello \\", 2, true); str("main() { printf(\"hello \\ world", 2, false); str("main() { printf(\"hello \\ world\", \"hi", 2, false); // escaped newline normal("main() { printf(\"hello \\\n world\"); }", 0); // newlines do not have to be escaped! normal("main() { printf(\"hello \n world\"); }", 0); test("\"a\" 'b' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" '\\n' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" '\\\\' (", ML::ST_NORMAL, 1, 0, '('); // here, the "'b" is to be treated as a type variable test("\"a\" 'b (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" ('b) (", ML::ST_NORMAL, 1, 0, '('); // and here it is a prime ending the name of a variable test("\"a\" b' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" (b') (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" let b=b' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" let b=b'' (", ML::ST_NORMAL, 1, 0, '('); test("\"a\" let b=b''' (", ML::ST_NORMAL, 1, 0, '('); // test comments, particularly testing test("(", ML::ST_NORMAL, 1, 0, '('); test("(*", ML::ST_NORMAL, 0, 1, 0); test("(*)", ML::ST_NORMAL, 0, 1, ')'); test("(*)(", ML::ST_NORMAL, 0, 1, '('); test("(*)(*", ML::ST_NORMAL, 0, 2, 0); test("(*)(*)", ML::ST_NORMAL, 0, 2, ')'); test("(*)(*)*", ML::ST_NORMAL, 0, 2, '*'); test("(*)(*)*)", ML::ST_NORMAL, 0, 1, ')'); test("(*)(*)*)*", ML::ST_NORMAL, 0, 1, '*'); test("(*)(*)*)*)", ML::ST_NORMAL, 0, 0, ')'); test("(*(*(*(*", ML::ST_NORMAL, 0, 4, 0); yes("main() {}"); yes("main() { printf(\"foo\", 3, 4 (*yep{*)); }"); yes("some (* junk {\n more*)"); yes("'\\''"); yes("\"\\\"\""); yes("[][][][][]"); yes("\"[[[\""); yes("*"); yes("(* [ / * [ *)"); yes("(* \"(*\" *)"); // quoted open-comment ignored no("\""); no("("); no(" ( (* ) *) "); name("int main()", "main"); name("int eval(Environment &env)", "eval"); name("man()", "man"); badname("("); badname(" ("); badname(" "); badname(""); bad(")"); badname("main"); cout << "\nmlsstr: all tests PASSED\n"; return 0; } int main(int argc, char *argv[]) { //xBase::logExceptions = false; try { Test t; return t.main(argc, argv); } catch (xBase &x) { cout << endl << x << endl; return 10; } } #endif // TEST_MLSSTR <|endoftext|>
<commit_before>// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_REGION_HPP #define TOML11_REGION_HPP #include "exception.hpp" #include <memory> #include <vector> #include <algorithm> #include <initializer_list> #include <iterator> #include <iomanip> namespace toml { namespace detail { // helper function to avoid std::string(0, 'c') or std::string(iter, iter) template<typename Iterator> std::string make_string(Iterator first, Iterator last) { if(first == last) {return "";} return std::string(first, last); } inline std::string make_string(std::size_t len, char c) { if(len == 0) {return "";} return std::string(len, c); } // region_base is a base class of location and region that are defined below. // it will be used to generate better error messages. struct region_base { region_base() = default; virtual ~region_base() = default; region_base(const region_base&) = default; region_base(region_base&& ) = default; region_base& operator=(const region_base&) = default; region_base& operator=(region_base&& ) = default; virtual bool is_ok() const noexcept {return false;} virtual std::string str() const {return std::string("unknown region");} virtual std::string name() const {return std::string("unknown file");} virtual std::string line() const {return std::string("unknown line");} virtual std::string line_num() const {return std::string("?");} // length of the region virtual std::size_t size() const noexcept {return 0;} // number of characters in the line before the region virtual std::size_t before() const noexcept {return 0;} // number of characters in the line after the region virtual std::size_t after() const noexcept {return 0;} virtual std::string comment_before() const {return "";} // just before virtual std::string comment_inline() const {return "";} // in the same line virtual std::string comment() const {return "";} // concatenate // ```toml // # comment_before // key = "value" # comment_inline // ``` }; // location represents a position in a container, which contains a file content. // it can be considered as a region that contains only one character. // // it contains pointer to the file content and iterator that points the current // location. template<typename Container> struct location final : public region_base { using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; static_assert(std::is_same<char, typename Container::value_type>::value,""); static_assert(std::is_same<std::random_access_iterator_tag, typename std::iterator_traits<const_iterator>::iterator_category>::value, "container should be randomly accessible"); location(std::string name, Container cont) : source_(std::make_shared<Container>(std::move(cont))), line_number_(1), source_name_(std::move(name)), iter_(source_->cbegin()) {} location(const location&) = default; location(location&&) = default; location& operator=(const location&) = default; location& operator=(location&&) = default; ~location() = default; bool is_ok() const noexcept override {return static_cast<bool>(source_);} // this const prohibits codes like `++(loc.iter())`. const const_iterator iter() const noexcept {return iter_;} const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} // XXX `location::line_num()` used to be implemented using `std::count` to // count a number of '\n'. But with a long toml file (typically, 10k lines), // it becomes intolerably slow because each time it generates error messages, // it counts '\n' from thousands of characters. To workaround it, I decided // to introduce `location::line_number_` member variable and synchronize it // to the location changes the point to look. So an overload of `iter()` // which returns mutable reference is removed and `advance()`, `retrace()` // and `reset()` is added. void advance(std::size_t n = 1) noexcept { this->line_number_ += std::count(this->iter_, this->iter_ + n, '\n'); this->iter_ += n; return; } void retrace(std::size_t n = 1) noexcept { this->line_number_ -= std::count(this->iter_ - n, this->iter_, '\n'); this->iter_ -= n; return; } void reset(const_iterator rollback) noexcept { // since c++11, std::distance works in both ways for random-access // iterators and returns a negative value if `first > last`. if(0 <= std::distance(rollback, this->iter_)) // rollback < iter { this->line_number_ -= std::count(rollback, this->iter_, '\n'); } else // iter < rollback [[unlikely]] { this->line_number_ += std::count(this->iter_, rollback, '\n'); } this->iter_ = rollback; return; } std::string str() const override {return make_string(1, *this->iter());} std::string name() const override {return source_name_;} std::string line_num() const override { return std::to_string(this->line_number_); } std::string line() const override { return make_string(this->line_begin(), this->line_end()); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->iter()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->iter(), this->end(), '\n'); } // location is always points a character. so the size is 1. std::size_t size() const noexcept override { return 1u; } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->iter()); } std::size_t after() const noexcept override { return std::distance(this->iter(), this->line_end()); } source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} private: source_ptr source_; std::size_t line_number_; std::string source_name_; const_iterator iter_; }; // region represents a range in a container, which contains a file content. // // it contains pointer to the file content and iterator that points the first // and last location. template<typename Container> struct region final : public region_base { using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; static_assert(std::is_same<char, typename Container::value_type>::value,""); static_assert(std::is_same<std::random_access_iterator_tag, typename std::iterator_traits<const_iterator>::iterator_category>::value, "container should be randomly accessible"); // delete default constructor. source_ never be null. region() = delete; region(const location<Container>& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(location<Container>&& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(const location<Container>& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(location<Container>&& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(const region&) = default; region(region&&) = default; region& operator=(const region&) = default; region& operator=(region&&) = default; ~region() = default; region& operator+=(const region& other) { if(this->begin() != other.begin() || this->end() != other.end() || this->last_ != other.first_) { throw internal_error("invalid region concatenation"); } this->last_ = other.last_; return *this; } bool is_ok() const noexcept override {return static_cast<bool>(source_);} std::string str() const override {return make_string(first_, last_);} std::string line() const override { if(this->contain_newline()) { return make_string(this->line_begin(), std::find(this->line_begin(), this->last(), '\n')); } return make_string(this->line_begin(), this->line_end()); } std::string line_num() const override { return std::to_string(1 + std::count(this->begin(), this->first(), '\n')); } std::size_t size() const noexcept override { return std::distance(first_, last_); } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->first()); } std::size_t after() const noexcept override { return std::distance(this->last(), this->line_end()); } bool contain_newline() const noexcept { return std::find(this->first(), this->last(), '\n') != this->last(); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->first()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->last(), this->end(), '\n'); } const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} const_iterator first() const noexcept {return first_;} const_iterator last() const noexcept {return last_;} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string name() const override {return source_name_;} std::string comment_before() const override { auto iter = this->line_begin(); // points the first element std::vector<std::pair<decltype(iter), decltype(iter)>> comments; while(iter != this->begin()) { iter = std::prev(iter); using rev_iter = std::reverse_iterator<decltype(iter)>; auto line_before = std::find(rev_iter(iter), rev_iter(this->begin()), '\n').base(); // range [line_before, iter) represents the previous line auto comment_found = std::find(line_before, iter, '#'); if(iter != comment_found && std::all_of(line_before, comment_found, [](const char c) noexcept -> bool { return c == ' ' || c == '\t'; })) { // the line before this range contains only a comment. comments.push_back(std::make_pair(comment_found, iter)); } else { break; } iter = line_before; } std::string com; for(auto i = comments.crbegin(), e = comments.crend(); i!=e; ++i) { if(i != comments.crbegin()) {com += '\n';} com += std::string(i->first, i->second); } return com; } std::string comment_inline() const override { if(this->contain_newline()) { std::string com; // check both the first and the last line. const auto first_line_end = std::find(this->line_begin(), this->last(), '\n'); const auto first_comment_found = std::find(this->line_begin(), first_line_end, '#'); if(first_comment_found != first_line_end) { com += std::string(first_comment_found, first_line_end); } const auto last_comment_found = std::find(this->last(), this->line_end(), '#'); if(last_comment_found != this->line_end()) { if(!com.empty()){com += '\n';} com += std::string(last_comment_found, this->line_end()); } return com; } const auto comment_found = std::find(this->line_begin(), this->line_end(), '#'); return std::string(comment_found, this->line_end()); } std::string comment() const override { std::string com_bef = this->comment_before(); std::string com_inl = this->comment_inline(); if(!com_bef.empty() && !com_inl.empty()) { com_bef += '\n'; return com_bef + com_inl; } else if(com_bef.empty()) { return com_inl; } else { return com_bef; } } private: source_ptr source_; std::string source_name_; const_iterator first_, last_; }; // to show a better error message. inline std::string format_underline(const std::string& message, const std::vector<std::pair<region_base const*, std::string>>& reg_com, const std::vector<std::string>& helps = {}) { assert(!reg_com.empty()); const auto line_num_width = std::max_element(reg_com.begin(), reg_com.end(), [](std::pair<region_base const*, std::string> const& lhs, std::pair<region_base const*, std::string> const& rhs) { return lhs.first->line_num().size() < rhs.first->line_num().size(); } )->first->line_num().size(); std::ostringstream retval; retval << message << '\n'; for(auto iter = reg_com.begin(); iter != reg_com.end(); ++iter) { // if the filenames are the same, print "..." if(iter != reg_com.begin() && std::prev(iter)->first->name() == iter->first->name()) { retval << "\n ...\n"; } else // if filename differs, print " --> filename.toml" { if(iter != reg_com.begin()) {retval << '\n';} retval << " --> " << iter->first->name() << '\n'; } const region_base* const reg = iter->first; const std::string& comment = iter->second; retval << ' ' << std::setw(line_num_width) << reg->line_num(); retval << " | " << reg->line() << '\n'; retval << make_string(line_num_width + 1, ' '); retval << " | " << make_string(reg->before(), ' '); if(reg->size() == 1) { // invalid // ^------ retval << '^'; retval << make_string(reg->after(), '-'); } else { // invalid // ~~~~~~~ const auto underline_len = std::min(reg->size(), reg->line().size()); retval << make_string(underline_len, '~'); } retval << ' '; retval << comment; } if(!helps.empty()) { retval << '\n'; retval << make_string(line_num_width + 1, ' '); retval << " | "; for(const auto help : helps) { retval << "\nHint: "; retval << help; } } return retval.str(); } } // detail } // toml #endif// TOML11_REGION_H <commit_msg>fix: add missing include file<commit_after>// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_REGION_HPP #define TOML11_REGION_HPP #include "exception.hpp" #include <memory> #include <vector> #include <algorithm> #include <initializer_list> #include <iterator> #include <iomanip> #include <cassert> namespace toml { namespace detail { // helper function to avoid std::string(0, 'c') or std::string(iter, iter) template<typename Iterator> std::string make_string(Iterator first, Iterator last) { if(first == last) {return "";} return std::string(first, last); } inline std::string make_string(std::size_t len, char c) { if(len == 0) {return "";} return std::string(len, c); } // region_base is a base class of location and region that are defined below. // it will be used to generate better error messages. struct region_base { region_base() = default; virtual ~region_base() = default; region_base(const region_base&) = default; region_base(region_base&& ) = default; region_base& operator=(const region_base&) = default; region_base& operator=(region_base&& ) = default; virtual bool is_ok() const noexcept {return false;} virtual std::string str() const {return std::string("unknown region");} virtual std::string name() const {return std::string("unknown file");} virtual std::string line() const {return std::string("unknown line");} virtual std::string line_num() const {return std::string("?");} // length of the region virtual std::size_t size() const noexcept {return 0;} // number of characters in the line before the region virtual std::size_t before() const noexcept {return 0;} // number of characters in the line after the region virtual std::size_t after() const noexcept {return 0;} virtual std::string comment_before() const {return "";} // just before virtual std::string comment_inline() const {return "";} // in the same line virtual std::string comment() const {return "";} // concatenate // ```toml // # comment_before // key = "value" # comment_inline // ``` }; // location represents a position in a container, which contains a file content. // it can be considered as a region that contains only one character. // // it contains pointer to the file content and iterator that points the current // location. template<typename Container> struct location final : public region_base { using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; static_assert(std::is_same<char, typename Container::value_type>::value,""); static_assert(std::is_same<std::random_access_iterator_tag, typename std::iterator_traits<const_iterator>::iterator_category>::value, "container should be randomly accessible"); location(std::string name, Container cont) : source_(std::make_shared<Container>(std::move(cont))), line_number_(1), source_name_(std::move(name)), iter_(source_->cbegin()) {} location(const location&) = default; location(location&&) = default; location& operator=(const location&) = default; location& operator=(location&&) = default; ~location() = default; bool is_ok() const noexcept override {return static_cast<bool>(source_);} // this const prohibits codes like `++(loc.iter())`. const const_iterator iter() const noexcept {return iter_;} const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} // XXX `location::line_num()` used to be implemented using `std::count` to // count a number of '\n'. But with a long toml file (typically, 10k lines), // it becomes intolerably slow because each time it generates error messages, // it counts '\n' from thousands of characters. To workaround it, I decided // to introduce `location::line_number_` member variable and synchronize it // to the location changes the point to look. So an overload of `iter()` // which returns mutable reference is removed and `advance()`, `retrace()` // and `reset()` is added. void advance(std::size_t n = 1) noexcept { this->line_number_ += std::count(this->iter_, this->iter_ + n, '\n'); this->iter_ += n; return; } void retrace(std::size_t n = 1) noexcept { this->line_number_ -= std::count(this->iter_ - n, this->iter_, '\n'); this->iter_ -= n; return; } void reset(const_iterator rollback) noexcept { // since c++11, std::distance works in both ways for random-access // iterators and returns a negative value if `first > last`. if(0 <= std::distance(rollback, this->iter_)) // rollback < iter { this->line_number_ -= std::count(rollback, this->iter_, '\n'); } else // iter < rollback [[unlikely]] { this->line_number_ += std::count(this->iter_, rollback, '\n'); } this->iter_ = rollback; return; } std::string str() const override {return make_string(1, *this->iter());} std::string name() const override {return source_name_;} std::string line_num() const override { return std::to_string(this->line_number_); } std::string line() const override { return make_string(this->line_begin(), this->line_end()); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->iter()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->iter(), this->end(), '\n'); } // location is always points a character. so the size is 1. std::size_t size() const noexcept override { return 1u; } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->iter()); } std::size_t after() const noexcept override { return std::distance(this->iter(), this->line_end()); } source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} private: source_ptr source_; std::size_t line_number_; std::string source_name_; const_iterator iter_; }; // region represents a range in a container, which contains a file content. // // it contains pointer to the file content and iterator that points the first // and last location. template<typename Container> struct region final : public region_base { using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; static_assert(std::is_same<char, typename Container::value_type>::value,""); static_assert(std::is_same<std::random_access_iterator_tag, typename std::iterator_traits<const_iterator>::iterator_category>::value, "container should be randomly accessible"); // delete default constructor. source_ never be null. region() = delete; region(const location<Container>& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(location<Container>&& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(const location<Container>& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(location<Container>&& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(const region&) = default; region(region&&) = default; region& operator=(const region&) = default; region& operator=(region&&) = default; ~region() = default; region& operator+=(const region& other) { if(this->begin() != other.begin() || this->end() != other.end() || this->last_ != other.first_) { throw internal_error("invalid region concatenation"); } this->last_ = other.last_; return *this; } bool is_ok() const noexcept override {return static_cast<bool>(source_);} std::string str() const override {return make_string(first_, last_);} std::string line() const override { if(this->contain_newline()) { return make_string(this->line_begin(), std::find(this->line_begin(), this->last(), '\n')); } return make_string(this->line_begin(), this->line_end()); } std::string line_num() const override { return std::to_string(1 + std::count(this->begin(), this->first(), '\n')); } std::size_t size() const noexcept override { return std::distance(first_, last_); } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->first()); } std::size_t after() const noexcept override { return std::distance(this->last(), this->line_end()); } bool contain_newline() const noexcept { return std::find(this->first(), this->last(), '\n') != this->last(); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->first()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->last(), this->end(), '\n'); } const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} const_iterator first() const noexcept {return first_;} const_iterator last() const noexcept {return last_;} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string name() const override {return source_name_;} std::string comment_before() const override { auto iter = this->line_begin(); // points the first element std::vector<std::pair<decltype(iter), decltype(iter)>> comments; while(iter != this->begin()) { iter = std::prev(iter); using rev_iter = std::reverse_iterator<decltype(iter)>; auto line_before = std::find(rev_iter(iter), rev_iter(this->begin()), '\n').base(); // range [line_before, iter) represents the previous line auto comment_found = std::find(line_before, iter, '#'); if(iter != comment_found && std::all_of(line_before, comment_found, [](const char c) noexcept -> bool { return c == ' ' || c == '\t'; })) { // the line before this range contains only a comment. comments.push_back(std::make_pair(comment_found, iter)); } else { break; } iter = line_before; } std::string com; for(auto i = comments.crbegin(), e = comments.crend(); i!=e; ++i) { if(i != comments.crbegin()) {com += '\n';} com += std::string(i->first, i->second); } return com; } std::string comment_inline() const override { if(this->contain_newline()) { std::string com; // check both the first and the last line. const auto first_line_end = std::find(this->line_begin(), this->last(), '\n'); const auto first_comment_found = std::find(this->line_begin(), first_line_end, '#'); if(first_comment_found != first_line_end) { com += std::string(first_comment_found, first_line_end); } const auto last_comment_found = std::find(this->last(), this->line_end(), '#'); if(last_comment_found != this->line_end()) { if(!com.empty()){com += '\n';} com += std::string(last_comment_found, this->line_end()); } return com; } const auto comment_found = std::find(this->line_begin(), this->line_end(), '#'); return std::string(comment_found, this->line_end()); } std::string comment() const override { std::string com_bef = this->comment_before(); std::string com_inl = this->comment_inline(); if(!com_bef.empty() && !com_inl.empty()) { com_bef += '\n'; return com_bef + com_inl; } else if(com_bef.empty()) { return com_inl; } else { return com_bef; } } private: source_ptr source_; std::string source_name_; const_iterator first_, last_; }; // to show a better error message. inline std::string format_underline(const std::string& message, const std::vector<std::pair<region_base const*, std::string>>& reg_com, const std::vector<std::string>& helps = {}) { assert(!reg_com.empty()); const auto line_num_width = std::max_element(reg_com.begin(), reg_com.end(), [](std::pair<region_base const*, std::string> const& lhs, std::pair<region_base const*, std::string> const& rhs) { return lhs.first->line_num().size() < rhs.first->line_num().size(); } )->first->line_num().size(); std::ostringstream retval; retval << message << '\n'; for(auto iter = reg_com.begin(); iter != reg_com.end(); ++iter) { // if the filenames are the same, print "..." if(iter != reg_com.begin() && std::prev(iter)->first->name() == iter->first->name()) { retval << "\n ...\n"; } else // if filename differs, print " --> filename.toml" { if(iter != reg_com.begin()) {retval << '\n';} retval << " --> " << iter->first->name() << '\n'; } const region_base* const reg = iter->first; const std::string& comment = iter->second; retval << ' ' << std::setw(line_num_width) << reg->line_num(); retval << " | " << reg->line() << '\n'; retval << make_string(line_num_width + 1, ' '); retval << " | " << make_string(reg->before(), ' '); if(reg->size() == 1) { // invalid // ^------ retval << '^'; retval << make_string(reg->after(), '-'); } else { // invalid // ~~~~~~~ const auto underline_len = std::min(reg->size(), reg->line().size()); retval << make_string(underline_len, '~'); } retval << ' '; retval << comment; } if(!helps.empty()) { retval << '\n'; retval << make_string(line_num_width + 1, ' '); retval << " | "; for(const auto help : helps) { retval << "\nHint: "; retval << help; } } return retval.str(); } } // detail } // toml #endif// TOML11_REGION_H <|endoftext|>