hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
886b9a9a31b4a81273f54697a992fa197c725052
3,238
cc
C++
server/core/test/test_service.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
[ "MIT" ]
null
null
null
server/core/test/test_service.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
[ "MIT" ]
1
2019-07-02T09:59:27.000Z
2019-07-02T09:59:49.000Z
server/core/test/test_service.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2022-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ /** * * @verbatim * Revision History * * Date Who Description * 08-09-2014 Martin Brampton Initial implementation * * @endverbatim */ // To ensure that ss_info_assert asserts also when builing in non-debug mode. #if !defined (SS_DEBUG) #define SS_DEBUG #endif #if defined (NDEBUG) #undef NDEBUG #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <maxscale/maxscale_test.h> #include <maxscale/paths.h> #include <maxscale/alloc.h> #include "../internal/service.hh" #include "test_utils.h" #include "../config.cc" /** * test1 Allocate a service and do lots of other things * */ static int test1() { Service* service; MXS_SESSION* session; DCB* dcb; int result; int argc = 3; init_test_env(NULL); set_libdir(MXS_STRDUP_A("../../modules/authenticator/MySQLAuth/")); load_module("mysqlauth", MODULE_AUTHENTICATOR); set_libdir(MXS_STRDUP_A("../../modules/protocol/MySQL/mariadbclient/")); load_module("mariadbclient", MODULE_PROTOCOL); set_libdir(MXS_STRDUP_A("../../modules/routing/readconnroute/")); load_module("readconnroute", MODULE_ROUTER); /* Service tests */ fprintf(stderr, "testservice : creating service called MyService with router nonexistent"); service = service_alloc("MyService", "non-existent", NULL); mxb_assert_message(NULL == service, "New service with invalid router should be null"); mxb_assert_message(0 == service_isvalid(service), "Service must not be valid after incorrect creation"); fprintf(stderr, "\t..done\nValid service creation, router testroute."); service = service_alloc("MyService", "readconnroute", NULL); mxb_assert_message(NULL != service, "New service with valid router must not be null"); mxb_assert_message(0 != service_isvalid(service), "Service must be valid after creation"); mxb_assert_message(0 == strcmp("MyService", service->name), "Service must have given name"); fprintf(stderr, "\t..done\nAdding protocol testprotocol."); mxb_assert_message(serviceCreateListener(service, "TestProtocol", "mariadbclient", "localhost", 9876, "MySQLAuth", NULL, NULL), "Add Protocol should succeed"); mxb_assert_message(0 != serviceHasListener(service, "TestProtocol", "mariadbclient", "localhost", 9876), "Service should have new protocol as requested"); return 0; } int main(int argc, char** argv) { int result = 0; result += test1(); exit(result); }
32.38
108
0.622915
tut-blog
886c0606c27af098cf18eb343f5de319872b424b
26,827
cpp
C++
src/se3-trajectory-generator.cpp
jviereck/sot-torque-control
90409a656e5b5be4dd4ff937724154579861c20f
[ "BSD-2-Clause" ]
null
null
null
src/se3-trajectory-generator.cpp
jviereck/sot-torque-control
90409a656e5b5be4dd4ff937724154579861c20f
[ "BSD-2-Clause" ]
null
null
null
src/se3-trajectory-generator.cpp
jviereck/sot-torque-control
90409a656e5b5be4dd4ff937724154579861c20f
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2017, Andrea Del Prete, LAAS-CNRS * * This file is part of sot-torque-control. * sot-torque-control 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. * sot-torque-control 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 sot-torque-control. If not, see <http://www.gnu.org/licenses/>. */ #include <sot/torque_control/se3-trajectory-generator.hh> #include <sot/core/debug.hh> #include <dynamic-graph/factory.h> #include <sot/torque_control/commands-helper.hh> #include <sot/torque_control/utils/stop-watch.hh> namespace dynamicgraph { namespace sot { namespace torque_control { namespace dg = ::dynamicgraph; using namespace dg; using namespace dg::command; using namespace std; using namespace Eigen; #define PROFILE_SE3_POSITION_DESIRED_COMPUTATION "SE3TrajGen: traj computation" /// Define EntityClassName here rather than in the header file /// so that it can be used by the macros DEFINE_SIGNAL_**_FUNCTION. typedef SE3TrajectoryGenerator EntityClassName; /* --- DG FACTORY ---------------------------------------------------- */ DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(SE3TrajectoryGenerator, "SE3TrajectoryGenerator"); /* ------------------------------------------------------------------- */ /* --- CONSTRUCTION -------------------------------------------------- */ /* ------------------------------------------------------------------- */ SE3TrajectoryGenerator:: SE3TrajectoryGenerator(const std::string& name) : Entity(name) ,CONSTRUCT_SIGNAL_IN(initial_value,dynamicgraph::Vector) ,CONSTRUCT_SIGNAL_IN(trigger,bool) ,CONSTRUCT_SIGNAL(x, OUT, dynamicgraph::Vector) ,CONSTRUCT_SIGNAL_OUT(dx, dynamicgraph::Vector, m_xSOUT) ,CONSTRUCT_SIGNAL_OUT(ddx, dynamicgraph::Vector, m_xSOUT) ,m_firstIter(true) ,m_initSucceeded(false) ,m_splineReady(false) ,m_t(0) ,m_np(12) ,m_nv(6) ,m_iterLast(0) { BIND_SIGNAL_TO_FUNCTION(x, OUT, dynamicgraph::Vector); Entity::signalRegistration( m_xSOUT << m_dxSOUT << m_ddxSOUT << m_initial_valueSIN <<m_triggerSIN ); /* Commands. */ addCommand("init", makeCommandVoid1(*this, &SE3TrajectoryGenerator::init, docCommandVoid1("Initialize the entity.", "Time period in seconds (double)"))); addCommand("getValue", makeCommandVoid1(*this, &SE3TrajectoryGenerator::getValue, docCommandVoid1("Get the current value of the specified index.", "index (int)"))); addCommand("playTrajectoryFile", makeCommandVoid1(*this, &SE3TrajectoryGenerator::playTrajectoryFile, docCommandVoid1("Play the trajectory read from the specified text file.", "(string) File name, path included"))); addCommand("setSpline", makeCommandVoid3(*this, &SE3TrajectoryGenerator::setSpline, docCommandVoid3("Load serialized spline from file", "(string) filename", "(double) time to initial conf", "(Matrix) orientation of the point"))); addCommand("startSinusoid", makeCommandVoid3(*this, &SE3TrajectoryGenerator::startSinusoid, docCommandVoid3("Start an infinite sinusoid motion.", "(int) index", "(double) final value", "(double) time to reach the final value in sec"))); addCommand("startTriangle", makeCommandVoid4(*this, &SE3TrajectoryGenerator::startTriangle, docCommandVoid4("Start an infinite triangle wave.", "(int) index", "(double) final values", "(double) time to reach the final value in sec", "(double) time to accelerate in sec"))); addCommand("startConstAcc", makeCommandVoid3(*this, &SE3TrajectoryGenerator::startConstAcc, docCommandVoid3("Start an infinite trajectory with piece-wise constant acceleration.", "(int) index", "(double) final values", "(double) time to reach the final value in sec"))); addCommand("startLinChirp", makeCommandVoid5(*this, &SE3TrajectoryGenerator::startLinearChirp, docCommandVoid5("Start a linear-chirp motion.", "(int) index", "(double) final values", "(double) initial frequency [Hz]", "(double) final frequency [Hz]", "(double) trajectory time [sec]"))); addCommand("move", makeCommandVoid3(*this, &SE3TrajectoryGenerator::move, docCommandVoid3("Move component corresponding to index to the specified value with a minimum jerk trajectory.", "(int) index", "(double) final values", "(double) time to reach the final value in sec"))); addCommand("stop", makeCommandVoid1(*this, &SE3TrajectoryGenerator::stop, docCommandVoid1("Stop the motion of the specified index, or of all components of the vector if index is equal to -1.", "(int) index"))); } void SE3TrajectoryGenerator::init(const double& dt) { if(dt<=0.0) return SEND_MSG("Timestep must be positive", MSG_TYPE_ERROR); m_firstIter = true; m_dt = dt; m_status.resize(m_np, TG_STOP); m_minJerkTrajGen.resize(m_np); m_sinTrajGen.resize(m_np); m_triangleTrajGen.resize(m_np); m_constAccTrajGen.resize(m_np); m_linChirpTrajGen.resize(m_np); m_currentTrajGen.resize(m_np); m_noTrajGen.resize(m_np); for(int i=0; i<m_np; i++) { m_minJerkTrajGen[i] = new MinimumJerkTrajectoryGenerator(dt,5.0,1); m_sinTrajGen[i] = new SinusoidTrajectoryGenerator(dt,5.0,1); m_triangleTrajGen[i] = new TriangleTrajectoryGenerator(dt,5.0,1); m_constAccTrajGen[i] = new ConstantAccelerationTrajectoryGenerator(dt,5.0,1); m_linChirpTrajGen[i] = new LinearChirpTrajectoryGenerator(dt,5.0,1); m_noTrajGen[i] = new NoTrajectoryGenerator(1); m_currentTrajGen[i] = m_noTrajGen[i]; } m_splineTrajGen = new parametriccurves::Spline<double,Eigen::Dynamic>(); m_textFileTrajGen = new TextFileTrajectoryGenerator(dt, m_np); m_initSucceeded = true; } /* ------------------------------------------------------------------- */ /* --- SIGNALS ------------------------------------------------------- */ /* ------------------------------------------------------------------- */ DEFINE_SIGNAL_OUT_FUNCTION(x, dynamicgraph::Vector) { if(!m_initSucceeded) { SEND_WARNING_STREAM_MSG("Cannot compute signal positionDes before initialization!"); return s; } getProfiler().start(PROFILE_SE3_POSITION_DESIRED_COMPUTATION); { if(s.size()!=m_np) s.resize(m_np); // at first iteration store initial values if(m_firstIter) { const dynamicgraph::Vector& initial_value = m_initial_valueSIN(iter); if(initial_value.size()!=m_np) { SEND_ERROR_STREAM_MSG("Unexpected size of input signal initial_value: "+toString(initial_value.size())); getProfiler().stop(PROFILE_SE3_POSITION_DESIRED_COMPUTATION); return s; } for(unsigned int i=0; i<m_np; i++) m_currentTrajGen[i]->set_initial_point(initial_value(i)); m_firstIter = false; } else if(iter == m_iterLast) { if (m_triggerSIN(iter)==true && m_splineReady) startSpline(); if(m_status[0]==TG_TEXT_FILE) { for(unsigned int i=0; i<m_np; i++) s(i) = m_textFileTrajGen->getPos()[i]; } else if(m_status[0]==TG_SPLINE) { const Eigen::Vector3d& t= (*m_splineTrajGen)(m_t); s.head<3>() = t; s.segment<3>(3) = m_splineRotation.row(0); s.segment<3>(6) = m_splineRotation.row(1); s.segment<3>(9) = m_splineRotation.row(2); } else for(unsigned int i=0; i<m_np; i++) s(i) = m_currentTrajGen[i]->getPos()(0); getProfiler().stop(PROFILE_SE3_POSITION_DESIRED_COMPUTATION); return s; } m_iterLast = iter; if (m_triggerSIN(iter)==true && m_splineReady) startSpline(); if(m_status[0]==TG_TEXT_FILE) { const VectorXd& xRef = m_textFileTrajGen->compute_next_point(); for(unsigned int i=0; i<m_np; i++) { s(i) = xRef[i]; if(m_textFileTrajGen->isTrajectoryEnded()) { m_noTrajGen[i]->set_initial_point(s(i)); m_status[i] = TG_STOP; } } if(m_textFileTrajGen->isTrajectoryEnded()) SEND_MSG("Text file trajectory ended.", MSG_TYPE_INFO); } else if(m_status[0]==TG_SPLINE) { m_t += m_dt; if(!m_splineTrajGen->checkRange(m_t)) { const Eigen::Vector3d& t= (*m_splineTrajGen)(m_splineTrajGen->tmax()); s.head<3>() = t; s.segment<3>(3) = m_splineRotation.row(0); s.segment<3>(6) = m_splineRotation.row(1); s.segment<3>(9) = m_splineRotation.row(2); for(unsigned int i=0; i<m_np; i++) { m_noTrajGen[i]->set_initial_point(s(i)); m_status[i] = TG_STOP; } m_splineReady =false; SEND_MSG("Spline trajectory ended. Remember to turn off the trigger.", MSG_TYPE_INFO); m_t =0; } else { const Eigen::Vector3d& t= (*m_splineTrajGen)(m_t); s.head<3>() = t; s.segment<3>(3) = m_splineRotation.row(0); s.segment<3>(6) = m_splineRotation.row(1); s.segment<3>(9) = m_splineRotation.row(2); } } else { for(unsigned int i=0; i<m_np; i++) { s(i) = m_currentTrajGen[i]->compute_next_point()(0); if(m_currentTrajGen[i]->isTrajectoryEnded()) { m_currentTrajGen[i] = m_noTrajGen[i]; m_noTrajGen[i]->set_initial_point(s(i)); m_status[i] = TG_STOP; SEND_MSG("Trajectory of index "+toString(i)+" ended.", MSG_TYPE_INFO); } } } } getProfiler().stop(PROFILE_SE3_POSITION_DESIRED_COMPUTATION); return s; } DEFINE_SIGNAL_OUT_FUNCTION(dx, dynamicgraph::Vector) { if(!m_initSucceeded) { SEND_WARNING_STREAM_MSG("Cannot compute signal positionDes before initialization!"); return s; } const dynamicgraph::Vector& x = m_xSOUT(iter); if(s.size()!=m_nv) s.resize(m_nv); if(m_status[0]==TG_TEXT_FILE) { for(unsigned int i=0; i<m_nv; i++) s(i) = m_textFileTrajGen->getVel()[i]; } else if(m_status[0]==TG_SPLINE) { const Eigen::Vector3d& t= m_splineTrajGen->derivate(m_t,1); s.segment<3>(0) = t; s.segment<3>(3).setZero(); } else for(unsigned int i=0; i<m_nv; i++) s(i) = m_currentTrajGen[i]->getVel()(0); return s; } DEFINE_SIGNAL_OUT_FUNCTION(ddx, dynamicgraph::Vector) { if(!m_initSucceeded) { SEND_WARNING_STREAM_MSG("Cannot compute signal positionDes before initialization!"); return s; } const dynamicgraph::Vector& x = m_xSOUT(iter); if(s.size()!=m_nv) s.resize(m_nv); if(m_status[0]==TG_TEXT_FILE) { for(unsigned int i=0; i<m_nv; i++) s(i) = m_textFileTrajGen->getAcc()[i]; } else if(m_status[0]==TG_SPLINE) { const Eigen::Vector3d& t= m_splineTrajGen->derivate(m_t,2); s.segment<3>(0) = t; s.segment<3>(3).setZero(); } else for(unsigned int i=0; i<m_nv; i++) s(i) = m_currentTrajGen[i]->getAcc()(0); return s; } /* ------------------------------------------------------------------- */ /* --- COMMANDS ------------------------------------------------------ */ /* ------------------------------------------------------------------- */ void SE3TrajectoryGenerator::getValue(const int& id) { if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); SEND_MSG("Current value of component "+toString(id)+" is "+toString( m_currentTrajGen[id]->getPos()(0) ), MSG_TYPE_INFO); } void SE3TrajectoryGenerator::playTrajectoryFile(const std::string& fileName) { if(!m_initSucceeded) return SEND_MSG("Cannot start sinusoid before initialization!",MSG_TYPE_ERROR); for(unsigned int i=0; i<m_np; i++) if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot control component "+toString(i)+" because it is already controlled.", MSG_TYPE_ERROR); if(!m_textFileTrajGen->loadTextFile(fileName)) return SEND_MSG("Error while loading text file "+fileName, MSG_TYPE_ERROR); // check current configuration is not too far from initial trajectory configuration bool needToMoveToInitConf = false; const VectorXd& xInit = m_textFileTrajGen->get_initial_point(); for(unsigned int i=0; i<m_np; i++) if(fabs(xInit[i] - m_currentTrajGen[i]->getPos()(0)) > 0.001) { needToMoveToInitConf = true; SEND_MSG("Component "+ toString(i) +" is too far from initial configuration so first i will move it there.", MSG_TYPE_WARNING); } // if necessary move joints to initial configuration if(needToMoveToInitConf) { for(unsigned int i=0; i<m_np; i++) { m_minJerkTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos()); m_minJerkTrajGen[i]->set_final_point(xInit[i]); m_minJerkTrajGen[i]->set_trajectory_time(4.0); m_status[i] = TG_MIN_JERK; m_currentTrajGen[i] = m_minJerkTrajGen[i]; } return; } for(unsigned int i=0; i<m_np; i++) { m_status[i] = TG_TEXT_FILE; } } void SE3TrajectoryGenerator::setSpline(const std::string& fileName, const double& timeToInitConf, const Eigen::MatrixXd& init_rotation) { if(!m_initSucceeded) return SEND_MSG("Cannot start sinusoid before initialization!",MSG_TYPE_ERROR); for(unsigned int i=0; i<m_np; i++) if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot control component "+toString(i)+" because it is already controlled.", MSG_TYPE_ERROR); if(!m_splineTrajGen->loadFromFile(fileName)) return SEND_MSG("Error while loading text file "+fileName, MSG_TYPE_ERROR); // check current configuration is not too far from initial trajectory configuration bool needToMoveToInitConf = false; m_splineReady = true; m_splineRotation = init_rotation; if(timeToInitConf < 0) { SEND_MSG("Spline Ready. Set trigger to true to start playing", MSG_TYPE_INFO); return; } const VectorXd& t= (*m_splineTrajGen)(0.0); VectorXd xInit(12); xInit.segment<3>(3) = m_splineRotation.row(0); xInit.segment<3>(6) = m_splineRotation.row(1); xInit.segment<3>(9) = m_splineRotation.row(2); xInit.head<3>() = t; for(unsigned int i=0; i<m_np; i++) if(fabs(xInit[i] - m_currentTrajGen[i]->getPos()(0)) > 0.001) { needToMoveToInitConf = true; SEND_MSG("Component "+ toString(i) +" is too far from initial configuration so first i will move it there.", MSG_TYPE_WARNING); } // if necessary move joints to initial configuration if(needToMoveToInitConf) { for(unsigned int i=0; i<m_np; i++) { m_minJerkTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos()); m_minJerkTrajGen[i]->set_final_point(xInit[i]); m_minJerkTrajGen[i]->set_trajectory_time(timeToInitConf); m_status[i] = TG_MIN_JERK; m_currentTrajGen[i] = m_minJerkTrajGen[i]; } return; } SEND_MSG("Spline Ready. Set trigger to true to start playing", MSG_TYPE_INFO); } void SE3TrajectoryGenerator::startSpline() { if(m_status[0]==TG_SPLINE) return; m_t = 0.0; for(unsigned int i=0; i<m_np; i++) { m_status[i] = TG_SPLINE; } } void SE3TrajectoryGenerator::startSinusoid(const int& id, const double& xFinal, const double& time) { if(!m_initSucceeded) return SEND_MSG("Cannot start sinusoid before initialization!",MSG_TYPE_ERROR); if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); unsigned int i = id; if(time<=0.0) return SEND_MSG("Trajectory time must be a positive number", MSG_TYPE_ERROR); if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot move the specified component because it is already controlled.", MSG_TYPE_ERROR); m_sinTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos()); SEND_MSG("Set initial point of sinusoid to "+toString(m_sinTrajGen[i]->getPos()),MSG_TYPE_DEBUG); m_sinTrajGen[i]->set_final_point(xFinal); m_sinTrajGen[i]->set_trajectory_time(time); m_status[i] = TG_SINUSOID; m_currentTrajGen[i] = m_sinTrajGen[i]; } void SE3TrajectoryGenerator::startTriangle(const int& id, const double& xFinal, const double& time, const double& Tacc) { if(!m_initSucceeded) return SEND_MSG("Cannot start triangle before initialization!",MSG_TYPE_ERROR); if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); unsigned int i = id; if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot move the specified component because it is already controlled.", MSG_TYPE_ERROR); m_triangleTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos()); SEND_MSG("Set initial point of triangular trajectory to "+toString(m_triangleTrajGen[i]->getPos()),MSG_TYPE_DEBUG); m_triangleTrajGen[i]->set_final_point(xFinal); if(!m_triangleTrajGen[i]->set_trajectory_time(time)) return SEND_MSG("Trajectory time cannot be negative.", MSG_TYPE_ERROR); if(!m_triangleTrajGen[i]->set_acceleration_time(Tacc)) return SEND_MSG("Acceleration time cannot be negative or larger than half the trajectory time.", MSG_TYPE_ERROR); m_status[i] = TG_TRIANGLE; m_currentTrajGen[i] = m_triangleTrajGen[i]; } void SE3TrajectoryGenerator::startConstAcc(const int& id, const double& xFinal, const double& time) { if(!m_initSucceeded) return SEND_MSG("Cannot start constant-acceleration trajectory before initialization!",MSG_TYPE_ERROR); if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); unsigned int i = id; if(time<=0.0) return SEND_MSG("Trajectory time must be a positive number", MSG_TYPE_ERROR); if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot move the specified component because it is already controlled.", MSG_TYPE_ERROR); m_constAccTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos()); SEND_MSG("Set initial point of const-acc trajectory to "+toString(m_constAccTrajGen[i]->getPos()),MSG_TYPE_DEBUG); m_constAccTrajGen[i]->set_final_point(xFinal); m_constAccTrajGen[i]->set_trajectory_time(time); m_status[i] = TG_CONST_ACC; m_currentTrajGen[i] = m_constAccTrajGen[i]; } void SE3TrajectoryGenerator::startLinearChirp(const int& id, const double& xFinal, const double& f0, const double& f1, const double& time) { if(!m_initSucceeded) return SEND_MSG("Cannot start linear chirp before initialization!",MSG_TYPE_ERROR); if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); unsigned int i = id; if(time<=0.0) return SEND_MSG("Trajectory time must be a positive number", MSG_TYPE_ERROR); if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot move the specified component because it is already controlled.", MSG_TYPE_ERROR); if(f0>f1) return SEND_MSG("f0 "+toString(f0)+" cannot to be more than f1 "+toString(f1),MSG_TYPE_ERROR); if(f0<=0.0) return SEND_MSG("Frequency has to be positive "+toString(f0),MSG_TYPE_ERROR); if(!m_linChirpTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos())) return SEND_MSG("Error while setting initial point "+toString(m_noTrajGen[i]->getPos()), MSG_TYPE_ERROR); if(!m_linChirpTrajGen[i]->set_final_point(xFinal)) return SEND_MSG("Error while setting final point "+toString(xFinal), MSG_TYPE_ERROR); if(!m_linChirpTrajGen[i]->set_trajectory_time(time)) return SEND_MSG("Error while setting trajectory time "+toString(time), MSG_TYPE_ERROR); if(!m_linChirpTrajGen[i]->set_initial_frequency(f0)) return SEND_MSG("Error while setting initial frequency "+toString(f0), MSG_TYPE_ERROR); if(!m_linChirpTrajGen[i]->set_final_frequency(f1)) return SEND_MSG("Error while setting final frequency "+toString(f1), MSG_TYPE_ERROR); m_status[i] = TG_LIN_CHIRP; m_currentTrajGen[i] = m_linChirpTrajGen[i]; } void SE3TrajectoryGenerator::move(const int& id, const double& xFinal, const double& time) { if(!m_initSucceeded) return SEND_MSG("Cannot move value before initialization!",MSG_TYPE_ERROR); unsigned int i = id; if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); if(time<=0.0) return SEND_MSG("Trajectory time must be a positive number", MSG_TYPE_ERROR); if(m_status[i]!=TG_STOP) return SEND_MSG("You cannot move the specified component because it is already controlled.", MSG_TYPE_ERROR); m_minJerkTrajGen[i]->set_initial_point(m_noTrajGen[i]->getPos()); m_minJerkTrajGen[i]->set_final_point(xFinal); m_minJerkTrajGen[i]->set_trajectory_time(time); m_status[i] = TG_MIN_JERK; m_currentTrajGen[i] = m_minJerkTrajGen[i]; } void SE3TrajectoryGenerator::stop(const int& id) { if(!m_initSucceeded) return SEND_MSG("Cannot stop value before initialization!",MSG_TYPE_ERROR); const dynamicgraph::Vector& initial_value = m_initial_valueSIN.accessCopy(); if(id==-1) //Stop entire vector { for(unsigned int i=0; i<m_np; i++) { m_status[i] = TG_STOP; // update the initial value m_noTrajGen[i]->set_initial_point(m_currentTrajGen[i]->getPos()); m_currentTrajGen[i] = m_noTrajGen[i]; } return; } if(id<0 || id>=m_np) return SEND_MSG("Index is out of bounds", MSG_TYPE_ERROR); unsigned int i = id; m_noTrajGen[i]->set_initial_point(m_currentTrajGen[i]->getPos()); m_status[i] = TG_STOP; m_currentTrajGen[i] = m_noTrajGen[i]; m_splineReady=false; m_t=0.0; } /* ------------------------------------------------------------------- */ /* --- ENTITY -------------------------------------------------------- */ /* ------------------------------------------------------------------- */ void SE3TrajectoryGenerator::display(std::ostream& os) const { os << "SE3TrajectoryGenerator "<<getName(); try { getProfiler().report_all(3, os); } catch (ExceptionSignal e) {} } } // namespace torquecontrol } // namespace sot } // namespace dynamicgraph
42.991987
154
0.549707
jviereck
886e28f31fc3ecf418f93e2e80ff6995594f4255
1,122
hpp
C++
tests/utils/include/utils/test.hpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
tests/utils/include/utils/test.hpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
tests/utils/include/utils/test.hpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
1
2022-03-28T07:52:21.000Z
2022-03-28T07:52:21.000Z
/******************************************************************************* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #ifndef DML_TESTING_ACTUAL_API_HPP #define DML_TESTING_ACTUAL_API_HPP #if !defined(OS_WINDOWS) && !defined(OS_UNIX) #error "Operating system is undefined!" #endif #if !defined(C_API) && !defined(CPP_API) #error "API is undefined!" #endif #if !defined(SW_PATH) && !defined(HW_PATH) && !defined(AUTO_PATH) #error "Execution path is undefined!" #endif #ifdef C_API #include <dml/dml.h> #include <utils/job.hpp> #ifdef SW_PATH constexpr auto execution_path = DML_PATH_SW; #endif #ifdef HW_PATH constexpr auto execution_path = DML_PATH_HW; #endif #ifdef AUTO_PATH constexpr auto execution_path = DML_PATH_AUTO; #endif #endif #ifdef CPP_API #include <dml/dml.hpp> #ifdef SW_PATH using execution_path = dml::software; #endif #ifdef HW_PATH using execution_path = dml::hardware; #endif #ifdef AUTO_PATH using execution_path = dml::automatic; #endif #endif #endif// ACTUAL_API_HPP
20.035714
80
0.651515
hhb584520
886ef9a9c147b1c0edd663e41011c9498d00fdd1
5,241
cxx
C++
example/example-1/main.cxx
usagi/wonderland.subsystem
342b3dc2489f9a12d6dba43fca7d7a2a0854e144
[ "MIT" ]
1
2015-08-29T00:14:05.000Z
2015-08-29T00:14:05.000Z
example/example-1/main.cxx
usagi/wonderland.subsystem
342b3dc2489f9a12d6dba43fca7d7a2a0854e144
[ "MIT" ]
null
null
null
example/example-1/main.cxx
usagi/wonderland.subsystem
342b3dc2489f9a12d6dba43fca7d7a2a0854e144
[ "MIT" ]
null
null
null
#include <chrono> #include <thread> #include <iostream> #include <iomanip> #include <boost/property_tree/ini_parser.hpp> #ifdef EMSCRIPTEN #include <emscripten/emscripten.h> #endif // define or take a compiler option: c++ ... -DWRP_WONDERLAND_SUBSYSTEM_GLFW3 main.cxx //#define WRP_WONDERLAND_SUBSYSTEM_GLFW3 //#define WRP_WONDERLAND_SUBSYSTEM_GLFW2 // include subsystem #include <wonder_rabbit_project/wonderland.subsystem.hxx> int main() { // using using wonder_rabbit_project::wonderland::subsystem::subsystem_t; using wonder_rabbit_project::wonderland::subsystem::key; // generate the subsystem auto subsystem = std::make_shared<subsystem_t>(); // get initialize params ( not need if initilize with default settings ) auto ips = subsystem -> default_initialize_params(); // print ips in INI(1) std::cerr << "\n -- print ips in INI(1) -- \n"; boost::property_tree::write_ini(std::cerr, ips); // change title ips.put ("title" , std::string("hello, subsystem ") + subsystem->name() + " version " + subsystem->version().to_string() ); // print ips in INI(2) std::cerr << "\n -- print ips in INI(2) -- \n"; boost::property_tree::write_ini(std::cerr, ips); // initialize the subsystem subsystem -> initialize( std::move(ips) ); // invoke world pattern 1: consign main-loop to subsystem // set your world update code const auto keyboard_test = [ &subsystem ] { auto key_counter = 0; for ( auto key = 0; key < 255; ++key ) if ( subsystem -> keyboard_state( key ) ) { ++key_counter; std::cerr << key << " "; } if ( key_counter ) std::cerr << "\n"; }; const auto pointing_test = [ &subsystem ] { auto button_counter = 0; for ( auto button = 0; button < 8; ++button ) if ( subsystem -> pointing_states_button( button ) ) { ++button_counter; std::cerr << "pointing_button[" << button << "] "; } if ( button_counter ) { const auto position = subsystem -> pointing_states_position(); std::cerr << " with position(" << position.x << ", " << position.y << ")\n"; } const auto wheel = subsystem -> pointing_states_wheel(); if ( wheel.x not_eq 0 ) std::cerr << "wheel-dx: " << wheel.x << "\n"; if ( wheel.y not_eq 0 ) std::cerr << "wheel-dy: " << wheel.y << "\n"; }; const auto joystick_test = [ &subsystem ] { for ( const auto joystick : subsystem -> joysticks_states() ) { const auto& digitals = joystick.digitals(); const auto& analogs = joystick.analogs(); const auto& balls = joystick.balls(); const auto& hats = joystick.hats(); if ( std::any_of(std::begin(digitals), std::end(digitals), [](const bool v){ return v; } ) or std::any_of(std::begin(hats), std::end(hats), [](const glm::vec2& v){ return v not_eq glm::vec2(); } ) ) { std::cerr << joystick.name() << ": D{ "; for ( const auto digital : digitals ) std::cerr << digital << " "; std::cerr << "} A{ "; for ( const auto analog : analogs ) std::cerr << std::setw(5) << std::right << std::setprecision(2) << std::fixed << analog << " "; std::cerr << "} B{ "; for ( const auto ball : balls ) std::cerr << "(" << ball.x << "," << ball.y << ") "; std::cerr << "} H{ "; for ( const auto hat : hats ) std::cerr << "(" << hat.x << "," << hat.y << ") "; std::cerr << "}\n"; } } }; const auto esc_to_exit = [ &subsystem ] { if ( subsystem -> keyboard_state< key::escape >() ) subsystem -> to_continue( false ); }; subsystem -> update_functors.emplace_front( keyboard_test ); subsystem -> update_functors.emplace_front( pointing_test ); subsystem -> update_functors.emplace_front( joystick_test ); subsystem -> update_functors.emplace_front( esc_to_exit ); subsystem -> update_functors.emplace_front( [] { // do update your world } ); // set your world render code //#ifndef EMSCRIPTEN const auto adjust_wait = [ ] { static auto before = std::chrono::high_resolution_clock::now(); const auto elapsed = std::chrono::high_resolution_clock::now() - before; const auto wait = std::chrono::milliseconds(100) - elapsed; std::this_thread::sleep_for(wait); before = std::chrono::high_resolution_clock::now(); }; //#endif subsystem -> render_functors.emplace_front( [] { // do render your world } ); //#ifndef EMSCRIPTEN subsystem -> render_functors.emplace_front( adjust_wait ); //#endif // invoke your world subsystem -> invoke(); // invoke world pattern 2: original main-loop system with use subsystem /* #ifdef EMSCRIPTEN emscripten_set_main_loop( [] #else do #endif { subsystem -> before_update(); // do update world { } subsystem -> after_update(); subsystem -> before_render(); // do render with GL(glXxx) { } subsystem -> after_render(); } #ifdef EMSCRIPTEN , 0, 1); #else while ( subsystem -> to_continue ); #endif */ }
27.584211
111
0.589964
usagi
8872016682c7b970e1df80ba5ceed3b6c0728a8d
611
hpp
C++
include/lol/def/LolAccountVerificationSendTokenRequest.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolAccountVerificationSendTokenRequest.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolAccountVerificationSendTokenRequest.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LolAccountVerificationSendTokenRequest { std::string mediator; std::string locale; std::string device; }; inline void to_json(json& j, const LolAccountVerificationSendTokenRequest& v) { j["mediator"] = v.mediator; j["locale"] = v.locale; j["device"] = v.device; } inline void from_json(const json& j, LolAccountVerificationSendTokenRequest& v) { v.mediator = j.at("mediator").get<std::string>(); v.locale = j.at("locale").get<std::string>(); v.device = j.at("device").get<std::string>(); } }
32.157895
83
0.653028
Maufeat
88726207f5fb0ad5bb1d8f64dfdb7e09e1358eed
721
cpp
C++
HackerEarth/PrateekAndHisFriends.cpp
sawantaditi24/Competitive-Programming
36e024215d8041c92c5ec78a22561aaa0025f8d2
[ "MIT" ]
2
2020-06-01T09:16:47.000Z
2021-09-04T12:39:41.000Z
HackerEarth/PrateekAndHisFriends.cpp
gauravsingh58/competitive-programming
fa5548f435cdf2aa059e1d6ab733885790c6a592
[ "MIT" ]
1
2020-10-10T16:14:54.000Z
2020-10-10T16:14:54.000Z
HackerEarth/PrateekAndHisFriends.cpp
gauravsingh58/competitive-programming
fa5548f435cdf2aa059e1d6ab733885790c6a592
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
#include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long t, n, x; cin >>t; while(t--){ cin >>n >>x; vector<long> arr(n); for(long i = 0; i < n; i++) cin >>arr[i]; for(long i = 1; i < n; i++) arr[i] += arr[i-1]; bool found = false; for(long i = 0; i < n-1; i++){ for(long j = i+1; j < n; j++){ long sum = arr[j] - arr[i]; if(sum == x) found = true; } } if(found) cout <<"YES" <<"\n"; else cout <<"NO" <<"\n"; } return 0; }
23.258065
43
0.371706
sawantaditi24
887c90e853811beaba1fe90e0e5808fad420a766
1,965
cpp
C++
src/Frontends/CleanupResources.cpp
VANDAL/Sigil2
67e0762201d79575a25bdfe59eab257d206cff39
[ "BSD-3-Clause" ]
8
2018-12-08T15:35:34.000Z
2021-10-25T00:10:51.000Z
src/Frontends/CleanupResources.cpp
VANDAL/Sigil2
67e0762201d79575a25bdfe59eab257d206cff39
[ "BSD-3-Clause" ]
6
2018-06-01T23:09:25.000Z
2021-01-05T20:15:44.000Z
src/Frontends/CleanupResources.cpp
mdlui/Sigil2
67e0762201d79575a25bdfe59eab257d206cff39
[ "BSD-3-Clause" ]
3
2019-11-17T16:13:06.000Z
2021-07-23T01:27:59.000Z
#include <csignal> #include <cstdlib> #include <cstring> #include <dirent.h> #include <iostream> #include <mutex> namespace Cleanup { namespace { std::mutex cleanupMtx; bool initialized; std::string cleanupDir; std::terminate_handler prev_terminate_handler; using signal_handler = void(*)(int); signal_handler prev_sigint_handler; signal_handler prev_sigsegv_handler; auto cleanupHandler() { if (cleanupDir.empty() == false) { DIR *d = opendir(cleanupDir.c_str()); if (d != nullptr) { dirent *dir = readdir(d); char fullPath[256]; while (dir != nullptr) { /* TODO check path length */ sprintf(fullPath, "%s/%s", cleanupDir.c_str(), dir->d_name); remove(fullPath); dir = readdir(d); } int ret = remove(cleanupDir.c_str()); if (ret < 0) std::cerr << "error removing " + cleanupDir + " -- " + strerror(errno) << std::endl; } } } }; auto setCleanupDir(std::string dir) -> void { std::lock_guard<std::mutex> lock(cleanupMtx); if (initialized == false) { cleanupDir = dir; /* Cleanup at normal exit */ std::atexit(cleanupHandler); /* or SIGINT/SIGSEGV */ auto dummy = [](int){}; prev_sigint_handler = std::signal(SIGINT, dummy); prev_sigsegv_handler = std::signal(SIGSEGV, dummy); std::signal(SIGINT, [](int signum){ cleanupHandler(); prev_sigint_handler(signum); }); std::signal(SIGSEGV, [](int signum){ cleanupHandler(); prev_sigsegv_handler(signum); }); /* or unhandled exception */ #if __GNUC__ < 5 prev_terminate_handler = std::abort; #else prev_terminate_handler = std::get_terminate(); #endif std::set_terminate([]{ cleanupHandler(); prev_terminate_handler(); }); initialized = true; } } }; //end namespace Cleanup
24.873418
100
0.588295
VANDAL
887e2ba4297878ba8019c3f1b93fac2f19b5338e
1,218
hpp
C++
src/database/net.hpp
martun/verilog_netlist_parser
bf616bc5b5dab3e1b93f7740b29774d7dbc72281
[ "MIT" ]
1
2018-12-18T02:16:16.000Z
2018-12-18T02:16:16.000Z
src/database/net.hpp
martun/verilog_netlist_parser
bf616bc5b5dab3e1b93f7740b29774d7dbc72281
[ "MIT" ]
null
null
null
src/database/net.hpp
martun/verilog_netlist_parser
bf616bc5b5dab3e1b93f7740b29774d7dbc72281
[ "MIT" ]
null
null
null
#ifndef NET_H #define NET_H #include <string> #include <vector> class Port; /// Class for Net. class Net { public: /** \brief Constructor by name. * \param[in] name - Name of the Net. * \param[in] source_port - Source port for the net, if not provided sets to NULL. */ Net(const std::string name, const Port * source_port = 0); /// \brief Getter for the name of the Net. const std::string& get_name() const; /// \brief Returns the source port if exists, else throws an exception. const Port& get_source_port() const; /** \brief Sets source port. * \param[in] source_port - New Source Port. */ void set_source_port(const Port& source_port); /// \brief Getter for all the destination ports of the Net. const std::vector<const Port* >& get_destination_ports() const; /** \brief Adds a destination port to the Net. * \param[in] destination_port - New destination Port for this net. */ void add_destination_port( const Port * destination_port); private: /// Name of the wire. std::string m_name; /// Source port for current Net. const Port * m_source_port; /// The collection of destination ports for this net. std::vector<const Port*> m_destination_ports; }; #endif // NET_H
22.981132
83
0.698686
martun
888412b4fc2d122ddc1d56e67a32fad537a1e890
32,511
hpp
C++
src/utils/opencx.hpp
deepguider/RoadGPS
7db4669a54da98a854886b89b6922fb8c7a60f33
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-05-22T12:47:34.000Z
2019-05-23T15:43:47.000Z
src/utils/opencx.hpp
deepguider/RoadGPS
7db4669a54da98a854886b89b6922fb8c7a60f33
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/utils/opencx.hpp
deepguider/RoadGPS
7db4669a54da98a854886b89b6922fb8c7a60f33
[ "Apache-2.0", "BSD-3-Clause" ]
1
2019-08-09T06:50:46.000Z
2019-08-09T06:50:46.000Z
/** * OpenCX: Sunglok's OpenCV Extension * * OpenCX aims to provide extended functionality and tools to OpenCV for more convenience. * It consists of several header files, 'opencx.hpp' and others, which only depend on OpenCV in C++. * Just include the file to your project. It will work without complex configuration and dependency. * OpenCX is Beerware so that it is free to use and distribute. * * - Homepage: https://github.com/sunglok/opencx * * @author Sunglok Choi (http://sites.google.com/site/sunglok) * @version 0.4 (05/28/2020) */ /** * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <sunglok@hanmail.net> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Sunglok Choi * ---------------------------------------------------------------------------- */ #ifndef __OPEN_CX__ #define __OPEN_CX__ #include "opencv2/opencv.hpp" #include "opensx.hpp" #include "ekf.hpp" #ifndef CX_LOAD_PARAM_TO /** A macro function to load a value from cv::FileNode */ # define CX_LOAD_PARAM(fn, name_cfg, name_var) \ if (!(fn)[name_cfg].empty()) { (fn)[name_cfg] >> name_var; } #endif #ifndef CX_LOAD_PARAM_RESULT /** A macro function to load a value from cv::FileNode and increase the given counter if successful */ # define CX_LOAD_PARAM_COUNT(fn, name_cfg, name_var, success_counter) \ if (!(fn)[name_cfg].empty()) { (fn)[name_cfg] >> name_var; success_counter++; } #endif namespace cx { /** * @brief More convenient Algorithm * * This is an extension of cv::Algorithm to provide simple ways to configure various parameters if its readParam() function is defined. * The pre-built functions, setParam(), setParamValue(), and setParamText(), enable to set a value (scalar, vector, text) for each parameter through its name. * Please refer its example at example.cpp. */ class Algorithm : public cv::Algorithm { public: /** * Read parameters from cv::FileNode * @param fs The instance of cv::FileStorage to read parameters * @return The number of updated parameters */ virtual int readParam(const cv::FileNode& fn) { return 0; } /** * Write parameters and their values to cv::FileStorage * @param fs The instance of cv::FileStorage to write parameters * @return True if successful (false if failed) */ virtual bool writeParam(cv::FileStorage& fs) const { return fs.isOpened(); } /** * Read parameters from the given file * @param filename The filename to read parameters * @return Result of success (true) or failure (false) */ int loadParam(const std::string& filename) { cv::FileStorage fs(filename, cv::FileStorage::READ); if (!fs.isOpened()) return false; return readParam(fs.root()); } /** * Write parameters and their values to he given file * @param filename The filename to write parameters * @return True if successful (false if failed) */ bool saveParam(const std::string& filename) { cv::FileStorage fs(filename, cv::FileStorage::WRITE); if (!fs.isOpened()) return false; time_t rawtime; time(&rawtime); fs << "date" << asctime(localtime(&rawtime)); return writeParam(fs); } /** * Set a single (or multiple) parameter from a string to describes the parameter in YAML * @param config A string to describes the parameter in YAML * @return True if successful (false if failed) */ bool setParam(const std::string& config) { if (config.empty()) return false; std::string yaml; getline(std::istringstream(config), yaml); if (yaml == "%YAML:1.0" || yaml == "%YAML 1.0") yaml = config; else yaml = "%YAML:1.0\n" + config; cv::FileStorage fs(yaml, cv::FileStorage::READ | cv::FileStorage::MEMORY | cv::FileStorage::FORMAT_YAML); return readParam(fs.root()) > 0; } /** * Set a parameter from its name and value * @param param The name of the parameter * @param value The value of the parameter * @return True if successful (false if failed) */ bool setParamValue(const std::string& param, double value) { if (param.empty()) return false; std::string yaml = param + cv::format(": %f", value); return setParam(yaml); } /** * Set a parameter from its name and value in a vector form * @param param The name of the parameter * @param values The value of the parameter in a vector form * @return True if successful (false if failed) */ bool setParamValue(const std::string& param, const std::vector<double>& values) { if (param.empty()) return false; std::string yaml = param + ": [ "; for (size_t i = 0; i < values.size(); i++) { yaml += cv::format("%f", values[i]); if (i < values.size() - 1) yaml += ", "; } yaml += " ]"; return setParam(yaml); } /** * Set a parameter from its name and value * @param param The name of the parameter * @param value The value of the parameter * @return True if successful (false if failed) */ bool setParamTexts(const std::string& param, const std::string& value) { if (param.empty()) return false; std::string yaml = param + ": " + value; return setParam(yaml); } }; // End of 'Algorithm' /** * @brief Easier VideoWriter * * This is an extension of cv::VideoWriter to enable to call open() without the size and channel of images. * For convenience, those two informations are automatically configured when the first image is given to the video recorder. */ class VideoWriter : public cv::VideoWriter { public: /** The default constructor */ VideoWriter() { open("", -1); } /** * A constructor with initialization of member variables * @param filename The name of video file * @param fps The frame rate of video file * @param fourcc The codec of video file */ VideoWriter(const std::string& filename, double fps = 10, int fourcc = cv::VideoWriter::fourcc('X', 'V', 'I', 'D')) { open(filename, fps, fourcc); } /** * Initialize to record a video * @param filename The name of video file * @param fps The frame rate of video file * @param fourcc The codec of video file * @return True if successful (false if failed) */ virtual bool open(const std::string& filename, double fps = 10, int fourcc = cv::VideoWriter::fourcc('X', 'V', 'I', 'D')) { m_filename = filename; m_fps = fps; m_fourcc = fourcc; return true; } /** * Check whether VideoWriter is properly initialized * @return True if successfully configured (false if not) */ virtual bool isConfigured() const { return !m_filename.empty() && m_fps > 0; } /** * Push the given image to the recording video * @param image An image to record */ virtual void write(const cv::Mat& image) { if (isOpened()) cv::VideoWriter::write(image); else if (isConfigured()) { if (cv::VideoWriter::open(m_filename, m_fourcc, m_fps, image.size(), image.channels() > 1)) cv::VideoWriter::write(image); } } /** * Terminate to record the video */ virtual void release() { cv::VideoWriter::release(); open("", -1); } /** * Push the given image to the recording video * @param vr The given video recording instance * @param image An image to record * @return The given video recording instance */ friend VideoWriter& operator<<(VideoWriter& vr, const cv::Mat& image) { vr.write(image); return vr; } protected: /** The name of video file */ std::string m_filename; /** The frame rate of video file */ double m_fps; /** The codec of video file */ int m_fourcc; }; // End of 'VideoWriter' class Painter { public: Painter() { configCanvas(cx::RangeDbl(0, 100), cx::RangeDbl(0, 100), cv::Size(640, 480), 20, 20); } bool configCanvas(const RangeDbl& range_x, const RangeDbl& range_y, const cv::Point2d& px_per_val, const cv::Point& margin, const cv::Point& padding) { m_min_val = { range_x.min, range_y.min }; if (px_per_val.x > 0) m_px_per_val.x = px_per_val.x; if (px_per_val.y > 0) m_px_per_val.y = px_per_val.y; if (margin.x >= 0) m_img_margin.x = margin.x; if (margin.y >= 0) m_img_margin.y = margin.y; if (padding.x >= 0) m_img_padding.x = padding.x; if (padding.y >= 0) m_img_padding.y = padding.y; m_img_size.width = static_cast<int>(range_x.length() * m_px_per_val.x + 0.5) + 2 * (m_img_padding.x + m_img_margin.x); // + 0.5: Rounding m_img_size.height = static_cast<int>(range_y.length() * m_px_per_val.y + 0.5) + 2 * (m_img_padding.y + m_img_margin.y); // + 0.5: Rounding m_img_box = getInnerBox(m_img_size, m_img_margin); m_img_offset = getOffset(m_min_val, m_px_per_val, m_img_size, m_img_margin, m_img_padding); return true; } bool configCanvas(const RangeDbl& range_x, const RangeDbl& range_y, const cv::Size& img_size, const cv::Point& margin, const cv::Point& padding) { m_min_val = { range_x.min, range_y.min }; if (img_size.width > 0) m_img_size.width = img_size.width; if (img_size.height > 0) m_img_size.height = img_size.height; if (margin.x >= 0) m_img_margin.x = margin.x; if (margin.y >= 0) m_img_margin.y = margin.y; if (padding.x >= 0) m_img_padding.x = padding.x; if (padding.y >= 0) m_img_padding.y = padding.y; m_img_box = getInnerBox(m_img_size, m_img_margin); m_px_per_val.x = (m_img_box.width - 2 * m_img_padding.x) / range_x.length(); m_px_per_val.y = (m_img_box.height - 2 * m_img_padding.y) / range_y.length(); m_img_offset = getOffset(m_min_val, m_px_per_val, m_img_size, m_img_margin, m_img_padding); return true; } bool configCanvas(const cv::Point2d& origin_px, const cv::Point2d& px_per_val, const cv::Size& img_size, const cv::Point& margin, const cv::Point& padding) { if (img_size.width > 0) m_img_size.width = img_size.width; if (img_size.height > 0) m_img_size.height = img_size.height; if (px_per_val.x > 0) m_px_per_val.x = px_per_val.x; if (px_per_val.y > 0) m_px_per_val.y = px_per_val.y; if (margin.x >= 0) m_img_margin.x = margin.x; if (margin.y >= 0) m_img_margin.y = margin.y; if (padding.x >= 0) m_img_padding.x = padding.x; if (padding.y >= 0) m_img_padding.y = padding.y; m_img_box = getInnerBox(m_img_size, m_img_margin); CV_DbgAssert(m_px_per_val.x > 0 && m_px_per_val.y > 0); m_min_val.x = (m_img_box.x + m_img_padding.x - origin_px.x) / m_px_per_val.x; m_min_val.y = (origin_px.y - m_img_box.y - m_img_box.height) / m_px_per_val.y; m_img_offset = getOffset(m_min_val, m_px_per_val, m_img_size, m_img_margin, m_img_padding); return true; } cv::Point2d getPixel2Value() const { return m_px_per_val; } bool configCanvas(const RangeDbl& range_x, const RangeDbl& range_y, const cv::Point2d& px_per_val, int margin = -1, int padding = -1) { return configCanvas(range_x, range_y, px_per_val, cv::Point(margin, margin), cv::Point(padding, padding)); } bool configCanvas(const RangeDbl& range_x, const RangeDbl& range_y, const cv::Size& img_size = cv::Size(-1, -1), int margin = -1, int padding = -1) { return configCanvas(range_x, range_y, img_size, cv::Point(margin, margin), cv::Point(padding, padding)); } bool configCanvas(const cv::Point2d& origin_px, const cv::Point2d& px_per_val = cv::Point2d(-1, -1), const cv::Size& img_size = cv::Size(-1, -1), int margin = -1, int padding = -1) { return configCanvas(origin_px, px_per_val, img_size, cv::Point(margin, margin), cv::Point(padding, padding)); } bool clearCanvas(cv::Mat& image, const cv::Vec3b& color = cv::Vec3b(255, 255, 255)) const { if (m_img_size.width <= 0 || m_img_size.height <= 0) return false; image.create(m_img_size, CV_8UC3); if (image.empty()) return false; image = color; return true; } void setImageRotation(double rad) { m_img_rotation = rad; } double getImageRotation() { return m_img_rotation; } cv::Point2d cvtValue2Pixel(const cv::Point2d& val) const { cv::Point2d px; double cost = cos(-m_img_rotation); double sint = sin(-m_img_rotation); px.x = (val.x * m_px_per_val.x) * cost - (-val.y * m_px_per_val.y) * sint + m_img_offset.x; px.y = (val.x * m_px_per_val.x) * sint + (-val.y * m_px_per_val.y) * cost + m_img_offset.y; return px; } cv::Point2d cvtPixel2Value(const cv::Point2d& px) const { CV_DbgAssert(m_px_per_val.x > 0 && m_px_per_val.y > 0); cv::Point2d val; double cost = cos(-m_img_rotation); double sint = sin(-m_img_rotation); val.x = ((px.x - m_img_offset.x) * cost + (px.y - m_img_offset.y) * sint) / m_px_per_val.x; val.y = -(-(px.x - m_img_offset.x) * sint + (px.y - m_img_offset.y) * cost) / m_px_per_val.y; return val; } bool drawPoint(cv::Mat& image, const cv::Point2d& center, int radius, const cv::Vec3b& color, int thickness = -1, int linetype = cv::LineTypes::LINE_8) const { if (image.empty()) clearCanvas(image); cv::Point center_px = cvtValue2Pixel(center) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::circle(image, center_px, radius, color, thickness, linetype); return true; } bool drawPoints(cv::Mat& image, const std::vector<cv::Point2d>& pts, int radius, const cv::Vec3b& color, int thickness = -1, int linetype = cv::LineTypes::LINE_8) const { if (image.empty()) clearCanvas(image); for (auto pt = pts.begin(); pt != pts.end(); pt++) { cv::Point pt_px = cvtValue2Pixel(*pt) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::circle(image, pt_px, radius, color, thickness, linetype); } return true; } bool drawLine(cv::Mat& image, const cv::Point2d& val1, const cv::Point2d& val2, const cv::Vec3b& color, int thickness = 1, int linetype = cv::LineTypes::LINE_8) const { if (thickness <= 0) return false; if (image.empty()) clearCanvas(image); cv::Point px1 = cvtValue2Pixel(val1) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::Point px2 = cvtValue2Pixel(val2) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::line(image, px1, px2, color, thickness, linetype); return true; } bool drawLine(cv::Mat& image, const std::vector<cv::Point2d>& vals, const cv::Vec3b& color, int thickness = 1, int linetype = cv::LineTypes::LINE_8) const { if (thickness <= 0 || vals.size() < 2) return false; if (image.empty()) clearCanvas(image); cv::Point px_prev = cvtValue2Pixel(vals.front()) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding for (size_t i = 1; i < vals.size(); i++) { cv::Point px = cvtValue2Pixel(vals[i]) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::line(image, px_prev, px, color, thickness, linetype); px_prev = px; } return true; } bool drawBoundary(cv::Mat& image, const cv::Vec3b& color, int thickness = 1) const { if (thickness <= 0) return false; if (image.empty()) clearCanvas(image); cv::rectangle(image, m_img_box, color, thickness); return true; } bool drawOrigin(cv::Mat& image, const cv::Point2d& length, const cv::Vec3b& color_x, const cv::Vec3b& color_y, int thickness = 1) const { if (length.x <= 0 || length.y <= 0 || thickness <= 0) return false; if (image.empty()) clearCanvas(image); cv::Point origin = cvtValue2Pixel(cv::Point2d(0, 0)) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::Point axes_x = cvtValue2Pixel(cv::Point2d(length.x, 0)) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::Point axes_y = cvtValue2Pixel(cv::Point2d(0, length.y)) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::line(image, origin, axes_x, color_x, thickness); cv::line(image, origin, axes_y, color_y, thickness); return true; } bool drawOrigin(cv::Mat& image, double length, const cv::Vec3b& color_x, const cv::Vec3b& color_y, int thickness = 1) const { return drawOrigin(image, cv::Point2d(length, length), color_x, color_y, thickness); } bool drawAxes(cv::Mat& image, const cv::Vec3b& color_x, const cv::Vec3b& color_y, int thickness = 1) const { if (thickness <= 0) return false; if (image.empty()) clearCanvas(image); cv::Point origin = cvtValue2Pixel(cv::Point2d(0, 0)) + cv::Point2d(0.5, 0.5); // + 0.5: Rounding cv::line(image, cv::Point2d(m_img_box.tl().x, origin.y), cv::Point2d(m_img_box.br().x, origin.y), color_x, thickness); // The X axis cv::line(image, cv::Point2d(origin.x, m_img_box.tl().y), cv::Point2d(origin.x, m_img_box.br().y), color_y, thickness); // The Y axis return true; } bool drawGrid(cv::Mat& image, const cv::Point2d& grid_step, const cv::Vec3b& color, int thickness = 1, double unit_font_scale = 0.5, const cv::Vec3b& unit_color = cv::Vec3b(0, 0, 0), cv::Point unit_pos = cv::Point(20, 15)) const { if (grid_step.x <= 0 || grid_step.y <= 0 || thickness <= 0) return false; if (image.empty()) clearCanvas(image); cv::Point2d center_grid = cvtValue2Pixel(cv::Point2d(0, 0)); for (int i = 0;; i++) { double y = center_grid.y - grid_step.y * i * m_px_per_val.y; if (y < m_img_box.tl().y || y > m_img_box.br().y) break; cv::line(image, cv::Point2d(m_img_box.tl().x, y), cv::Point2d(m_img_box.br().x, y), color, thickness); // Upward X-directional grids } for (int i = 1;; i++) { double y = center_grid.y + grid_step.y * i * m_px_per_val.y; if (y < m_img_box.tl().y || y > m_img_box.br().y) break; cv::line(image, cv::Point2d(m_img_box.tl().x, y), cv::Point2d(m_img_box.br().x, y), color, thickness); // Downward X-directional grids } for (int i = 0;; i++) { double x = center_grid.x + grid_step.x * i * m_px_per_val.x; if (x < m_img_box.tl().x || x > m_img_box.br().x) break; cv::line(image, cv::Point2d(x, m_img_box.tl().y), cv::Point2d(x, m_img_box.br().y), color, thickness); // Rightward Y-directional grids } for (int i = 1;; i++) { double x = center_grid.x - grid_step.x * i * m_px_per_val.x; if (x < m_img_box.tl().x || x > m_img_box.br().x) break; cv::line(image, cv::Point2d(x, m_img_box.tl().y), cv::Point2d(x, m_img_box.br().y), color, thickness); // Leftward Y-directional grids } if (unit_font_scale > 0) { if (unit_pos.x < 0) unit_pos.x = image.cols + unit_pos.x; if (unit_pos.y < 0) unit_pos.y = image.rows + unit_pos.y; cv::putText(image, cv::format("XGrid: %.1f, YGrid: %.1f", grid_step.x, grid_step.y), unit_pos, cv::FONT_HERSHEY_DUPLEX, unit_font_scale, unit_color); } return true; } static bool pasteImage(cv::Mat& image, const cv::Mat& stamp, const cv::Point& offset, double alpha = 1) { if (image.empty() || stamp.empty()) return false; cv::Mat stamp_img = stamp; if (image.channels() != stamp_img.channels()) { int code = cv::COLOR_BGR2GRAY; if (image.channels() == 3) code = cv::COLOR_GRAY2BGR; cv::cvtColor(stamp_img, stamp_img, code); } cv::Rect stamp_box(offset.x, offset.y, stamp_img.cols, stamp_img.rows); cv::Rect image_box(cv::Point(), image.size()); cv::Rect dst_box = stamp_box & image_box; cv::Rect src_box = (stamp_box - offset) & (image_box - offset); image(dst_box) = (1 - alpha) * image(dst_box) + alpha * stamp_img(src_box); return true; } static std::vector<cv::Point2d> getPtsVector(const cv::InputArray _data) { if (_data.empty()) return std::vector<cv::Point2d>(); cv::Mat data = _data.getMat(); if (data.depth() != CV_64F) data.convertTo(data, CV_64F); if (data.channels() == 2) return data; if (data.rows == 2 && data.cols != 2) data = data.t(); if (data.cols != 2) return std::vector<cv::Point2d>(); return data.reshape(2); } static bool getRange(const cv::InputArray data, RangeDbl& range_x, RangeDbl& range_y) { std::vector<cv::Point2d> pts = getPtsVector(data); if (pts.empty()) return false; // Find the minimum and maximum of data range_x.min = pts.front().x; range_x.max = pts.front().x; range_y.min = pts.front().y; range_y.max = pts.front().y; for (auto pt = pts.begin(); pt != pts.end(); pt++) { if (pt->x < range_x.min) range_x.min = pt->x; if (pt->x > range_x.max) range_x.max = pt->x; if (pt->y < range_y.min) range_y.min = pt->y; if (pt->y > range_y.max) range_y.max = pt->y; } return true; } protected: static cv::Rect getInnerBox(const cv::Size& sz, const cv::Point& margin) { return cv::Rect(margin.x, margin.y, sz.width - 2 * margin.x, sz.height - 2 * margin.y); } static cv::Point2d getOffset(const cv::Point2d& min_val, const cv::Point2d& ppv, const cv::Size& sz, const cv::Point& margin, const cv::Point& padding) { return cv::Point2d(padding.x + margin.x - min_val.x * ppv.x, sz.height - (padding.y + margin.y - min_val.y * ppv.y)); } cv::Size m_img_size; cv::Point m_img_padding; cv::Point m_img_margin; cv::Rect m_img_box; cv::Point2d m_img_offset; cv::Point2d m_min_val; cv::Point2d m_px_per_val; double m_img_rotation = 0; // radian }; /** * Convert an angle's unit from radian to degree * @param radian An angle in radian unit * @return The angle in degree unit */ inline double cvtRad2Deg(double radian) { return radian * 180 / CV_PI; } /** * Convert an angle's unit from degree to radian * @param degree An angle in degree unit * @return The angle in radian unit */ inline double cvtDeg2Rad(double degree) { return degree * CV_PI / 180; } /** * Make an angle within [-CV_PI, CV_PI) * @param radian An angle in radian unit * @return The trimmed angle in radian unit */ inline double trimRad(double radian) { radian -= static_cast<int>(radian / (2 * CV_PI)) * (2 * CV_PI); if (radian >= CV_PI) radian -= 2 * CV_PI; if (radian < -CV_PI) radian += 2 * CV_PI; return radian; } /** * Return an x-axis rotation matrix * @param theta The given angle (Unit: [rad]) * @return A 3D rotation matrix */ inline cv::Matx33d Rx(double theta) { double c = cos(theta), s = sin(theta); return cv::Matx33d(1, 0, 0, 0, c, -s, 0, s, c); } /** * Return an y-axis rotation matrix * @param theta The given angle (Unit: [rad]) * @return A 3D rotation matrix */ inline cv::Matx33d Ry(double theta) { double c = cos(theta), s = sin(theta); return cv::Matx33d(c, 0, s, 0, 1, 0, -s, 0, c); } /** * Return an z-axis rotation matrix * @param theta The given angle (Unit: [rad]) * @return A 3D rotation matrix */ inline cv::Matx33d Rz(double theta) { double c = cos(theta), s = sin(theta); return cv::Matx33d(c, -s, 0, s, c, 0, 0, 0, 1); } /** * Convert a quaternion vector to a 3D rotation matrix * @param w The 1st component in the given quaternion vector * @param x The 2nd component in the given quaternion vector * @param y The 3rd component in the given quaternion vector * @param z The 4th component in the given quaternion vector * @return The converted 3D rotation matrix */ inline cv::Matx33d cvtQuat2R(double w, double x, double y, double z) { // Reference) http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm double norm2 = w * w + x * x + y * y + z * z; double coeff = (norm2 == 0) ? 0 : 2 / norm2; double _2xx = coeff * x * x; double _2xy = coeff * x * y; double _2xz = coeff * x * z; double _2xw = coeff * w * x; double _2yy = coeff * y * y; double _2yz = coeff * y * z; double _2yw = coeff * w * y; double _2zz = coeff * z * z; double _2zw = coeff * w * z; return cv::Matx33d( 1 - _2yy - _2zz, _2xy - _2zw, _2xz + _2yw, _2xy + _2zw, 1 - _2xx - _2zz, _2yz - _2xw, _2xz - _2yw, _2yz + _2xw, 1 - _2xx - _2yy); } /** * Convert a quaternion vector to a 3D rotation matrix * @param q The given quaternion vector * @return The converted 3D rotation matrix */ inline cv::Matx33d cvtQuat2R(const cv::Vec4d& q) { return cvtQuat2R(q(0), q(1), q(2), q(3)); } /** * Convert a quaternion vector to Euler angles * @param w The 1st component in the given quaternion vector * @param x The 2nd component in the given quaternion vector * @param y The 3rd component in the given quaternion vector * @param z The 4th component in the given quaternion vector * @return The converted Euler angles */ inline cv::Point3d cvtQuat2EulerAng(double w, double x, double y, double z) { // Reference) https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles cv::Point3d euler; double sinr_cosp = 2 * (w * x + y * z); double cosr_cosp = 1 - 2 * (x * x + y * y); euler.x = atan2(sinr_cosp, cosr_cosp); double sinp = 2 * (w * y - z * x); if (sinp >= 1) euler.y = CV_PI; if (sinp <= -1) euler.y = -CV_PI; else euler.y = asin(sinp); double siny_cosp = 2 * (w * z + x * y); double cosy_cosp = 1 - 2 * (y * y + z * z); euler.z = atan2(siny_cosp, cosy_cosp); return euler; } /** * Convert a quaternion vector to Euler angles * @param q The given quaternion vector * @return The converted Euler angles */ inline cv::Point3d cvtQuat2EulerAng(const cv::Vec4d& q) { return cvtQuat2EulerAng(q(0), q(1), q(2), q(3)); } /** * Convert a 3D rotation matrix to a quaternion vector * @param R The given 3D rotation matrix * @return The converted quaternion vector */ inline cv::Vec4d cvtR2Quat(const cv::Matx33d& R) { // Reference) http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm double trace = R(0, 0) + R(1, 1) + R(2, 2), w, x, y, z; if (trace > 0) { double s = sqrt(trace + 1) * 2; w = 0.25 * s; x = (R(2, 1) - R(1, 2)) / s; y = (R(0, 2) - R(2, 0)) / s; z = (R(1, 0) - R(0, 1)) / s; } else if ((R(0, 0) > R(1, 1)) & (R(0, 0) > R(2, 2))) { double s = sqrt(1 + R(0, 0) - R(1, 1) - R(2, 2)) * 2; w = (R(2, 1) - R(1, 2)) / s; x = 0.25 * s; y = (R(0, 1) + R(1, 0)) / s; z = (R(0, 2) + R(2, 0)) / s; } else if (R(1, 1) > R(2, 2)) { double s = sqrt(1 + R(1, 1) - R(0, 0) - R(2, 2)) * 2; w = (R(0, 2) - R(2, 0)) / s; x = (R(0, 1) + R(1, 0)) / s; y = 0.25 * s; z = (R(1, 2) + R(2, 1)) / s; } else { double s = sqrt(1 + R(2, 2) - R(0, 0) - R(1, 1)) * 2; w = (R(1, 0) - R(0, 1)) / s; x = (R(0, 2) + R(2, 0)) / s; y = (R(1, 2) + R(2, 1)) / s; z = 0.25 * s; } return cv::Vec4d(w, x, y, z); } /** * Convert an axis-angle notation embedding angular magnitude (a.k.a. Rodrigue rotation notation) to a 3D rotation matrix * @param axis The given Rodrigue rotation vector * @return The converted 3D rotation matrix */ inline cv::Matx33d cvtAxisAng2R(const cv::Vec3d& axis) { cv::Matx33d R; cv::Rodrigues(axis, R); return R; } /** * Convert a 3D rotation matrix to an axis-angle notation embedding angular magnitude (a.k.a. Rodrigue rotation notation) * @param R The given 3D rotation matrix * @return The converted Rodrigue rotation vector */ inline cv::Vec3d cvtR2AxisAng(const cv::Matx33d& R) { cv::Vec3d axis; cv::Rodrigues(R, axis); return axis; } /** A color code for red */ const cv::Vec3b COLOR_RED(0, 0, 255); /** A color code for green */ const cv::Vec3b COLOR_GREEN(0, 255, 0); /** A color code for blue */ const cv::Vec3b COLOR_BLUE(255, 0, 0); /** A color code for cyan */ const cv::Vec3b COLOR_CYAN(255, 255, 0); /** A color code for magenta */ const cv::Vec3b COLOR_MAGENTA(255, 0, 255); /** A color code for yellow */ const cv::Vec3b COLOR_YELLOW(0, 255, 255); /** A color code for black */ const cv::Vec3b COLOR_BLACK(0, 0, 0); /** A color code for white */ const cv::Vec3b COLOR_WHITE(255, 255, 255); /** A color code for gray */ const cv::Vec3b COLOR_GRAY(127, 127, 127); /** A key code for _Line Feed (LF)_ */ const int KEY_LF = '\n'; /** A key code for _Carriage Return (CR)_, usually _Enter_ */ const int KEY_CR = '\r'; /** A key code for _Tab_ */ const int KEY_TAB = '\t'; /** A key code for _Escape (ESC)_ */ const int KEY_ESC = 0x1B; /** A key code for _Space_ */ const int KEY_SPACE = 0x20; } // End of 'cx' #endif // End of '__OPEN_CX__'
39.503038
281
0.553536
deepguider
88876c8b894fedadd892e259ed9892a30f93f902
5,900
hpp
C++
include/circular_buffer.hpp
Algorithms-and-Data-Structures-2021/semester-work-circular-buffer
7520845b51fd2e16cccfcac247140dd8cc8a459d
[ "MIT" ]
null
null
null
include/circular_buffer.hpp
Algorithms-and-Data-Structures-2021/semester-work-circular-buffer
7520845b51fd2e16cccfcac247140dd8cc8a459d
[ "MIT" ]
null
null
null
include/circular_buffer.hpp
Algorithms-and-Data-Structures-2021/semester-work-circular-buffer
7520845b51fd2e16cccfcac247140dd8cc8a459d
[ "MIT" ]
1
2021-04-25T19:14:57.000Z
2021-04-25T19:14:57.000Z
#pragma once #include <cstddef> #include <optional> #include <stdexcept> // logic_error #include <cassert> // assert using std::size_t; // Заголовочный файл с объявлением структуры данных namespace itis { // Tip 1: объявите здесь необходимые структуры, функции, константы и прочее // Пример: объявление константы времени компиляции в заголовочном файле inline constexpr auto kStringConstant = "Hello, stranger!"; // Пример: объявление структуры с полями и методами template<class T> struct circular_buffer { private: size_t size_{0}; size_t capacity_{0}; T *data_{nullptr}; size_t tail_{0}; size_t head_{0}; void incrementHead() { head_ = (head_ + 1) % capacity_; } // замыкание кольцевого буфера - после последнего элемента в массиве data_ будет следовать первый void incrementTail() { tail_ = (tail_ + 1) % capacity_; } void decrementHead() { if (head_ == 0) /* т.к. тип size_t не может принять отриц. значение, проврка такая */{ head_ = capacity_ - 1; } else { head_ -= 1; } } void decrementTail() { if (tail_ == 0) /* т.к. тип size_t не может принять отриц. значение, проврка такая */{ tail_ = capacity_ - 1; } else { tail_ -= 1; } } // Tip 2: На начальном этапе разработки структуры данных можете определения методов задавать в // заголовочном файле, как только работа будет завершена, можно будет оставить здесь только объявления. public: explicit circular_buffer(size_t max_size_) : data_(new T[max_size_]), capacity_(max_size_) {} // добавление элемента в конец void EnqueueBack(T &elem) { if (isFull()) { // буфер полон - перезаписываем данные incrementHead(); incrementTail(); data_[tail_] = elem; } else if (isEmpty()) { // буфер пуст - добавляем первый элемент куда угодно, но я решил, что на нулевую позицию head_ = 0; tail_ = 0; data_[tail_] = elem; size_ += 1; } else { // просто добавляем новый элемент в конец incrementTail(); data_[tail_] = elem; size_ += 1; } } // добавление элемента в начало void EnqueueFront(T &elem) { if (isFull()) { // буфер полон - перезаписываем данные decrementHead(); decrementTail(); data_[head_] = elem; } else if (isEmpty()) { // буфер пуст - добавляем первый элемент куда угодно, но я решил, что на нулевую позицию head_ = 0; tail_ = 0; data_[head_] = elem; size_ += 1; } else { // просто добавляем новый элемент в конец decrementHead(); data_[head_] = elem; size_ += 1; } } // взятие элемента с конца и его удаление T DequeueBack() { if (isEmpty()) { // из пустого буфера нечего удалять throw std::logic_error("cannot dequeue from empty buffer"); } T to_return; if (size() == 1) { // в случае одного элемента нет нужды в том чтобы перемещать индекс после очищения буфера to_return = data_[tail_]; size_ = 0; } else { // просто перемещаем указатель, тем самым разрешая перезаписать элемент, к нему больше не будет доступа to_return = data_[tail_]; decrementTail(); size_ -= 1; } return to_return; } // взятие элемента с начала и его удаление T DequeueFront() { if (isEmpty()) { // из пустого буфера нечего удалять throw std::logic_error("cannot dequeue from empty buffer"); } T to_return; if (size() == 1) { // в случае одного элемента нет нужды в том чтобы перемещать индекс после очищения буфера to_return = data_[head_]; size_ = 0; } else { // просто перемещаем указатель, тем самым разрешая перезаписать элемент, к нему больше не будет доступа to_return = data_[head_]; incrementHead(); size_ -= 1; } return to_return; } // получение элемента с конца без его удаления std::optional<T> getFront() const { return size_ == 0 ? std::nullopt : std::make_optional(data_[head_]); } // получение элемента с начала без его удаления std::optional<T> getBack() const { return size_ == 0 ? std::nullopt : std::make_optional(data_[tail_]); } bool isFull() const { return size_ == capacity_; } bool isEmpty() const { return size_ == 0; } size_t size() const { return size_; } size_t capacity() const { return capacity_; } // увеличение вместительности буфера void Resize(size_t new_capacity) { assert(new_capacity > capacity_); T *new_data = new T[new_capacity]; if (head_ <= tail_) { // первый случай - начало левее конца: [x, x, 1, 2, 3, 4, x] std::copy(data_ + head_, data_ + tail_ + 1, new_data); } else { // второй случай - начало правее конца: [3, 4, x, x, x, 1, 2] std::copy(data_ + head_, data_ + capacity_, new_data); std::copy(data_, data_ + tail_ + 1, new_data + capacity_ - head_); } if (size_ > 0) { // данные переместились в начало массива - обновим указатели head_ = 0; tail_ = size_ - 1; } capacity_ = new_capacity; // высвободим память из-под старого массива delete[] data_; data_ = new_data; } void Clear() { // менять значения указателей необязательно, они все равно поменяются, если добавить в пустой буфер элемент size_ = 0; } ~circular_buffer() { tail_ = 0; head_ = 0; size_ = 0; capacity_ = 0; // не забываем высвободить память delete[] data_; data_ = nullptr; } }; } // namespace itis
27.962085
113
0.589492
Algorithms-and-Data-Structures-2021
88884f168d3fc8582b42bf0cbcb746c51033c860
1,144
cpp
C++
leetCode/MajorityElement.cpp
ChairInkitchenAmer/study
56650ccb1c9879f22cbd692883db7f26f5a8c54b
[ "Apache-2.0" ]
null
null
null
leetCode/MajorityElement.cpp
ChairInkitchenAmer/study
56650ccb1c9879f22cbd692883db7f26f5a8c54b
[ "Apache-2.0" ]
null
null
null
leetCode/MajorityElement.cpp
ChairInkitchenAmer/study
56650ccb1c9879f22cbd692883db7f26f5a8c54b
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <unordered_map> #include <algorithm> using namespace std; class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int,int> map; if(nums.size() == 1){ return nums[0]; } for(int i=0; i < nums.size(); i++){ auto item = map.find(nums[i]); if(item != map.end() && item->second +1 > nums.size()/2){ return item->first; } else { map[nums[i]]++; } } return -1; } }; class Solution1 { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); int lastValue=0; int lastCount=0; for(int i=0; i< nums.size(); i++){ if(nums[i]== lastValue){ lastCount++; } else{ lastValue=nums[i]; lastCount=1; } if(lastCount > nums.size() / 2){ return lastValue; } } return -1; } };
21.185185
69
0.414336
ChairInkitchenAmer
8888ca65a0b111d92522e95eeb4592d34962bd30
1,100
cpp
C++
CPPProgramExample/LAB04/LAB04/CLASS02.cpp
mahmoudShaheen/RandomCollegeProjects
6bcede0ad8b09ac738d8f49e6fed6d2b7a111cfd
[ "MIT" ]
null
null
null
CPPProgramExample/LAB04/LAB04/CLASS02.cpp
mahmoudShaheen/RandomCollegeProjects
6bcede0ad8b09ac738d8f49e6fed6d2b7a111cfd
[ "MIT" ]
null
null
null
CPPProgramExample/LAB04/LAB04/CLASS02.cpp
mahmoudShaheen/RandomCollegeProjects
6bcede0ad8b09ac738d8f49e6fed6d2b7a111cfd
[ "MIT" ]
null
null
null
#include <iostream> #include <windows.h> #include <process.h> #include <conio.h> using namespace std; class point{ int x,y; public: point (int u, int v){x=u; y=v;} // function definition -- requires windows.h void gotoxy() { HANDLE hConsoleOutput; COORD dwCursorPosition; cout.flush(); dwCursorPosition.X= x; dwCursorPosition.Y= y; hConsoleOutput= GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition); } int operator <=(point p) {return (x<=p.x && y<=p.y);} int operator >=(point p) {return (x>=p.x && y>=p.y);} point operator +=(point p) {return point(x+=p.x, y+=p.y);} }; int main() { system("cls"); // function definition -- requires process.h for (point p1(20,5);p1<=point(60,5);p1+=point(1,0)) {p1.gotoxy(); _putch('*');} for (point p4(60,5);p4<=point(60,20);p4+=point(0,1)) {p4.gotoxy(); _putch('*');} for (point p2(60,20);p2>=point(20,20);p2+=point(-1,0)) {p2.gotoxy (); _putch('*');} for (point p3(20,5);p3<=point(20,20);p3+=point(0,1)) {p3.gotoxy(); _putch('*');} cout<<"\n"; return 0; }
22.44898
63
0.621818
mahmoudShaheen
888a058571d9a181953e547daae797b61c5b4041
17,894
cpp
C++
esp32/TinyCPCEMttgovga32/CPCem/FDC.cpp
rpsubc8/ESP32TinyCPC
386a0d1d47fc6f32c0b3dace67a6c2197a846a9d
[ "WTFPL" ]
19
2020-12-04T15:12:45.000Z
2022-02-07T19:46:36.000Z
esp32/TinyCPCEMttgovga32/CPCem/FDC.cpp
rpsubc8/ESP32TinyCPC
386a0d1d47fc6f32c0b3dace67a6c2197a846a9d
[ "WTFPL" ]
3
2021-02-20T08:42:09.000Z
2022-03-11T05:11:26.000Z
esp32/TinyCPCEMttgovga32/CPCem/FDC.cpp
rpsubc8/ESP32TinyCPC
386a0d1d47fc6f32c0b3dace67a6c2197a846a9d
[ "WTFPL" ]
4
2021-02-20T08:07:04.000Z
2022-03-27T21:52:45.000Z
//C72B - try command //A9B0 #include <stdio.h> #include <string.h> #include <stdlib.h> #include "FDC.h" #include "gb_globals.h" #include "dataFlash/gbdsk.h" #include <iostream> //unsigned char gb_select_dsk_disk=0; //int gb_ptrBeginDataDisc[42][11]; //Donde empieza el disco int startreal; unsigned char discon; int endread; int fdcint=0; unsigned char fdcstatus=0x80; int params=0; int readparams=0; unsigned char paramdat[16]; //Escrive disco revisar unsigned char command; unsigned char st0,st1,st2,st3; int fdctrack; int starttrack,startsector,endsector; int posinsector; unsigned char reading=0; Tdiscsect *discsects; //JJ int disctracks; //no lo necesito //JJ int discsects[40]; //esta en rom //JJ unsigned char discdat[42][11][512]; //unsigned char discid[42][11][4]; Tdiscid *discid; Tdiscdat *discdat; using namespace std; void dumpdisc() { //JJ FILE *f=fopen("disk.dmp","wb"); //JJ fwrite(discdat[0][0],512,1,f); //JJ fclose(f); } void loaddsk2Flash(unsigned char id) { discid = (Tdiscid *)gb_list_dsk_discid[id]; discdat = (Tdiscdat *)gb_list_dsk_discdat[id];; /* int contBuffer=0; int numsect; int c,d; char head[40]; unsigned char dskhead[256],trkhead[256]; gb_select_dsk_disk = id; memcpy(dskhead,&gb_list_dsk_data[id][contBuffer],256); cout<<"Fichero "<<dskhead<<"\n"; contBuffer+= 256; for (c=0;c<40;c++) head[c]=0; for (c=0;c<0x21;c++) head[c]=dskhead[c]; disctracks=dskhead[0x30]; //printf ("Head\nDisc tracks %d ",disctracks); for (d=0;d<disctracks;d++) { memcpy(trkhead,&gb_list_dsk_data[id][contBuffer],256); contBuffer+= 256; //cout<< "cont " <<contBuffer<<"\n"; while (strncmp((const char *)trkhead,"Track-Info",10) && contBuffer< gb_list_dsk_size[id]) {//194816 bytes normalmente memcpy(trkhead,&gb_list_dsk_data[id][contBuffer],256); contBuffer+= 256; //printf ("cont %d\n", contBuffer); if (contBuffer > gb_list_dsk_size[id]) return; } discsects[d]=numsect=trkhead[0x15]; //printf ("Num sects %d\n", numsect); for (c=0;c<numsect;c++) { //if (c == 0) //{ // gb_ptrBeginDataDisc[d] = contBuffer; //Donde empieza disco // printf("Disco begin %d Track ",gb_ptrBeginDataDisc[d],d); //} discid[d][c][0]=trkhead[0x18+(c<<3)]; discid[d][c][1]=trkhead[0x19+(c<<3)]; discid[d][c][2]=trkhead[0x1A+(c<<3)]; discid[d][c][3]=trkhead[0x1B+(c<<3)]; //printf("%i %i %i %i ",discid[d][c][0],discid[d][c][1],discid[d][c][2],discid[d][c][3]); //JJ memcpy(&(discdat[d][(discid[d][c][2]-1)&15]),&(gb_list_dsk_data[id][contBuffer]),512); gb_ptrBeginDataDisc[d][c]=contBuffer; //printf("Begin Track:%d Sector:%d Address:%d\n",d,c,gb_ptrBeginDataDisc[d][c]); contBuffer+= 512; } } //printf ("\n"); */ } /* void loaddsk() { int numsect; int c,d; char head[40]; unsigned char dskhead[256],trkhead[256]; FILE *f=fopen(discname,"rb"); if (!f) return; fread(dskhead,256,1,f); for (c=0;c<40;c++) head[c]=0; for (c=0;c<0x21;c++) head[c]=dskhead[c]; disctracks=dskhead[0x30]; // printf("%i tracks\n",dskhead[0x30]); // printf("%s\n",head); for (d=0;d<disctracks;d++) { fread(trkhead,256,1,f); //JJ while (strncmp(trkhead,"Track-Info",10) && !feof(f)) while (strncmp((const char *)trkhead,"Track-Info",10) && !feof(f)) fread(trkhead,256,1,f); // printf("Track %i ftell %05X : ",d,ftell(f)-256); if (feof(f)) { fclose(f); return; } discsects[d]=numsect=trkhead[0x15]; // printf("%i sectors\n",discsects[d]); for (c=0;c<numsect;c++) { discid[d][c][0]=trkhead[0x18+(c<<3)]; discid[d][c][1]=trkhead[0x19+(c<<3)]; discid[d][c][2]=trkhead[0x1A+(c<<3)]; discid[d][c][3]=trkhead[0x1B+(c<<3)]; // printf("%i %i %i %i ",discid[d][c][0],discid[d][c][1],discid[d][c][2],discid[d][c][3]); //JJ fread(discdat[d][(discid[d][c][2]-1)&15],512,1,f); } // printf("\n"); } // printf("DSK pos %i\n",ftell(f)); fclose(f); } */ unsigned char readfdc(unsigned short addr) { unsigned char aux_discdat/*[11]*/[1024]; int c; unsigned char temp; // printf("Read %04X %04X\n",addr,pc); if (addr&1) { if (!readparams) { //printf("Reading but no params - last command %02X\n",command); exit(-1); } switch (command) { case 0x04: //Sense drive status readparams=0; fdcstatus=0x80; return st3; case 0x06: //Read sectors if (reading) { temp=discdat->datos[fdctrack][startsector-1][posinsector]; // printf("Read track %i sector %i pos %i\n",fdctrack,startreal,posinsector); // printf("%c",temp); posinsector++; if (posinsector==512) { if ((startsector&15)==(endsector&15)) { reading=0; readparams=7; // output=1; fdcstatus=0xD0; // if (startsector==4) output=1; // printf("Done it %04X\n",pc); endread=1; fdcint=1; discon=0; // output=1; // dumpregs(); // dumpram(); // exit(-1); } else { posinsector=0; startsector++; //JJ if ((startsector&15)==(discsects[fdctrack]+1)) if ((startsector&15)==(discsects->datos[fdctrack]+1)) { if (command&0x80) fdctrack++; startsector=0xC1; } startreal=0; for (c=0;c<11;c++) { if ((discid->datos[starttrack][c][2]&15)==(startsector&15)) { startreal=c; break; } } } } return temp; } readparams--; switch (readparams) { case 6: st0=0x40; st1=0x80; st2=0; return st0; case 5: return st1; case 4: return st2; case 3: return fdctrack; case 2: return 0; case 1: return startsector; case 0: fdcstatus=0x80; return 2; } break; case 0x86: /*Read sector fail*/ readparams--; switch (readparams) { case 6: st0=0x40; st1=0x84; st2=0; return st0; case 5: return st1; case 4: return st2; case 3: return fdctrack; case 2: return 0; case 1: return startsector; case 0: fdcstatus=0x80; return 2; } break; case 0x08: /*Sense interrupt state*/ readparams--; if (readparams==1) return st0; fdcstatus=0x80; return fdctrack; case 0x0A: /*Read sector ID*/ readparams--; switch (readparams) { case 6: return st0; case 5: return st1; case 4: return st2; case 3: return discid->datos[fdctrack][startsector][0]; case 2: return discid->datos[fdctrack][startsector][1]; case 1: return discid->datos[fdctrack][startsector][2]; case 0: fdcstatus=0x80; return discid->datos[fdctrack][startsector][3]; } break; default: //printf("Reading command %02X\n",command); exit(-1); } } else { // if (reading) // fdcstatus^=0x80; return fdcstatus; } } void writefdc(unsigned short addr, unsigned char val) { int c; // printf("Write %04X %02X %04X\n",addr,val,pc); if (addr==0xFA7E) { //JJ motoron=val&1;//No necesito estado motor disco return; } if (addr&1) { if (params) { paramdat[params-1]=val; params--; if (!params) { switch (command) { case 0x03: /*Specify*/ // printf("Specified %02X %02X\n",paramdat[1],paramdat[0]); fdcstatus=0x80; break; case 0x04: /*Sense drive status*/ st3=0x60; if (!fdctrack) st3|=0x10; fdcstatus=0xD0; readparams=1; break; case 0x06: /*Read sectors*/ // printf("Read sectors %02X %02X %02X %02X %02X %02X %02X %02X\n",paramdat[7],paramdat[6],paramdat[5],paramdat[4],paramdat[3],paramdat[2],paramdat[1],paramdat[0]); starttrack=paramdat[6]; startsector=paramdat[4]&15; endsector=paramdat[2]&15; startreal=0; /* for (c=0;c<11;c++) { printf("Sector %i ID %02X\n",c,discid[starttrack][c][2]); if (discid[starttrack][c][2]==paramdat[4]) { startreal=c; break; } } if (c==11) { printf("Sector %02X not found on track %02X\n",startsector,starttrack); command=0x86; reading=0; readparams=7; fdcstatus=0xD0; // exit(-1); } else {*/ // printf("FDC read %02X %02X %i %i %i\n",paramdat[4],endsector,startreal,c,starttrack); // printf("FDC Read sector track %i start %i end %i\n",starttrack,startsector,endsector); posinsector=0; readparams=1; reading=1; fdcstatus=0xF0; // } // printf("Start - track %i sector %i\n",starttrack,startsector); break; case 0x07: /*Recalibrate*/ // printf("Recalibrate %02X\n",paramdat[0]); fdcstatus=0x80; fdctrack=0; fdcint=1; break; case 0x0A: /*Read sector ID*/ fdcstatus|=0x60; readparams=7; break; case 0x0F: /*Seek*/ // printf("Seek %02X %02X\n",paramdat[1],paramdat[0]); fdcstatus=0x80; fdctrack=paramdat[0]; fdcint=1; // output=1; break; default: //printf("Executing bad command %02X\n",command); exit(-1); } } } else { command=val&0x1F; switch (command) { case 0: case 0x1F: return; /*Invalid*/ case 0x03: /*Specify*/ params=2; fdcstatus|=0x10; break; case 0x04: /*Sense drive status*/ params=1; fdcstatus|=0x10; break; case 0x06: /*Read sectors*/ // if (output) exit(0); params=8; fdcstatus|=0x10; discon=1; break; case 0x07: /*Recalibrate*/ params=1; fdcstatus|=0x10; break; case 0x08: /*Sense interrupt state*/ st0=0x21; if (!fdcint) st0|=0x80; else fdcint=0; fdcstatus|=0xD0; readparams=2; break; case 0x0A: /*Read sector ID*/ params=1; fdcstatus|=0x10; break; case 0x0F: /*Seek*/ params=2; fdcstatus|=0x10; break; default: //printf("Starting bad command %02X\n",command); exit(-1); } } } }
42.402844
204
0.323181
rpsubc8
888d2a94e10138c5f4a34eb6e24236ab0c000973
16,372
cpp
C++
src/Lagrange.cpp
clauderichard/OptimistRacing
808ffcef44307c9097035bf5dacdcae8fc7663a7
[ "MIT" ]
null
null
null
src/Lagrange.cpp
clauderichard/OptimistRacing
808ffcef44307c9097035bf5dacdcae8fc7663a7
[ "MIT" ]
null
null
null
src/Lagrange.cpp
clauderichard/OptimistRacing
808ffcef44307c9097035bf5dacdcae8fc7663a7
[ "MIT" ]
null
null
null
/* Copyright (C) 2012 Claude Richard * * Optimist Racing 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. * * Optimist Racing 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 Optimist Racing. If not, see <http://www.gnu.org/licenses/>. */ #include "Lagrange.hpp" #include <algorithm> #include <cmath> /** * \file This file deals with a specific model of Lagrangian Mechanics for the game. */ namespace Lagrange { LagrangianRacer::LagrangianRacer( const BezierPatchGrid* bezierPatchGrid, double gravity, double length, double massBottom, double massTop, double IBottom, double ITopX, double ITopY, double ITopZ, double xdotmax, double ydotmax, double zdotmax, double thetadotmax, double phidotmax, double x, double y, double theta, double phi, double xdot, double ydot, double thetadot, double phidot ) : mBezierPatchGrid( bezierPatchGrid ) , mGravity( gravity ) , mLength( length ) , mMassBottom( massBottom ) , mMassTop( massTop ) , mIBottom( IBottom ) , mITopX( ITopX ) , mITopY( ITopY ) , mITopZ( ITopZ ) , mXDotMax( xdotmax ) , mYDotMax( ydotmax ) , mZDotMax( zdotmax ) , mThetaDotMax( thetadotmax ) , mPhiDotMax( phidotmax ) , mAlpha( massBottom + massTop ) , mBeta( massTop*length*length + ITopX ) , mGamma( massTop*length*length + ITopY ) , mDelta( massTop*length ) , mEpsilon( massTop*length*length + ITopX - ITopZ ) , mLength1( massBottom / (massBottom+massTop) ) , mLength2( length - mLength1 ) , mZeta( massTop*mLength1*mLength1 + massBottom*mLength2*mLength2 + ITopX ) , mEta( mZeta - ITopZ ) , mIota( mEta / ( massTop*mLength1*mLength1 + massBottom*mLength2*mLength2 + ITopY ) ) , mX( x ) , mY( y ) , mZ( bezierPatchGrid->computeFOnly( x, y ) ) , mTheta( theta ) , mPhi( phi ) , mXDot( xdot ) , mYDot( ydot ) , mThetaDot( thetadot ) , mPhiDot( phidot ) , mForceBottomWorld( 0.0, 0.0, 0.0 ) , mForceTopWorld( 0.0, 0.0, 0.0 ) , mTorqueBottomModelZ( 0.0 ) , mTorqueTopModel( 0.0, 0.0, 0.0 ) { MatrixMxN comp = mBezierPatchGrid->compute( x, y ); mZDot = comp[1][0]*mXDot + comp[0][1]*mYDot; } LagrangianRacer::~LagrangianRacer() { } LagrangianRacer* LagrangianRacer::create( const BezierPatchGrid* bezierPatchGrid, double gravity, double size, double x, double y, double theta, double phi, double xdot, double ydot, double thetadot, double phidot ) { return new LagrangianRacer( bezierPatchGrid, gravity, RACER_LENGTH, RACER_MASS_DEFAULT*size, RACER_MASS_DEFAULT*size, 2.0*RACER_MASS_DEFAULT*RACER_RADIUS_DEFAULT*RACER_RADIUS_DEFAULT*size*size*size/5, 2.0*RACER_MASS_DEFAULT*RACER_RADIUS_DEFAULT*RACER_RADIUS_DEFAULT*size*size*size/5, 2.0*RACER_MASS_DEFAULT*RACER_RADIUS_DEFAULT*RACER_RADIUS_DEFAULT*size*size*size/5, 2.0*RACER_MASS_DEFAULT*RACER_RADIUS_DEFAULT*RACER_RADIUS_DEFAULT*size*size*size/5, RACER_XDOT_MAX, RACER_YDOT_MAX, RACER_ZDOT_MAX, RACER_THETADOT_MAX, RACER_PHIDOT_MAX, x, y, theta, phi, xdot, ydot, thetadot, phidot ); } const BezierPatchGrid* LagrangianRacer::getBezierPatchGrid() const { return mBezierPatchGrid; } double LagrangianRacer::getGravity() const { return mGravity; } double LagrangianRacer::getLength() const { return mLength; } double LagrangianRacer::getMassBottom() const { return mMassBottom; } double LagrangianRacer::getMassTop() const { return mMassTop; } double LagrangianRacer::getIBottom() const { return mIBottom; } double LagrangianRacer::getITopX() const { return mITopX; } double LagrangianRacer::getITopY() const { return mITopY; } double LagrangianRacer::getITopZ() const { return mITopZ; } double LagrangianRacer::getX() const { return mX; } double LagrangianRacer::getY() const { return mY; } double LagrangianRacer::getZ() const { return mZ; } double LagrangianRacer::getTheta() const { return mTheta; } double LagrangianRacer::getPhi() const { return mPhi; } double LagrangianRacer::getXDot() const { return mXDot; } double LagrangianRacer::getYDot() const { return mYDot; } double LagrangianRacer::getZDot() const { return mZDot; } double LagrangianRacer::getThetaDot() const { return mThetaDot; } double LagrangianRacer::getPhiDot() const { return mPhiDot; } Vector3D LagrangianRacer::getBottomPosition() const { return Vector3D( mX, mY, mZ ); } Vector3D LagrangianRacer::getTopPosition() const { return Vector3D( mX, mY, mZ ) + mLength*Vector3D(cos(mTheta)*sin(mPhi), sin(mTheta)*sin(mPhi), cos(mPhi)); } void LagrangianRacer::clearForces() { mForceBottomWorld = Vector3D(0,0,0); mForceTopWorld = Vector3D(0,0,0); mTorqueTopModel = Vector3D(0,0,0); mTorqueBottomModelZ = 0; } void LagrangianRacer::setForceBottomWorld( const Vector3D& force ) { mForceBottomWorld = force; } void LagrangianRacer::setForceTopWorld( const Vector3D& force ) { mForceTopWorld = force; } void LagrangianRacer::setForceBottomModel( const Vector3D& force ) { double fx = force[0]; double fy = force[1]; double costheta = cos(mTheta); double sintheta = sin(mTheta); mForceBottomWorld[0] = fx*costheta - fy*sintheta; mForceBottomWorld[1] = fx*sintheta + fy*costheta; mForceBottomWorld[2] = force[2]; } void LagrangianRacer::setForceTopModel( const Vector3D& force ) { double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); double fx = force[0]; double fy = force[1]; double fz = force[2]; mForceTopWorld[0] = fx*costheta*cosphi - fy*sintheta + fz*costheta*sinphi; mForceTopWorld[1] = fx*sintheta*cosphi + fy*costheta + fz*sintheta*sinphi; mForceTopWorld[2] = fz*cosphi - fx*sinphi; } void LagrangianRacer::setTorqueBottomModelZ( double torque ) { mTorqueBottomModelZ = torque; } void LagrangianRacer::setTorqueBottomModel( const Vector3D& torque ) { mTorqueBottomModelZ = torque[2]; } void LagrangianRacer::setTorqueTopModel( const Vector3D& torque ) { mTorqueTopModel = torque; } void LagrangianRacer::setTorqueTopWorld( const Vector3D& torque ) { double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); double tx = torque[0]; double ty = torque[1]; double tz = torque[2]; mTorqueTopModel[0] = tx*costheta*cosphi + ty*sintheta*cosphi - tz*sinphi; mTorqueTopModel[1] = ty*costheta - tx*sintheta; mTorqueTopModel[2] = tx*costheta*sinphi + ty*sintheta*sinphi + tz*cosphi; } void LagrangianRacer::addForceBottomWorld( const Vector3D& force ) { mForceBottomWorld = mForceBottomWorld + force; } void LagrangianRacer::addForceTopWorld( const Vector3D& force ) { mForceTopWorld = mForceTopWorld + force; } void LagrangianRacer::addForceBottomModel( const Vector3D& force ) { double fx = force[0]; double fy = force[1]; double costheta = cos(mTheta); double sintheta = sin(mTheta); mForceBottomWorld[0] += fx*costheta - fy*sintheta; mForceBottomWorld[1] += fx*sintheta + fy*costheta; mForceBottomWorld[2] += force[2]; } void LagrangianRacer::addForceTopModel( const Vector3D& force ) { double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); double fx = force[0]; double fy = force[1]; double fz = force[2]; mForceTopWorld[0] += fx*costheta*cosphi - fy*sintheta + fz*costheta*sinphi; mForceTopWorld[1] += fx*sintheta*cosphi + fy*costheta + fz*sintheta*sinphi; mForceTopWorld[2] += fz*cosphi - fx*sinphi; } void LagrangianRacer::addTorqueBottomModelZ( double torque ) { mTorqueBottomModelZ += torque; } void LagrangianRacer::addTorqueBottomModel( const Vector3D& torque ) { mTorqueBottomModelZ += torque[2]; } void LagrangianRacer::addTorqueTopModel( const Vector3D& torque ) { mTorqueTopModel = mTorqueTopModel + torque; } void LagrangianRacer::addTorqueTopWorld( const Vector3D& torque ) { double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); double tx = torque[0]; double ty = torque[1]; double tz = torque[2]; mTorqueTopModel[0] += tx*costheta*cosphi + ty*sintheta*cosphi - tz*sinphi; mTorqueTopModel[1] += ty*costheta - tx*sintheta; mTorqueTopModel[2] += tx*costheta*sinphi + ty*sintheta*sinphi + tz*cosphi; } void LagrangianRacer::stepRacing( double seconds ) { MatrixMxN FBezier = mBezierPatchGrid->compute(mX, mY); double f = FBezier[0][0]; double fx = FBezier[1][0]; double fy = FBezier[0][1]; double fxx = FBezier[2][0]; double fxy = FBezier[1][1]; double fyy = FBezier[0][2]; double alphaFx = mAlpha*fx; double alphaFy = mAlpha*fy; double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); double xdot2 = mXDot*mXDot; double ydot2 = mYDot*mYDot; double thetadot2 = mThetaDot*mThetaDot; double phidot2 = mPhiDot*mPhiDot; double xydot = 2*mXDot*mYDot; double thetaphidot = 2*mThetaDot*mPhiDot; double a = xdot2*fxx + ydot2*fyy + xydot*fxy + mGravity; double mtlcossin = mDelta*costheta*sinphi; double epsilonsamesincos = mEpsilon*sinphi*cosphi; double thetadot2plusphidot2 = thetadot2 + phidot2; // vector b double b1 = alphaFx*a - mDelta*( costheta*sinphi*(thetadot2plusphidot2) + cosphi*(fx*phidot2 + sintheta*thetaphidot) ); double b2 = alphaFy*a - mDelta*( sintheta*sinphi*(thetadot2plusphidot2) + cosphi*(fy*phidot2 - costheta*thetaphidot) ); double b3 = mEpsilon*sinphi*cosphi*thetaphidot; double b4 = - sinphi*(mDelta*a + mEpsilon*cosphi*thetadot2); // generalized forces double qx = mForceBottomWorld[0] + mForceTopWorld[0] + fx*(mForceBottomWorld[2] + mForceTopWorld[2]); double qy = mForceBottomWorld[1] + mForceTopWorld[1] + fy*(mForceBottomWorld[2] + mForceTopWorld[2]); double qtheta = mLength*sinphi*(mForceTopWorld[1]*costheta - mForceTopWorld[0]*sintheta) + mTorqueBottomModelZ + mTorqueTopModel[2]*cosphi - mTorqueTopModel[0]*sinphi; double qphi = mLength*( cosphi*(mForceTopWorld[0]*costheta+mForceTopWorld[1]*sintheta) - sinphi*mForceTopWorld[2]) + mTorqueTopModel[1]; // matrix A double a11 = mAlpha*(1+fx*fx); double a12 = mAlpha*fx*fy; double a22 = mAlpha*(1+fy*fy); double a13 = - mDelta*sintheta*sinphi; double a23 = mDelta*costheta*sinphi; double a33 = mBeta*sinphi*sinphi + mITopZ*cosphi*cosphi + mIBottom; double a14 = mDelta*(costheta*cosphi-fx*sinphi); double a24 = mDelta*(sintheta*cosphi-fy*sinphi); double avalues[16] = { a11, a12, a13, a14, a12, a22, a23, a24, a13, a23, a33, 0, a14, a24, 0, mGamma }; double vecvalues[4] = { qx-b1, qy-b2, qtheta-b3, qphi-b4 }; MatrixMxN XDotDot = MatrixMxN(4,4,avalues).invert() * MatrixMxN(4,1,vecvalues); // use XDotDot to update the state mX = mX + mXDot*seconds + seconds*seconds*XDotDot[0][0]/2; mY = mY + mYDot*seconds + seconds*seconds*XDotDot[1][0]/2; mZ = mBezierPatchGrid->computeFOnly(mX, mY); mTheta = mTheta + mThetaDot*seconds + seconds*seconds*XDotDot[2][0]/2; mPhi = mPhi + mPhiDot*seconds + seconds*seconds*XDotDot[3][0]/2; mXDot = mXDot + seconds*XDotDot[0][0]; mYDot = mYDot + seconds*XDotDot[1][0]; mThetaDot = mThetaDot + seconds*XDotDot[2][0]; mPhiDot = mPhiDot + seconds*XDotDot[3][0]; mXDot = std::min(mXDotMax, std::max(-mXDotMax,mXDot)); mYDot = std::min(mYDotMax, std::max(-mYDotMax,mYDot)); mZDot = fx*mXDot + fy*mYDot; mThetaDot = std::min(mThetaDotMax, std::max(-mThetaDotMax,mThetaDot)); mPhiDot = std::min(mPhiDotMax, std::max(-mPhiDotMax,mPhiDot)); } void LagrangianRacer::stepFlying( double seconds ) { double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); double xthetadot = mXDot*mThetaDot; double xphidot = mXDot*mPhiDot; double ythetadot = mYDot*mThetaDot; double yphidot = mYDot*mPhiDot; double zphidot = mZDot*mPhiDot; double thetadot2 = mThetaDot*mThetaDot; double phidot2 = mPhiDot*mPhiDot; double thetaphidot = 2*mThetaDot*mPhiDot; //double mtlcossin = mDelta*costheta*sinphi; //double epsilonsamesincos = mEpsilon*sinphi*cosphi; double thetadot2plusphidot2 = thetadot2 + phidot2; double sincosphi = sinphi*cosphi; double eps = mEpsilon*sincosphi; // vector b double b1 = -mDelta*(costheta*sinphi*thetadot2plusphidot2 - thetaphidot*sintheta*cosphi); double b2 = -mDelta*(sintheta*sinphi*thetadot2plusphidot2 + thetaphidot*costheta*cosphi); double b3 = mAlpha*mGravity - mDelta*cosphi*phidot2; double b4 = thetaphidot*eps - mDelta*(xthetadot*costheta*sinphi + ythetadot*sintheta*sinphi + xphidot*sintheta*cosphi - yphidot*costheta*cosphi); double b5 = -thetadot2*eps - mDelta*mGravity*sinphi; // generalized forces double qx = mForceBottomWorld[0] + mForceTopWorld[0]; double qy = mForceBottomWorld[1] + mForceTopWorld[1]; double qz = mForceBottomWorld[2] + mForceTopWorld[2]; double qtheta = mLength*sinphi*(mForceTopWorld[1]*costheta - mForceTopWorld[0]*sintheta) + mTorqueBottomModelZ + mTorqueTopModel[2]*cosphi - mTorqueTopModel[0]*sinphi; double qphi = mLength*( cosphi*(mForceTopWorld[0]*costheta+mForceTopWorld[1]*sintheta) - sinphi*mForceTopWorld[2]) + mTorqueTopModel[1]; // matrix A double a14 = -mDelta*sintheta*sinphi; double a15 = mDelta*costheta*cosphi; double a24 = mDelta*costheta*sinphi; double a25 = mDelta*sintheta*cosphi; double a35 = -mDelta*sinphi; double a44 = mBeta*sinphi*sinphi + mITopZ*cosphi*cosphi + mIBottom; // find XDotDot vector double avalues[25] = { mAlpha, 0, 0, a14, a15, 0, mAlpha, 0, a24, a25, 0, 0, mAlpha, 0, a35, a14, a24, 0, a44, 0, a15, a25, a35, 0, mGamma }; double vecvalues[5] = { qx-b1, qy-b2, qz-b3, qtheta-b4, qphi-b5 }; MatrixMxN XDotDot = MatrixMxN(5,5,avalues).invert() * MatrixMxN(5,1,vecvalues); // use XDotDot to update the state mX += mXDot*seconds + seconds*seconds*XDotDot[0][0]/2; mY += mYDot*seconds + seconds*seconds*XDotDot[1][0]/2; mZ += mZDot*seconds + seconds*seconds*XDotDot[2][0]/2; mTheta += mThetaDot*seconds + seconds*seconds*XDotDot[3][0]/2; mPhi += mPhiDot*seconds + seconds*seconds*XDotDot[4][0]/2; mXDot = mXDot + seconds*XDotDot[0][0]; mYDot = mYDot + seconds*XDotDot[1][0]; mZDot = mZDot + seconds*XDotDot[2][0]; mThetaDot = mThetaDot + seconds*XDotDot[3][0]; mPhiDot = mPhiDot + seconds*XDotDot[4][0]; mXDot = std::min(mXDotMax, std::max(-mXDotMax,mXDot)); mYDot = std::min(mYDotMax, std::max(-mYDotMax,mYDot)); mZDot = std::min(mZDotMax, std::max(-mZDotMax,mZDot)); mThetaDot = std::min(mThetaDotMax, std::max(-mThetaDotMax,mThetaDot)); mPhiDot = std::min(mPhiDotMax, std::max(-mPhiDotMax,mPhiDot)); } void LagrangianRacer::land() { double costheta = cos(mTheta); double sintheta = sin(mTheta); double cosphi = cos(mPhi); double sinphi = sin(mPhi); // matrix A double a14 = -mDelta*sintheta*sinphi; double a15 = mDelta*costheta*cosphi; double a24 = mDelta*costheta*sinphi; double a25 = mDelta*sintheta*cosphi; double a35 = -mDelta*sinphi; double a44 = mBeta*sinphi*sinphi + mITopZ*cosphi*cosphi + mIBottom; double avalues[25] = { mAlpha, 0, 0, a14, a15, 0, mAlpha, 0, a24, a25, 0, 0, mAlpha, 0, a35, a14, a24, 0, a44, 0, a15, a25, a35, 0, mGamma }; MatrixMxN Ainv = MatrixMxN(5,5,avalues).invert(); // compute f MatrixMxN FBezier = mBezierPatchGrid->compute(mX, mY); double f = FBezier[0][0]; double fx = FBezier[1][0]; double fy = FBezier[0][1]; // vectors q and N double nval[5] = { -fx, -fy, 1, 0, 0 }; VectorND N( 5, nval ); VectorND q = N; double xdotval[5] = { mXDot, mYDot, mZDot, mThetaDot, mPhiDot }; VectorND xdot( 5, xdotval ); VectorND ydot = xdot - Ainv * ( ( xdot.dot(N) / (Ainv*q).dot(N) ) * q ); mXDot = ydot[0]; mYDot = ydot[1]; mZDot = ydot[2]; mThetaDot = ydot[3]; mPhiDot = ydot[4]; mZ = f; }; void LagrangianRacer::resetState( const LagrangianRacer& templateRacer ) { mX = templateRacer.mX; mY = templateRacer.mY; mZ = templateRacer.mZ; mTheta = templateRacer.mTheta; mPhi = templateRacer.mPhi; mXDot = templateRacer.mXDot; mYDot = templateRacer.mYDot; mZDot = templateRacer.mZDot; mThetaDot = templateRacer.mThetaDot; mPhiDot = templateRacer.mPhiDot; } }
34.908316
142
0.722392
clauderichard
888dad20edcc4f53d38f434073758c9fbba5f948
3,302
cpp
C++
src/dxapi/native/tickdb/http/xml/validate_qql_request.cpp
noop-dev/TimeBaseClientCpp
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
[ "Apache-2.0" ]
null
null
null
src/dxapi/native/tickdb/http/xml/validate_qql_request.cpp
noop-dev/TimeBaseClientCpp
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
[ "Apache-2.0" ]
null
null
null
src/dxapi/native/tickdb/http/xml/validate_qql_request.cpp
noop-dev/TimeBaseClientCpp
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
[ "Apache-2.0" ]
2
2021-05-14T09:39:50.000Z
2022-03-24T23:42:41.000Z
/* * Copyright 2021 EPAM Systems, Inc * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 "tickdb/common.h" #include "validate_qql_request.h" using namespace std; using namespace tinyxml2; using namespace DxApiImpl; ValidateQqlRequest::ValidateQqlRequest(TickDbImpl &db, const std::string &qql) : XmlRequest(db, "validateQQL", false) { add("qql", qql); } using namespace XmlParse; template<> bool XmlParse::parse(QqlTokenType &type, const char * from) { return NULL == from ? false : (type = QqlTokenType(from), true); } template<> bool XmlParse::parse(QqlState::Range &range, const char * from) { return NULL == from ? false : parse(range.value, from); } static bool parse(QqlState::Token &token, XMLElement * element) { return parse(token.type, getText(element, "type")) && parse(token.location, getText(element, "location")); } bool ValidateQqlRequest::getState(QqlState &state) { state.tokens.reset(); state.errorLocation.value = -1; if (!executeAndParseResponse()) { return false; } XMLElement * rootElement = response_.root(); if (!nameEquals(rootElement, "validateQQLResponse")) { return false; } XMLElement * resultElement = rootElement->FirstChildElement("result"); if (NULL == resultElement) { DBGLOGERR((string*)NULL, "ERR: 'result' element not found!"); return false; } XMLElement * tokensElement = resultElement->FirstChildElement("tokens"); /*if (NULL == tokensElement) { DBGLOGERR((string*)NULL, "ERR: 'tokens' element not found!"); return false; }*/ auto errorLocationText = getText(resultElement, "errorLocation"); state.errorLocation.value = -1; if (NULL != errorLocationText && !parse(state.errorLocation, errorLocationText)) { DBGLOGERR((string*)NULL, "ERR: Unable to parse 'errorLocation' field!"); return false; } if (NULL != tokensElement) { std::vector<QqlState::Token> tokens; for (XMLElement * item = (XMLElement *)tokensElement; NULL != item; item = item->NextSiblingElement("tokens")) { QqlState::Token token; if (!parse(token, item)) { DBGLOGERR((string*)NULL, "ERR: Unable to parse qql state token!"); return false; } tokens.push_back(token); //tokens.push_back(QqlState::Token()); /*if (!parse(tokens[tokens.size() - 1], getText(item))) { DBGLOGERR((string*)NULL, "ERR: Unable to parse qql state token!"); return false; }*/ } state.tokens = tokens; } return true; }
29.221239
120
0.650515
noop-dev
888f003791b7375286b79eec304e33195f88bcca
1,567
cpp
C++
Src/renderer/loading_screen/LoadingScreen.cpp
Kataglyphis/GraphicEngine
f3b87a36b761fe13e747011be9301f6f9fe0c3f0
[ "BSD-3-Clause" ]
null
null
null
Src/renderer/loading_screen/LoadingScreen.cpp
Kataglyphis/GraphicEngine
f3b87a36b761fe13e747011be9301f6f9fe0c3f0
[ "BSD-3-Clause" ]
null
null
null
Src/renderer/loading_screen/LoadingScreen.cpp
Kataglyphis/GraphicEngine
f3b87a36b761fe13e747011be9301f6f9fe0c3f0
[ "BSD-3-Clause" ]
null
null
null
#include "LoadingScreen.h" #include <sstream> LoadingScreen::LoadingScreen() { create_shader_program(); } void LoadingScreen::init() { std::stringstream texture_base_dir; texture_base_dir << CMAKELISTS_DIR; texture_base_dir << "/Resources/Textures/"; std::stringstream texture_loading_screen; texture_loading_screen << texture_base_dir.str() << "Loading_Screen/ukraine.jpg"; loading_screen_tex = Texture( texture_loading_screen.str().c_str(), std::make_shared<RepeatMode>()); loading_screen_tex.load_texture_without_alpha_channel(); std::stringstream texture_logo; texture_logo << texture_base_dir.str() << "Loading_Screen/Engine_logo.png"; logo_tex = Texture(texture_logo.str().c_str(), std::make_shared<RepeatMode>()); logo_tex.load_texture_with_alpha_channel(); } void LoadingScreen::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); loading_screen_tex.use_texture(0); loading_screen_shader_program->use_shader_program(); loading_screen_quad.render(); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void LoadingScreen::create_shader_program() { loading_screen_shader_program = std::make_shared<ShaderProgram>(ShaderProgram{}); loading_screen_shader_program->create_from_files( "loading_screen/loading_screen.vert", "loading_screen/loading_screen.frag"); } LoadingScreen::~LoadingScreen() { }
25.274194
94
0.675814
Kataglyphis
8893078ef61860196278182425ba76a2a3bd387f
566
cpp
C++
examples/backend/asymmetric_coroutine.cpp
Manu343726/coroutine
dbf7ed9ef161351535ea835ccb0ed80bf6a3c5a9
[ "MIT" ]
12
2017-09-14T04:09:35.000Z
2020-03-22T01:39:31.000Z
examples/backend/asymmetric_coroutine.cpp
Manu343726/coroutine
dbf7ed9ef161351535ea835ccb0ed80bf6a3c5a9
[ "MIT" ]
null
null
null
examples/backend/asymmetric_coroutine.cpp
Manu343726/coroutine
dbf7ed9ef161351535ea835ccb0ed80bf6a3c5a9
[ "MIT" ]
4
2017-09-17T08:04:13.000Z
2020-05-16T12:35:31.000Z
#include <coroutine/backend/asymmetric_coroutine.hpp> #include <iostream> using pull_t = coro::back::asymmetric_coroutine::pull_type<int>; using push_t = coro::back::asymmetric_coroutine::push_type<int>; int main() { pull_t source{[&](push_t& sink) { for(int i = 0; i < 3; ++i) { std::cout << "source " << i << "\n"; sink(i); } std::cout << "end of source\n"; }}; for(int i : source) { std::cout << "main thread " << i << "\n"; } std::cout << "end of main thread\n"; }
20.962963
64
0.524735
Manu343726
88941a2351f5a90aab7045ed95a69a096fd3c8be
9,866
cxx
C++
MUON/MUONmapping/AliMpBusPatch.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
MUON/MUONmapping/AliMpBusPatch.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
MUON/MUONmapping/AliMpBusPatch.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // $MpId: AliMpBusPatch.cxx,v 1.4 2006/05/24 13:58:34 ivana Exp $ //----------------------------------------------------------------------------- // Class AliMpBusPatch // -------------------- // The class defines the properties of BusPatch // Author: Ivana Hrivnacova, IPN Orsay //----------------------------------------------------------------------------- #include "AliMpBusPatch.h" #include "AliDAQ.h" #include "AliMpConstants.h" #include "AliMpDEManager.h" #include "AliMpSegmentation.h" #include "AliMpSlat.h" #include "AliMpPCB.h" #include "AliMpMotifPosition.h" #include "AliLog.h" #include <Riostream.h> using std::cout; using std::endl; /// \cond CLASSIMP ClassImp(AliMpBusPatch) /// \endcond const Int_t AliMpBusPatch::fgkOffset = 100; // // static methods // //____________________________________________________________________ Int_t AliMpBusPatch::GetGlobalBusID(Int_t localID, Int_t ddlID) { /// return global bus id from local bus and ddl id return ddlID*fgkOffset + localID; } //____________________________________________________________________ Int_t AliMpBusPatch::GetLocalBusID(Int_t globalID, Int_t ddlID) { /// return local bus id from local bus id return globalID - ddlID*fgkOffset; } //______________________________________________________________________________ AliMpBusPatch::AliMpBusPatch(Int_t id, Int_t detElemId, Int_t ddlId) : TObject(), fId(id), fDEId(detElemId), fDdlId(ddlId), fManus(false), fNofManusPerModule(false), fCableLength(-1), fCableLabel(), fTranslatorLabel(), fFrtId(0) { /// Standard constructor } //______________________________________________________________________________ AliMpBusPatch::AliMpBusPatch(TRootIOCtor* /*ioCtor*/) : TObject(), fId(), fDEId(), fDdlId(), fManus(false), fNofManusPerModule(false), fCableLength(-1), fCableLabel(), fTranslatorLabel(), fFrtId(0) { /// Root IO constructor } //______________________________________________________________________________ AliMpBusPatch::~AliMpBusPatch() { /// Destructor } // // public methods // //______________________________________________________________________________ Bool_t AliMpBusPatch::AddManu(Int_t manuId) { /// Add detection element with given detElemId. /// Return true if the detection element was added if ( HasManu(manuId) ) { AliWarningStream() << "Manu with manuId=" << manuId << " already present." << endl; return false; } fManus.Add(manuId); return true; } //______________________________________________________________________________ Bool_t AliMpBusPatch::SetNofManusPerModule(Int_t manuNumber) { /// Set the number of manus per patch module (PCB): /// - for stations 1 all manus are connected to one PCB, /// - for stations 2 there maximum two PCBs per buspatch, /// - for slat stations there are maximum three PCBs per buspatch if ( AliMpDEManager::GetStation12Type(fDEId) == AliMq::kStation1) { // simply fill the number of manus, no bridge for station 1 fNofManusPerModule.Add(GetNofManus()); return true; } if ( AliMpDEManager::GetStation12Type(fDEId) == AliMq::kStation2) { // there is max two patch modules per buspatch fNofManusPerModule.Add(manuNumber); if (manuNumber != GetNofManus()) fNofManusPerModule.Add(GetNofManus() - manuNumber); return true; } if ( AliMpDEManager::GetStationType(fDEId) == AliMp::kStation345 ) { const AliMpSlat* kSlat0 = AliMpSegmentation::Instance()->GetSlat(fDEId, AliMp::kCath0); const AliMpSlat* kSlat1 = AliMpSegmentation::Instance()->GetSlat(fDEId, AliMp::kCath1); Int_t iPcb = 0; Int_t iPcbPrev = -1; Int_t manuPerPcb = 0; Double_t x = 0.; Double_t length = 0.; // Loop over manu for (Int_t iManu = 0; iManu < GetNofManus(); ++iManu) { Int_t manuId = GetManuId(iManu); AliMpMotifPosition* motifPos0 = kSlat0->FindMotifPosition(manuId); AliMpMotifPosition* motifPos1 = kSlat1->FindMotifPosition(manuId); if ( !motifPos0 && !motifPos1 ) { // should never happen AliErrorStream() << "Motif position for manuId = " << manuId << "not found" << endl; return false; } // find PCB id if ( motifPos0 ) { x = motifPos0->GetPositionX(); length = kSlat0->GetPCB(0)->DX()*2.; } if ( motifPos1 ) { x = motifPos1->GetPositionX(); length = kSlat1->GetPCB(0)->DX()*2.; } iPcb = Int_t(x/length + AliMpConstants::LengthTolerance()); // check when going to next PCB if ( iPcb == iPcbPrev ) manuPerPcb++; else if ( iPcbPrev != -1 ) { //vec.Set(vec.GetSize()+1); //vec[vec.GetSize()-1] = manuPerPcb+1; fNofManusPerModule.Add(manuPerPcb+1); manuPerPcb = 0; } iPcbPrev = iPcb; } // store last PCB //vec.Set(vec.GetSize()+1); //vec[vec.GetSize()-1] = manuPerPcb+1; fNofManusPerModule.Add(manuPerPcb+1); return true; } return false; } //______________________________________________________________________________ void AliMpBusPatch::RevertReadout() { /// Revert order of manus fManus.Revert(); } //______________________________________________________________________________ void AliMpBusPatch::ResetReadout() { /// Revert order of manus fManus.Reset(); } //______________________________________________________________________________ Int_t AliMpBusPatch::GetNofManus() const { /// Return the number of detection elements connected to this DDL return fManus.GetSize(); } //______________________________________________________________________________ Int_t AliMpBusPatch::GetManuId(Int_t index) const { /// Return the detection element by index (in loop) return fManus.GetValue(index); } //______________________________________________________________________________ Bool_t AliMpBusPatch::HasManu(Int_t manuId) const { /// Return true if bus patch has manu with given manuId return fManus.HasValue(manuId); } //______________________________________________________________________________ Int_t AliMpBusPatch::GetNofPatchModules() const { /// Return the number of patch modules (PCB) connected to this bus patch. return fNofManusPerModule.GetSize(); } //______________________________________________________________________________ TString AliMpBusPatch::GetFRTPosition() const { /// Return CRXX-Y-Z where XX is the Crocus number, Y the FRT number /// and Z the local bus patch number. return Form("CR%2d-%d-%d",fDdlId,fFrtId+1,GetLocalBusID(fId,fDdlId)); } //______________________________________________________________________________ Int_t AliMpBusPatch::GetNofManusPerModule(Int_t patchModule) const { /// Return the number of manus per patch module (PCB) if ( patchModule < 0 || patchModule >= GetNofPatchModules() ) { AliErrorStream() << "Invalid patch module number = " << patchModule << endl; return 0; } return fNofManusPerModule.GetValue(patchModule); } //______________________________________________________________________________ void AliMpBusPatch::Print(Option_t* opt) const { /// Printout cout << Form("BusPatch %04d DDL %d : %s <> %s / %s", fId, AliDAQ::DdlID("MUONTRK",fDdlId), GetFRTPosition().Data(), fCableLabel.Data(), fTranslatorLabel.Data()) << endl; TString sopt(opt); sopt.ToUpper(); if ( sopt.Contains("FULL") ) { cout << Form("Nof of PCBs (i.e. patch modules) = %d",fNofManusPerModule.GetSize()) << endl; for ( Int_t i = 0; i < fNofManusPerModule.GetSize(); ++i ) { cout << Form("\t\t %d manus in patch module %d",fNofManusPerModule.GetValue(i),i) << endl; } if ( sopt.Contains("MANU") ) { cout << "Manus of that buspatch=" << endl; for ( Int_t i = 0; i < fManus.GetSize(); ++i ) { cout << Form("%4d,",fManus.GetValue(i)); } cout << endl; } } // Int_t fId; ///< Identifier (unique) // Int_t fDEId; ///< Detection element to which this bus patch is connected // Int_t fDdlId; ///< DDL to which this bus patch is connected // AliMpArrayI fManus; ///< Manu Ids connected to this bus patch // AliMpArrayI fNofManusPerModule; ///< Nof Manus per patch modules (PCBs) // Float_t fCableLength; ///< length of the buspatch cable // TString fCableLabel; ///< label of the buspatch cable // TString fTranslatorLabel; ///< label of the translator board // Int_t fFrtId; ///< FRT Ids connected to this bus patch }
29.538922
96
0.647476
AllaMaevskaya
889b7fa955d64191cebb708ce71eafc6590b632f
231
hpp
C++
include/toy/gadget/IntToChar.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
4
2017-07-06T22:18:41.000Z
2021-05-24T21:28:37.000Z
include/toy/gadget/IntToChar.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
null
null
null
include/toy/gadget/IntToChar.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
1
2020-08-02T13:00:38.000Z
2020-08-02T13:00:38.000Z
#pragma once #include "toy/Standard.hpp" #include "toy/gadget/Export.hpp" namespace toy{ namespace gadget{ // 1 -> '1' // 2 -> '2' // 9 -> '9' // 10 -> [error] // -1 -> [error] TOY_API_GADGET extern char IntToChar(int); }}
12.833333
42
0.597403
ToyAuthor
889c204f9d2ff5d0b16913fd99d5fd47c7c33159
975
cpp
C++
tests/cpp/Units.cpp
aTrotier/sycomore
32e438d3a90ca0a9d051bb6acff461e06079116d
[ "MIT" ]
14
2019-11-06T09:23:09.000Z
2022-01-11T19:08:36.000Z
tests/cpp/Units.cpp
aTrotier/sycomore
32e438d3a90ca0a9d051bb6acff461e06079116d
[ "MIT" ]
2
2020-12-01T15:48:27.000Z
2020-12-04T15:19:37.000Z
tests/cpp/Units.cpp
aTrotier/sycomore
32e438d3a90ca0a9d051bb6acff461e06079116d
[ "MIT" ]
2
2020-08-12T04:36:36.000Z
2021-05-27T13:17:34.000Z
#define BOOST_TEST_MODULE Units #include <boost/test/unit_test.hpp> #include "sycomore/units.h" BOOST_AUTO_TEST_CASE(BasicLiteral) { using namespace sycomore::units; sycomore::Quantity const length = 100_cm; BOOST_TEST(length.magnitude == 1.); BOOST_TEST(length.dimensions == sycomore::Length); } BOOST_AUTO_TEST_CASE(DefinedBasicUnit) { using namespace sycomore::units; sycomore::Quantity const length = 100*cm; BOOST_TEST(length.magnitude == 1.); BOOST_TEST(length.dimensions == sycomore::Length); } BOOST_AUTO_TEST_CASE(DerivedLiteral) { using namespace sycomore::units; sycomore::Quantity const force = 1_N; BOOST_TEST(force.magnitude == 1.); BOOST_TEST(force.dimensions == sycomore::Force); } BOOST_AUTO_TEST_CASE(DefinedDerivedUnit) { using namespace sycomore::units; sycomore::Quantity const force = 1*kN; BOOST_TEST(force.magnitude == 1000.); BOOST_TEST(force.dimensions == sycomore::Force); }
23.780488
54
0.727179
aTrotier
889c45242a1cd2c573d08386e06c9a181851cb3f
454
cpp
C++
final/pointers/pointers_to_functions.cpp
coderica/effective_cpp
456d30cf42c6c71dc7187d88e362651dd79ac3fe
[ "MIT" ]
null
null
null
final/pointers/pointers_to_functions.cpp
coderica/effective_cpp
456d30cf42c6c71dc7187d88e362651dd79ac3fe
[ "MIT" ]
null
null
null
final/pointers/pointers_to_functions.cpp
coderica/effective_cpp
456d30cf42c6c71dc7187d88e362651dd79ac3fe
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int addThem(int, int); int subtractThem(int, int); int main() { int addResult, subResult; int (*opPtr)(int, int); opPtr = addThem; addResult = opPtr(3, 2); opPtr = subtractThem; subResult = opPtr(3, 2); cout << "Adding: " << addResult << " Subtracting: " << subResult << endl; } int addThem(int a, int b) { return a + b; } int subtractThem(int a, int b) { return a - b; }
16.214286
75
0.599119
coderica
889c8b9fa38c3010c71d1e2b7426666342bb5772
571
hpp
C++
src/Main/buildLIZandCommLists.hpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
1
2022-01-27T14:45:51.000Z
2022-01-27T14:45:51.000Z
src/Main/buildLIZandCommLists.hpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
3
2021-09-14T01:30:26.000Z
2021-09-25T14:05:10.000Z
src/Main/buildLIZandCommLists.hpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
1
2022-01-03T18:16:26.000Z
2022-01-03T18:16:26.000Z
#ifndef LSMS_BUILDLIZANDCOMMLISTS_HPP #define LSMS_BUILDLIZANDCOMMLISTS_HPP #include "Real.hpp" #include "SystemParameters.hpp" #include "SingleSite/AtomData.hpp" #include "Communication/LSMSCommunication.hpp" class LIZInfoType { public: int idx; Real p1, p2, p3; Real dSqr; }; class NodeIdxInfo { public: int node, localIdx, globalIdx; }; void buildLIZandCommLists(LSMSCommunication &comm, LSMSSystemParameters &lsms, CrystalParameters &crystal, LocalTypeInfo &local); #endif
19.033333
53
0.676007
pmu2022
889e2e4d0c63113975d8ec6fb0621891e6e0b794
3,470
cpp
C++
PGTests/PGTests/GeometryTests.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
2
2018-01-14T17:47:22.000Z
2021-11-15T10:34:24.000Z
PGTests/PGTests/GeometryTests.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
23
2017-07-31T19:43:00.000Z
2018-11-11T18:51:28.000Z
PGTests/PGTests/GeometryTests.cpp
mcdreamer/PG
a047615d9eae7f2229a203a262f239106cf7f39c
[ "MIT" ]
null
null
null
#include "GeometryTests.h" #include "gtest/gtest.h" #include "PG/core/RectUtils.h" #include "PG/core/Rect.h" #include "PG/core/Point.h" #include "PG/entities/TilePositionCalculator.h" #include "PG/app/GameConstants.h" using namespace PG; //-------------------------------------------------------- TEST(GeometryTests,testTilePositionCalculator) { TilePositionCalculator tpc; EXPECT_EQ(2, GameConstants::tileSize()); EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(0, 0))); EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(0.5, 0.5))); EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(1, 1))); EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(1.5, 1.5))); EXPECT_EQ(TileCoord(1, 1), tpc.calculateTileCoord(Point(2, 2))); EXPECT_EQ(Point(1, 1), tpc.calculatePoint(TileCoord(0, 0))); EXPECT_EQ(Point(3, 1), tpc.calculatePoint(TileCoord(1, 0))); EXPECT_EQ(Point(1, 3), tpc.calculatePoint(TileCoord(0, 1))); EXPECT_EQ(Point(3, 3), tpc.calculatePoint(TileCoord(1, 1))); } //-------------------------------------------------------- TEST(GeometryTests,testPGRectUtils_ContainsPoint) { const Rect rect(Point(100, 100), Size(50, 50)); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(100, 100))); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(80, 100))); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(100, 80))); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(80, 80))); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(100, 120))); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(120, 100))); EXPECT_TRUE(RectUtils::containsPoint(rect, Point(120, 120))); EXPECT_FALSE(RectUtils::containsPoint(rect, Point(70, 70))); EXPECT_FALSE(RectUtils::containsPoint(rect, Point(130, 130))); } //-------------------------------------------------------- TEST(GeometryTests,testPGRectUtils_CombineRects) { { const auto r = RectUtils::combineRects(Rect(Point(100, 100), Size(50, 50)), Rect(Point(100, 100), Size(50, 50))); EXPECT_EQ(Rect(Point(100, 100), Size(50, 50)), r); } { const auto r = RectUtils::combineRects(Rect(Point(100, 100), Size(50, 100)), Rect(Point(100, 100), Size(50, 50))); EXPECT_EQ(Rect(Point(100, 100), Size(50, 100)), r); } { const auto r = RectUtils::combineRects(Rect(Point(0, 0), Size(50, 50)), Rect(Point(100, 100), Size(50, 50))); EXPECT_EQ(Rect(Point(50, 50), Size(150, 150)), r); } } //-------------------------------------------------------- TEST(GeometryTests,testPGRectUtils_isEmpty) { EXPECT_TRUE(RectUtils::isEmpty(Rect(Point(100, 100), Size(0, 0)))); EXPECT_TRUE(RectUtils::isEmpty(Rect(Point(100, 100), Size(10, 0)))); EXPECT_TRUE(RectUtils::isEmpty(Rect(Point(100, 100), Size(0, 10)))); EXPECT_FALSE(RectUtils::isEmpty(Rect(Point(100, 100), Size(10, 10)))); } //-------------------------------------------------------- TEST(GeometryTests,testPGRectUtils_getIntersection) { const Rect rect(Point(100, 100), Size(50, 50)); { const auto i = RectUtils::getIntersection(rect, Rect(Point(100, 49), Size(50, 50))); EXPECT_TRUE(RectUtils::isEmpty(i)); } { const auto i = RectUtils::getIntersection(rect, Rect(Point(100, 50), Size(50, 50))); EXPECT_TRUE(RectUtils::isEmpty(i)); } }
36.526316
86
0.597118
mcdreamer
889f20fedc4efa743b4474b7d965cae1db87239c
2,385
hpp
C++
include/esp32_simple_ota.hpp
willson556/esp32-https-ota
9ecb2e8cbde06e89771445a91f5e5a7c787875a6
[ "MIT" ]
1
2020-03-17T01:59:58.000Z
2020-03-17T01:59:58.000Z
include/esp32_simple_ota.hpp
willson556/esp32-simple-ota
9ecb2e8cbde06e89771445a91f5e5a7c787875a6
[ "MIT" ]
null
null
null
include/esp32_simple_ota.hpp
willson556/esp32-simple-ota
9ecb2e8cbde06e89771445a91f5e5a7c787875a6
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <thread> namespace esp32_simple_ota { /** * @brief The OTA manager periodically checks for updates. * * @details If the version number of the installed app doesn't * match the version in the feed, the app from the feed will * be downloaded and installed. * * The ESP32 `pthreads` library is used for the update task. If * you experience a stack overflow, try increasing the default * stack size in the sdkconfig. * */ class OTAManager { public: /** * @brief Construct a new OTAManager object. * * @param feed_url URL to the JSON feed. * @param installed_version Currently installed version of your app. * @param updateCheckInterval Interval, in seconds, between update checks. * @param preUpdateCallback Function to call before performing an update. Use this to save data if required. * @param safeToUpdateCallback Function to call to see if it's an acceptable time to perform an update. * Return true if it is. Return false to cancel the update. */ OTAManager(const char *feed_url, const char *installed_version, unsigned updateCheckInterval, std::function<void()> preUpdateCallback = nullptr, std::function<bool()> safeToUpdateCallback = nullptr) : feed_url{feed_url}, installed_version{installed_version}, updateCheckInterval{updateCheckInterval}, preUpdateCallback{preUpdateCallback}, safeToUpdateCallback{safeToUpdateCallback} { } /** * @brief Begin periodically checking for updates. * * @details This function should be called once a network connection has been established. */ void launchTask() { thread = std::thread([this]{ thread_func(); }); thread.detach(); } ~OTAManager() { thread_running = false; thread.join(); } private: const char *feed_url; const char *installed_version; const unsigned updateCheckInterval; const std::function<void()> preUpdateCallback; const std::function<bool()> safeToUpdateCallback; std::thread thread; void thread_func(); volatile bool thread_running{true}; bool update_available(char* url, size_t url_buffer_size); void install_update(const char *url); }; } // namespace esp32_simple_ota
30.974026
112
0.67673
willson556
88a8e8c0a917c63a5bbc9709faca4b4637b9e4b1
26,514
cpp
C++
samsung/hardware/exynos3/s5pc110/libhwcomposer/SecHWC.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
null
null
null
samsung/hardware/exynos3/s5pc110/libhwcomposer/SecHWC.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
null
null
null
samsung/hardware/exynos3/s5pc110/libhwcomposer/SecHWC.cpp
DrDoubt/android_device_samsung_universal9810-common-1
5a937d2994044c041c3c19192d7744200a036cc8
[ "Apache-2.0" ]
2
2021-07-04T19:41:36.000Z
2021-07-29T12:59:47.000Z
/* * Copyright (C) 2010 The Android Open Source Project * * 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. */ /* * * @author Rama, Meka(v.meka@samsung.com) Sangwoo, Park(sw5771.park@samsung.com) Jamie Oh (jung-min.oh@samsung.com) * @date 2011-07-28 * */ #define HWC_REMOVE_DEPRECATED_VERSIONS 1 #include <sys/resource.h> #include <cutils/log.h> #include <cutils/atomic.h> #include <EGL/egl.h> #include <GLES/gl.h> #include <hardware_legacy/uevent.h> #include "SecHWCUtils.h" static IMG_gralloc_module_public_t *gpsGrallocModule; static int hwc_device_open(const struct hw_module_t* module, const char* name, struct hw_device_t** device); static struct hw_module_methods_t hwc_module_methods = { open: hwc_device_open }; hwc_module_t HAL_MODULE_INFO_SYM = { common: { tag: HARDWARE_MODULE_TAG, module_api_version: HWC_MODULE_API_VERSION_0_1, hal_api_version: HARDWARE_HAL_API_VERSION, id: HWC_HARDWARE_MODULE_ID, name: "Samsung S5PC11X hwcomposer module", author: "SAMSUNG", methods: &hwc_module_methods, } }; static void dump_layer(hwc_layer_1_t const* l) { ALOGD("\ttype=%d, flags=%08x, handle=%p, tr=%02x, blend=%04x, {%d,%d,%d,%d}, {%d,%d,%d,%d}", l->compositionType, l->flags, l->handle, l->transform, l->blending, l->sourceCrop.left, l->sourceCrop.top, l->sourceCrop.right, l->sourceCrop.bottom, l->displayFrame.left, l->displayFrame.top, l->displayFrame.right, l->displayFrame.bottom); } static int set_src_dst_info(hwc_layer_1_t *cur, struct hwc_win_info_t *win, struct sec_img *src_img, struct sec_img *dst_img, struct sec_rect *src_rect, struct sec_rect *dst_rect, int win_idx) { IMG_native_handle_t *prev_handle = (IMG_native_handle_t *)(cur->handle); // set src image src_img->w = prev_handle->iWidth; src_img->h = prev_handle->iHeight; src_img->format = prev_handle->iFormat; src_img->base = 0; src_img->offset = 0; src_img->mem_id = 0; src_img->mem_type = HWC_PHYS_MEM_TYPE; src_img->w = (src_img->w + 15) & (~15); src_img->h = (src_img->h + 1) & (~1) ; //set src rect src_rect->x = SEC_MAX(cur->sourceCrop.left, 0); src_rect->y = SEC_MAX(cur->sourceCrop.top, 0); src_rect->w = SEC_MAX(cur->sourceCrop.right - cur->sourceCrop.left, 0); src_rect->w = SEC_MIN(src_rect->w, src_img->w - src_rect->x); src_rect->h = SEC_MAX(cur->sourceCrop.bottom - cur->sourceCrop.top, 0); src_rect->h = SEC_MIN(src_rect->h, src_img->h - src_rect->y); //set dst image dst_img->w = win->lcd_info.xres; dst_img->h = win->lcd_info.yres; switch (win->lcd_info.bits_per_pixel) { case 32: dst_img->format = HAL_PIXEL_FORMAT_RGBX_8888; break; default: dst_img->format = HAL_PIXEL_FORMAT_RGB_565; break; } dst_img->base = win->addr[win->buf_index]; dst_img->offset = 0; dst_img->mem_id = 0; dst_img->mem_type = HWC_PHYS_MEM_TYPE; //set dst rect //fimc dst image will be stored from left top corner dst_rect->x = 0; dst_rect->y = 0; dst_rect->w = win->rect_info.w; dst_rect->h = win->rect_info.h; ALOGV("%s::sr_x %d sr_y %d sr_w %d sr_h %d dr_x %d dr_y %d dr_w %d dr_h %d ", __func__, src_rect->x, src_rect->y, src_rect->w, src_rect->h, dst_rect->x, dst_rect->y, dst_rect->w, dst_rect->h); return 0; } static int get_hwc_compos_decision(hwc_layer_1_t* cur) { if(cur->flags & HWC_SKIP_LAYER || !cur->handle) { ALOGV("%s::is_skip_layer %d cur->handle %x", __func__, cur->flags & HWC_SKIP_LAYER, (uint32_t)cur->handle); return HWC_FRAMEBUFFER; } IMG_native_handle_t *prev_handle = (IMG_native_handle_t *)(cur->handle); int compositionType = HWC_FRAMEBUFFER; /* check here....if we have any resolution constraints */ if (((cur->sourceCrop.right - cur->sourceCrop.left) < 16) || ((cur->sourceCrop.bottom - cur->sourceCrop.top) < 8)) return compositionType; if ((cur->transform == HAL_TRANSFORM_ROT_90) || (cur->transform == HAL_TRANSFORM_ROT_270)) { if(((cur->displayFrame.right - cur->displayFrame.left) < 4)|| ((cur->displayFrame.bottom - cur->displayFrame.top) < 8)) return compositionType; } else if (((cur->displayFrame.right - cur->displayFrame.left) < 8) || ((cur->displayFrame.bottom - cur->displayFrame.top) < 4)) return compositionType; if((prev_handle->usage & GRALLOC_USAGE_PHYS_CONTIG) && (cur->blending == HWC_BLENDING_NONE)) compositionType = HWC_OVERLAY; else compositionType = HWC_FRAMEBUFFER; ALOGV("%s::compositionType %d bpp %d format %x usage %x", __func__,compositionType, prev_handle->uiBpp, prev_handle->iFormat, prev_handle->usage & GRALLOC_USAGE_PHYS_CONTIG); return compositionType; } static int assign_overlay_window(struct hwc_context_t *ctx, hwc_layer_1_t *cur, int win_idx, int layer_idx) { struct hwc_win_info_t *win; sec_rect rect; int ret = 0; if(NUM_OF_WIN <= win_idx) return -1; win = &ctx->win[win_idx]; rect.x = SEC_MAX(cur->displayFrame.left, 0); rect.y = SEC_MAX(cur->displayFrame.top, 0); rect.w = SEC_MIN(cur->displayFrame.right - rect.x, win->lcd_info.xres - rect.x); rect.h = SEC_MIN(cur->displayFrame.bottom - rect.y, win->lcd_info.yres - rect.y); win->set_win_flag = 0; if((rect.x != win->rect_info.x) || (rect.y != win->rect_info.y) || (rect.w != win->rect_info.w) || (rect.h != win->rect_info.h)){ win->rect_info.x = rect.x; win->rect_info.y = rect.y; win->rect_info.w = rect.w; win->rect_info.h = rect.h; win->set_win_flag = 1; win->layer_prev_buf = 0; } win->layer_index = layer_idx; win->status = HWC_WIN_RESERVED; ALOGV("%s:: win_x %d win_y %d win_w %d win_h %d lay_idx %d win_idx %d", __func__, win->rect_info.x, win->rect_info.y, win->rect_info.w, win->rect_info.h, win->layer_index, win_idx ); return 0; } static void reset_win_rect_info(hwc_win_info_t *win) { win->rect_info.x = 0; win->rect_info.y = 0; win->rect_info.w = 0; win->rect_info.h = 0; return; } static int hwc_prepare(hwc_composer_device_1_t *dev, size_t numDisplays, hwc_display_contents_1_t** displays) { struct hwc_context_t* ctx = (struct hwc_context_t*)dev; int overlay_win_cnt = 0; int compositionType = 0; int ret; // Compat hwc_display_contents_1_t* list = NULL; if (numDisplays > 0) { list = displays[0]; } //if geometry is not changed, there is no need to do any work here if( !list || (!(list->flags & HWC_GEOMETRY_CHANGED))) return 0; //all the windows are free here.... for (int i = 0; i < NUM_OF_WIN; i++) { ctx->win[i].status = HWC_WIN_FREE; ctx->win[i].buf_index = 0; } ctx->num_of_hwc_layer = 0; ctx->num_of_fb_layer = 0; ALOGV("%s:: hwc_prepare list->numHwLayers %d", __func__, list->numHwLayers); for (int i = 0; i < list->numHwLayers ; i++) { hwc_layer_1_t* cur = &list->hwLayers[i]; if (overlay_win_cnt < NUM_OF_WIN) { compositionType = get_hwc_compos_decision(cur); if (compositionType == HWC_FRAMEBUFFER) { cur->compositionType = HWC_FRAMEBUFFER; ctx->num_of_fb_layer++; } else { ret = assign_overlay_window(ctx, cur, overlay_win_cnt, i); if (ret != 0) { cur->compositionType = HWC_FRAMEBUFFER; ctx->num_of_fb_layer++; continue; } cur->compositionType = HWC_OVERLAY; cur->hints = HWC_HINT_CLEAR_FB; overlay_win_cnt++; ctx->num_of_hwc_layer++; } } else { cur->compositionType = HWC_FRAMEBUFFER; ctx->num_of_fb_layer++; } } if(list->numHwLayers != (ctx->num_of_fb_layer + ctx->num_of_hwc_layer)) ALOGV("%s:: numHwLayers %d num_of_fb_layer %d num_of_hwc_layer %d ", __func__, list->numHwLayers, ctx->num_of_fb_layer, ctx->num_of_hwc_layer); if (overlay_win_cnt < NUM_OF_WIN) { //turn off the free windows for (int i = overlay_win_cnt; i < NUM_OF_WIN; i++) { window_hide(&ctx->win[i]); reset_win_rect_info(&ctx->win[i]); } } return 0; } static int hwc_set(hwc_composer_device_1_t *dev, size_t numDisplays, hwc_display_contents_1_t** displays) { struct hwc_context_t *ctx = (struct hwc_context_t *)dev; unsigned int phyAddr[MAX_NUM_PLANES]; int skipped_window_mask = 0; hwc_layer_1_t* cur; struct hwc_win_info_t *win; int ret; struct sec_img src_img; struct sec_img dst_img; struct sec_rect src_rect; struct sec_rect dst_rect; // Only support one display hwc_display_t dpy = displays[0]->dpy; hwc_surface_t sur = displays[0]->sur; hwc_display_contents_1_t* list = displays[0]; if (dpy == NULL && sur == NULL && list == NULL) { // release our resources, the screen is turning off // in our case, there is nothing to do. ctx->num_of_fb_layer_prev = 0; return 0; } bool need_swap_buffers = ctx->num_of_fb_layer > 0; /* * H/W composer documentation states: * There is an implicit layer containing opaque black * pixels behind all the layers in the list. * It is the responsibility of the hwcomposer module to make * sure black pixels are output (or blended from). * * Since we're using a blitter, we need to erase the frame-buffer when * switching to all-overlay mode. * */ if (ctx->num_of_hwc_layer && ctx->num_of_fb_layer==0 && ctx->num_of_fb_layer_prev) { /* we're clearing the screen using GLES here, this is very * hack-ish, ideal we would use the fimc (if it can do it) */ glDisable(GL_SCISSOR_TEST); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_SCISSOR_TEST); need_swap_buffers = true; } ctx->num_of_fb_layer_prev = ctx->num_of_fb_layer; if (need_swap_buffers || !list) { EGLBoolean sucess = eglSwapBuffers((EGLDisplay)dpy, (EGLSurface)sur); if (!sucess) { return HWC_EGL_ERROR; } } if (!list) { /* turn off the all windows */ for (int i = 0; i < NUM_OF_WIN; i++) { window_hide(&ctx->win[i]); reset_win_rect_info(&ctx->win[i]); ctx->win[i].status = HWC_WIN_FREE; } ctx->num_of_hwc_layer = 0; return 0; } if(ctx->num_of_hwc_layer > NUM_OF_WIN) ctx->num_of_hwc_layer = NUM_OF_WIN; /* compose hardware layers here */ for (uint32_t i = 0; i < ctx->num_of_hwc_layer; i++) { win = &ctx->win[i]; if (win->status == HWC_WIN_RESERVED) { cur = &list->hwLayers[win->layer_index]; if (cur->compositionType == HWC_OVERLAY) { ret = gpsGrallocModule->GetPhyAddrs(gpsGrallocModule, cur->handle, phyAddr); if (ret) { ALOGE("%s::GetPhyAddrs fail : ret=%d\n", __func__, ret); skipped_window_mask |= (1 << i); continue; } /* initialize the src & dist context for fimc */ set_src_dst_info (cur, win, &src_img, &dst_img, &src_rect, &dst_rect, i); ret = runFimc(ctx, &src_img, &src_rect, &dst_img, &dst_rect, phyAddr, cur->transform); if (ret < 0){ ALOGE("%s::runFimc fail : ret=%d\n", __func__, ret); skipped_window_mask |= (1 << i); continue; } if (win->set_win_flag == 1) { /* turnoff the window and set the window position with new conf... */ if (window_set_pos(win) < 0) { ALOGE("%s::window_set_pos is failed : %s", __func__, strerror(errno)); skipped_window_mask |= (1 << i); continue; } win->set_win_flag = 0; } /* is the frame didn't change, it needs to be composited * because something else below it could have changed, however * it doesn't need to be swapped. */ if (win->layer_prev_buf != (uint32_t)cur->handle) { win->layer_prev_buf = (uint32_t)cur->handle; window_pan_display(win); win->buf_index = (win->buf_index + 1) % NUM_OF_WIN_BUF; } if(win->power_state == 0) window_show(win); } else { ALOGE("%s:: error : layer %d compositionType should have been \ HWC_OVERLAY", __func__, win->layer_index); skipped_window_mask |= (1 << i); continue; } } else { ALOGE("%s:: error : window status should have been HWC_WIN_RESERVED \ by now... ", __func__); skipped_window_mask |= (1 << i); continue; } } if (skipped_window_mask) { //turn off the free windows for (int i = 0; i < NUM_OF_WIN; i++) { if (skipped_window_mask & (1 << i)) window_hide(&ctx->win[i]); } } #if defined(BOARD_USES_HDMI) hdmi_device_t* hdmi = ctx->hdmi; if (ctx->num_of_hwc_layer == 1 && hdmi) { if ((src_img.format == HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED)|| (src_img.format == HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP)) { ADDRS * addr = (ADDRS *)(src_img.base); hdmi->blit(hdmi, src_img.w, src_img.h, src_img.format, (unsigned int)addr->addr_y, (unsigned int)addr->addr_cbcr, (unsigned int)addr->addr_cbcr, 0, 0, HDMI_MODE_VIDEO, ctx->num_of_hwc_layer); } else if ((src_img.format == HAL_PIXEL_FORMAT_YCbCr_420_SP) || (src_img.format == HAL_PIXEL_FORMAT_YCrCb_420_SP) || (src_img.format == HAL_PIXEL_FORMAT_YCbCr_420_P) || (src_img.format == HAL_PIXEL_FORMAT_YV12)) { hdmi->blit(hdmi, src_img.w, src_img.h, src_img.format, (unsigned int)ctx->fimc.params.src.buf_addr_phy_rgb_y, (unsigned int)ctx->fimc.params.src.buf_addr_phy_cb, (unsigned int)ctx->fimc.params.src.buf_addr_phy_cr, 0, 0, HDMI_MODE_VIDEO, ctx->num_of_hwc_layer); } else { ALOGE("%s: Unsupported format = %d for hdmi", __func__, src_img.format); } } #endif return 0; } static void hwc_registerProcs(struct hwc_composer_device_1* dev, hwc_procs_t const* procs) { struct hwc_context_t* ctx = (struct hwc_context_t*)dev; ctx->procs = const_cast<hwc_procs_t *>(procs); } static int hwc_blank(struct hwc_composer_device_1 *dev, int disp, int blank) { struct hwc_context_t* ctx = (struct hwc_context_t*)dev; if (blank) { // release our resources, the screen is turning off // in our case, there is nothing to do. ctx->num_of_fb_layer_prev = 0; return 0; } else { // No need to unblank, will unblank on set() return 0; } } static int hwc_query(struct hwc_composer_device_1* dev, int what, int* value) { struct hwc_context_t* ctx = (struct hwc_context_t*)dev; switch (what) { case HWC_BACKGROUND_LAYER_SUPPORTED: // we don't support the background layer yet value[0] = 0; break; case HWC_VSYNC_PERIOD: // vsync period in nanosecond value[0] = 1000000000.0 / gpsGrallocModule->psFrameBufferDevice->base.fps; break; default: // unsupported query return -EINVAL; } return 0; } #ifdef VSYNC_IOCTL // Linux version of a manual reset event to control when // and when not to ask the video card for a VSYNC. This // stops the worker thread from asking for a VSYNC when // there is nothing useful to do with it and more closely // mimicks the original uevent mechanism int vsync_enable = 0; pthread_mutex_t vsync_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t vsync_condition = PTHREAD_COND_INITIALIZER; #endif static int hwc_eventControl(struct hwc_composer_device_1* dev, int dpy, int event, int enabled) { struct hwc_context_t* ctx = (struct hwc_context_t*)dev; switch (event) { case HWC_EVENT_VSYNC: int val = !!enabled; int err = ioctl(ctx->global_lcd_win.fd, S3CFB_SET_VSYNC_INT, &val); if (err < 0) return -errno; #if VSYNC_IOCTL // Enable or disable the ability for the worker thread // to ask for VSYNC events from the video driver pthread_mutex_lock(&vsync_mutex); if(enabled) { vsync_enable = 1; pthread_cond_broadcast(&vsync_condition); } else vsync_enable = 0; pthread_mutex_unlock(&vsync_mutex); #endif return 0; } return -EINVAL; } void handle_vsync_uevent(hwc_context_t *ctx, const char *buff, int len) { uint64_t timestamp = 0; const char *s = buff; if(!ctx->procs || !ctx->procs->vsync) return; s += strlen(s) + 1; while(*s) { if (!strncmp(s, "VSYNC=", strlen("VSYNC="))) timestamp = strtoull(s + strlen("VSYNC="), NULL, 0); s += strlen(s) + 1; if (s - buff >= len) break; } ctx->procs->vsync(ctx->procs, 0, timestamp); } static void *hwc_vsync_thread(void *data) { hwc_context_t *ctx = (hwc_context_t *)(data); #ifdef VSYNC_IOCTL uint64_t timestamp = 0; #else char uevent_desc[4096]; memset(uevent_desc, 0, sizeof(uevent_desc)); #endif setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY); #ifndef VSYNC_IOCTL uevent_init(); #endif while(true) { #ifdef VSYNC_IOCTL // Only continue if hwc_eventControl is enabled, otherwise // just sit here and wait until it is. This stops the code // from constantly looking for the VSYNC event with the screen // turned off. pthread_mutex_lock(&vsync_mutex); if(!vsync_enable) pthread_cond_wait(&vsync_condition, &vsync_mutex); pthread_mutex_unlock(&vsync_mutex); timestamp = 0; // Reset the timestamp value // S3CFB_WAIT_FOR_VSYNC is a custom IOCTL I added to wait for // the VSYNC interrupt, and then return the timestamp that was // originally being communicated via a uevent. The uevent was // spamming the UEventObserver and events/0 process with more // information than this device could really deal with every 18ms int res = ioctl(ctx->global_lcd_win.fd, S3CFB_WAIT_FOR_VSYNC, &timestamp); if(res > 0) { if(!ctx->procs || !ctx->procs->vsync) continue; ctx->procs->vsync(ctx->procs, 0, timestamp); } #else int len = uevent_next_event(uevent_desc, sizeof(uevent_desc) - 2); bool vsync = !strcmp(uevent_desc, "change@/devices/platform/s3cfb"); if(vsync) handle_vsync_uevent(ctx, uevent_desc, len); #endif } return NULL; } static int hwc_device_close(struct hw_device_t *dev) { struct hwc_context_t* ctx = (struct hwc_context_t*)dev; int ret = 0; int i; if (ctx) { if (destroyFimc(&ctx->fimc) < 0) { ALOGE("%s::destroyFimc fail", __func__); ret = -1; } if (window_close(&ctx->global_lcd_win) < 0) { ALOGE("%s::window_close() fail", __func__); ret = -1; } for (i = 0; i < NUM_OF_WIN; i++) { if (window_close(&ctx->win[i]) < 0) { ALOGE("%s::window_close() fail", __func__); ret = -1; } } // TODO: stop vsync_thread free(ctx); } return ret; } static int hwc_device_open(const struct hw_module_t* module, const char* name, struct hw_device_t** device) { int status = 0; int err; struct hwc_win_info_t *win; #if defined(BOARD_USES_HDMI) struct hw_module_t *hdmi_module; #endif if(hw_get_module(GRALLOC_HARDWARE_MODULE_ID, (const hw_module_t**)&gpsGrallocModule)) return -EINVAL; if(strcmp(gpsGrallocModule->base.common.author, "Imagination Technologies")) return -EINVAL; if (strcmp(name, HWC_HARDWARE_COMPOSER)) return -EINVAL; struct hwc_context_t *dev; dev = (hwc_context_t*)malloc(sizeof(*dev)); /* initialize our state here */ memset(dev, 0, sizeof(*dev)); /* initialize the procs */ dev->device.common.tag = HARDWARE_DEVICE_TAG; dev->device.common.version = HWC_DEVICE_API_VERSION_1_0; dev->device.common.module = const_cast<hw_module_t*>(module); dev->device.common.close = hwc_device_close; dev->device.prepare = hwc_prepare; dev->device.set = hwc_set; dev->device.eventControl = hwc_eventControl; dev->device.blank = hwc_blank; dev->device.query = hwc_query; dev->device.registerProcs = hwc_registerProcs; *device = &dev->device.common; #if defined(BOARD_USES_HDMI) dev->hdmi = NULL; if(hw_get_module(HDMI_HARDWARE_MODULE_ID, (const hw_module_t**)&hdmi_module)) { ALOGE("%s:: HDMI device not present", __func__); } else { int ret = module->methods->open(hdmi_module, "hdmi-composer", (hw_device_t **)&dev->hdmi); if(ret < 0) { ALOGE("%s:: Failed to open hdmi device : %s", __func__, strerror(ret)); } } #endif /* initializing */ memset(&(dev->fimc), 0, sizeof(s5p_fimc_t)); dev->fimc.dev_fd = -1; /* open WIN0 & WIN1 here */ for (int i = 0; i < NUM_OF_WIN; i++) { if (window_open(&(dev->win[i]), i) < 0) { ALOGE("%s:: Failed to open window %d device ", __func__, i); status = -EINVAL; goto err; } } /* open window 2, used to query global LCD info */ if (window_open(&dev->global_lcd_win, 2) < 0) { ALOGE("%s:: Failed to open window 2 device ", __func__); status = -EINVAL; goto err; } /* get default window config */ if (window_get_global_lcd_info(dev) < 0) { ALOGE("%s::window_get_global_lcd_info is failed : %s", __func__, strerror(errno)); status = -EINVAL; goto err; } dev->lcd_info.yres_virtual = dev->lcd_info.yres * NUM_OF_WIN_BUF; /* initialize the window context */ for (int i = 0; i < NUM_OF_WIN; i++) { win = &dev->win[i]; memcpy(&win->lcd_info, &dev->lcd_info, sizeof(struct fb_var_screeninfo)); memcpy(&win->var_info, &dev->lcd_info, sizeof(struct fb_var_screeninfo)); win->rect_info.x = 0; win->rect_info.y = 0; win->rect_info.w = win->var_info.xres; win->rect_info.h = win->var_info.yres; if (window_set_pos(win) < 0) { ALOGE("%s::window_set_pos is failed : %s", __func__, strerror(errno)); status = -EINVAL; goto err; } if (window_get_info(win) < 0) { ALOGE("%s::window_get_info is failed : %s", __func__, strerror(errno)); status = -EINVAL; goto err; } win->size = win->fix_info.line_length * win->var_info.yres; if (!win->fix_info.smem_start){ ALOGE("%s:: win-%d failed to get the reserved memory", __func__, i); status = -EINVAL; goto err; } for (int j = 0; j < NUM_OF_WIN_BUF; j++) { win->addr[j] = win->fix_info.smem_start + (win->size * j); ALOGI("%s::win-%d add[%d] %x ", __func__, i, j, win->addr[j]); } } /* open pp */ if (createFimc(&dev->fimc) < 0) { ALOGE("%s::creatFimc() fail", __func__); status = -EINVAL; goto err; } err = pthread_create(&dev->vsync_thread, NULL, hwc_vsync_thread, dev); if (err) { ALOGE("%s::pthread_create() failed : %s", __func__, strerror(err)); status = -err; goto err; } ALOGD("%s:: success\n", __func__); return 0; err: if (destroyFimc(&dev->fimc) < 0) ALOGE("%s::destroyFimc() fail", __func__); if (window_close(&dev->global_lcd_win) < 0) ALOGE("%s::window_close() fail", __func__); for (int i = 0; i < NUM_OF_WIN; i++) { if (window_close(&dev->win[i]) < 0) ALOGE("%s::window_close() fail", __func__); } return status; }
32.373626
96
0.575092
DrDoubt
88ae2cc132969bdc602ff5b218cdb40326513132
12,504
cpp
C++
camera/hal/test/mpi/src/video_test.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
null
null
null
camera/hal/test/mpi/src/video_test.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
null
null
null
camera/hal/test/mpi/src/video_test.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
2
2021-09-13T10:12:47.000Z
2021-09-13T11:16:31.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file expected 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 "video_test.h" using namespace OHOS; using namespace std; using namespace testing::ext; using namespace OHOS::Camera; void VideoTest::SetUpTestCase(void) {} void VideoTest::TearDownTestCase(void) {} void VideoTest::SetUp(void) { Test_ = std::make_shared<OHOS::Camera::Test>(); Test_->Init(); Test_->Open(); } void VideoTest::TearDown(void) { Test_->Close(); } /** * @tc.name: Video * @tc.desc: Preview and video streams, Commit 2 streams together, capture in order. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0001, TestSize.Level0) { std::cout << "==========[test log]Check video: Preview and video streams, "; std::cout << "Commit 2 streams together, capture in order." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); // Post-processing sleep(10); Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds.push_back(Test_->streamId_preview); Test_->streamIds.push_back(Test_->streamId_video); Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Preview and video streams + 3A, Commit 2 streams together, capture in order. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0002, TestSize.Level1) { std::cout << "==========[test log]Check video: Preview and video streams + 3A, "; std::cout << "Commit 2 streams together, capture in order." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Issue 3A parameters to increase exposure std::shared_ptr<Camera::CameraSetting> meta = std::make_shared<Camera::CameraSetting>(100, 2000); int32_t expo = 0xb0; meta->addEntry(OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &expo, 1); Test_->rc = Test_->cameraDevice->UpdateSettings(meta); if (Test_->rc == Camera::NO_ERROR) { std::cout << "==========[test log]check Capture: UpdateSettings success, for 10s." << std::endl; } else { std::cout << "==========[test log]check Capture: UpdateSettings fail, rc = " << Test_->rc << std::endl; } // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); sleep(5); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Preview + video, commit together, then close device, and preview + video again. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0003, TestSize.Level1) { std::cout << "==========[test log]Check video: Preview + video, "; std::cout << "commit together, then close device, and preview + video again." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->consumerMap_.clear(); std::cout << "==========[test log]Check video: The 2nd time." << std::endl; // second Configure two stream information // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Preview + video, commit together, then close device, and preview + capture. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0004, TestSize.Level1) { std::cout << "==========[test log]Check video: Preview + video, "; std::cout << "commit together, then close device, and preview + capture." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->consumerMap_.clear(); std::cout << "==========[test log]Check video: The 2nd time." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::STILL_CAPTURE}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Capture camera stream, continuous capture Test_->StartCapture(Test_->streamId_capture, Test_->captureId_capture, false, true); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_capture}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_capture}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Preview + video, commit together, success. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0005, TestSize.Level0) { std::cout << "==========[test log]Check video: Preview + video, commit together, success." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Dynamic Video mode, preview, success. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0020, TestSize.Level1) { std::cout << "==========[test log]Check video: Video mode, preview, success." << std::endl; // Start preview stream Test_->intents = {Camera::PREVIEW}; Test_->StartStream(Test_->intents); // Get preview Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Start stream Test_->intents = {Camera::VIDEO}; Test_->StartStream(Test_->intents); // Start capture Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); // Release stream Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Video mode, preview, set 3A, success. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0021, TestSize.Level1) { std::cout << "==========[test log]Check video: Video mode, preview, set 3A, success." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Issue 3A parameters to increase exposure std::shared_ptr<Camera::CameraSetting> meta = std::make_shared<Camera::CameraSetting>(100, 2000); int32_t expo = 0xc0; meta->addEntry(OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &expo, 1); Test_->rc = Test_->cameraDevice->UpdateSettings(meta); if (Test_->rc == Camera::NO_ERROR) { std::cout << "==========[test log]check Capture: UpdateSettings success, for 10s." << std::endl; } else { std::cout << "==========[test log]check Capture: UpdateSettings fail, rc = " << Test_->rc << std::endl; } // Capture preview stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); sleep(5); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); Test_->StopConsumer(Test_->intents); } /** * @tc.name: Video * @tc.desc: Preview and video streams + 3A, Commit 2 streams together, video in order. * @tc.size: MediumTest * @tc.type: Function */ HWTEST_F(VideoTest, Camera_Video_0022, TestSize.Level2) { std::cout << "==========[test log]Check video: Preview and video streams + 3A, "; std::cout << "Commit 2 streams together, capture in order." << std::endl; // Configure two stream information Test_->intents = {Camera::PREVIEW, Camera::VIDEO}; Test_->StartStream(Test_->intents); Test_->StopConsumer({Camera::VIDEO}); // Capture preview stream Test_->StartCapture(Test_->streamId_preview, Test_->captureId_preview, false, true); // Issue 3A parameters to increase exposure std::shared_ptr<Camera::CameraSetting> meta = std::make_shared<Camera::CameraSetting>(100, 2000); int32_t expo = 0xb0; meta->addEntry(OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &expo, 1); Test_->rc = Test_->cameraDevice->UpdateSettings(meta); if (Test_->rc == Camera::NO_ERROR) { std::cout << "==========[test log]check Capture: UpdateSettings success, for 10s." << std::endl; } else { std::cout << "==========[test log]check Capture: UpdateSettings fail, rc = " << Test_->rc << std::endl; } // Capture video stream Test_->StartCapture(Test_->streamId_video, Test_->captureId_video, false, true); sleep(180); // Post-processing Test_->captureIds = {Test_->captureId_preview, Test_->captureId_video}; Test_->streamIds = {Test_->streamId_preview, Test_->streamId_video}; Test_->StopStream(Test_->captureIds, Test_->streamIds); }
42.969072
111
0.68722
openharmony-gitee-mirror
88ae512084cae3dce1817e54429e2a9f2947912d
1,095
cc
C++
codeforces/Round582-Div.3/D.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
67
2019-07-14T05:38:41.000Z
2021-12-23T11:52:51.000Z
codeforces/Round582-Div.3/D.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
null
null
null
codeforces/Round582-Div.3/D.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
12
2020-01-16T10:48:01.000Z
2021-06-11T16:49:04.000Z
// // Created by OFShare on 2019-09-10 // #include <bits/stdc++.h> const int maxn = 2e5 + 5; int n, k; int A[maxn]; // canNumber[i]记录可以变成i这个数,的个数 int canNumber[maxn]; // cntNumber[i][j]记录变成i时需要j次操作,的个数 int cntNumber[maxn][30]; void preprocess(int x) { int cnt = 0; while(x){ canNumber[x]++; cntNumber[x][cnt]++; x /= 2; cnt++; } canNumber[0]++; cntNumber[x][cnt]++; } int main() { scanf("%d %d", &n, &k); for(int i = 1; i <= n; ++i){ scanf("%d", &A[i]); preprocess(A[i]); } int ans = 1e9; // 枚举最后k个相等的数为i时 for(int i = 0; i <= 2e5; ++i) { if(canNumber[i] >= k) { int sum = 0, number = 0; for(int j = 0; j <= 30; ++j) { // 一个一个的贡献 while(cntNumber[i][j] > 0 && number < k) { cntNumber[i][j]--; number++; sum += j; } if(number == k) break; } ans = std::min(ans, sum); } } printf("%d", ans); return 0; }
20.660377
58
0.415525
OFShare
88b4111e7ee5665a71371b9f5090bb8392bc44a4
397
cc
C++
result.cc
espindola/libcthulhu
8ab74385abd257abcd49f780675b0849a8c69bfb
[ "0BSD" ]
12
2020-09-10T03:01:45.000Z
2022-03-10T09:03:03.000Z
result.cc
espindola/libcthulhu
8ab74385abd257abcd49f780675b0849a8c69bfb
[ "0BSD" ]
null
null
null
result.cc
espindola/libcthulhu
8ab74385abd257abcd49f780675b0849a8c69bfb
[ "0BSD" ]
1
2021-05-13T06:27:19.000Z
2021-05-13T06:27:19.000Z
// Copyright (C) 2019 ScyllaDB #include <cthulhu/result.hh> #include <errno.h> #include <string.h> using namespace cthulhu; posix_error::posix_error(int error_number) : error_number(error_number) { assert(error_number && "not an error"); } posix_error posix_error::current() { return errno; } void posix_error::print_error(FILE *stream) { fprintf(stream, "%s", strerror(error_number)); }
18.904762
73
0.732997
espindola
88b531150b66b022405b6adf18210d4400508cea
20
cpp
C++
lib/cpp/Tree.cpp
Moonshile/MyAlgorithmCandy
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
[ "Apache-2.0" ]
2
2016-11-26T02:56:35.000Z
2019-06-17T04:09:02.000Z
lib/cpp/Tree.cpp
Moonshile/MyAlgorithmCandy
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
[ "Apache-2.0" ]
null
null
null
lib/cpp/Tree.cpp
Moonshile/MyAlgorithmCandy
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
[ "Apache-2.0" ]
3
2016-07-18T14:13:20.000Z
2019-06-17T04:08:32.000Z
#include "Tree.cpp"
10
19
0.7
Moonshile
88b89dbd5d774ccf7b6a7014d649875ec9b40fd8
4,327
cpp
C++
80/prog.cpp
alexsyrom/ProjectEuler
78c3e2a0e2d4948ef4faa5d65ff58defd5835620
[ "MIT" ]
null
null
null
80/prog.cpp
alexsyrom/ProjectEuler
78c3e2a0e2d4948ef4faa5d65ff58defd5835620
[ "MIT" ]
null
null
null
80/prog.cpp
alexsyrom/ProjectEuler
78c3e2a0e2d4948ef4faa5d65ff58defd5835620
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <cmath> #include <algorithm> template <class Class> void Print(Class instance) { std::cout << instance << std::endl; } void Print() { std::cout << std::endl; } class UnsignedDecimalFloat { public: static const size_t kBase = 10; static const size_t kPrecision = 204; UnsignedDecimalFloat(size_t number = 0) : digits_(kPrecision, 0) { digits_[0] = number; } UnsignedDecimalFloat operator* (const UnsignedDecimalFloat& multiplier) const { UnsignedDecimalFloat result = 0; for (size_t result_index = 0; result_index < kPrecision; ++result_index) { for (size_t this_index = 0; this_index <= result_index; ++ this_index) { size_t multiplier_index = result_index - this_index; result.digits_[result_index] += this->digits_[this_index] * multiplier.digits_[multiplier_index]; } } for (size_t result_index = kPrecision - 1; result_index > 0; --result_index) { result.digits_[result_index - 1] += result.digits_[result_index] / kBase; result.digits_[result_index] %= kBase; } return result; } UnsignedDecimalFloat operator+ (const UnsignedDecimalFloat& other) const { UnsignedDecimalFloat result = 0; for (size_t index = 0; index < kPrecision; ++index) { result.digits_[index] = this->digits_[index] + other.digits_[index]; } for (size_t index = kPrecision - 1; index > 0; --index) { result.digits_[index - 1] += result.digits_[index] / kBase; result.digits_[index] %= kBase; } return result; } UnsignedDecimalFloat operator/ (size_t other) const { UnsignedDecimalFloat result = *this; for (size_t index = 0; index < kPrecision - 1; ++index) { result.digits_[index + 1] += kBase * (result.digits_[index] % other); result.digits_[index] /= other; } result.digits_[kPrecision - 1] /= other; return result; } bool operator< (const UnsignedDecimalFloat& other) const { return digits_ < other.digits_; } size_t ComputeNFirstDigitsSum(size_t first_digits_number) { first_digits_number = std::min(first_digits_number, kPrecision); return std::accumulate(digits_.begin(), digits_.begin() + first_digits_number, 0); } static UnsignedDecimalFloat GetMinimumNonZeroNumber() { UnsignedDecimalFloat result = 0; result.digits_[kPrecision - 1] = 1; return result; } static UnsignedDecimalFloat GetMinimumNonZeroNumberWithHalvedPrecision() { UnsignedDecimalFloat result = 0; result.digits_[kPrecision / 2 - 1] = 1; return result; } private: // digits_[0] is the integer part of the number, others are true digits after the point std::vector<size_t> digits_; }; const UnsignedDecimalFloat kEpsilon = UnsignedDecimalFloat::GetMinimumNonZeroNumber(); const UnsignedDecimalFloat kEpsilonSqrt = UnsignedDecimalFloat::GetMinimumNonZeroNumberWithHalvedPrecision(); bool IsSquare(size_t number) { uint64_t root = std::sqrt(number); for (uint64_t index = root - 1; index < root + 2; ++index) { if (index * index == number) { return true; } } return false; } UnsignedDecimalFloat Sqrt( const UnsignedDecimalFloat& number, UnsignedDecimalFloat left, UnsignedDecimalFloat right, const UnsignedDecimalFloat& epsilon = kEpsilonSqrt) { while (left + epsilon < right) { auto medium = (left + right) / 2; if (number < medium * medium) { right = medium; } else { left = medium; } } return left; } int main() { std::ofstream output_stream("output.txt"); size_t digit_sum = 0; UnsignedDecimalFloat previous_root = 1; for (size_t index = 2; index < 100; ++index) { if (IsSquare(index)) { continue; } UnsignedDecimalFloat root = Sqrt(index, previous_root, index); previous_root = root; digit_sum += root.ComputeNFirstDigitsSum(100); } output_stream << digit_sum; return 0; }
30.471831
92
0.623758
alexsyrom
88ba1214b01266b549602efee89b52bd888e7983
1,744
cpp
C++
src/domain/finite_element/finite_element.cpp
SlaybaughLab/Transport
8eb32cb8ae50c92875526a7540350ef9a85bc050
[ "MIT" ]
12
2018-03-14T12:30:53.000Z
2022-01-23T14:46:44.000Z
src/domain/finite_element/finite_element.cpp
SlaybaughLab/Transport
8eb32cb8ae50c92875526a7540350ef9a85bc050
[ "MIT" ]
194
2017-07-07T01:38:15.000Z
2021-05-19T18:21:19.000Z
src/domain/finite_element/finite_element.cpp
SlaybaughLab/Transport
8eb32cb8ae50c92875526a7540350ef9a85bc050
[ "MIT" ]
10
2017-07-06T22:58:59.000Z
2021-03-15T07:01:21.000Z
#include "domain/finite_element/finite_element.hpp" namespace bart::domain::finite_element { template <int dim> auto FiniteElement<dim>::SetCell(const domain::CellPtr<dim> &to_set) -> bool { bool already_set{ false }; if (values_reinit_called_) { already_set = (values_->get_cell()->id() == to_set->id()); } if (!already_set) { values_->reinit(to_set); values_reinit_called_ = true; } return !already_set; } template <int dim> auto FiniteElement<dim>::SetFace(const domain::CellPtr<dim> &to_set, const domain::FaceIndex face) -> bool{ bool already_set{ false }; bool cell_already_set{ false }; if (face_values_reinit_called_) { cell_already_set = (face_values_->get_cell()->id() == to_set->id()); bool face_already_set = (static_cast<int>(face_values_->get_face_index()) == face.get()); already_set = (cell_already_set && face_already_set); } if (!already_set) { face_values_->reinit(to_set, face.get()); face_values_reinit_called_ = true; } return !cell_already_set; } template<int dim> auto FiniteElement<dim>::ValueAtQuadrature(const DealiiVector& values_at_dofs) const -> std::vector<double> { std::vector<double> return_vector(n_cell_quad_pts(), 0); values_->get_function_values(values_at_dofs, return_vector); return return_vector; } template<int dim> auto FiniteElement<dim>::ValueAtFaceQuadrature(const DealiiVector& values_at_dofs) const -> std::vector<double> { std::vector<double> return_vector(n_face_quad_pts(), 0); face_values_->get_function_values(values_at_dofs, return_vector); return return_vector; } template class FiniteElement<1>; template class FiniteElement<2>; template class FiniteElement<3>; } // namespace bart::domain::finite_element
30.068966
113
0.735092
SlaybaughLab
88bc4a6f30756e262d4acab589acca2a10e72e0d
1,410
cpp
C++
Minigin/ColliderComponent.cpp
Zakatos/Component-Game-Engine
c52f49ada5c23cdee502f4d3a8ce09392d6bcae9
[ "MIT" ]
null
null
null
Minigin/ColliderComponent.cpp
Zakatos/Component-Game-Engine
c52f49ada5c23cdee502f4d3a8ce09392d6bcae9
[ "MIT" ]
null
null
null
Minigin/ColliderComponent.cpp
Zakatos/Component-Game-Engine
c52f49ada5c23cdee502f4d3a8ce09392d6bcae9
[ "MIT" ]
null
null
null
#include "MiniginPCH.h" #include "ECS/ColliderComponent.h" #include "RendererComponent.h" ColliderComponent::ColliderComponent(const std::string& t) :m_Tag(t) { } ColliderComponent::ColliderComponent(const std::string& t, int xpos, int ypos, int size) :m_Tag(t) { m_Collider.x = xpos; m_Collider.y = ypos; m_Collider.h = m_Collider.w = size; } ColliderComponent::~ColliderComponent() { SDL_DestroyTexture(m_pTex); //delete m_pRenderer; //m_pRenderer = nullptr; } void ColliderComponent::init() { if (!m_pEntity->hasComponent<TransformComponent>()) { m_pEntity->addComponent<TransformComponent>(); } m_pTransform = &m_pEntity->getComponent<TransformComponent>(); m_pRenderer = &m_pEntity->getComponent<RendererComponent>(); m_pTex = m_pRenderer->LoadTexture("assets/coltex.png"); m_SrcR = { 0, 0, 32, 32 }; m_destR = { m_Collider.x, m_Collider.y, m_Collider.w, m_Collider.h }; } void ColliderComponent::update() { if (m_Tag != "terrain") { m_Collider.x = static_cast<int>(m_pTransform->GetPosition().m_X); m_Collider.y = static_cast<int>(m_pTransform->GetPosition().m_Y); m_Collider.w = m_pTransform->GetWidth() * m_pTransform->GetScale(); m_Collider.h = m_pTransform->GetHeight() * m_pTransform->GetScale(); } m_destR.x = m_Collider.x; m_destR.y = m_Collider.y; } void ColliderComponent::draw() { m_pRenderer->Draw(m_pTex, m_SrcR, m_destR, SDL_FLIP_NONE); }
21.692308
88
0.721986
Zakatos
88be67da0af117a229707f23f68cdfac44d90052
189
hh
C++
vpp/core/box2d.hh
jjzhang166/videopp
f1421b16b8ffcefb3d1697460940d868e31ba79d
[ "MIT" ]
624
2015-01-05T16:40:41.000Z
2022-03-01T03:09:43.000Z
vpp/core/box2d.hh
jjzhang166/videopp
f1421b16b8ffcefb3d1697460940d868e31ba79d
[ "MIT" ]
10
2015-01-22T20:50:13.000Z
2018-05-15T10:41:34.000Z
vpp/core/box2d.hh
jjzhang166/videopp
f1421b16b8ffcefb3d1697460940d868e31ba79d
[ "MIT" ]
113
2015-01-19T11:58:35.000Z
2022-03-28T05:15:20.000Z
#ifndef VPP_BOX2D_HH__ # define VPP_BOX2D_HH__ namespace vpp { class box2d { public: box2d(vint2 a, vint2 b); private: vint2 first_; vint2 last_; }; }; #endif
8.217391
28
0.624339
jjzhang166
88bf8710845fd1f475cf7116bac1189f91ac7555
487
cpp
C++
code-examples/cppcoro/io.cpp
schra/presentation-coroutine-workshop
e4290e2499b72327a04062901809353514450968
[ "BSD-3-Clause" ]
8
2019-10-11T07:59:03.000Z
2020-11-09T02:06:17.000Z
code-examples/cppcoro/io.cpp
schra/presentation-coroutine-workshop
e4290e2499b72327a04062901809353514450968
[ "BSD-3-Clause" ]
1
2020-10-15T14:45:34.000Z
2020-10-15T14:45:34.000Z
code-examples/cppcoro/io.cpp
schra/presentation-coroutine-workshop
e4290e2499b72327a04062901809353514450968
[ "BSD-3-Clause" ]
3
2019-05-29T19:53:50.000Z
2020-01-25T22:08:17.000Z
#include <cppcoro/read_only_file.hpp> #include <cppcoro/task.hpp> cppcoro::task<int> count_lines(std::string path) { auto file = co_await cppcoro::read_only_file::open(path); int lineCount = 0; char buffer[1024]; size_t bytesRead; std::uint64_t offset = 0; do { bytesRead = co_await file.read(offset, buffer, sizeof(buffer)); lineCount += std::count(buffer, buffer + bytesRead, '\n'); offset += bytesRead; } while (bytesRead > 0); co_return lineCount; }
23.190476
67
0.683778
schra
88c09ab4de4d0c9bc17fa28ec94636cc1fbc7bdc
7,317
cpp
C++
Astar.cpp
burflip/belkan
ff4b0516f47d46b337a7af1be8ff22947a36adfc
[ "MIT" ]
null
null
null
Astar.cpp
burflip/belkan
ff4b0516f47d46b337a7af1be8ff22947a36adfc
[ "MIT" ]
null
null
null
Astar.cpp
burflip/belkan
ff4b0516f47d46b337a7af1be8ff22947a36adfc
[ "MIT" ]
null
null
null
/* * Astar.cpp * * Created on: 8 de may. de 2016 * Author: valentin */ #include "Astar.h" #include "Node.h" #include <climits> #include <vector> #include <deque> #include <iostream> #include <cmath> #include <cstdlib> using namespace std; Astar::Astar() { this->ignore_better_choices = false; } Astar::~Astar() { // TODO Auto-generated destructor stub } Astar::Astar(char mapa_entorno_[][MAP_MAX_SIZE], char mapa_objetos_[][MAP_MAX_SIZE], pair<int, int> origin, pair<int, int> goal, bool ignore_better_choices) { this->goal = goal; this->origin = origin; this->ignore_better_choices = ignore_better_choices; translate_map(mapa_entorno_, mapa_objetos_); } int Astar::heuristic(pair<int, int> coords) { return abs(coords.first - goal.first) + abs(coords.second - goal.second); } pair<bool,bool> Astar::solve() { bool solution = false; bool there_is_solution = true; bool goal_recalculated = false; Node n = Node(make_pair(origin.first, origin.second), heuristic(origin)); nodes.insert(pair<pair<int, int>, Node>(origin, n)); this->actual_node_coords = origin; closed.push_back(origin); calculateAndOpenAdjacents(origin); while (!solution && there_is_solution) { if (open.size() == 0) { there_is_solution = false; } else { findBestOpenedChoiceAndCloseIt(); if (this->actual_node_coords == goal) { solution = true; buildSolution(); } else { if (calculateAndOpenAdjacents(this->actual_node_coords)) { this->goal = this->actual_node_coords; solution = true; goal_recalculated = true; buildSolution(); } } } } return pair<bool,bool>(there_is_solution,goal_recalculated); } void Astar::assingActual(pair<int, int> coords) { if (nodes.find(coords) != nodes.end()) { this->actual_node_coords = coords; } } bool Astar::calculateAndOpenAdjacents(pair<int, int> coords) { pair<int, int> new_node_coordinates; bool may_recalculate = false; for (int i = 0; i < 4 && !may_recalculate; i++) { switch (i) { case 0: new_node_coordinates = pair<int, int>(coords.first, coords.second - 1); may_recalculate = createAndInsertNode(coords, new_node_coordinates); break; case 1: new_node_coordinates = pair<int, int>(coords.first + 1, coords.second); may_recalculate = createAndInsertNode(coords, new_node_coordinates); break; case 2: new_node_coordinates = pair<int, int>(coords.first, coords.second + 1); may_recalculate = createAndInsertNode(coords, new_node_coordinates); break; case 3: new_node_coordinates = pair<int, int>(coords.first - 1, coords.second); may_recalculate = createAndInsertNode(coords, new_node_coordinates); break; } } return may_recalculate; } /** * (is_ok to create node, new goal in map: new hidden zone) */ pair<bool, bool> Astar::checkCoordinates(pair<int, int> coords) { bool is_ok = false; bool new_goal = false; if (coords.first >= 0 && coords.second >= 0 && coords.first <= MAP_MAX_SIZE && coords.second <= MAP_MAX_SIZE) { if (the_map.find(coords) != the_map.end()) { if (the_map[coords] == '?') { if(!this->ignore_better_choices) new_goal = true; // Cuando se encuentra una zona desconocida del mapa en la búsqueda del trayecto, cambiar goal. is_ok = true; } else if (the_map[coords] == '-') { is_ok = true; } } } return make_pair(is_ok, new_goal); } bool Astar::createAndInsertNode(pair<int, int> parent_coordinates, pair<int, int> coordinates) { pair<bool, bool> checked = checkCoordinates(coordinates); if (checked.first) { int g_cost = nodes[parent_coordinates].getG() + 10; Node n = Node(pair<int, int>(coordinates.first, coordinates.second), heuristic(coordinates), g_cost); n.calculateF(); n.setParent(nodes[this->actual_node_coords]); pair<map<pair<int, int>, Node>::iterator, bool> can_insert = nodes.insert(pair<pair<int, int>, Node>(coordinates, n)); if (can_insert.second == true) { open.push_back(coordinates); } else { if (n.getF() < (*can_insert.first).second.getF()) { nodes[coordinates] = n; } } if (checked.second) { closed.push_back(coordinates); this->actual_node_coords = coordinates; } } return checked.second; } void Astar::translate_map(char mapa_entorno_[][MAP_MAX_SIZE], char mapa_surface_[][MAP_MAX_SIZE]) { for (int i = 0; i < MAP_MAX_SIZE; i++) { for (int j = 0; j < MAP_MAX_SIZE; j++) { if ((mapa_entorno_[i][j] == 'S' || mapa_entorno_[i][j] == 'T' || mapa_entorno_[i][j] == '?' || mapa_entorno_[i][j] == 'K') && (mapa_surface_[i][j] <= 'a' || mapa_surface_[i][j] >= 'z')) { if (mapa_entorno_[i][j] == '?') { the_map[make_pair(j,i)] = '?'; } else { the_map[make_pair(j,i)] = '-'; } } else { the_map[make_pair(j,i)] = 'x'; } } } } pair<int, int> Astar::findBestOpenedChoiceAndCloseIt() { vector<pair<int, int> >::iterator best_pos, it = open.begin(); pair<int, int> best_node_coordinates; int best_f = INT_MAX; while (it != open.end()) { int current_f = nodes[(*it)].getF(); if (current_f < best_f) { best_f = current_f; best_node_coordinates = *it; best_pos = it; } it++; } open.erase(best_pos); closed.push_back(best_node_coordinates); actual_node_coords = best_node_coordinates; return actual_node_coords; } void Astar::buildSolution() { pair<int, int> current_coordinates = nodes[goal].getCoords(); //cout << "SOLUTION:" << endl; while (current_coordinates != origin) { //cout << current_coordinates.first << " " << current_coordinates.second << ", "; current_coordinates = nodes[current_coordinates].getParentCoords(); solution.push_front(current_coordinates); } solution.pop_front(); /** cout << endl; cout << "SOLUTION SIZE: " << solution.size() << endl; cout << endl; **/ } void Astar::printRoute() { cout << "Ruta escogida desde " << "(" << origin.first << "," << origin.second << "):"<< endl; deque<pair<int,int> >::iterator it = solution.begin(); while(it != solution.end()) { cout << "(" << (*it).first << "," << (*it).second << "), "; it ++; } cout << endl; } void Astar::printPartialMap() { vector<vector<char>> matrix; for(unsigned int i=0;i<solution.size()*2;i++) { vector<char> tmp_vec; for(unsigned int j=0;j<solution.size()*2;j++){ if(i==solution.size() && j==solution.size()) { tmp_vec.push_back('O'); } else if(the_map[make_pair(j+origin.first,i+origin.second)] != 'x') { tmp_vec.push_back('-'); } else { tmp_vec.push_back('s'); } } matrix.push_back(vector<char>(tmp_vec)); } for(unsigned int i=0;i<solution.size()*2;i++) { for(unsigned int j=0;j<solution.size()*2;j++){ deque<pair<int,int> >::iterator it = solution.begin(); bool printed = false; while(it != solution.end()) { if(((*it).first-origin.first+solution.size()-1) == j && ((*it).second-origin.second+solution.size()-1) == i) { cout << "X "; printed = true; } it ++; } if(!printed) cout << matrix[i][j] << " "; } cout << endl; } cout << "Matrix: " << solution.size() << endl; } void Astar::printFullMap() { cout << "------------------------------------------" << endl; for(int i=0; i<MAP_MAX_SIZE;i++){ for(int j=0; j<MAP_MAX_SIZE; j++){ cout << the_map[make_pair(j,i)] << " "; } cout << endl; } cout << "------------------------------------------" << endl; }
29.035714
158
0.64398
burflip
88c7062b5b08b56a9f720804dd2b438ca58fade3
1,267
cpp
C++
src/prod/src/ServiceModel/SingleInstanceApplicationUpgradeDescription.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/SingleInstanceApplicationUpgradeDescription.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/SingleInstanceApplicationUpgradeDescription.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Management::ClusterManager; using namespace ServiceModel; SingleInstanceApplicationUpgradeDescription::SingleInstanceApplicationUpgradeDescription( wstring && deploymentName, wstring && applicationName, UpgradeType::Enum upgradeType, RollingUpgradeMode::Enum upgradeMode, bool const forceRestart, RollingUpgradeMonitoringPolicy && monitoringPolicy, bool const isHealthPolicyValid, ApplicationHealthPolicy && applicationHealthPolicy, TimeSpan const & replicaSetCheckTimeout, ModelV2::ApplicationDescription const & targetApplicationDescription) : SingleInstanceDeploymentUpgradeDescription( move(deploymentName), move(applicationName), upgradeType, upgradeMode, forceRestart, move(monitoringPolicy), isHealthPolicyValid, move(applicationHealthPolicy), replicaSetCheckTimeout) , TargetApplicationDescription(targetApplicationDescription) { }
35.194444
89
0.66693
gridgentoo
88c74c39378a3adb3eb8fb80d7c50d248aecc6d0
721
cpp
C++
Aula24/P1_GrowlingGears/GrowlingGears.cpp
VanessaMMH/ProgComp2021A
03a3e0394b26eb78801246c7d6b7888fe53141bd
[ "BSD-3-Clause" ]
null
null
null
Aula24/P1_GrowlingGears/GrowlingGears.cpp
VanessaMMH/ProgComp2021A
03a3e0394b26eb78801246c7d6b7888fe53141bd
[ "BSD-3-Clause" ]
null
null
null
Aula24/P1_GrowlingGears/GrowlingGears.cpp
VanessaMMH/ProgComp2021A
03a3e0394b26eb78801246c7d6b7888fe53141bd
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* link:https://open.kattis.com/problems/growlinggears */ int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int q; cin >> q; for (int i = 0; i < q; i++) { int n, index; double max = -500000.0; cin >> n; for (int j = 0; j < n; j++) { double a, b, c, T = 1; cin >> a >> b >> c; b /= a; c /= a; T /= a; b /= 2; b *= b; c += b; c /= T; if (c > max) { max = c; index = j + 1; } } cout << index << "\n"; } }
18.973684
51
0.330097
VanessaMMH
88c84d9159cc16011dcbf448c36abe10bf766683
1,848
cpp
C++
Problem/src/SampleProblem.cpp
tut-cc/DiceTilingMeu
d07d6e27370385ff7b4bce48f34f64bb1caa41ee
[ "MIT" ]
8
2015-10-12T05:39:06.000Z
2016-08-20T06:12:26.000Z
Problem/src/SampleProblem.cpp
tut-cc/DiceTilingMeu
d07d6e27370385ff7b4bce48f34f64bb1caa41ee
[ "MIT" ]
null
null
null
Problem/src/SampleProblem.cpp
tut-cc/DiceTilingMeu
d07d6e27370385ff7b4bce48f34f64bb1caa41ee
[ "MIT" ]
null
null
null
#include "SampleProblem.hpp" #include <string> #include <iostream> #include <fstream> #include <cstdlib> SampleProblem::SampleProblem(std::string p) { std::ifstream ifs(p); if (ifs.fail()) { std::cout << "failed" << std::endl; } std::string str; for (int i = 0; i < 32; i++) { ifs >> str; field.push_back(str); // std::cout << str << std::endl; } /* ifs >> num; std::cout << num << std::endl; */ ifs >> str; num = std::atoi(str.c_str()); // std::cout << num << std::endl; for (int i = 0; i < num; i++) { std::vector<std::string> tmp_stone; for (int j = 0; j < 8; j++) { ifs >> str; tmp_stone.push_back(str); // std::cout << str << std::endl; } stones.push_back(tmp_stone); // std::cout << std::endl; } /* std::cout << "test" << std::endl; std::cin >> str; */ } SampleProblem::SampleProblem(){ std::ifstream ifs("problem/53.txt"); if (ifs.fail()){ std::cout << "failed" << std::endl; } std::string str; for (int i = 0; i < 32; i++){ ifs >> str; field.push_back(str); // std::cout << str << std::endl; } /* ifs >> num; std::cout << num << std::endl; */ ifs >> str; num = std::atoi(str.c_str()); // std::cout << num << std::endl; for (int i = 0; i < num; i++){ std::vector<std::string> tmp_stone; for (int j = 0; j < 8; j++){ ifs >> str; tmp_stone.push_back(str); // std::cout << str << std::endl; } stones.push_back(tmp_stone); // std::cout << std::endl; } /* std::cout << "test" << std::endl; std::cin >> str; */ } std::vector<std::string> SampleProblem::get_field_str() const { return field; } std::vector<std::vector<std::string>> SampleProblem::get_stones_str() const { return stones; } std::vector<std::string> SampleProblem::get_stone_str(int idx) const { return stones[idx]; } int SampleProblem::num_of_stones() const { return num; }
18.29703
75
0.573593
tut-cc
88cd3b4417ca3d4c21482f577a21bedaf034cf88
81,243
cc
C++
mysql-server/storage/innobase/pars/lexyy.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/innobase/pars/lexyy.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/innobase/pars/lexyy.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
#include "univ.i" static char *yytext; #line 2 "lexyy.cc" #line 4 "lexyy.cc" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 39 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern yy_size_t yyleng; static FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) #define YY_LINENO_REWIND_TO(ptr) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE *yy_buffer_stack = nullptr; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */ yy_size_t yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *)nullptr; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; static void yyrestart (FILE *input_file ); MY_ATTRIBUTE((unused)) static void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); static YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); static void yy_delete_buffer (YY_BUFFER_STATE b ); static void yy_flush_buffer (YY_BUFFER_STATE b ); MY_ATTRIBUTE((unused)) static void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); MY_ATTRIBUTE((unused)) static void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ); static void *yyalloc (yy_size_t ); static void *yyrealloc (void *,yy_size_t ); static void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define yywrap() 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; static int yylineno = 1; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 114 #define YY_END_OF_BUFFER 115 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[372] = { 0, 0, 0, 109, 109, 0, 0, 0, 0, 115, 113, 112, 112, 8, 113, 104, 5, 93, 99, 102, 100, 97, 101, 113, 103, 1, 113, 98, 96, 94, 95, 107, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 105, 106, 109, 110, 6, 7, 9, 10, 112, 4, 88, 108, 2, 1, 3, 89, 90, 92, 91, 0, 86, 0, 86, 86, 86, 86, 86, 44, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 28, 17, 25, 86, 86, 86, 86, 86, 86, 54, 63, 86, 14, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 109, 110, 110, 111, 6, 7, 9, 10, 2, 0, 87, 13, 45, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 27, 86, 86, 86, 41, 86, 86, 86, 86, 21, 86, 86, 86, 86, 86, 15, 86, 86, 86, 18, 86, 86, 86, 86, 86, 51, 86, 12, 86, 36, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 0, 87, 86, 86, 86, 20, 86, 24, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 46, 86, 86, 30, 86, 79, 86, 86, 39, 86, 86, 86, 86, 86, 48, 86, 84, 81, 32, 83, 86, 11, 66, 86, 86, 42, 86, 86, 86, 86, 86, 86, 29, 86, 86, 86, 86, 86, 86, 86, 77, 0, 26, 86, 86, 86, 68, 86, 86, 86, 86, 37, 86, 86, 86, 86, 86, 86, 86, 31, 67, 23, 86, 59, 86, 73, 86, 86, 86, 43, 86, 86, 86, 86, 82, 86, 56, 86, 86, 86, 86, 86, 40, 33, 0, 85, 19, 86, 86, 75, 86, 72, 55, 86, 65, 86, 52, 86, 86, 86, 47, 86, 74, 86, 86, 34, 86, 35, 71, 86, 60, 86, 50, 49, 86, 86, 57, 53, 64, 86, 86, 86, 22, 86, 86, 86, 86, 86, 86, 86, 38, 86, 80, 69, 86, 76, 86, 78, 86, 61, 86, 16, 70, 58, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 62, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 4, 5, 6, 7, 1, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 1, 1, 1, 1, 51, 1, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 52, 34, 34, 34, 34, 53, 34, 54, 34, 34, 34, 34, 34, 34, 34, 55, 1, 56, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[57] = { 0, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 5, 1, 1, 1, 1, 6, 7, 1, 1, 1, 8, 1, 1, 6, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1 } ; static yyconst flex_int16_t yy_base[385] = { 0, 0, 0, 304, 293, 283, 277, 278, 265, 260, 1174, 55, 57, 1174, 0, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 240, 242, 46, 206, 1174, 43, 1174, 202, 1174, 46, 50, 56, 52, 66, 64, 51, 81, 92, 91, 94, 96, 111, 113, 116, 130, 127, 53, 134, 1174, 1174, 0, 106, 0, 213, 0, 216, 157, 0, 1174, 1174, 192, 56, 185, 1174, 1174, 1174, 1174, 195, 140, 179, 147, 152, 154, 156, 158, 165, 167, 172, 177, 174, 183, 192, 186, 189, 188, 208, 210, 214, 217, 221, 223, 226, 224, 233, 228, 230, 235, 251, 255, 249, 250, 256, 265, 268, 271, 272, 278, 282, 284, 285, 287, 289, 298, 307, 303, 294, 314, 312, 318, 327, 325, 0, 112, 133, 1174, 0, 178, 0, 180, 160, 93, 0, 328, 334, 337, 339, 349, 352, 353, 359, 364, 366, 365, 370, 375, 369, 380, 381, 393, 397, 399, 398, 402, 408, 409, 413, 419, 423, 424, 429, 430, 433, 439, 440, 449, 451, 452, 455, 462, 464, 466, 473, 476, 477, 480, 483, 492, 490, 493, 494, 496, 499, 506, 508, 510, 513, 517, 524, 527, 528, 529, 531, 60, 0, 540, 543, 544, 545, 547, 559, 560, 561, 563, 574, 576, 564, 578, 587, 588, 590, 593, 594, 597, 604, 607, 608, 609, 610, 619, 620, 623, 624, 629, 633, 630, 634, 635, 636, 640, 646, 649, 650, 652, 653, 662, 664, 666, 667, 668, 671, 681, 683, 684, 687, 690, 696, 700, 701, 705, 706, 720, 702, 42, 716, 722, 723, 726, 727, 732, 736, 738, 739, 743, 752, 754, 755, 758, 769, 770, 771, 772, 775, 786, 787, 788, 789, 790, 799, 800, 801, 802, 803, 805, 814, 818, 820, 821, 824, 831, 825, 834, 835, 836, 837, 841, 73, 850, 851, 852, 854, 857, 861, 864, 866, 867, 868, 870, 873, 877, 882, 884, 886, 891, 893, 896, 898, 900, 902, 903, 912, 914, 916, 921, 925, 928, 930, 931, 932, 935, 937, 941, 942, 946, 948, 951, 952, 953, 957, 967, 958, 973, 974, 976, 980, 986, 987, 989, 990, 991, 993, 996, 1002, 1005, 1007, 1009, 1012, 1014, 1018, 1019, 1024, 1025, 1030, 1031, 1035, 1040, 1041, 1037, 1047, 1174, 1086, 1095, 1104, 1107, 1110, 1114, 1123, 1132, 1141, 1150, 1157, 1161, 1164 } ; static yyconst flex_int16_t yy_def[385] = { 0, 371, 1, 372, 372, 373, 373, 374, 374, 371, 371, 371, 371, 371, 375, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 376, 371, 371, 371, 371, 371, 377, 377, 377, 377, 377, 34, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 371, 371, 378, 379, 380, 371, 381, 371, 371, 375, 371, 371, 371, 371, 376, 371, 371, 371, 371, 382, 377, 383, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 378, 379, 379, 371, 380, 371, 381, 371, 371, 371, 384, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 371, 384, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 371, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 371, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 0, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371 } ; static yyconst flex_int16_t yy_nxt[1231] = { 0, 10, 11, 12, 13, 10, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 10, 32, 33, 34, 35, 36, 37, 38, 38, 39, 38, 38, 40, 41, 42, 43, 44, 38, 45, 46, 47, 48, 49, 50, 38, 38, 38, 38, 38, 38, 38, 51, 52, 59, 59, 59, 59, 63, 70, 64, 67, 68, 70, 70, 70, 70, 72, 63, 70, 64, 72, 72, 72, 72, 121, 75, 72, 84, 70, 76, 73, 85, 77, 134, 79, 74, 72, 86, 80, 90, 298, 81, 71, 70, 82, 78, 91, 83, 87, 92, 88, 72, 93, 70, 70, 94, 70, 95, 70, 255, 89, 72, 72, 126, 72, 96, 72, 98, 127, 371, 97, 99, 104, 70, 371, 70, 101, 100, 70, 102, 105, 72, 106, 72, 107, 103, 72, 108, 110, 70, 126, 112, 70, 195, 113, 127, 70, 72, 111, 109, 72, 116, 70, 114, 72, 59, 59, 115, 117, 70, 72, 119, 122, 120, 70, 118, 70, 72, 70, 123, 70, 135, 72, 132, 72, 136, 72, 70, 72, 70, 131, 137, 129, 138, 70, 72, 70, 72, 141, 70, 139, 70, 72, 140, 72, 70, 133, 72, 70, 147, 70, 70, 371, 72, 70, 132, 72, 142, 72, 72, 144, 145, 72, 143, 153, 149, 131, 129, 146, 69, 70, 148, 70, 66, 150, 152, 70, 154, 72, 70, 72, 151, 155, 70, 72, 70, 70, 72, 70, 156, 70, 72, 70, 72, 72, 70, 72, 70, 72, 62, 72, 61, 158, 72, 157, 72, 371, 162, 160, 159, 161, 70, 70, 70, 165, 58, 166, 70, 70, 72, 72, 72, 163, 164, 167, 72, 72, 70, 58, 169, 70, 56, 171, 70, 70, 72, 168, 56, 72, 170, 70, 72, 72, 172, 70, 173, 70, 70, 72, 70, 54, 70, 72, 176, 72, 72, 70, 72, 181, 72, 70, 54, 174, 175, 72, 70, 178, 179, 72, 70, 183, 182, 177, 72, 70, 180, 70, 72, 186, 185, 70, 184, 72, 371, 72, 371, 190, 70, 72, 70, 70, 187, 371, 188, 371, 72, 70, 72, 72, 70, 191, 70, 192, 189, 72, 371, 193, 72, 371, 72, 371, 70, 371, 194, 70, 70, 197, 371, 198, 72, 199, 70, 72, 72, 200, 201, 70, 70, 70, 72, 371, 70, 70, 371, 72, 72, 72, 70, 207, 72, 72, 202, 70, 70, 371, 72, 209, 371, 203, 205, 72, 72, 206, 204, 208, 70, 213, 210, 211, 70, 70, 70, 212, 72, 70, 371, 214, 72, 72, 72, 70, 70, 72, 217, 371, 70, 371, 218, 72, 72, 371, 70, 220, 72, 221, 70, 70, 215, 216, 72, 371, 70, 70, 72, 72, 70, 371, 223, 219, 72, 72, 70, 70, 72, 224, 225, 222, 371, 227, 72, 72, 70, 371, 70, 70, 230, 229, 70, 228, 72, 226, 72, 72, 371, 70, 72, 70, 233, 70, 371, 231, 234, 72, 371, 72, 70, 72, 232, 70, 70, 371, 237, 70, 72, 235, 70, 72, 72, 236, 238, 72, 239, 70, 72, 70, 70, 70, 371, 70, 371, 72, 70, 72, 72, 72, 241, 72, 242, 70, 72, 70, 240, 70, 371, 371, 70, 72, 371, 72, 70, 72, 243, 247, 72, 371, 244, 70, 72, 245, 70, 70, 70, 246, 70, 72, 250, 249, 72, 72, 72, 248, 72, 70, 371, 371, 70, 70, 70, 371, 70, 72, 253, 254, 72, 72, 72, 252, 72, 251, 371, 371, 70, 70, 70, 256, 70, 70, 257, 259, 72, 72, 72, 258, 72, 72, 260, 70, 371, 70, 371, 70, 371, 262, 371, 72, 263, 72, 264, 72, 70, 70, 261, 70, 371, 265, 70, 70, 72, 72, 70, 72, 269, 267, 72, 72, 371, 70, 72, 266, 70, 70, 70, 70, 268, 72, 371, 271, 72, 72, 72, 72, 70, 70, 270, 273, 70, 70, 371, 274, 72, 72, 70, 70, 72, 72, 70, 70, 70, 70, 72, 72, 272, 70, 72, 72, 72, 72, 280, 70, 275, 72, 70, 70, 276, 70, 70, 72, 278, 277, 72, 72, 279, 72, 72, 70, 281, 70, 371, 70, 70, 70, 371, 72, 70, 72, 282, 72, 72, 72, 284, 286, 72, 371, 70, 287, 70, 70, 371, 371, 70, 283, 72, 70, 72, 72, 285, 288, 72, 70, 290, 72, 371, 70, 70, 70, 371, 72, 70, 70, 291, 72, 72, 72, 289, 371, 72, 72, 293, 70, 371, 295, 296, 70, 371, 70, 70, 72, 292, 70, 70, 72, 294, 72, 72, 70, 297, 72, 72, 70, 371, 70, 70, 72, 371, 371, 70, 72, 302, 72, 72, 371, 304, 299, 72, 70, 371, 70, 70, 300, 371, 70, 371, 72, 301, 72, 72, 303, 306, 72, 305, 371, 70, 70, 70, 70, 371, 371, 70, 307, 72, 72, 72, 72, 308, 310, 72, 309, 371, 70, 70, 70, 70, 70, 371, 311, 312, 72, 72, 72, 72, 72, 70, 70, 70, 70, 70, 313, 70, 371, 72, 72, 72, 72, 72, 315, 72, 70, 318, 316, 314, 70, 371, 70, 70, 72, 320, 70, 70, 72, 319, 72, 72, 317, 70, 72, 72, 70, 70, 70, 70, 324, 72, 371, 70, 72, 72, 72, 72, 321, 322, 326, 72, 70, 70, 70, 323, 70, 371, 325, 70, 72, 72, 72, 70, 72, 327, 70, 72, 70, 70, 70, 72, 70, 371, 72, 70, 72, 72, 72, 70, 72, 328, 329, 72, 70, 332, 70, 72, 70, 371, 333, 330, 72, 70, 72, 70, 72, 331, 70, 371, 70, 72, 70, 72, 70, 70, 72, 334, 72, 335, 72, 371, 72, 72, 70, 339, 70, 371, 70, 336, 337, 371, 72, 70, 72, 340, 72, 70, 371, 338, 70, 72, 70, 70, 70, 72, 341, 70, 72, 70, 72, 72, 72, 70, 70, 72, 343, 72, 70, 342, 70, 72, 72, 70, 70, 70, 72, 371, 72, 70, 70, 72, 72, 72, 371, 347, 371, 72, 72, 70, 346, 344, 345, 371, 349, 70, 70, 72, 70, 371, 348, 351, 70, 72, 72, 350, 72, 353, 70, 70, 72, 70, 70, 70, 352, 70, 72, 72, 70, 72, 72, 72, 355, 72, 70, 371, 72, 70, 357, 70, 371, 70, 72, 354, 70, 72, 70, 72, 358, 72, 70, 70, 72, 371, 72, 356, 70, 70, 72, 72, 371, 359, 70, 70, 72, 72, 371, 70, 362, 70, 72, 72, 70, 70, 360, 72, 366, 72, 363, 70, 72, 72, 371, 365, 371, 361, 371, 72, 367, 371, 371, 371, 364, 371, 371, 368, 371, 371, 371, 369, 371, 371, 370, 53, 53, 53, 53, 53, 53, 53, 53, 53, 55, 55, 55, 55, 55, 55, 55, 55, 55, 57, 57, 57, 57, 57, 57, 57, 57, 57, 60, 371, 60, 65, 65, 65, 71, 71, 371, 71, 124, 124, 124, 124, 371, 124, 124, 124, 124, 125, 125, 125, 125, 125, 125, 125, 125, 125, 128, 128, 128, 371, 128, 128, 128, 128, 128, 130, 371, 130, 130, 130, 130, 130, 130, 130, 134, 371, 371, 371, 371, 371, 134, 72, 72, 371, 72, 196, 371, 196, 9, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371 } ; static yyconst flex_int16_t yy_chk[1231] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 11, 12, 12, 25, 32, 25, 28, 28, 33, 38, 35, 49, 32, 64, 34, 64, 33, 38, 35, 49, 49, 33, 34, 35, 36, 33, 32, 35, 33, 298, 34, 32, 36, 35, 34, 37, 255, 34, 37, 39, 34, 33, 37, 34, 36, 37, 36, 39, 37, 41, 40, 37, 42, 39, 43, 195, 36, 41, 40, 54, 42, 39, 43, 40, 54, 125, 39, 40, 43, 44, 125, 45, 41, 40, 46, 42, 43, 44, 43, 45, 43, 42, 46, 43, 45, 48, 126, 46, 47, 133, 46, 126, 50, 48, 45, 44, 47, 47, 71, 46, 50, 59, 59, 46, 47, 73, 71, 48, 50, 48, 74, 47, 75, 73, 76, 50, 77, 73, 74, 132, 75, 74, 76, 78, 77, 79, 131, 75, 129, 76, 80, 78, 82, 79, 79, 81, 76, 72, 80, 77, 82, 83, 70, 81, 85, 82, 87, 86, 65, 83, 84, 63, 85, 80, 87, 86, 81, 81, 84, 80, 86, 84, 58, 56, 81, 30, 88, 83, 89, 26, 84, 85, 90, 87, 88, 91, 89, 84, 88, 92, 90, 93, 95, 91, 94, 89, 97, 92, 98, 93, 95, 96, 94, 99, 97, 24, 98, 23, 91, 96, 90, 99, 9, 96, 93, 92, 94, 102, 103, 100, 98, 8, 99, 101, 104, 102, 103, 100, 96, 96, 100, 101, 104, 105, 7, 101, 106, 6, 103, 107, 108, 105, 100, 5, 106, 102, 109, 107, 108, 106, 110, 107, 111, 112, 109, 113, 4, 114, 110, 110, 111, 112, 118, 113, 113, 114, 115, 3, 108, 109, 118, 117, 111, 112, 115, 116, 115, 114, 110, 117, 120, 112, 119, 116, 117, 116, 121, 115, 120, 0, 119, 0, 120, 123, 121, 122, 135, 118, 0, 119, 0, 123, 136, 122, 135, 137, 121, 138, 122, 119, 136, 0, 122, 137, 0, 138, 0, 139, 0, 123, 140, 141, 137, 0, 138, 139, 139, 142, 140, 141, 140, 140, 143, 145, 144, 142, 0, 148, 146, 0, 143, 145, 144, 147, 145, 148, 146, 141, 149, 150, 0, 147, 147, 0, 142, 144, 149, 150, 144, 143, 146, 151, 150, 148, 148, 152, 154, 153, 149, 151, 155, 0, 151, 152, 154, 153, 156, 157, 155, 154, 0, 158, 0, 154, 156, 157, 0, 159, 157, 158, 158, 160, 161, 152, 153, 159, 0, 162, 163, 160, 161, 164, 0, 161, 156, 162, 163, 165, 166, 164, 162, 163, 160, 0, 164, 165, 166, 167, 0, 168, 169, 166, 165, 170, 164, 167, 163, 168, 169, 0, 171, 170, 172, 169, 173, 0, 167, 170, 171, 0, 172, 174, 173, 168, 175, 176, 0, 173, 177, 174, 171, 178, 175, 176, 172, 175, 177, 176, 180, 178, 179, 181, 182, 0, 183, 0, 180, 184, 179, 181, 182, 178, 183, 179, 185, 184, 186, 177, 187, 0, 0, 188, 185, 0, 186, 189, 187, 181, 187, 188, 0, 183, 190, 189, 185, 191, 192, 193, 186, 194, 190, 190, 189, 191, 192, 193, 188, 194, 197, 0, 0, 198, 199, 200, 0, 201, 197, 193, 194, 198, 199, 200, 192, 201, 191, 0, 0, 202, 203, 204, 197, 205, 208, 198, 201, 202, 203, 204, 199, 205, 208, 203, 206, 0, 207, 0, 209, 0, 205, 0, 206, 206, 207, 207, 209, 210, 211, 204, 212, 0, 208, 213, 214, 210, 211, 215, 212, 212, 210, 213, 214, 0, 216, 215, 209, 217, 218, 219, 220, 211, 216, 0, 215, 217, 218, 219, 220, 221, 222, 213, 218, 223, 224, 0, 220, 221, 222, 225, 227, 223, 224, 226, 228, 229, 230, 225, 227, 216, 231, 226, 228, 229, 230, 227, 232, 221, 231, 233, 234, 223, 235, 236, 232, 225, 224, 233, 234, 226, 235, 236, 237, 229, 238, 0, 239, 240, 241, 0, 237, 242, 238, 234, 239, 240, 241, 238, 241, 242, 0, 243, 242, 244, 245, 0, 0, 246, 237, 243, 247, 244, 245, 240, 243, 246, 248, 245, 247, 0, 249, 250, 254, 0, 248, 251, 252, 247, 249, 250, 254, 244, 0, 251, 252, 249, 256, 0, 251, 252, 253, 0, 257, 258, 256, 248, 259, 260, 253, 250, 257, 258, 261, 253, 259, 260, 262, 0, 263, 264, 261, 0, 0, 265, 262, 261, 263, 264, 0, 263, 257, 265, 266, 0, 267, 268, 258, 0, 269, 0, 266, 259, 267, 268, 262, 266, 269, 264, 0, 270, 271, 272, 273, 0, 0, 274, 267, 270, 271, 272, 273, 268, 270, 274, 269, 0, 275, 276, 277, 278, 279, 0, 271, 272, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 276, 285, 0, 280, 281, 282, 283, 284, 280, 285, 286, 284, 281, 278, 287, 0, 288, 289, 286, 286, 290, 292, 287, 285, 288, 289, 282, 291, 290, 292, 293, 294, 295, 296, 292, 291, 0, 297, 293, 294, 295, 296, 287, 289, 294, 297, 299, 300, 301, 291, 302, 0, 293, 303, 299, 300, 301, 304, 302, 295, 305, 303, 306, 307, 308, 304, 309, 0, 305, 310, 306, 307, 308, 311, 309, 301, 302, 310, 312, 309, 313, 311, 314, 0, 311, 304, 312, 315, 313, 316, 314, 307, 317, 0, 318, 315, 319, 316, 320, 321, 317, 312, 318, 313, 319, 0, 320, 321, 322, 320, 323, 0, 324, 315, 317, 0, 322, 325, 323, 323, 324, 326, 0, 318, 327, 325, 328, 329, 330, 326, 325, 331, 327, 332, 328, 329, 330, 333, 334, 331, 329, 332, 335, 328, 336, 333, 334, 337, 338, 339, 335, 0, 336, 340, 342, 337, 338, 339, 0, 337, 0, 340, 342, 341, 335, 333, 334, 0, 339, 343, 344, 341, 345, 0, 338, 341, 346, 343, 344, 340, 345, 343, 347, 348, 346, 349, 350, 351, 342, 352, 347, 348, 353, 349, 350, 351, 348, 352, 354, 0, 353, 355, 352, 356, 0, 357, 354, 345, 358, 355, 359, 356, 354, 357, 360, 361, 358, 0, 359, 350, 362, 363, 360, 361, 0, 358, 364, 365, 362, 363, 0, 366, 361, 369, 364, 365, 367, 368, 359, 366, 365, 369, 362, 370, 367, 368, 0, 364, 0, 360, 0, 370, 366, 0, 0, 0, 363, 0, 0, 367, 0, 0, 0, 368, 0, 0, 369, 372, 372, 372, 372, 372, 372, 372, 372, 372, 373, 373, 373, 373, 373, 373, 373, 373, 373, 374, 374, 374, 374, 374, 374, 374, 374, 374, 375, 0, 375, 376, 376, 376, 377, 377, 0, 377, 378, 378, 378, 378, 0, 378, 378, 378, 378, 379, 379, 379, 379, 379, 379, 379, 379, 379, 380, 380, 380, 0, 380, 380, 380, 380, 380, 381, 0, 381, 381, 381, 381, 381, 381, 381, 382, 0, 0, 0, 0, 0, 382, 383, 383, 0, 383, 384, 0, 384, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371, 371 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; static int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "pars0lex.l" /***************************************************************************** Copyright (c) 1997, 2019, Oracle and/or its affiliates. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ /****************************************************** SQL parser lexical analyzer: input file for the GNU Flex lexer generator The InnoDB parser is frozen because MySQL takes care of SQL parsing. Therefore we normally keep the InnoDB parser C files as they are, and do not automatically generate them from pars0grm.y and pars0lex.l. How to make the InnoDB parser and lexer C files: 1. Run ./make_flex.sh to generate lexer files. 2. Run ./make_bison.sh to generate parser files. These instructions seem to work at least with bison-1.875d and flex-2.5.31 on Linux. Created 12/14/1997 Heikki Tuuri *******************************************************/ #define YY_NO_INPUT 1 #define YY_NO_UNISTD_H 1 #line 53 "pars0lex.l" #define YYSTYPE que_node_t* #include "univ.i" #include "pars0pars.h" #include "pars0grm.h" #include "pars0sym.h" #include "mem0mem.h" #include "os0proc.h" #define malloc(A) ut_malloc_nokey(A) #define free(A) ut_free(A) #define realloc(P, A) ut_realloc(P, A) #define exit(A) ut_error /* Note: We cast result from int to yy_size_t */ #define YY_INPUT(buf, result, max_size) \ ((result) = pars_get_lex_chars(buf, max_size)) /* String buffer for removing quotes */ static ulint stringbuf_len_alloc = 0; /* Allocated length */ static ulint stringbuf_len = 0; /* Current length */ static char* stringbuf; /* Start of buffer */ /** Appends a string to the buffer. */ static void string_append( /*==========*/ const char* str, /*!< in: string to be appended */ ulint len) /*!< in: length of the string */ { if (stringbuf == nullptr) { stringbuf = static_cast<char *>(malloc(1)); stringbuf_len_alloc = 1; } if (stringbuf_len + len > stringbuf_len_alloc) { while (stringbuf_len + len > stringbuf_len_alloc) { stringbuf_len_alloc <<= 1; } stringbuf = static_cast<char*>( realloc(stringbuf, stringbuf_len_alloc)); } memcpy(stringbuf + stringbuf_len, str, len); stringbuf_len += len; } #line 947 "lexyy.cc" #define INITIAL 0 #define comment 1 #define quoted 2 #define id 3 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ MY_ATTRIBUTE((unused)) static int yylex_destroy (void ); MY_ATTRIBUTE((unused)) static int yyget_debug (void ); MY_ATTRIBUTE((unused)) static void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); MY_ATTRIBUTE((unused)) static FILE *yyget_in (void ); MY_ATTRIBUTE((unused)) static void yyset_in (FILE * in_str ); MY_ATTRIBUTE((unused)) static FILE *yyget_out (void ); MY_ATTRIBUTE((unused)) static void yyset_out (FILE * out_str ); yy_size_t yyget_leng (void ); MY_ATTRIBUTE((unused)) static char *yyget_text (void ); MY_ATTRIBUTE((unused)) static int yyget_lineno (void ); MY_ATTRIBUTE((unused)) static void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } { #line 112 "pars0lex.l" #line 1165 "lexyy.cc" while ( true ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 372 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 371 ); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 114 "pars0lex.l" { yylval = sym_tab_add_int_lit(pars_sym_tab_global, atoi(yytext)); return(PARS_INT_LIT); } YY_BREAK case 2: YY_RULE_SETUP #line 120 "pars0lex.l" { ut_error; /* not implemented */ return(PARS_FLOAT_LIT); } YY_BREAK case 3: YY_RULE_SETUP #line 126 "pars0lex.l" { ulint type; yylval = sym_tab_add_bound_lit(pars_sym_tab_global, yytext + 1, &type); return((int) type); } YY_BREAK case 4: YY_RULE_SETUP #line 135 "pars0lex.l" { yylval = sym_tab_add_bound_id(pars_sym_tab_global, yytext + 1); return(PARS_ID_TOKEN); } YY_BREAK case 5: YY_RULE_SETUP #line 142 "pars0lex.l" { /* Quoted character string literals are handled in an explicit start state 'quoted'. This state is entered and the buffer for the scanned string is emptied upon encountering a starting quote. In the state 'quoted', only two actions are possible (defined below). */ BEGIN(quoted); stringbuf_len = 0; } YY_BREAK case 6: /* rule 6 can match eol */ YY_RULE_SETUP #line 151 "pars0lex.l" { /* Got a sequence of characters other than "'": append to string buffer */ string_append(yytext, yyleng); } YY_BREAK case 7: YY_RULE_SETUP #line 156 "pars0lex.l" { /* Got a sequence of "'" characters: append half of them to string buffer, as "''" represents a single "'". We apply truncating division, so that "'''" will result in "'". */ string_append(yytext, yyleng / 2); /* If we got an odd number of quotes, then the last quote we got is the terminating quote. At the end of the string, we return to the initial start state and report the scanned string literal. */ if (yyleng % 2) { BEGIN(INITIAL); yylval = sym_tab_add_str_lit( pars_sym_tab_global, (byte*) stringbuf, stringbuf_len); return(PARS_STR_LIT); } } YY_BREAK case 8: YY_RULE_SETUP #line 180 "pars0lex.l" { /* Quoted identifiers are handled in an explicit start state 'id'. This state is entered and the buffer for the scanned string is emptied upon encountering a starting quote. In the state 'id', only two actions are possible (defined below). */ BEGIN(id); stringbuf_len = 0; } YY_BREAK case 9: /* rule 9 can match eol */ YY_RULE_SETUP #line 189 "pars0lex.l" { /* Got a sequence of characters other than '"': append to string buffer */ string_append(yytext, yyleng); } YY_BREAK case 10: YY_RULE_SETUP #line 194 "pars0lex.l" { /* Got a sequence of '"' characters: append half of them to string buffer, as '""' represents a single '"'. We apply truncating division, so that '"""' will result in '"'. */ string_append(yytext, yyleng / 2); /* If we got an odd number of quotes, then the last quote we got is the terminating quote. At the end of the string, we return to the initial start state and report the scanned identifier. */ if (yyleng % 2) { BEGIN(INITIAL); yylval = sym_tab_add_id( pars_sym_tab_global, (byte*) stringbuf, stringbuf_len); return(PARS_ID_TOKEN); } } YY_BREAK case 11: YY_RULE_SETUP #line 219 "pars0lex.l" { yylval = sym_tab_add_null_lit(pars_sym_tab_global); return(PARS_NULL_LIT); } YY_BREAK case 12: YY_RULE_SETUP #line 225 "pars0lex.l" { /* Implicit cursor name */ yylval = sym_tab_add_str_lit(pars_sym_tab_global, (byte*) yytext, yyleng); return(PARS_SQL_TOKEN); } YY_BREAK case 13: YY_RULE_SETUP #line 232 "pars0lex.l" { return(PARS_AND_TOKEN); } YY_BREAK case 14: YY_RULE_SETUP #line 236 "pars0lex.l" { return(PARS_OR_TOKEN); } YY_BREAK case 15: YY_RULE_SETUP #line 240 "pars0lex.l" { return(PARS_NOT_TOKEN); } YY_BREAK case 16: YY_RULE_SETUP #line 244 "pars0lex.l" { return(PARS_PROCEDURE_TOKEN); } YY_BREAK case 17: YY_RULE_SETUP #line 248 "pars0lex.l" { return(PARS_IN_TOKEN); } YY_BREAK case 18: YY_RULE_SETUP #line 252 "pars0lex.l" { return(PARS_OUT_TOKEN); } YY_BREAK case 19: YY_RULE_SETUP #line 256 "pars0lex.l" { return(PARS_BINARY_TOKEN); } YY_BREAK case 20: YY_RULE_SETUP #line 260 "pars0lex.l" { return(PARS_BLOB_TOKEN); } YY_BREAK case 21: YY_RULE_SETUP #line 264 "pars0lex.l" { return(PARS_INT_TOKEN); } YY_BREAK case 22: YY_RULE_SETUP #line 268 "pars0lex.l" { return(PARS_INT_TOKEN); } YY_BREAK case 23: YY_RULE_SETUP #line 272 "pars0lex.l" { return(PARS_FLOAT_TOKEN); } YY_BREAK case 24: YY_RULE_SETUP #line 276 "pars0lex.l" { return(PARS_CHAR_TOKEN); } YY_BREAK case 25: YY_RULE_SETUP #line 280 "pars0lex.l" { return(PARS_IS_TOKEN); } YY_BREAK case 26: YY_RULE_SETUP #line 284 "pars0lex.l" { return(PARS_BEGIN_TOKEN); } YY_BREAK case 27: YY_RULE_SETUP #line 288 "pars0lex.l" { return(PARS_END_TOKEN); } YY_BREAK case 28: YY_RULE_SETUP #line 292 "pars0lex.l" { return(PARS_IF_TOKEN); } YY_BREAK case 29: YY_RULE_SETUP #line 296 "pars0lex.l" { return(PARS_THEN_TOKEN); } YY_BREAK case 30: YY_RULE_SETUP #line 300 "pars0lex.l" { return(PARS_ELSE_TOKEN); } YY_BREAK case 31: YY_RULE_SETUP #line 304 "pars0lex.l" { return(PARS_ELSIF_TOKEN); } YY_BREAK case 32: YY_RULE_SETUP #line 308 "pars0lex.l" { return(PARS_LOOP_TOKEN); } YY_BREAK case 33: YY_RULE_SETUP #line 312 "pars0lex.l" { return(PARS_WHILE_TOKEN); } YY_BREAK case 34: YY_RULE_SETUP #line 316 "pars0lex.l" { return(PARS_RETURN_TOKEN); } YY_BREAK case 35: YY_RULE_SETUP #line 320 "pars0lex.l" { return(PARS_SELECT_TOKEN); } YY_BREAK case 36: YY_RULE_SETUP #line 324 "pars0lex.l" { return(PARS_SUM_TOKEN); } YY_BREAK case 37: YY_RULE_SETUP #line 328 "pars0lex.l" { return(PARS_COUNT_TOKEN); } YY_BREAK case 38: YY_RULE_SETUP #line 332 "pars0lex.l" { return(PARS_DISTINCT_TOKEN); } YY_BREAK case 39: YY_RULE_SETUP #line 336 "pars0lex.l" { return(PARS_FROM_TOKEN); } YY_BREAK case 40: YY_RULE_SETUP #line 340 "pars0lex.l" { return(PARS_WHERE_TOKEN); } YY_BREAK case 41: YY_RULE_SETUP #line 344 "pars0lex.l" { return(PARS_FOR_TOKEN); } YY_BREAK case 42: YY_RULE_SETUP #line 348 "pars0lex.l" { return(PARS_READ_TOKEN); } YY_BREAK case 43: YY_RULE_SETUP #line 352 "pars0lex.l" { return(PARS_ORDER_TOKEN); } YY_BREAK case 44: YY_RULE_SETUP #line 356 "pars0lex.l" { return(PARS_BY_TOKEN); } YY_BREAK case 45: YY_RULE_SETUP #line 360 "pars0lex.l" { return(PARS_ASC_TOKEN); } YY_BREAK case 46: YY_RULE_SETUP #line 364 "pars0lex.l" { return(PARS_DESC_TOKEN); } YY_BREAK case 47: YY_RULE_SETUP #line 368 "pars0lex.l" { return(PARS_INSERT_TOKEN); } YY_BREAK case 48: YY_RULE_SETUP #line 372 "pars0lex.l" { return(PARS_INTO_TOKEN); } YY_BREAK case 49: YY_RULE_SETUP #line 376 "pars0lex.l" { return(PARS_VALUES_TOKEN); } YY_BREAK case 50: YY_RULE_SETUP #line 380 "pars0lex.l" { return(PARS_UPDATE_TOKEN); } YY_BREAK case 51: YY_RULE_SETUP #line 384 "pars0lex.l" { return(PARS_SET_TOKEN); } YY_BREAK case 52: YY_RULE_SETUP #line 388 "pars0lex.l" { return(PARS_DELETE_TOKEN); } YY_BREAK case 53: YY_RULE_SETUP #line 392 "pars0lex.l" { return(PARS_CURRENT_TOKEN); } YY_BREAK case 54: YY_RULE_SETUP #line 396 "pars0lex.l" { return(PARS_OF_TOKEN); } YY_BREAK case 55: YY_RULE_SETUP #line 400 "pars0lex.l" { return(PARS_CREATE_TOKEN); } YY_BREAK case 56: YY_RULE_SETUP #line 404 "pars0lex.l" { return(PARS_TABLE_TOKEN); } YY_BREAK case 57: YY_RULE_SETUP #line 408 "pars0lex.l" { return(PARS_COMPACT_TOKEN); } YY_BREAK case 58: YY_RULE_SETUP #line 412 "pars0lex.l" { return(PARS_BLOCK_SIZE_TOKEN); } YY_BREAK case 59: YY_RULE_SETUP #line 416 "pars0lex.l" { return(PARS_INDEX_TOKEN); } YY_BREAK case 60: YY_RULE_SETUP #line 420 "pars0lex.l" { return(PARS_UNIQUE_TOKEN); } YY_BREAK case 61: YY_RULE_SETUP #line 424 "pars0lex.l" { return(PARS_CLUSTERED_TOKEN); } YY_BREAK case 62: YY_RULE_SETUP #line 428 "pars0lex.l" { return(PARS_DOES_NOT_FIT_IN_MEM_TOKEN); } YY_BREAK case 63: YY_RULE_SETUP #line 432 "pars0lex.l" { return(PARS_ON_TOKEN); } YY_BREAK case 64: YY_RULE_SETUP #line 436 "pars0lex.l" { return(PARS_DECLARE_TOKEN); } YY_BREAK case 65: YY_RULE_SETUP #line 440 "pars0lex.l" { return(PARS_CURSOR_TOKEN); } YY_BREAK case 66: YY_RULE_SETUP #line 444 "pars0lex.l" { return(PARS_OPEN_TOKEN); } YY_BREAK case 67: YY_RULE_SETUP #line 448 "pars0lex.l" { return(PARS_FETCH_TOKEN); } YY_BREAK case 68: YY_RULE_SETUP #line 452 "pars0lex.l" { return(PARS_CLOSE_TOKEN); } YY_BREAK case 69: YY_RULE_SETUP #line 456 "pars0lex.l" { return(PARS_NOTFOUND_TOKEN); } YY_BREAK case 70: YY_RULE_SETUP #line 460 "pars0lex.l" { return(PARS_TO_BINARY_TOKEN); } YY_BREAK case 71: YY_RULE_SETUP #line 464 "pars0lex.l" { return(PARS_SUBSTR_TOKEN); } YY_BREAK case 72: YY_RULE_SETUP #line 468 "pars0lex.l" { return(PARS_CONCAT_TOKEN); } YY_BREAK case 73: YY_RULE_SETUP #line 472 "pars0lex.l" { return(PARS_INSTR_TOKEN); } YY_BREAK case 74: YY_RULE_SETUP #line 476 "pars0lex.l" { return(PARS_LENGTH_TOKEN); } YY_BREAK case 75: YY_RULE_SETUP #line 480 "pars0lex.l" { return(PARS_COMMIT_TOKEN); } YY_BREAK case 76: YY_RULE_SETUP #line 484 "pars0lex.l" { return(PARS_ROLLBACK_TOKEN); } YY_BREAK case 77: YY_RULE_SETUP #line 488 "pars0lex.l" { return(PARS_WORK_TOKEN); } YY_BREAK case 78: YY_RULE_SETUP #line 492 "pars0lex.l" { return(PARS_UNSIGNED_TOKEN); } YY_BREAK case 79: YY_RULE_SETUP #line 496 "pars0lex.l" { return(PARS_EXIT_TOKEN); } YY_BREAK case 80: YY_RULE_SETUP #line 500 "pars0lex.l" { return(PARS_FUNCTION_TOKEN); } YY_BREAK case 81: YY_RULE_SETUP #line 504 "pars0lex.l" { return(PARS_LOCK_TOKEN); } YY_BREAK case 82: YY_RULE_SETUP #line 508 "pars0lex.l" { return(PARS_SHARE_TOKEN); } YY_BREAK case 83: YY_RULE_SETUP #line 512 "pars0lex.l" { return(PARS_MODE_TOKEN); } YY_BREAK case 84: YY_RULE_SETUP #line 516 "pars0lex.l" { return(PARS_LIKE_TOKEN); } YY_BREAK case 85: YY_RULE_SETUP #line 520 "pars0lex.l" { return(PARS_BIGINT_TOKEN); } YY_BREAK case 86: YY_RULE_SETUP #line 524 "pars0lex.l" { yylval = sym_tab_add_id(pars_sym_tab_global, (byte*) yytext, ut_strlen(yytext)); return(PARS_ID_TOKEN); } YY_BREAK case 87: YY_RULE_SETUP #line 531 "pars0lex.l" { yylval = sym_tab_add_id(pars_sym_tab_global, (byte*) yytext, ut_strlen(yytext)); return(PARS_TABLE_NAME_TOKEN); } YY_BREAK case 88: YY_RULE_SETUP #line 538 "pars0lex.l" { return(PARS_DDOT_TOKEN); } YY_BREAK case 89: YY_RULE_SETUP #line 542 "pars0lex.l" { return(PARS_ASSIGN_TOKEN); } YY_BREAK case 90: YY_RULE_SETUP #line 546 "pars0lex.l" { return(PARS_LE_TOKEN); } YY_BREAK case 91: YY_RULE_SETUP #line 550 "pars0lex.l" { return(PARS_GE_TOKEN); } YY_BREAK case 92: YY_RULE_SETUP #line 554 "pars0lex.l" { return(PARS_NE_TOKEN); } YY_BREAK case 93: YY_RULE_SETUP #line 558 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 94: YY_RULE_SETUP #line 563 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 95: YY_RULE_SETUP #line 568 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 96: YY_RULE_SETUP #line 573 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 97: YY_RULE_SETUP #line 578 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 98: YY_RULE_SETUP #line 583 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 99: YY_RULE_SETUP #line 588 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 100: YY_RULE_SETUP #line 593 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 101: YY_RULE_SETUP #line 598 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 102: YY_RULE_SETUP #line 603 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 103: YY_RULE_SETUP #line 608 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 104: YY_RULE_SETUP #line 613 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 105: YY_RULE_SETUP #line 618 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 106: YY_RULE_SETUP #line 623 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 107: YY_RULE_SETUP #line 628 "pars0lex.l" { return((int)(*yytext)); } YY_BREAK case 108: YY_RULE_SETUP #line 633 "pars0lex.l" BEGIN(comment); /* eat up comment */ YY_BREAK case 109: /* rule 109 can match eol */ YY_RULE_SETUP #line 635 "pars0lex.l" YY_BREAK case 110: /* rule 110 can match eol */ YY_RULE_SETUP #line 636 "pars0lex.l" YY_BREAK case 111: YY_RULE_SETUP #line 637 "pars0lex.l" BEGIN(INITIAL); YY_BREAK case 112: /* rule 112 can match eol */ YY_RULE_SETUP #line 639 "pars0lex.l" /* eat up whitespace */ YY_BREAK case 113: YY_RULE_SETUP #line 642 "pars0lex.l" { fprintf(stderr,"Unrecognized character: %02x\n", *yytext); ut_error; return(0); } YY_BREAK case 114: YY_RULE_SETUP #line 651 "pars0lex.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 2109 "lexyy.cc" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(comment): case YY_STATE_EOF(quoted): case YY_STATE_EOF(id): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = (yytext_ptr); int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = nullptr; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { yy_state_type yy_current_state; char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 372 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { int yy_is_jam; char *yy_cp = (yy_c_buf_p); YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 372 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 371); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ static void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ MY_ATTRIBUTE((unused)) static void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ static YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ static void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) nullptr; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ static void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ MY_ATTRIBUTE((unused)) static void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == nullptr) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if (YY_CURRENT_BUFFER) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ MY_ATTRIBUTE((unused)) static void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = nullptr; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ MY_ATTRIBUTE((unused)) static int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ MY_ATTRIBUTE((unused)) static FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ MY_ATTRIBUTE((unused)) static FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ yy_size_t yyget_leng (void) { return yyleng; } /** Get the current token. * */ MY_ATTRIBUTE((unused)) static char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number line number * */ MY_ATTRIBUTE((unused)) static void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ MY_ATTRIBUTE((unused)) static void yyset_in (FILE * in_str ) { yyin = in_str ; } MY_ATTRIBUTE((unused)) static void yyset_out (FILE * out_str ) { yyout = out_str ; } MY_ATTRIBUTE((unused)) static int yyget_debug (void) { return yy_flex_debug; } MY_ATTRIBUTE((unused)) static void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = nullptr; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *)nullptr; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *)nullptr; yyout = (FILE *)nullptr; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ MY_ATTRIBUTE((unused)) static int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = nullptr; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = nullptr; /* Reset the globals. This is important in a non-reentrant scanner so * the next time yylex() is called, initialization will occur. */ yy_init_globals(); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif static void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } static void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } static void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 650 "pars0lex.l" /********************************************************************** Release any resources used by the lexer. */ void pars_lexer_close(void) /*==================*/ { yylex_destroy(); free(stringbuf); stringbuf = nullptr; stringbuf_len_alloc = stringbuf_len = 0; }
27.008976
116
0.590611
silenc3502
88cea4245e1afd4b8b01c0337241f46a7b92f1b1
589
cpp
C++
src/semantic/semantic-utils.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
1
2019-07-01T02:02:40.000Z
2019-07-01T02:02:40.000Z
src/semantic/semantic-utils.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
src/semantic/semantic-utils.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
#include "semantic-utils.hpp" #include "semantic-pass.hpp" #include "ast/ast.hpp" namespace Noctis { StdUnorderedSet<QualNameSPtr> ExtractImportModules(AstTree& tree) { class ImportExtractor : public AstSemanticPass { public: ImportExtractor() : AstSemanticPass("import extractor") { } void Visit(AstImportStmt& node) override { QualNameSPtr qualName = QualName::Create(node.moduleIdens); qualNames.insert(qualName); } StdUnorderedSet<QualNameSPtr> qualNames; } extractor; extractor.Process(tree); return extractor.qualNames; } }
19
66
0.714771
noct-lang
88cef625917719a69838ff753fbbfb149edf66ee
2,982
cpp
C++
storage/sstable/writer/sharding_sstable_writer.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
264
2015-01-03T11:50:17.000Z
2022-03-17T02:38:34.000Z
storage/sstable/writer/sharding_sstable_writer.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
12
2015-04-27T15:17:34.000Z
2021-05-01T04:31:18.000Z
storage/sstable/writer/sharding_sstable_writer.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
128
2015-02-07T18:13:10.000Z
2022-02-21T14:24:14.000Z
// Copyright (c) 2013, The Toft Authors. // All rights reserved. // // Author: Ye Shunping <yeshunping@gmail.com> #include "toft/storage/sstable/writer/sharding_sstable_writer.h" #include "toft/base/stl_util.h" #include "toft/base/string/format.h" #include "toft/base/string/number.h" #include "toft/hash/fingerprint.h" #include "toft/storage/sharding/sharding.h" #include "toft/storage/sstable/writer/composited_sstable_writer.h" #include "thirdparty/glog/logging.h" namespace toft { const std::string ShardingSSTableWriter::GetShardingPath(const std::string &path, int shard_index, int shard_num) { return StringPrint("%s-%05d-of-%05d", path.c_str(), shard_index, shard_num); } ShardingSSTableWriter::ShardingSSTableWriter(int shard_num, const SSTableWriteOption &option) : SSTableWriter(option), shard_num_(shard_num), set_id_(0) { std::string policy = option.sharding_policy(); sharding_policy_.reset(TOFT_CREATE_SHARDING_POLICY(policy)); CHECK(sharding_policy_.get()) << "sharding policy is invalid: " << policy; sharding_policy_->SetShardingNumber(shard_num_); std::string set_finger = StringPrint("%s/%ld", option.path().c_str(), time(NULL)); set_id_ = Fingerprint64(set_finger); VLOG(1) << "set_id_:" << set_id_; for (int i = 0; i < shard_num_; ++i) { SSTableWriteOption opt(option); opt.set_path(GetShardingPath(option.path(), i, shard_num_)); builders_.push_back(new CompositedSSTableWriter(opt)); } } ShardingSSTableWriter::~ShardingSSTableWriter() { DeleteElements(&builders_); } bool ShardingSSTableWriter::Add(const std::string &key, const std::string &value) { int index = sharding_policy_->Shard(key); CHECK_GE(index, 0) << "bad index, key:" << key; return builders_[index]->Add(key, value); } void ShardingSSTableWriter::AddMetaData(const std::string &key, const std::string &value) { file_info_meta_[key] = value; } bool ShardingSSTableWriter::Flush() { SetMetaData(); bool result = true; for (int i = 0; i < shard_num_; ++i) { if (!builders_[i]->Flush()) result = false; } return result; } void ShardingSSTableWriter::SetMetaData() { std::string total_shard = NumberToString(shard_num_); for (int i = 0; i < shard_num_; ++i) { for (std::map<std::string, std::string>::const_iterator it = file_info_meta_.begin(); it != file_info_meta_.end(); ++it) builders_[i]->AddMetaData(it->first, it->second); builders_[i]->AddMetaData(kShardID, NumberToString(i)); builders_[i]->AddMetaData(kShardTotalNum, total_shard); builders_[i]->AddMetaData(kShardPolicy, option_.sharding_policy()); builders_[i]->AddMetaData(kSSTableSetID, NumberToString(set_id_)); } } } // namespace toft
35.5
93
0.653588
hjinlin
88d3df327a998aec29ea949377ccf13648683831
15,051
cpp
C++
src/main.cpp
GlyphXTools/chunk-viewer
d5163969e8986d557b6cfbb524279f36235fda02
[ "MIT" ]
7
2017-01-22T09:09:40.000Z
2021-11-13T08:51:31.000Z
src/main.cpp
GlyphXTools/chunk-viewer
d5163969e8986d557b6cfbb524279f36235fda02
[ "MIT" ]
null
null
null
src/main.cpp
GlyphXTools/chunk-viewer
d5163969e8986d557b6cfbb524279f36235fda02
[ "MIT" ]
1
2019-04-07T05:09:11.000Z
2019-04-07T05:09:11.000Z
#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <commdlg.h> #include <commctrl.h> #include <shlobj.h> #include "resource.h" #include <afxres.h> #include <tchar.h> #include <algorithm> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include "ChunkFile.h" #include "Exceptions.h" using namespace std; typedef basic_string<TCHAR> tstring; typedef basic_stringstream<TCHAR> tstringstream; // Global info about the applications struct ApplicationInfo { HINSTANCE hInstance; HWND hMainWnd; HWND hNodeTree; HWND hNodeInfo; HWND hWidthLabel; HWND hWidthUpDown; HWND hWidthEdit; tstring filename; vector<pair<int, char*> > nodeData; }; static bool IsProbablyMiniChunk(int size, char* data) { while (size > 2 && data[1] != 0) { int msize = (unsigned char)data[1] + 2; size -= msize; data += msize; } return (size == 0); } static void RemoveChildren( HWND hTree, HTREEITEM hItem) { HTREEITEM hChild; while ((hChild = TreeView_GetChild(hTree, hItem)) != NULL) { RemoveChildren(hTree, hChild); TreeView_DeleteItem(hTree, hChild); } } static void SetNodes( vector<pair<int, char*> >& nodeData, HWND hTree, HTREEITEM hParent, File* input) { HTREEITEM hItem = TreeView_GetChild(hTree, hParent); while (!input->eof()) { Chunk chunk(input); unsigned long start = input->tell(); tstringstream str; str << hex << setw(8) << setfill(TEXT('0')) << chunk.getType() << "h (" << setw(8) << chunk.getSize() << "h)"; tstring title = str.str(); TVINSERTSTRUCT item; item.item.mask = TVIF_CHILDREN | TVIF_TEXT | TVIF_PARAM; item.item.hItem = hItem; item.item.cChildren = (chunk.isGroup() ? 1 : 0); item.item.pszText = const_cast<tstring::value_type*>(title.c_str()); item.item.lParam = (chunk.isGroup() ? -1 : nodeData.size()); if (hItem == NULL) { // Add it item.hParent = hParent; item.hInsertAfter = TVI_LAST; hItem = TreeView_InsertItem(hTree, &item); } else { // Edit it if (!chunk.isGroup()) { // Remove all the node's children RemoveChildren(hTree, hItem); } TreeView_SetItem(hTree, &item.item); } if (chunk.isGroup()) { SetNodes(nodeData, hTree, hItem, chunk.getStream() ); } else { // Set the node data int size = chunk.getSize(); char* data = chunk.getData(); if (size < 0x1000 && IsProbablyMiniChunk(size, data)) { size = -size; } nodeData.push_back( make_pair(size, data) ); } input->seek( start + chunk.getSize() ); hItem = TreeView_GetNextSibling(hTree, hItem); } // Remove any trailing nodes while (hItem != NULL) { RemoveChildren(hTree, hItem); HTREEITEM hNext = TreeView_GetNextSibling(hTree, hItem); TreeView_DeleteItem(hTree, hItem); hItem = hNext; } } static void FillNodeTree( ApplicationInfo* info, File* file ) { // Clear previous for (vector<pair<int, char*> >::iterator i = info->nodeData.begin(); i != info->nodeData.end(); i++) { delete[] i->second; } info->nodeData.clear(); HTREEITEM hRoot = TreeView_GetRoot(info->hNodeTree); if (hRoot == NULL) { TVINSERTSTRUCT item; item.hParent = NULL; item.hInsertAfter = TVI_ROOT; item.item.mask = TVIF_CHILDREN | TVIF_TEXT | TVIF_PARAM; item.item.cChildren = 1; item.item.pszText = TEXT("Chunk File"); item.item.lParam = -1; hRoot = TreeView_InsertItem(info->hNodeTree, &item); } SetNodes(info->nodeData, info->hNodeTree, hRoot, file); TreeView_Expand( info->hNodeTree, hRoot, TVE_EXPAND); } static tstring FormatNodeInfo( int size, char* data, int width, const char* prefix = "") { tstringstream str; str << hex; for (int i = 0; i < size; i++) { if (i % width == 0) str << prefix; str << setw(2) << setfill(TEXT('0')) << (int)(unsigned char)data[i] << " "; if (i % width == width - 1 || i == size - 1) { for (int k = i; k % width < width - 1; k++) str << " "; str << " | "; for (int j = (i / width) * width; j <= i; j++) { str << (isprint((unsigned char)data[j]) ? data[j] : '.'); } str << "\r\n"; } } return str.str(); } static void SetNodeInfo( HWND hWnd, int size, char* data, int width = 16 ) { width = max(1, width); tstring text; if (size < 0) { // Parse as mini-chunks size = -size; tstringstream str; while (size > 0) { int type = (unsigned char)data[0]; int msize = (unsigned char)data[1]; tstring chunk = FormatNodeInfo(msize, data + 2, width, " "); if (!chunk.empty()) chunk = chunk.substr(7); str << hex << setw(2) << setfill(TEXT('0')) << type << " " << setw(2) << setfill(TEXT('0')) << msize << ": " << chunk; size -= msize + 2; data += msize + 2; } text = str.str(); } else { text = FormatNodeInfo(size, data, width); } SetWindowText(hWnd, text.c_str()); } static void OnNodeSelected(ApplicationInfo* info, int index) { if (index >= 0 && (size_t)index < info->nodeData.size()) { int size = info->nodeData[ index ].first; char* data = info->nodeData[ index ].second; BOOL error; int width = (int)SendMessage(info->hWidthUpDown, UDM_GETPOS32, 0, (LPARAM)&error); if (error) width = 16; SetNodeInfo( info->hNodeInfo, size, data, width ); } else { SetWindowText(info->hNodeInfo, TEXT("")); } } static void DlgOpenFile( ApplicationInfo *info ) { try { TCHAR filename[MAX_PATH]; filename[0] = TEXT('\0'); OPENFILENAME ofn; memset(&ofn, 0, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = info->hMainWnd; ofn.hInstance = info->hInstance; ofn.lpstrFilter = TEXT("Alamo Chunk Files (*.alo, *.ala, *.ted, *.tem, *.bui, *.rec)\0*.ALO; *.ALA; *.TED; *.TEM; *.BUI; *.REC\0All Files (*.*)\0*.*\0\0"); ofn.nFilterIndex = 0; ofn.lpstrFile = filename; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; if (GetOpenFileName( &ofn ) != 0) { // Clear previous info->filename = filename; File* file = new PhysicalFile(info->filename); SetWindowText(info->hNodeInfo, TEXT("")); FillNodeTree( info, file ); EnableMenuItem(GetMenu(info->hMainWnd), ID_FILE_REFRESH, MF_BYCOMMAND | MF_ENABLED); SetFocus(info->hNodeTree); SAFE_RELEASE(file); } } catch (exception&) { MessageBox(NULL, TEXT("Unable to open the specified file"), NULL, MB_OK | MB_ICONHAND ); } } static void RefreshFile(ApplicationInfo* info) { try { File* file = new PhysicalFile(info->filename); FillNodeTree( info, file ); SAFE_RELEASE(file); // Refresh selection TVITEM item; if ((item.hItem = TreeView_GetSelection(info->hNodeTree)) != NULL) { item.mask = TVIF_PARAM; TreeView_GetItem(info->hNodeTree, &item); OnNodeSelected(info, (int)item.lParam); } } catch (exception&) { MessageBox(NULL, TEXT("Unable to refresh the opened file"), NULL, MB_OK | MB_ICONHAND ); } } static void DoSelectAll() { HWND hFocus = GetFocus(); TCHAR classname[256]; GetClassName(hFocus, classname, 256); if (_tcscmp(classname, TEXT("Edit")) == 0) { // Select all text SendMessage(hFocus, EM_SETSEL, 0, -1); } } static LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { ApplicationInfo* info = (ApplicationInfo*)(LONG_PTR)GetWindowLongPtr(hWnd, GWLP_USERDATA); switch (uMsg) { case WM_CREATE: { CREATESTRUCT* pcs = (CREATESTRUCT*)lParam; info = (ApplicationInfo*)pcs->lpCreateParams; SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)info ); RECT client; GetClientRect(hWnd, &client); if ((info->hNodeTree = CreateWindowEx(WS_EX_CLIENTEDGE, WC_TREEVIEW, TEXT(""), WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT, 0, 0, 400, client.bottom, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1; if ((info->hWidthLabel = CreateWindow(TEXT("STATIC"), TEXT("Width:"), WS_CHILD | WS_VISIBLE, 410, 6, 40, 12, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1; if ((info->hWidthEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_CHILD | WS_VISIBLE | ES_RIGHT | ES_NUMBER, 450, 4, 75, 20, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1; if ((info->hWidthUpDown = CreateWindow(UPDOWN_CLASS, TEXT(""), WS_CHILD | WS_VISIBLE | UDS_NOTHOUSANDS | UDS_SETBUDDYINT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_ALIGNRIGHT, 400, 0, 10, 10, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1; if ((info->hNodeInfo = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_READONLY | WS_VSCROLL | WS_HSCROLL, 400, 30, client.right - 600, client.bottom, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1; SendMessage(info->hWidthUpDown, UDM_SETRANGE32, (WPARAM)1, (LPARAM)INT_MAX); SendMessage(info->hWidthUpDown, UDM_SETPOS32, 0, (LPARAM)16); HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); SendMessage(info->hNodeTree, WM_SETFONT, (WPARAM)hFont, FALSE); SendMessage(info->hWidthLabel, WM_SETFONT, (WPARAM)hFont, FALSE); SendMessage(info->hWidthEdit, WM_SETFONT, (WPARAM)hFont, FALSE); SendMessage(info->hNodeInfo, WM_SETFONT, (WPARAM)GetStockObject(OEM_FIXED_FONT), FALSE); break; } case WM_SETFOCUS: SetFocus(info->hNodeTree); break; case WM_COMMAND: if (lParam == 0) { // Menu or accelerator switch (LOWORD(wParam)) { case ID_FILE_OPEN: if (info != NULL) { DlgOpenFile(info); } break; case ID_FILE_REFRESH: if (info != NULL) { RefreshFile(info); } break; case ID_FILE_EXIT: PostQuitMessage(0); break; case ID_EDIT_COPY: SendMessage(GetFocus(), WM_COPY, 0, 0); break; case ID_EDIT_SELECTALL: DoSelectAll(); break; case ID_HELP_ABOUT: MessageBox(hWnd, TEXT("Alamo Chunk Viewer 1.0\n\nBy Mike Lankamp"), TEXT("About"), MB_OK); break; } } else if (info != NULL) { // Control switch (HIWORD(wParam)) { case EN_CHANGE: { TCHAR strWidth[32]; GetWindowText( info->hWidthEdit, strWidth, 32 ); TVITEM item; item.mask = TVIF_PARAM; item.hItem = TreeView_GetSelection(info->hNodeTree); TreeView_GetItem(info->hNodeTree, &item); if (item.hItem != NULL && item.lParam != -1) { int width = _tcstoul(strWidth, 0, NULL); int size = info->nodeData[ item.lParam ].first; char* data = info->nodeData[ item.lParam ].second; SetNodeInfo( info->hNodeInfo, size, data, width ); } break; } } } break; case WM_NOTIFY: if (info != NULL) { NMHDR* nmhdr = (NMHDR*)lParam; switch (nmhdr->code) { case TVN_SELCHANGED: { NMTREEVIEW* pnmtv = (NMTREEVIEW*)lParam; OnNodeSelected(info, (int)pnmtv->itemNew.lParam); break; } case UDN_DELTAPOS: { NM_UPDOWN* nmud = (NM_UPDOWN*)nmhdr; int width = nmud->iPos + nmud->iDelta; TVITEM item; item.mask = TVIF_PARAM; item.hItem = TreeView_GetSelection(info->hNodeTree); TreeView_GetItem(info->hNodeTree, &item); if (item.hItem != NULL && item.lParam != -1) { int size = info->nodeData[ item.lParam ].first; char* data = info->nodeData[ item.lParam ].second; SetNodeInfo( info->hNodeInfo, size, data, width ); } break; } } } break; case WM_SIZE: if (info != NULL) { RECT client; GetClientRect(info->hMainWnd, &client); MoveWindow(info->hNodeTree, 0, 0, 400, client.bottom, TRUE); MoveWindow(info->hNodeInfo, 400, 30, client.right - 400, client.bottom - 30, TRUE); } break; case WM_SIZING: { const int MIN_WIDTH = 750; const int MIN_HEIGHT = 300; RECT* rect = (RECT*)lParam; bool left = (wParam == WMSZ_BOTTOMLEFT) || (wParam == WMSZ_LEFT) || (wParam == WMSZ_TOPLEFT); bool top = (wParam == WMSZ_TOPLEFT) || (wParam == WMSZ_TOP) || (wParam == WMSZ_TOPRIGHT); if (rect->right - rect->left < MIN_WIDTH) { if (left) rect->left = rect->right - MIN_WIDTH; else rect->right = rect->left + MIN_WIDTH; } if (rect->bottom - rect->top < MIN_HEIGHT) { if (top) rect->top = rect->bottom - MIN_HEIGHT; else rect->bottom = rect->top + MIN_HEIGHT; } break; } case WM_CLOSE: PostQuitMessage(0); break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } void main( ApplicationInfo* info ) { ShowWindow(info->hMainWnd, SW_SHOW); HACCEL hAccel = LoadAccelerators( info->hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); MSG msg; while (GetMessage(&msg, NULL, 0, 0) != 0) { if (!TranslateAccelerator(info->hMainWnd, hAccel, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } // Create the main window and its child windows static void CreateMainWindow( ApplicationInfo* info ) { WNDCLASSEX wcx; wcx.cbSize = sizeof wcx; wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.lpfnWndProc = MainWindowProc; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.hInstance = info->hInstance; wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcx.hCursor = LoadCursor(NULL, IDC_ARROW); wcx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); wcx.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1); wcx.lpszClassName = TEXT("ChunkViewer"); wcx.hIconSm = NULL; if (RegisterClassEx(&wcx) == 0) { throw runtime_error("Unable to register window class"); } if ((info->hMainWnd = CreateWindowEx(0, TEXT("ChunkViewer"), TEXT("Chunk File Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, info->hInstance, info)) == NULL) { UnregisterClass(TEXT("ChunkViewer"), info->hInstance); throw runtime_error("Unable to create main window"); } } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) { try { ApplicationInfo info; info.hInstance = hInstance; CreateMainWindow( &info ); main( &info ); } catch (exception& e) { MessageBoxA(NULL, e.what(), NULL, MB_OK ); } return 0; }
27.718232
158
0.601156
GlyphXTools
88d3e546ef779b08d698fbd3e2c8f12f22b60a5b
5,049
cpp
C++
samples/macOS/cpp/sample_tools/source/threading/WinThreadImpl.cpp
holgafx/gehtsoft
7bb1dfc23d3b5b45793a85e162bbed2ca963d3ed
[ "Apache-2.0" ]
26
2018-01-11T16:46:15.000Z
2021-05-15T17:20:19.000Z
samples/macOS/cpp/sample_tools/source/threading/WinThreadImpl.cpp
Trading-Lab/Forex-Connect-API-FXCM
0f1b2d0e8ca972ddc83b01acdb74e75d3aef9bf7
[ "Apache-2.0" ]
5
2019-03-07T16:14:59.000Z
2020-06-10T02:35:04.000Z
samples/macOS/cpp/sample_tools/source/threading/WinThreadImpl.cpp
Trading-Lab/Forex-Connect-API-FXCM
0f1b2d0e8ca972ddc83b01acdb74e75d3aef9bf7
[ "Apache-2.0" ]
26
2017-11-01T19:20:30.000Z
2022-02-10T22:10:00.000Z
/* Copyright 2011 Forex Capital Markets LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use these files 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 "stdafx.h" #ifdef WIN32 #include <process.h> #include <memory> #include "threading/AThread.h" #include "threading/ThreadHandle.h" #include "mutex/Mutex.h" using sample_tools::Mutex; using sample_tools::AThread; using sample_tools::ThreadHandle; AThread::AThread() : mIsStopRequested(false), mHandle(0), mAccessMutex(), mThread(NULL) { mDefaultPriority = GetThreadPriority(GetCurrentThread()); } AThread::~AThread() { Mutex::Lock lock(mAccessMutex); if (mThread) { // if the thread is still running and it's the not current thread // then suspend it. Note that normally it's expected that the thread // is already stopped here ThreadHandle *handler = ThreadHandle::getCurrentThread(); if (!mHandle.equals(handler)) ::SuspendThread(mThread); handler ? handler->release() : false; ::CloseHandle(mThread); mThread = NULL; mHandle.setHandle(0); } } ThreadHandle const *AThread::getHandle() const { return &mHandle; } bool AThread::start() { Mutex::Lock lock(mAccessMutex); if (isRunning()) return true; if (mThread) { ::CloseHandle(mThread); mThread = 0; } mIsStopRequested = false; unsigned int threadId = 0; mThread = (HANDLE)_beginthreadex(NULL, 0, threadRunner, reinterpret_cast<void*>(this), 0, &threadId); mHandle.setHandle(threadId); // http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.80).aspx // 0 on an error, in which case errno and _doserrno are set // or functions set errno to EINVAL and return -1 if (mThread == (void *)-1L || mThread == 0) { mThread = NULL; mHandle.setHandle(0); return false; } return true; } bool AThread::join(unsigned long waitMilliseconds) { HANDLE localCopy = NULL; { Mutex::Lock lock(mAccessMutex); if (!isRunning()) return true; DWORD dwExitCode = 0; if (!GetExitCodeThread(mThread, &dwExitCode)) return true; if (dwExitCode != STILL_ACTIVE) return true; // thread is already terminated, so nothing to join. if (mHandle.getHandle() == ::GetCurrentThreadId()) return true; localCopy = mThread; } switch (::WaitForSingleObject(localCopy, waitMilliseconds)) { case WAIT_OBJECT_0: { Mutex::Lock lock(mAccessMutex); if (mThread) { ::CloseHandle(mThread); mThread = NULL; mHandle.setHandle(0); } return true; } default: return false; } } void AThread::requestStop() { mIsStopRequested = true; } bool AThread::isStopRequested() const { return mIsStopRequested; } bool AThread::isRunning() const { Mutex::Lock lock(mAccessMutex); if (!mThread) return false; return ::WaitForSingleObject(mThread, 0) == WAIT_TIMEOUT; } unsigned int AThread::threadRunner(void *param) { if (!param) return 1; AThread *obj = reinterpret_cast<AThread*>(param); obj->run(); return 0; } AThread::PriorityLevel AThread::getPriority() const { int priority = GetThreadPriority(mThread); if (priority != THREAD_PRIORITY_ERROR_RETURN) { if (priority == mDefaultPriority) return PriorityDefault; else if (priority == THREAD_PRIORITY_BELOW_NORMAL) return PriorityLow; else if (priority == THREAD_PRIORITY_ABOVE_NORMAL) return PriorityHigh; else if (priority == THREAD_PRIORITY_NORMAL) return PriorityNormal; else return PriorityUnknown; } return PriorityError; } bool AThread::setPriority(PriorityLevel ePrior) { BOOL bResult = FALSE; switch (ePrior) { case PriorityDefault: bResult = SetThreadPriority(mThread, mDefaultPriority); break; case PriorityLow: bResult = SetThreadPriority(mThread, THREAD_PRIORITY_BELOW_NORMAL); break; case PriorityNormal: bResult = SetThreadPriority(mThread, THREAD_PRIORITY_NORMAL); break; case PriorityHigh: bResult = SetThreadPriority(mThread, THREAD_PRIORITY_ABOVE_NORMAL); break; default: bResult = FALSE; } return bResult == TRUE; } #endif // WIN32
23.16055
105
0.631214
holgafx
88d87eaf52fd28adfa40899cfc5a491398f4e95b
1,209
cpp
C++
src/types/cons.cpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
2
2021-01-14T11:19:02.000Z
2021-03-07T03:08:08.000Z
src/types/cons.cpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
null
null
null
src/types/cons.cpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
null
null
null
#include <string> #include <list> #include "operations/types.hpp" #include "expressions.hpp" #include "types.hpp" #include "utils.hpp" using std::string; using namespace type; using namespace interp; Cons::Cons() { type_car = new Any; type_cdr = new Any; set_invoker(op::mk_cons_type); } Cons::Cons(Type* tcar, Type* tcdr) { type_car = tcar; type_cdr = tcdr; set_invoker(op::mk_cons_type); } void Cons::mark_node() { if (marked) return; Object::mark_node(); type_car->mark_node(); type_cdr->mark_node(); } string Cons::to_string(LocalRuntime &r, LexicalScope &s) { return "Cons"; } expr::Object *Cons::check_type(expr::Object *obj) { if (expr::Cons *cns = get_inbuilt<expr::Cons *>(obj)) { if (type_car->check_type(cns->car)->null()) { return expr::nil::get(); } if (type_cdr->check_type(cns->cdr)->null()) { return expr::nil::get(); } return expr::t::get(); } else { return expr::nil::get(); } } expr::Object *Cons::subtype(Type *obj) { if (Cons *tcons = dynamic_cast<Cons*>(obj)) { if (type_car->subtype(tcons->type_car) && type_cdr->subtype(tcons->type_cdr)) return expr::t::get(); } return expr::nil::get(); }
20.491525
58
0.632754
rationalis-petra
88dfe7898f2eb493b0d80f5dbaa13612dd942e84
6,648
cpp
C++
runtime/vm/vm/Vm.cpp
fanx-dev/fanx
902128c44b4b5c236a8b0a49986569097c7ca0aa
[ "AFL-3.0" ]
146
2019-03-18T14:09:46.000Z
2022-01-22T21:58:22.000Z
runtime/vm/vm/Vm.cpp
fanx-dev/fanx
902128c44b4b5c236a8b0a49986569097c7ca0aa
[ "AFL-3.0" ]
11
2019-11-27T19:00:22.000Z
2022-03-24T02:15:46.000Z
runtime/vm/vm/Vm.cpp
fanx-dev/fanx
902128c44b4b5c236a8b0a49986569097c7ca0aa
[ "AFL-3.0" ]
12
2019-06-03T05:06:49.000Z
2021-09-09T05:59:30.000Z
// // FVM.cpp // vm // // Created by yangjiandong on 15/9/27. // Copyright (c) 2015, yangjiandong. All rights reserved. // #include "Vm.h" #include "Env.h" #include <assert.h> #include <atomic> #include "gc/Gc.h" #ifdef FR_LLVM #include "SimpleLLVMJIT.hpp" #endif Fvm *fvm = NULL; Fvm::Fvm(PodManager *podManager) : podManager(podManager), executeEngine(nullptr) { gc = new Gc(this); //gc->gcSupport = this; LinkedList_make(&globalRefList); #ifdef FR_LLVM executeEngine = new SimpleLLVMJIT(); #endif fvm = this; podManager->vm = this; } Fvm::~Fvm() { fvm = NULL; LinkedList_release(&globalRefList); delete executeEngine; } Fvm* Fvm::getCur() { return fvm; } void Fvm::start() { } void Fvm::stop() { } Env *Fvm::getEnv() { std::lock_guard<std::recursive_mutex> lock_guard(lock); std::thread::id tid = std::this_thread::get_id(); auto found = threads.find(tid); Env *env; if (found != threads.end()) { env = found->second; } else { env = new Env(this); threads[tid] = env; } return env; } void Fvm::releaseEnv(Env *env) { std::lock_guard<std::recursive_mutex> lock_guard(lock); std::thread::id tid = std::this_thread::get_id(); threads.erase(tid); delete env; } void Fvm::registerMethod(const char *name, fr_NativeFunc func) { std::lock_guard<std::recursive_mutex> lock_guard(lock); podManager->registerMethod(name, func); } void Fvm::onStartGc() { } void Fvm::printObj(GcObj *obj) { FType* type = (FType*)gc_getType(obj); printf("%p(%s)", obj, type->c_mangledName.c_str()); } int Fvm::allocSize(GcObj* gcobj) { Env* env = nullptr; FObj *fobj = fr_fromGcObj(gcobj); FType *ftype = fr_getFType((fr_Env)env, fobj); FType *objArray = podManager->findType(env, "sys", "Array"); if (ftype == objArray) { fr_Array* array = (fr_Array*)fobj; return sizeof(array) + (array->elemSize * array->size) + sizeof(struct GcObj_); } return ftype->c_allocSize + sizeof(struct GcObj_); } void Fvm::visitChildrenByType(Collector* gc, FObj* fobj, FType *ftype) { Env* env = nullptr; if (ftype->hasBase()) { FType* base = podManager->getType(env, ftype->c_pod, ftype->meta.base); visitChildrenByType(gc, fobj, base); } for (int i = 0; i < ftype->fields.size(); ++i) { FField& f = ftype->fields[i]; if ((f.flags & FFlags::Storage) == 0) { continue; } if (f.flags & FFlags::Static) { //pass; } else { fr_Value* val = podManager->getInstanceFieldValue(fobj, &f); fr_ValueType vtype = podManager->getValueType(env, ftype->c_pod, f.type); if (vtype == fr_vtObj) { //list->push_back((FObj*)val->o); gc->onVisit(fr_toGcObj((FObj*)(val->o))); } } } } void Fvm::visitChildren(Collector *gc, GcObj* gcobj) { Env *env = nullptr; FObj *fobj = fr_fromGcObj(gcobj); FType *ftype = fr_getFType((fr_Env)env, fobj); FType *objArray = podManager->findType(env, "sys", "Array"); FType* objAtomicRef = podManager->findType(env, "std", "AtomicRef"); if (ftype == objArray) { fr_Array *array = (fr_Array *)fobj; if (array->valueType == fr_vtObj) { for (size_t i=0; i<array->size; ++i) { FObj * elem = ((FObj**)(array->data))[i]; //list->push_back((FObj*)obj); gc->onVisit(fr_toGcObj((FObj*)elem)); } } return; } if (ftype == objAtomicRef) { FObj** valptr = (FObj**)fobj; FObj* val = *valptr; if (val) { GcObj* gp = fr_toGcObj(val); //list->push_back(gp); gc->onVisit(gp); } return; } visitChildrenByType(gc, fobj, ftype); } void Fvm::walkRoot(Collector *gc) { //global ref LinkedListElem *it = LinkedList_first(&globalRefList); LinkedListElem *end = LinkedList_end(&globalRefList); while (it != end) { gc->onVisit(fr_toGcObj(reinterpret_cast<FObj*>(it->data))); it = it->next; } //static field for (auto it = staticFieldRef.begin(); it != staticFieldRef.end(); ++it) { gc->onVisit(fr_toGcObj(*reinterpret_cast<FObj **>(*it))); } //local for (auto it = threads.begin(); it != threads.end(); ++it) { Env *env = it->second; env->walkLocalRoot(gc); } } void Fvm::finalizeObj(GcObj* obj) { Env *env = getEnv(); fr_TagValue val; val.type = fr_vtObj; val.any.o = fr_fromGcObj(obj); env->push(&val); FMethod *m = env->findMethod("sys", "Obj", "finalize"); env->callVirtual(m, 0); //env->callVirtualMethod("finalize", 0); } void Fvm::puaseWorld(bool bloking) { while (true) { bool isAllStoped = true; lock.lock(); std::thread::id tid = std::this_thread::get_id(); for (auto it = threads.begin(); it != threads.end(); ++it) { if (it->first == tid) continue; Env* env = it->second; if (!env->isStoped.load()) { isAllStoped = false; //std::atomic_thread_fence(std::memory_order_acquire); } } lock.unlock(); if (isAllStoped) return; System_sleep(2); } } void Fvm::resumeWorld() { // std::lock_guard<std::recursive_mutex> lock_guard(lock); // for (auto it = threads.begin(); it != threads.end(); ++it) { // Env *env = it->second; // env->needStop = false; // } // std::atomic_thread_fence(std::memory_order_release); } fr_Obj Fvm::newGlobalRef(FObj * obj) { std::lock_guard<std::recursive_mutex> lock_guard(lock); LinkedListElem *elem = LinkedList_newElem(&globalRefList, 0); elem->data = obj; LinkedList_add(&globalRefList, elem); fr_Obj objRef = (fr_Obj)(&elem->data); return objRef; } void Fvm::deleteGlobalRef(fr_Obj objRef) { std::lock_guard<std::recursive_mutex> lock_guard(lock); LinkedListElem *elem = reinterpret_cast<LinkedListElem *>((char*)(objRef) - offsetof(LinkedListElem, data)); elem->data = NULL; LinkedList_remove(&globalRefList, elem); } void Fvm::addStaticRef(fr_Obj obj) { std::lock_guard<std::recursive_mutex> lock_guard(lock); staticFieldRef.push_back(obj); }
28.655172
114
0.563929
fanx-dev
88e307413a54906a6923035771943e45d0d427d6
3,246
cpp
C++
Solutions/DK_LM3S9B96/DeviceCode/Bootstrap_HAL/CortexM3_functions_bootstrap.cpp
yangjunjiao/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
4
2019-01-21T11:47:53.000Z
2020-06-09T02:14:15.000Z
Solutions/DK_LM3S9B96/DeviceCode/Bootstrap_HAL/CortexM3_functions_bootstrap.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
null
null
null
Solutions/DK_LM3S9B96/DeviceCode/Bootstrap_HAL/CortexM3_functions_bootstrap.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
4
2019-01-21T11:48:00.000Z
2021-05-04T12:37:55.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // This file is part of the Microsoft .NET Micro Framework Porting Kit Code Samples and is unsupported. // Copyright (C) Microsoft Corporation. All rights reserved. Use of this sample source code is subject to // the terms of the Microsoft license agreement under which you licensed this sample source code. // // THIS SAMPLE CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> #include "inc/hw_ints.h" #include "inc/hw_memmap.h" #include "inc/hw_types.h" #include "driverlib/gpio.h" #include "driverlib/sysctl.h" #include "driverlib/uart.h" #include "set_pinout.h" #include "../BlockStorage_HAL/ssiflash.h" //#define CODE_IN_EXT_MEM 1 extern void PrepareImageRegions(); //***************************************************************************** // // Send a string to the UART. // //***************************************************************************** void UARTSend(unsigned long ulUartAddr, const char *pucBuffer) { // Loop while there are more characters to send. while(*pucBuffer) { // // Write the next character to the UART. // UARTCharPut(ulUartAddr, *pucBuffer++); } } //--// void BootstrapCode() { const char CompanyStr[] = "Golden IC Technology Co.,Ltd.\n"; const char CompanyWebStr[] = "Web: www.Golden-IC.com\n"; #ifdef CODE_IN_EXT_MEM PrepareImageRegions(); g_eDaughterType = DAUGHTER_NONE;//DAUGHTER_SRAM_FLASH; #else // Set the system clock to run at 80MHz from the PLL SysCtlClockSet(SYSCTL_SYSDIV_3 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // Set the device pinout appropriately for this board. This also enables // all the GPIO ports required. PinoutSet(); PrepareImageRegions(); #endif //Enable UART0 ,Configure the UART for 115,200, 8-N-1 operation. SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); UARTConfigSetExpClk(UART0_BASE, SysCtlClockGet(), 115200,(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE)); UARTSend(UART0_BASE,CompanyStr); UARTSend(UART0_BASE,CompanyWebStr); //Enable UART1 ,Configure the UART for 115,200, 8-N-1 operation. SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1); UARTConfigSetExpClk(UART1_BASE, SysCtlClockGet(), 115200,(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE)); UARTSend(UART1_BASE,CompanyStr); UARTSend(UART1_BASE,CompanyWebStr); // }
39.585366
200
0.60382
yangjunjiao
88f126095c5f840d7be7903ce6288711c15f9443
2,425
hpp
C++
manager/lib/borealis/library/include/borealis/dropdown.hpp
lunixoid/sys-clk
731d0de5f580a7fa853804e0c776ba2f1623c932
[ "Beerware" ]
492
2019-02-14T16:10:55.000Z
2022-03-31T00:01:27.000Z
manager/lib/borealis/library/include/borealis/dropdown.hpp
lunixoid/sys-clk
731d0de5f580a7fa853804e0c776ba2f1623c932
[ "Beerware" ]
51
2019-02-14T17:31:08.000Z
2022-03-24T00:10:09.000Z
manager/lib/borealis/library/include/borealis/dropdown.hpp
lunixoid/sys-clk
731d0de5f580a7fa853804e0c776ba2f1623c932
[ "Beerware" ]
75
2019-02-14T17:46:32.000Z
2022-03-28T07:19:25.000Z
/* Borealis, a Nintendo Switch UI Library Copyright (C) 2019-2020 natinusala Copyright (C) 2019-2020 p-sam This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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 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 <https://www.gnu.org/licenses/>. */ #pragma once #include <borealis/event.hpp> #include <borealis/list.hpp> #include <borealis/view.hpp> #include <string> namespace brls { // Fired when the user has selected a value // // Parameter is either the selected value index // or -1 if the user cancelled // // Assume that the Dropdown is deleted // as soon as this function is called typedef Event<int> ValueSelectedEvent; // Allows the user to select between multiple // values // Use Dropdown::open() class Dropdown : public View { private: Dropdown(std::string title, std::vector<std::string> values, ValueSelectedEvent::Callback cb, size_t selected = 0); std::string title; int valuesCount; ValueSelectedEvent valueEvent; List* list; Hint* hint; float topOffset; // for slide in animation protected: unsigned getShowAnimationDuration(ViewAnimation animation) override; public: ~Dropdown(); void draw(NVGcontext* vg, int x, int y, unsigned width, unsigned height, Style* style, FrameContext* ctx) override; void layout(NVGcontext* vg, Style* style, FontStash* stash) override; View* getDefaultFocus() override; virtual bool onCancel(); void show(std::function<void(void)> cb, bool animate = true, ViewAnimation animation = ViewAnimation::FADE) override; void willAppear(bool resetState = false) override; void willDisappear(bool resetState = false) override; static void open(std::string title, std::vector<std::string> values, ValueSelectedEvent::Callback cb, int selected = -1); bool isTranslucent() override { return true || View::isTranslucent(); } }; } // namespace brls
29.938272
125
0.718351
lunixoid
88f40d44b9d726b071d7f417f5c1b5075f28b583
239
hpp
C++
include/dungeon/horizontal_wall.hpp
tanacchi/rogue_game
fd8f655f95932513f6aa63e0c413bbe110a4418a
[ "MIT" ]
10
2018-09-13T14:47:07.000Z
2022-01-10T11:46:12.000Z
include/dungeon/horizontal_wall.hpp
tanacchi/rogue_game
fd8f655f95932513f6aa63e0c413bbe110a4418a
[ "MIT" ]
13
2018-09-18T19:36:32.000Z
2020-11-12T16:26:22.000Z
include/dungeon/horizontal_wall.hpp
tanacchi/rogue_game
fd8f655f95932513f6aa63e0c413bbe110a4418a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_HORIZONTAL_WALL_HPP #define INCLUDED_HORIZONTAL_WALL_HPP #include <dungeon/dungeon_elem.hpp> // '-' class HorizontalWall : public DungeonElem { public: HorizontalWall(); }; #endif // INCLUDED_HORIZONTAL_WALL_HPP
17.071429
41
0.778243
tanacchi
88f6e054906565a72309755b609a32cb3b2d9bd6
2,138
cpp
C++
Basil/src/Renderer/Renderer.cpp
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
Basil/src/Renderer/Renderer.cpp
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
Basil/src/Renderer/Renderer.cpp
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Platform/OpenGL/OpenGLRendererAPI.h" #include "Renderer/Renderer.h" #include "Renderer/Renderer2D.h" namespace Basil { // Set the render API currently in use Unique<RendererAPI> Renderer::rendererAPI = makeUnique<OpenGLRendererAPI>(); // Screate the scene data struct Unique<Renderer::SceneData> Renderer::sceneData = makeUnique<Renderer::SceneData>(); // Initialise renderer void Renderer::init() { PROFILE_FUNCTION(); rendererAPI->init(); Renderer2D::init(); } // Shutdown renderer void Renderer::shutdown() { Renderer2D::shutdown(); } // On window resize event void Renderer::onWindowResize(unsigned int width, unsigned int height) { rendererAPI->setViewport(0, 0, width, height); } // Begin a scene void Renderer::beginScene(OrthographicCamera& camera) { sceneData->viewProjectionMatrix = camera.getViewProjectionMatrix(); } // End a scene void Renderer::endScene() { } // Submit data to be rendered void Renderer::submit(const Shared<Shader>& shader, const Shared<VertexArray>& vao, const glm::mat4& transform) { PROFILE_FUNCTION(); // Bind the shader and upload the uniform shader->bind(); shader->setMat4("u_ViewProjection", sceneData->viewProjectionMatrix); shader->setMat4("u_Transform", transform); // Bind the vertex array and draw the data vao->bind(); Renderer::drawIndexed(vao); } // Set the clear colour void Renderer::setClearColor(const glm::vec4& color) { rendererAPI->setClearColor(color); } // Clear the screen void Renderer::clear() { rendererAPI->clear(); } // Draw the object(s) in the VAO void Renderer::drawIndexed(const Shared<VertexArray>& vao, uint32_t count) { rendererAPI->drawIndexed(vao, count); } // Draw lines void Renderer::drawLines(const Shared<VertexArray>& vertexArray, uint32_t vertexCount) { rendererAPI->drawLines(vertexArray, vertexCount); } // Set line width void Renderer::setLineWidth(float width) { rendererAPI->setLineWidth(width); } // Return the rendering API currently being used RendererAPI::API Renderer::getAPI() { return RendererAPI::getAPI(); } }
22.270833
112
0.721703
Tamookk
88fc0c8a0edad19a664de5dd9329f4a4c959c4e2
372
hpp
C++
src/rover/gps.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
1
2018-10-16T02:32:49.000Z
2018-10-16T02:32:49.000Z
src/rover/gps.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
13
2018-10-23T20:35:10.000Z
2018-11-23T22:44:32.000Z
src/subsystems_computer/gps.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
1
2018-10-16T03:11:39.000Z
2018-10-16T03:11:39.000Z
#include "../network/network.hpp" #include "../util/util.hpp" namespace gps { struct Position { float latitude; float longitude; }; enum class Error { OK, OPEN, GET_ATTR, SET_ATTR }; Error init(const char* device_id, util::Clock* global_clock); Position get_position(); float get_heading(); network::LocationMessage::FixStatus get_fix(); }
13.777778
61
0.680108
2535Rover
88fd4c24ab2707b32cb3ad984c7bc390690e3ce4
1,436
cpp
C++
tests/unit/src/stdts/algorithm.cpp
carlbrown/scraps
78925a738540415ec04b9cbe23cb319421f44978
[ "Apache-2.0" ]
null
null
null
tests/unit/src/stdts/algorithm.cpp
carlbrown/scraps
78925a738540415ec04b9cbe23cb319421f44978
[ "Apache-2.0" ]
null
null
null
tests/unit/src/stdts/algorithm.cpp
carlbrown/scraps
78925a738540415ec04b9cbe23cb319421f44978
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2016 BitTorrent 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. */ #include "../gtest.h" #include <stdts/algorithm.h> #include <random> TEST(stdts_algorithm, sample) { std::vector<int> set{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> counts(9, 0); std::random_device rd; for (int i = 0; i < 1000; ++i) { std::default_random_engine gen(rd()); std::vector<int> result(5); stdts::sample(set.begin(), set.end(), result.begin(), result.size(), gen); EXPECT_EQ(result.size(), 5); std::sort(result.begin(), result.end()); int prev = 0; for (auto i : result) { EXPECT_NE(i, prev); EXPECT_GT(i, 0); EXPECT_LT(i, 10); ++counts[i - 1]; prev = i; } } auto minmax = std::minmax_element(counts.begin(), counts.end()); EXPECT_GT(*minmax.first, *minmax.second * 0.8); }
27.09434
82
0.618384
carlbrown
88fe22937c74bbd8d1e82479b5d2cc015d32d1c1
4,237
cc
C++
sparse_operation_kit/kit_cc/kit_cc_infra/src/parameters/param_interface.cc
x-y-z/HugeCTR
17bf942215df60827ece9dc015af5191ef9219b7
[ "Apache-2.0" ]
130
2021-10-11T11:55:28.000Z
2022-03-31T21:53:07.000Z
sparse_operation_kit/kit_cc/kit_cc_infra/src/parameters/param_interface.cc
Teora/HugeCTR
c55a63401ad350669ccfcd374aefd7a5fc879ca2
[ "Apache-2.0" ]
72
2021-10-09T04:59:09.000Z
2022-03-31T11:27:54.000Z
sparse_operation_kit/kit_cc/kit_cc_infra/src/parameters/param_interface.cc
Teora/HugeCTR
c55a63401ad350669ccfcd374aefd7a5fc879ca2
[ "Apache-2.0" ]
29
2021-11-03T22:35:01.000Z
2022-03-30T13:11:59.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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 "parameters/param_interface.h" #include "parameters/raw_param.h" #include "common.h" namespace SparseOperationKit { // helper function to create Param Implementation std::shared_ptr<ParamInterface> ParamInterface::CreateParam( const ParamType param_type, const std::string& initializer, const bool use_hashtable, const std::vector<size_t> shape, const std::shared_ptr<ResourcesManager>& resource_mgr, const std::string var_name, const bool trainable, const DataType key_dtype, const DataType value_dtype) { std::shared_ptr<ParamInterface> param{nullptr}; switch (param_type) { case ParamType::RawParam: { RawParamCtor_t raw_param_creater = GetRawParamCtor(key_dtype, value_dtype); param = raw_param_creater(initializer, use_hashtable, shape, resource_mgr, var_name, trainable); break; } default: { throw std::runtime_error(ErrorBase + "UnKnown Parameter type."); } } // switch block return param; } ParamInterface::ParamInterface(const size_t max_vocabulary_size_per_gpu, const size_t embedding_vec_size, const bool trainable, const std::string var_name, const DataType dtype, const DataType key_dtype) : max_vocabulary_size_per_gpu_(max_vocabulary_size_per_gpu), embedding_vec_size_(embedding_vec_size), trainable_(trainable), var_name_(var_name), dtype_(dtype), key_dtype_(key_dtype) {} size_t ParamInterface::get_max_vocabulary_size_per_gpu() const { return max_vocabulary_size_per_gpu_; } size_t ParamInterface::get_embedding_vec_size() const { return embedding_vec_size_; } bool ParamInterface::trainable() const { return trainable_; } std::string ParamInterface::get_var_name() const { return var_name_; } DataType ParamInterface::dtype() const { return dtype_; } DataType ParamInterface::key_dtype() const { return key_dtype_; } void ParamInterface::set_user(std::shared_ptr<EmbeddingLayer>& embedding) { // It is not compulsory for the subclass to override this function. throw std::runtime_error(ErrorBase + "Not implemented."); } void ParamInterface::let_user_dump_to_file(const std::string filepath) { // by default, it does nothing. } void ParamInterface::let_user_restore_from_file(const std::string filepath) { // by default, it does nothing. } void ParamInterface::let_user_load_embedding_values( const std::shared_ptr<Tensor>& tensor_list) { // by default, it does nothing } std::shared_ptr<Tensor>& ParamInterface::get_tensor(const size_t local_replica_id) { return get_embedding_table_tensor(local_replica_id); } void ParamInterface::set_hashtable(std::shared_ptr<BaseSimpleHashtable> hashtable) { throw std::runtime_error(ErrorBase + "Not implemented."); } TypeIdentity::TypeIdentity(const DataType key_dtype, const DataType value_dtype) : key_dtype_(key_dtype), value_dtype_(value_dtype) {} size_t TypeIdentityHash::operator()(const TypeIdentity& type_id) const { return std::hash<DataType>()(type_id.key_dtype_) ^ (std::hash<DataType>()(type_id.value_dtype_) << 1); } bool TypeIdentityEqual::operator()(const TypeIdentity& lid, const TypeIdentity& rid) const { return (lid.key_dtype_ == rid.key_dtype_) && (lid.value_dtype_ == rid.value_dtype_); } } // namespace SparseOperationKit
35.016529
102
0.695067
x-y-z
88fe57dc7905b93b0e001c26362393f0d9c90f4c
1,199
hpp
C++
core/src/utils/NoiseUtils.hpp
lonnibesancon/utymap
6d14a3d1386aade8c2755da4abc00269284c90d4
[ "Apache-2.0" ]
1
2019-04-04T14:20:37.000Z
2019-04-04T14:20:37.000Z
core/src/utils/NoiseUtils.hpp
lonnibesancon/utymap
6d14a3d1386aade8c2755da4abc00269284c90d4
[ "Apache-2.0" ]
null
null
null
core/src/utils/NoiseUtils.hpp
lonnibesancon/utymap
6d14a3d1386aade8c2755da4abc00269284c90d4
[ "Apache-2.0" ]
null
null
null
#ifndef UTILS_NOISEUTILS_HPP_DEFINED #define UTILS_NOISEUTILS_HPP_DEFINED #include "math/Vector2.hpp" #include "math/Vector3.hpp" namespace utymap { namespace utils { /// Provides noise generation functions. /// Ported from C# code from here : http ://catlikecoding.com/unity/tutorials/noise/ class NoiseUtils final { public: /// Calculates perlin 2D noise. static double perlin2D(double x, double y, double frequency); /// Calculates perlin 3D noise. static double perlin3D(double x, double y, double z, double freq); private: static double dot(const utymap::math::Vector3& g, double x, double y, double z) { return g.x*x + g.y*y + g.z*z; } static double dot(const utymap::math::Vector2& g, double x, double y) { return g.x*x + g.y*y; } static double smooth(double t) { return t*t*t*(t*(t * 6 - 15) + 10); } static const int HashMask = 255; static const int GradientsMask2D = 7; static const int GradientsMask3D = 15; static const utymap::math::Vector2 Gradients2D[]; static const utymap::math::Vector3 Gradients3D[]; static const int Hash[]; }; }} #endif // UTILS_NOISEUTILS_HPP_DEFINED
25.510638
84
0.672227
lonnibesancon
000240dae58cd8e9747a272b41b6cff64dd7fea8
728
cpp
C++
Leetcode/Contains_Duplicate_II.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
1
2019-03-24T12:35:43.000Z
2019-03-24T12:35:43.000Z
Leetcode/Contains_Duplicate_II.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
Leetcode/Contains_Duplicate_II.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
//Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that //nums[i] = nums[j] and the difference between i and j is at most k. class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { if(nums.size()<=1) return false; map<int,int>M; map<int,int>::iterator it=M.begin(); for(int i=0;i<nums.size();i++) { it=M.find(nums[i]); if(it!=M.end()) return true; else { M[nums[i]]=i; if(i>k-1) M.erase(nums[i-k]); } } return false; } };
26.962963
125
0.483516
anishacharya
0002baa9008ce6d632eddd1c9323b18dacee890a
1,369
cpp
C++
JMap_Xbox.cpp
Gallard88/ROSV_Joystick
de44334526571a3b814bcee18ae873907f38ec57
[ "MIT" ]
null
null
null
JMap_Xbox.cpp
Gallard88/ROSV_Joystick
de44334526571a3b814bcee18ae873907f38ec57
[ "MIT" ]
null
null
null
JMap_Xbox.cpp
Gallard88/ROSV_Joystick
de44334526571a3b814bcee18ae873907f38ec57
[ "MIT" ]
null
null
null
#include <unistd.h> #include <fcntl.h> #include "JMap_Xbox.h" using namespace std; /* * Generix X-Box pad. * 8x Axis * 11x Buttons * */ JMap_Xbox::JMap_Xbox(JoyStickDriver *driver): Joy(driver), Depth(0), IncEdge(false), DecEdge(false) { } float JMap_Xbox::GetVectorValue(ControlVectors vector) { switch ( vector ) { case vecForward: return (Joy->GetAxis(1) * -100.0) / 32767; case vecTurn: return (Joy->GetAxis(0) * 100) / 32767; case vecStrafe: return (Joy->GetAxis(3) * 100.0) / 32767; case vecDepth: return (float)Depth; } return 0; } void JMap_Xbox::Run_Task(void) { int rv = 1; while ( rv > 0 ) { fd_set readFD; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1; int j_fd = Joy->GetFileDescript(); FD_ZERO(&readFD); FD_SET(j_fd, &readFD); rv = select(j_fd+1, &readFD, NULL, NULL, &timeout); if ( rv > 0 ) { if ( FD_ISSET(j_fd, &readFD) ) { Joy->Run(); } } CalcDepth(); } } void JMap_Xbox::CalcDepth(void) { bool edge = Joy->GetButton(5); if (( IncEdge == false ) && ( edge == true ) && ( Depth < 100 )) { Depth += 10; } IncEdge = edge; edge = Joy->GetButton(4); if (( DecEdge == false ) && ( edge == true ) && ( Depth > 0 )) { Depth -= 10; } DecEdge = edge; }
15.735632
55
0.558072
Gallard88
322dc8cbfbaafee58b6218555c23ba60c3eefcf3
4,685
cxx
C++
model_server/cmd/src/cmd_exec.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
model_server/cmd/src/cmd_exec.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
model_server/cmd/src/cmd_exec.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ // file cmd_exec.C // // // History: 10/02/91 M.Furman Initial coding. #ifndef ISO_CPP_HEADERS #include <fstream.h> #include <ctype.h> #include <stdio.h> #else /* ISO_CPP_HEADERS */ #include <fstream> using namespace std; #include <cctype> #include <cstdio> #endif /* ISO_CPP_HEADERS */ #include "cmd.h" #include "genError.h" #include "genString.h" #include "systemMessages.h" #include "messages.h" #include "msg.h" // Fills genString txt with text of a specified file. Returns // -1 if a file does not exist; // 0 if file is not an ASCII file // 1 if succeded // static int get_file_text (const char *fname, genString& txt) { Initialize(get_file_text); int count = 0; char *buf = 0; char ch; ifstream temp_in( fname, ios::in ); if ( !temp_in ) // open failed ? return -1; while (temp_in.get(ch)) // character count and type check { count++ ; if(! isascii(ch)) return 0; } // force a new line at the end buf = new char[++count + 1]; temp_in.close(); // beginning of file count = 0; ifstream second_temp_in( fname, ios::in ); while (second_temp_in.get(ch)) { buf[count] = ch; count++ ; } second_temp_in.close(); buf[count++] = '\n'; buf[count] = '\0'; // Instead of EOF for LEX. txt = buf; delete buf; return 1; } // Adds uniqe file name before single block // // static void check_func_or_block (genString& txt) { Initialize(check_func_or_block); static int b_counter = 0; char* body = txt; body = strchr(body, '{'); // find first left brace and ignore everything before if (body){ char buf[40]; char* body_end = strrchr(body, '}'); // find last right brace and ignore if (body_end) // everyting after body_end[1] = '\0'; if (b_counter) sprintf (buf, "%s%d%s","___cmd_journal", b_counter," () "); else sprintf (buf, "%s%s", "___cmd_journal", " () "); b_counter++; genString n_txt(buf); n_txt += body; IF (!body_end) // everyting after n_txt += "}"; txt.put_value ((const char *)n_txt); } } extern "C" void execute_regression(char *s); void cmd_execute(char *fname) { Initialize(cmd_execute); if (fname == 0) return; genString txt; int res = get_file_text (fname, txt); if (res == -1) { msg("ERROR: File $1 does not exist.") << fname << eom; return; } else if (res == 0) { msg("ERROR: File \'$1\' is not ASCII.") << fname << eom; return; } /* should be renamed "parse_regression_text: */ execute_regression ((char *)txt); }
31.233333
83
0.560085
kit-transue
322dcbfd67fdb62dd60f01ce589c0914e162206a
2,195
cpp
C++
USBCamera/readAndSave.cpp
sdbzzhaotq/DemoCollection
94cd136e7a67ee60634139886d45b69e1ffd0e4c
[ "MIT" ]
null
null
null
USBCamera/readAndSave.cpp
sdbzzhaotq/DemoCollection
94cd136e7a67ee60634139886d45b69e1ffd0e4c
[ "MIT" ]
null
null
null
USBCamera/readAndSave.cpp
sdbzzhaotq/DemoCollection
94cd136e7a67ee60634139886d45b69e1ffd0e4c
[ "MIT" ]
null
null
null
#include <opencv2/opencv.hpp> #include <iostream> #include <chrono> #include <ctime> #include "MatIO.h" const int ROAD_CAMERA_ID = 0; #define FRAME_WIDTH 1164 #define FRAME_HEIGHT 874 void write_mb() { //VideoCapture capture(ROAD_CAMERA_ID, cv::CAP_V4L2); cv::VideoCapture capture("ns.mov"); capture.set(cv::CAP_PROP_FRAME_WIDTH, 853); capture.set(cv::CAP_PROP_FRAME_HEIGHT, 480); capture.set(cv::CAP_PROP_FPS, 20); capture.set(cv::CAP_PROP_AUTOFOCUS, 0); capture.set(cv::CAP_PROP_FOCUS, 0); float ts[9] = {1.50330396, 0.0, -59.40969163, 0.0, 1.50330396, 76.20704846, 0.0, 0.0, 1.0}; assert(capture.isOpened()); cv::Size size(FRAME_WIDTH,FRAME_HEIGHT); const cv::Mat transform = cv::Mat(3, 3, CV_32F, ts); cv::Mat frame_mat, transformed_mat; char szFilename[20] = {}; std::string name; static int index = 0; for(;;) { capture >> frame_mat; cv::warpPerspective(frame_mat, transformed_mat, transform, size, cv::INTER_LINEAR, cv::BORDER_CONSTANT, 0); sprintf(szFilename,"mb/%d.mb",index); name.assign(szFilename); Utils::write(name,transformed_mat); cv::imshow("video", transformed_mat); index++; if (cv::waitKey(10) == 27) { std::cout << "Esc key is pressed by user. Stoppig the video" << std::endl; break; } } } void read_mb() { for(auto i=0;i<8991;i++) { char szFilename[20] = {}; std::string name; sprintf(szFilename,"mb/%d.mb",i); name.assign(szFilename); cv::Mat frame_mat = Utils::read(name); cv::imshow("video", frame_mat); if (cv::waitKey(10) == 27) { std::cout << "Esc key is pressed by user. Stoppig the video" << std::endl; break; } } } int main(int argc, char** argv) { if(argc < 2) { printf("argument is error, write or read\n"); return 0; } std::string arg = argv[1]; if("read" == arg){ read_mb(); } else if("write" == arg){ write_mb(); } else { printf("argument is error, write or read\n"); } return 0; }
28.141026
115
0.575399
sdbzzhaotq
322dfc8c02df49b996c3784d8e77b2864bb655eb
531
cpp
C++
source/discord/gateway.cpp
kociap/Discord-
fcbf30d199ec217e0e6289aee96e365de383dbda
[ "MIT" ]
null
null
null
source/discord/gateway.cpp
kociap/Discord-
fcbf30d199ec217e0e6289aee96e365de383dbda
[ "MIT" ]
2
2019-01-15T07:38:54.000Z
2019-01-15T07:44:35.000Z
source/discord/gateway.cpp
kociap/Discord-
fcbf30d199ec217e0e6289aee96e365de383dbda
[ "MIT" ]
1
2018-10-25T12:12:34.000Z
2018-10-25T12:12:34.000Z
#include "gateway.hpp" #include "nlohmann/json.hpp" #include "rpp/rpp.hpp" #include "urls.hpp" namespace discord { namespace gateway { String get_gateway() { rpp::Request req; req.set_verbose(true); req.set_verify_ssl(false); rpp::Response res = req.get(url::gateway); nlohmann::json json = nlohmann::json::parse(res.text); return json.at("url").get<String>() + "/?v=6&encoding=json"; } } // namespace gateway } // namespace discord
27.947368
72
0.585687
kociap
322f39bcfd3679a79ea8881ca81d3a6b5db56df2
62
cpp
C++
src/ov2math/ov2math.cpp
bluespeck/ov2math
dd1c8bfe1413c65d1622e201b9f559e9fcfe9cff
[ "MIT" ]
null
null
null
src/ov2math/ov2math.cpp
bluespeck/ov2math
dd1c8bfe1413c65d1622e201b9f559e9fcfe9cff
[ "MIT" ]
null
null
null
src/ov2math/ov2math.cpp
bluespeck/ov2math
dd1c8bfe1413c65d1622e201b9f559e9fcfe9cff
[ "MIT" ]
null
null
null
#include <version.hpp> #include <src/ov2math/vector2.hpp>
8.857143
34
0.709677
bluespeck
323426d24d8492974a62c33e7327e1a5a8b0deb2
76
cpp
C++
test/compile_include_text_view_2.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
null
null
null
test/compile_include_text_view_2.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
1
2021-03-05T12:56:59.000Z
2021-03-05T13:11:53.000Z
test/compile_include_text_view_2.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
3
2019-10-30T18:38:15.000Z
2021-03-05T12:10:13.000Z
#include <boost/text/string_view.hpp> #include <boost/text/string_view.hpp>
25.333333
37
0.789474
eightysquirrels
323cab871b1faef27055bd61b2d3302ef9503464
8,301
cpp
C++
hpvm/test/benchmarks/parboil/benchmarks/lbm/src/hpvm/lbm.cpp
vzyrianov/hpvm-autograd
521cc3b684531548aea75f9fe3cc673aaa4a2e90
[ "Apache-2.0" ]
null
null
null
hpvm/test/benchmarks/parboil/benchmarks/lbm/src/hpvm/lbm.cpp
vzyrianov/hpvm-autograd
521cc3b684531548aea75f9fe3cc673aaa4a2e90
[ "Apache-2.0" ]
null
null
null
hpvm/test/benchmarks/parboil/benchmarks/lbm/src/hpvm/lbm.cpp
vzyrianov/hpvm-autograd
521cc3b684531548aea75f9fe3cc673aaa4a2e90
[ "Apache-2.0" ]
1
2020-03-24T16:01:54.000Z
2020-03-24T16:01:54.000Z
/*************************************************************************** *cr *cr (C) Copyright 2010 The Board of Trustees of the *cr University of Illinois *cr All Rights Reserved *cr ***************************************************************************/ /*############################################################################*/ // includes, system #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // includes, project #include "lbm_macros.h" #include "layout_config.h" #include "lbm.h" /******************************************************************************/ /*############################################################################*/ void LBM_allocateGrid(float **ptr) { const size_t size = TOTAL_PADDED_CELLS * N_CELL_ENTRIES * sizeof(float); *ptr = (float *)malloc(size); if (!*ptr) { printf("LBM_allocateGrid: could not allocate %.1f MByte\n", size / (1024.0 * 1024.0)); exit(1); } memset(*ptr, 0, size); printf("LBM_allocateGrid: allocated %.1f MByte\n", size / (1024.0 * 1024.0)); *ptr += MARGIN; } /******************************************************************************/ /*############################################################################*/ void LBM_freeGrid(float **ptr) { free(*ptr - MARGIN); *ptr = NULL; } /******************************************************************************/ /*############################################################################*/ void LBM_initializeGrid(LBM_Grid grid) { SWEEP_VAR SWEEP_START(0, 0, 0, 0, 0, SIZE_Z) SRC_C(grid) = DFL1; SRC_N(grid) = DFL2; SRC_S(grid) = DFL2; SRC_E(grid) = DFL2; SRC_W(grid) = DFL2; SRC_T(grid) = DFL2; SRC_B(grid) = DFL2; SRC_NE(grid) = DFL3; SRC_NW(grid) = DFL3; SRC_SE(grid) = DFL3; SRC_SW(grid) = DFL3; SRC_NT(grid) = DFL3; SRC_NB(grid) = DFL3; SRC_ST(grid) = DFL3; SRC_SB(grid) = DFL3; SRC_ET(grid) = DFL3; SRC_EB(grid) = DFL3; SRC_WT(grid) = DFL3; SRC_WB(grid) = DFL3; CLEAR_ALL_FLAGS_SWEEP(grid); SWEEP_END } /******************************************************************************/ /*############################################################################*/ void LBM_swapGrids(LBM_Grid *grid1, LBM_Grid *grid2) { LBM_Grid aux = *grid1; *grid1 = *grid2; *grid2 = aux; } /*############################################################################*/ void LBM_loadObstacleFile(LBM_Grid grid, const char *filename) { int x, y, z; FILE *file = fopen(filename, "rb"); for (z = 0; z < SIZE_Z; z++) { for (y = 0; y < SIZE_Y; y++) { for (x = 0; x < SIZE_X; x++) { if (fgetc(file) != '.') SET_FLAG(grid, x, y, z, OBSTACLE); } fgetc(file); } fgetc(file); } fclose(file); } /*############################################################################*/ void LBM_initializeSpecialCellsForLDC(LBM_Grid grid) { int x, y, z; for (z = -2; z < SIZE_Z + 2; z++) { for (y = 0; y < SIZE_Y; y++) { for (x = 0; x < SIZE_X; x++) { if (x == 0 || x == SIZE_X - 1 || y == 0 || y == SIZE_Y - 1 || z == 0 || z == SIZE_Z - 1) { SET_FLAG(grid, x, y, z, OBSTACLE); } else { if ((z == 1 || z == SIZE_Z - 2) && x > 1 && x < SIZE_X - 2 && y > 1 && y < SIZE_Y - 2) { SET_FLAG(grid, x, y, z, ACCEL); } } } } } } /*############################################################################*/ void LBM_showGridStatistics(LBM_Grid grid) { int nObstacleCells = 0, nAccelCells = 0, nFluidCells = 0; float ux, uy, uz; float minU2 = 1e+30, maxU2 = -1e+30, u2; float minRho = 1e+30, maxRho = -1e+30, rho; float mass = 0; SWEEP_VAR SWEEP_START(0, 0, 0, 0, 0, SIZE_Z) rho = LOCAL(grid, C) + LOCAL(grid, N) + LOCAL(grid, S) + LOCAL(grid, E) + LOCAL(grid, W) + LOCAL(grid, T) + LOCAL(grid, B) + LOCAL(grid, NE) + LOCAL(grid, NW) + LOCAL(grid, SE) + LOCAL(grid, SW) + LOCAL(grid, NT) + LOCAL(grid, NB) + LOCAL(grid, ST) + LOCAL(grid, SB) + LOCAL(grid, ET) + LOCAL(grid, EB) + LOCAL(grid, WT) + LOCAL(grid, WB); if (rho < minRho) minRho = rho; if (rho > maxRho) maxRho = rho; mass += rho; if (TEST_FLAG_SWEEP(grid, OBSTACLE)) { nObstacleCells++; } else { if (TEST_FLAG_SWEEP(grid, ACCEL)) nAccelCells++; else nFluidCells++; ux = +LOCAL(grid, E) - LOCAL(grid, W) + LOCAL(grid, NE) - LOCAL(grid, NW) + LOCAL(grid, SE) - LOCAL(grid, SW) + LOCAL(grid, ET) + LOCAL(grid, EB) - LOCAL(grid, WT) - LOCAL(grid, WB); uy = +LOCAL(grid, N) - LOCAL(grid, S) + LOCAL(grid, NE) + LOCAL(grid, NW) - LOCAL(grid, SE) - LOCAL(grid, SW) + LOCAL(grid, NT) + LOCAL(grid, NB) - LOCAL(grid, ST) - LOCAL(grid, SB); uz = +LOCAL(grid, T) - LOCAL(grid, B) + LOCAL(grid, NT) - LOCAL(grid, NB) + LOCAL(grid, ST) - LOCAL(grid, SB) + LOCAL(grid, ET) - LOCAL(grid, EB) + LOCAL(grid, WT) - LOCAL(grid, WB); u2 = (ux * ux + uy * uy + uz * uz) / (rho * rho); if (u2 < minU2) minU2 = u2; if (u2 > maxU2) maxU2 = u2; } SWEEP_END printf("LBM_showGridStatistics:\n" "\tnObstacleCells: %7i nAccelCells: %7i nFluidCells: %7i\n" "\tminRho: %8.4f maxRho: %8.4f mass: %e\n" "\tminU: %e maxU: %e\n\n", nObstacleCells, nAccelCells, nFluidCells, minRho, maxRho, mass, sqrt(minU2), sqrt(maxU2)); } /*############################################################################*/ static void storeValue(FILE *file, OUTPUT_PRECISION *v) { const int litteBigEndianTest = 1; if ((*((unsigned char *)&litteBigEndianTest)) == 0) { /* big endian */ const char *vPtr = (char *)v; char buffer[sizeof(OUTPUT_PRECISION)]; int i; for (i = 0; i < sizeof(OUTPUT_PRECISION); i++) buffer[i] = vPtr[sizeof(OUTPUT_PRECISION) - i - 1]; fwrite(buffer, sizeof(OUTPUT_PRECISION), 1, file); } else { /* little endian */ fwrite(v, sizeof(OUTPUT_PRECISION), 1, file); } } /*############################################################################*/ static void loadValue(FILE *file, OUTPUT_PRECISION *v) { const int litteBigEndianTest = 1; if ((*((unsigned char *)&litteBigEndianTest)) == 0) { /* big endian */ char *vPtr = (char *)v; char buffer[sizeof(OUTPUT_PRECISION)]; int i; fread(buffer, sizeof(OUTPUT_PRECISION), 1, file); for (i = 0; i < sizeof(OUTPUT_PRECISION); i++) vPtr[i] = buffer[sizeof(OUTPUT_PRECISION) - i - 1]; } else { /* little endian */ fread(v, sizeof(OUTPUT_PRECISION), 1, file); } } /*############################################################################*/ void LBM_storeVelocityField(LBM_Grid grid, const char *filename, const int binary) { OUTPUT_PRECISION rho, ux, uy, uz; FILE *file = fopen(filename, (binary ? "wb" : "w")); SWEEP_VAR SWEEP_START(0, 0, 0, SIZE_X, SIZE_Y, SIZE_Z) rho = +SRC_C(grid) + SRC_N(grid) + SRC_S(grid) + SRC_E(grid) + SRC_W(grid) + SRC_T(grid) + SRC_B(grid) + SRC_NE(grid) + SRC_NW(grid) + SRC_SE(grid) + SRC_SW(grid) + SRC_NT(grid) + SRC_NB(grid) + SRC_ST(grid) + SRC_SB(grid) + SRC_ET(grid) + SRC_EB(grid) + SRC_WT(grid) + SRC_WB(grid); ux = +SRC_E(grid) - SRC_W(grid) + SRC_NE(grid) - SRC_NW(grid) + SRC_SE(grid) - SRC_SW(grid) + SRC_ET(grid) + SRC_EB(grid) - SRC_WT(grid) - SRC_WB(grid); uy = +SRC_N(grid) - SRC_S(grid) + SRC_NE(grid) + SRC_NW(grid) - SRC_SE(grid) - SRC_SW(grid) + SRC_NT(grid) + SRC_NB(grid) - SRC_ST(grid) - SRC_SB(grid); uz = +SRC_T(grid) - SRC_B(grid) + SRC_NT(grid) - SRC_NB(grid) + SRC_ST(grid) - SRC_SB(grid) + SRC_ET(grid) - SRC_EB(grid) + SRC_WT(grid) - SRC_WB(grid); ux /= rho; uy /= rho; uz /= rho; if (binary) { /* fwrite( &ux, sizeof( ux ), 1, file ); fwrite( &uy, sizeof( uy ), 1, file ); fwrite( &uz, sizeof( uz ), 1, file ); */ storeValue(file, &ux); storeValue(file, &uy); storeValue(file, &uz); } else fprintf(file, "%e %e %e\n", ux, uy, uz); SWEEP_END; fclose(file); }
30.518382
80
0.471871
vzyrianov
323da5f321daa53d0f824164dfcd12bca9cba176
2,185
cpp
C++
src/main/cpp/subsystems/DriveSubsytem.cpp
FRCTeamPhoenix/RomiTutorial2021
bd0f67e41c8104c1bd908f3145cdce1d6afb6339
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/cpp/subsystems/DriveSubsytem.cpp
FRCTeamPhoenix/RomiTutorial2021
bd0f67e41c8104c1bd908f3145cdce1d6afb6339
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/cpp/subsystems/DriveSubsytem.cpp
FRCTeamPhoenix/RomiTutorial2021
bd0f67e41c8104c1bd908f3145cdce1d6afb6339
[ "BSD-3-Clause", "MIT" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "subsystems/DriveSubsystem.h" #include <wpi/math> DriveSubsystem::DriveSubsystem() { m_gyro.Reset(); // Implementation of subsystem constructor goes here. m_rightMotor.SetInverted(true); m_leftEncoder.SetDistancePerPulse(wpi::math::pi * WHEEL_DIAMETER.to<double>() / TICKS_PER_REVOLUTION); m_rightEncoder.SetDistancePerPulse(wpi::math::pi * WHEEL_DIAMETER.to<double>() / TICKS_PER_REVOLUTION); //minimum velocity before considered stopped m_leftEncoder.SetMinRate(MIN_RATE.to<double>()); m_rightEncoder.SetMinRate(MIN_RATE.to<double>()); //how long to be below min rate before stopping m_leftEncoder.SetMaxPeriod(MAX_PERIOD); m_rightEncoder.SetMaxPeriod(MAX_PERIOD); m_leftEncoder.SetSamplesToAverage(2); m_rightEncoder.SetSamplesToAverage(2); } void DriveSubsystem::Periodic() { // Implementation of subsystem periodic method goes here. } void DriveSubsystem::SimulationPeriodic() { // Implementation of subsystem simulation periodic method goes here. } void DriveSubsystem::ArcadeDrive(double moveForward, double moveTurn){ m_differentialDrive.ArcadeDrive(moveForward, moveTurn); } void DriveSubsystem::TankDrive(double leftSide, double rightSide){ m_differentialDrive.TankDrive(leftSide, rightSide); } void DriveSubsystem::ZeroEncoders(){ m_rightEncoder.Reset(); m_leftEncoder.Reset(); } void DriveSubsystem::ZeroGyro(){ m_gyro.Reset(); } units::meter_t DriveSubsystem::LeftDistance(){ return units::meter_t(m_leftEncoder.GetDistance()); } units::meter_t DriveSubsystem::RightDistance(){ return units::meter_t(m_rightEncoder.GetDistance()); } units::meter_t DriveSubsystem::CurrentDistance(){ return (LeftDistance() + RightDistance()) / 2.0; } bool DriveSubsystem::IsStopped(){ return m_leftEncoder.GetStopped() && m_rightEncoder.GetStopped(); } units::radian_t DriveSubsystem::GetAngleZ(){ return units::degree_t(m_gyro.GetAngleZ()); } void DriveSubsystem::UpdateDebug(){ m_gyro.UpdateDebugValues(); }
28.376623
105
0.771167
FRCTeamPhoenix
3243202609864bdcaf4f693bc60b9af583121b1a
1,329
cpp
C++
AI/Src/SteeringBehavior_OffsetPursuit.cpp
ArvydasSlekaitis/ReginaGameEngine
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
[ "MIT" ]
1
2020-09-02T06:00:14.000Z
2020-09-02T06:00:14.000Z
AI/Src/SteeringBehavior_OffsetPursuit.cpp
ArvydasSlekaitis/ReginaGameEngine
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
[ "MIT" ]
null
null
null
AI/Src/SteeringBehavior_OffsetPursuit.cpp
ArvydasSlekaitis/ReginaGameEngine
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////// // SteeringBehavior_OffsetPursuit.cpp // Created on: 11-10-2009 // Last modified: 11-10-2009 // Original author: Arvydas Slekaitis (C) /////////////////////////////////////////////////////////// #include <SteeringBehavior_OffsetPursuit.h> using namespace Regina; //***************************************************************************** CSteeringBehavior_OffsetPursuit::CSteeringBehavior_OffsetPursuit(CMovingEntity* const iMovingEntity, const CMovingEntity* iLeader, const D3DXVECTOR2& iOffset) : CSteeringBehavior("OffsetPursuit", 6, 0.9, iMovingEntity), leader(iLeader), offset(iOffset) { } //***************************************************************************** D3DXVECTOR2 CSteeringBehavior_OffsetPursuit::CalculateForce() { D3DXVECTOR3 worldOffset; D3DXVec3TransformCoord(&worldOffset, &D3DXVECTOR3(Offset().x, 0, Offset().y), &(Leader()->Transformation())); float lookAheadTime = Distance(worldOffset.x, worldOffset.y, Entity()->PositionXZ().x, Entity()->PositionXZ().y) / ( Entity()->MaxSpeed() + Leader()->Speed()); CSteeringBehavior_Arrive arrive(Entity(), D3DXVECTOR2(worldOffset.x, worldOffset.z), 1); return arrive.CalculateForce(); } //*****************************************************************************
44.3
252
0.5538
ArvydasSlekaitis
3244dce417f97db8480ae08447b064ee314c37a0
496
cpp
C++
src/NavRouting/NavRoutingEndLocationSetFromSearchMessage.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
69
2017-06-07T10:47:03.000Z
2022-03-24T08:33:33.000Z
src/NavRouting/NavRoutingEndLocationSetFromSearchMessage.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
23
2017-06-07T10:47:00.000Z
2020-07-09T10:31:17.000Z
src/NavRouting/NavRoutingEndLocationSetFromSearchMessage.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
31
2017-08-12T13:19:32.000Z
2022-01-04T20:33:40.000Z
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "NavRoutingEndLocationSetFromSearchMessage.h" namespace ExampleApp { namespace NavRouting { NavRoutingEndLocationSetFromSearchMessage::NavRoutingEndLocationSetFromSearchMessage(SearchNavigationData data) : m_data(data) { } const SearchNavigationData& NavRoutingEndLocationSetFromSearchMessage::GetSearchData() const { return m_data; } } }
23.619048
119
0.6875
usamakhan049
324c668049c4a4374cc8ae171461f16914510fab
25,057
cpp
C++
steamfilter/replace.cpp
Pez42/steam-limiter
df95d2460faa0316573013d09db086826b3c825a
[ "BSD-2-Clause" ]
2
2016-02-24T09:49:07.000Z
2019-05-31T14:38:06.000Z
steamfilter/replace.cpp
Pez42/steam-limiter
df95d2460faa0316573013d09db086826b3c825a
[ "BSD-2-Clause" ]
null
null
null
steamfilter/replace.cpp
Pez42/steam-limiter
df95d2460faa0316573013d09db086826b3c825a
[ "BSD-2-Clause" ]
2
2015-09-22T15:53:59.000Z
2020-06-14T12:50:24.000Z
/**@addtogroup Filter Steam limiter filter hook DLL. * @{@file * * This defines a data structure to be used for managing replacement HTTP * content to be used when certain URL patterns are seen. * * @author Nigel Bree <nigel.bree@gmail.com> * * Copyright (C) 2013 Nigel Bree; 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. */ /* * The fundamental idea here is that we maintain a small set of data for * replacement documents (or document templates; although there doesn't seem * to be an immediate need for it here, obviously it would be desirable in some * contexts for the replacement document to be generated by template expansion) * along with a simple kind of state-tracking structure for socket handles. * * Since replacement events are expected to be rare, there is generally only * likely to be a single outstanding one, and generally it will be consumed in * a single read call, so a simple linked list should do for matching things. * * When a replacement URL is detected, the replacement data structure is set up * and the caller's request is discarded so that the connected peer does not * see the request being replaced at all (which saves the need to edit the * replaced response out of the data stream). In general, requests are sent as * a single write call - the problems caused by the behaviour of socket reads * (even in synchronous mode, even a single byte of data available causes an * immediate return to the caller) tend not to affect write processing. * * Then, on read processing if a replacement is set to occur for a socket * handle the replacement data is written to the user buffer (typically all of * it, although for robustness it's best to allow it to be drained in parts), * and once the replacement is drained then we can return to the caller. * * The final detail is the question of where the replacement documents are read * from, and when they are read. Potentially the reading could take place at * the time a filter rule is established, which would be most prudent if the * replacement is taken from a disk file and is thus likely to be expensive and * high-latency. However it seems more product to read the document from the * system registry if the document is likely to be small (as it is for Steam * content filtering) which means that the data encoding is better-specified * and due to aggressive system caching of the registry hive data is very * likely to be low-latency to access. */ #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #include <winsock2.h> #include "replace.h" /** * Cliche for measuring array lengths, to avoid mistakes with sizeof (). */ #define ARRAY_LENGTH(x) (sizeof (x) / sizeof (* (x))) /** * Base object for implementing socket state tracking. * * This is set up for binding sockets and event handles so that applications * get notified when a socket becomes readable, since the lack of true AIO in * classic sockets requires separate eventing mechanisms (from the simple to * the absurd as in epoll (), which is essentially socket-specific as well as * baroque and hard to use compared to a universal AIO model). */ class SocketTrack { /* * Friend-ing an entire template is not something you see often, but * it's been a part of the language for a while. */ template <class T> friend class SocketList; private: SocketTrack * m_next; SocketTrack * m_prev; SOCKET m_handle; public: WSAEVENT m_event; private: /* NOCOPY */ SocketTrack (const SocketTrack &); void operator = (const SocketTrack &); public: SocketTrack (SOCKET handle); SOCKET handle (void) const { return m_handle; } static void * operator new (size_t length) throw (); static void * operator new (size_t length, void * mem) throw (); static void operator delete (void * mem) throw (); }; /** * Regular replacement new, non-throwing. */ /* static */ void * SocketTrack :: operator new (size_t length) throw () { return HeapAlloc (GetProcessHeap (), 0, length); } /** * Non-throwing placement new, generally used with manual calls to the plain * operator function to allocate variable-sized memory blocks. */ /* static */ void * SocketTrack :: operator new (size_t length, void * mem) throw () { return mem; } /** * Trivial deallocator to match the replacement new. */ /* static */ void SocketTrack :: operator delete (void * mem) throw () { HeapFree (GetProcessHeap (), 0, mem); } /** * Trivial constructor. */ SocketTrack :: SocketTrack (SOCKET handle) : m_next (0), m_prev (0), m_handle (handle), m_event (0) { } /** * Simple list-holder. * * Intrusive lists have been a part of C++ forever, since they were the common * thing done in C for many years before. However, in early C++ what was done * in most programs was to convert a common node structure and extend it using * virtual functions. * * Although this could be done to be typesafe, it had problems not the least of * which was typesafety required constantly injecting new virtual functions * into the base classes or the moral equivalent (e.g. COM-style QueryInterface * which was elegant but not being integrated into the language, lots of work). * * Templates in the 1990 ARM promised to help with this by introducing some * parametric genericity, but being mostly a system pf complex hygenic macro- * expanders the quality of implementation was low and remained low for well * into the 2000s and even then tended to cause code explosion. Finally, around * the late 2000's quality implementations of templates style could really * rival the old pre-1990s one in total efficiency thanks to function-level * linking and deduplication (although that's not entirely free either, as it * can make for a disorienting debug experience). */ template <class T> struct SocketList { typedef CRITICAL_SECTION Mutex; Mutex m_lock [1]; T * m_head; SocketList (); ~ SocketList (); void free (void); void add (T & item); T * find (SOCKET handle); void remove (T * item, bool free = false); void remove (SOCKET handle); }; /** * Initialize an empty list. */ template <class T> SocketList<T> :: SocketList () : m_head (0) { InitializeCriticalSection (m_lock); } /** * Deinitialize the list and locking structure. */ template <class T> SocketList<T> :: ~ SocketList () { free (); DeleteCriticalSection (m_lock); } /** * Free all the list members, deallocating them. */ template <class T> void SocketList<T> :: free (void) { EnterCriticalSection (m_lock); while (m_head != 0) remove (m_head, true); LeaveCriticalSection (m_lock); } /** * Add a new item. */ template <class T> void SocketList<T> :: add (T & item) { EnterCriticalSection (m_lock); item.m_next = m_head; item.m_prev = 0; m_head = & item; LeaveCriticalSection (m_lock); } /** * Find an item. * * In a more general template, this would be a member template so that the * key type and comparison function could be parameterized, but this is just * a simplified example of the general style so I haven't bothered. * * The key reason this is here is to show a clean example of something memory- * light, which nothing in the modern STL can really claim to be (even for the * few good parts of classic STL, the retrofitting of exceptions into the STL * containers meant it's usually easier to ditch them in memory-constrained or * code-size-limited environments). */ template <class T> T * SocketList<T> :: find (SOCKET handle) { EnterCriticalSection (m_lock); T * scan = m_head; while (scan != 0) { if (scan->m_handle == handle) break; scan = (T *) scan->m_next; } LeaveCriticalSection (m_lock); return scan; } /** * Remove an item from the list, optionally freeing it. */ template <class T> void SocketList<T> :: remove (T * item, bool free) { EnterCriticalSection (m_lock); T * prev = (T *) item->m_prev; T * next = (T *) item->m_next; if (prev == 0) { m_head = next; } else prev->m_next = next; if (next != 0) next->m_prev = prev; LeaveCriticalSection (m_lock); if (free) delete item; } /** * Remove and free an item based on a key. */ template <class T> void SocketList<T> :: remove (SOCKET handle) { EnterCriticalSection (m_lock); T ** link = & m_head; T * scan = m_head; T * prev = 0; while ((scan = * link) != 0) { if (scan->m_handle == handle) { * link = (T *) scan->m_next; scan->m_prev = prev; break; } prev = scan; link = (T **) & scan->m_next; } LeaveCriticalSection (m_lock); if (scan != 0) delete scan; } /** * Structure for representing a replacement context. */ struct Replacement : public SocketTrack { unsigned long m_length; unsigned long m_offset; unsigned char * m_data; Replacement (SOCKET handle) : SocketTrack (handle) { } }; /** * Structure for representing an context where we're discarding output. */ struct Discarding : public SocketTrack { unsigned long m_length; Discarding (SOCKET handle) : SocketTrack (handle) { } }; /** * The global list of bound event handles for sockets. */ SocketList<SocketTrack> l_events; /** * The global list of active replacement items. */ SocketList<Replacement> l_replace; /** * Global list of sockets where we are discarding sent data. */ SocketList<Discarding> l_discard; /** * Root registry key in which replacement items are located. */ HKEY l_rootKey; /** * Set the root path used as the context for the names of replacement items. * * It would presumably be nice to support either or both of registry and file * paths here, so that users could choose. In the first instance I'll probably * only implement registry-hosted item support, but it would be sensible to * have the filesystem path setup present in the hosting machinery. */ void g_initReplacement (ReplaceHKEY key, const wchar_t * regPath) { LSTATUS status = ERROR_NOT_FOUND; HKEY result = 0; if (regPath != 0) { status = RegOpenKeyExW ((HKEY) key, regPath, 0, KEY_READ, & result); } if (status == ERROR_SUCCESS) l_rootKey = result; } /** * Do any unload-time cleanup. */ void g_unloadReplacement (void) { if (l_rootKey != 0) { RegCloseKey (l_rootKey); l_rootKey = 0; } l_replace.free (); l_events.free (); } /** * Add tracking for an event handle bound to a socket. * * This might potentially be used to change a binding from one event or even to * remove a binding, although most socket client applications don't do that. */ void g_addEventHandle (SOCKET handle, WSAEVENT event) { SocketTrack * item = l_events.find (handle); if (item != 0) { item->m_event = event; return; } item = new SocketTrack (handle); l_events.add (* item); } /** * When a socket handle is being closed, remove any tracking data for it. */ void g_removeTracking (SOCKET handle) { l_events.remove (handle); l_replace.remove (handle); l_discard.remove (handle); } /** * Add a potential replacement document to the replacement set. * * This is a hook into us performed during rule parsing, although if we're * sourcing data from the registry we will probably do nothing. * * Whether file or registry is preferred, the name of the source is always * going to be relative to something; another problem with file access is that * the source directory for such content is unlikely to be one we can arrange * as such in the context of Steam itself, and it will need to have been set up * for us during the filter load somehow. */ void g_replacementCache (const wchar_t * /* name */) { } /** * Format the current local date and time as an RFC 822/RFC 1123 string. */ bool l_formatDate (char * buffer, size_t length) { if (length < 32) return false; static char * days [7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char * months [13] = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; SYSTEMTIME now; GetSystemTime (& now); wsprintfA (buffer, "%s, %d %s %04d %02d:%02d:%02d GMT", days [now.wDayOfWeek], now.wDay, months [now.wMonth], now.wYear, now.wHour, now.wMinute, now.wSecond); return true; } /** * Helper for g_addReplacement (), create a replacement item record. */ bool g_addReplacement (SOCKET handle, const wchar_t * replacement, int status, const char * extraText) { /* * Compute the space required to hold a UTF-8 version of the input, and * any template-type substitution needed (not that we support that as * yet). */ int utf8 = 0; if (replacement != 0) { utf8 = WideCharToMultiByte (CP_UTF8, 0, replacement, - 1, 0, 0, 0, 0); if (utf8 == 0) return false; -- utf8; } /* * Given the size of the replacement document, we can prepare the HTTP * headers for it and thus know the size of the header and thus the * total combined space to allocate. */ char date [80]; if (! l_formatDate (date, ARRAY_LENGTH (date))) return false; char redirect [512]; const char * location = ""; const char * statusText = "UNKNOWN"; switch (status) { case 200: if (replacement == 0 && extraText != 0) utf8 = strlen (extraText); statusText = "OK"; break; case 302: if (extraText == 0) return false; wsprintfA (redirect, "Location: %s\r\n", extraText); location = redirect; statusText = "REDIRECT"; break; default: if (extraText != 0) statusText = extraText; break; } char header [1024]; wsprintfA (header, "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Expires: %s\r\n" "Content-Type: text/html; charset=UTF8\r\n" "Content-Length: %ld\r\n" "Connection: Keep-Alive\r\n" "%s" "\r\n", status, statusText, date, date, utf8, location); size_t headerLength = strlen (header); unsigned long size = sizeof (Replacement) + headerLength + utf8 + 1; /* * Allocate the replacement control structure, and copy the replacement * document text into it (converting to UTF-8). */ void * mem = Replacement :: operator new (size); if (mem == 0) return false; Replacement * item = new (mem) Replacement (handle); item->m_data = (unsigned char *) (item + 1); memcpy (item->m_data, header, headerLength); if (replacement != 0) { utf8 = WideCharToMultiByte (CP_UTF8, 0, replacement, - 1, (LPSTR) item->m_data + headerLength, utf8, 0, 0); if (utf8 == 0) { delete item; return false; } -- utf8; } else if (utf8 > 0) { /* * An alternative way to supply content via a #200 rule. In * this mode, we use ~ as an escape for '\n'; */ unsigned char * dest = item->m_data + headerLength; unsigned long count = utf8; while (count > 0) { unsigned char ch = * extraText; ++ extraText; if (ch == '~') ch = '\n'; * dest = ch; ++ dest; -- count; } } item->m_length = headerLength + utf8; item->m_offset = 0; l_replace.add (* item); /* * Look for a bound event handle for the owner socket, and signal it as * we're making read data available. */ SocketTrack * track = l_events.find (item->handle ()); if (track != 0) SetEvent (track->m_event); return true; } /** * Add a named replacement document item to be substituted on the indicated handle. */ bool g_addReplacement (SOCKET handle, const char * name, const char * /* url */) { wchar_t tempName [80]; int result; result = MultiByteToWideChar (CP_UTF8, 0, name, - 1, tempName, ARRAY_LENGTH (tempName)); if (result == 0) return false; /* * Determine whether the named item exists, and what its size in UTF-16 * characters is. */ LSTATUS status; unsigned long length = 0; status = RegQueryValueExW (l_rootKey, tempName, 0, 0, 0, & length); if (status != ERROR_SUCCESS) { OutputDebugStringA ("HTTP replacement not found\r\n"); return false; } wchar_t * replacement; replacement = (wchar_t *) HeapAlloc (GetProcessHeap (), 0, length); if (replacement == 0) return false; unsigned long type; status = RegQueryValueExW (l_rootKey, tempName, 0, & type, (LPBYTE) replacement, & length); if (status != ERROR_SUCCESS) { HeapFree (GetProcessHeap (), 0, replacement); return false; } if (type == REG_MULTI_SZ) { /* * For MULTI_SZ just join all the component strings by changing * the interior terminator bytes into newlines. */ length = length / sizeof (wchar_t); wchar_t * scan = replacement; wchar_t * end = scan + length - 1; for (; scan != end ; ++ scan) if (* scan == 0) * scan = '\n'; } else if (type == REG_SZ || type == REG_EXPAND_SZ) { length = length / sizeof (wchar_t); } else { HeapFree (GetProcessHeap (), 0, replacement); return false; } /* * Since a registry value has the potential to not be terminated, * ensure that a terminator is present. */ if (replacement [length - 1] != 0) { replacement [length] = 0; ++ length; } bool value; value = g_addReplacement (handle, replacement, 200, 0); HeapFree (GetProcessHeap (), 0, replacement); return value; } /** * Attempt to find a replacement item (and optionally, release it). */ Replacement * g_findReplacement (SOCKET handle) { return l_replace.find (handle); } /** * Given a replacement item, consume part of it for the caller. * * This is the simplest signature; it's up to the caller to adapt the incoming * API format to suit this (if we wanted to support multiple WSABUF structures, * for example, although for now we don't). * * Note that we're assuming here that a given source socket is only being read * on a single thread, so there is no need for locking here. That's probably * not a safe assumption in general to make if we ever get used with clients * written for high performance, but it's true of simple things like Steam. */ bool g_consumeReplacement (Replacement * item, unsigned long length, void * buf, unsigned long * copied) { if (item == 0 || buf == 0) return false; unsigned long avail = item->m_length - item->m_offset; if (length < avail) avail = length; memcpy (buf, item->m_data, avail); if (copied != 0) * copied = avail; item->m_offset += avail; if (item->m_offset != item->m_length) return true; /* * The replacement item has been consumed, remove it. */ l_replace.remove (item, true); return true; } /** * Add a notice to discard data from a handle */ bool g_addDiscard (SOCKET handle, unsigned long length) { if (length == 0) return false; /* * Allocate the replacement control structure, and copy the replacement * document text into it (converting to UTF-8). */ Discarding * item = new Discarding (handle); if (item == 0) return false; item->m_length = length; l_discard.add (* item); return true; } /** * Determine if we're discarding output from this socket. */ Discarding * g_findDiscard (SOCKET handle) { return l_discard.find (handle); } /** * Consume some amount of data from the discard record. */ bool g_consumeDiscard (Discarding * item, unsigned long length, unsigned long * skip) { unsigned long used = item->m_length; if (length < used) used = length; item->m_length -= used; length -= used; if (skip != 0) * skip = used; if (item->m_length == 0) l_discard.remove (item, true); return true; } /**@}*/
31.677623
88
0.563914
Pez42
3251bc8b1cde3aa927595ec3645a882894603708
1,181
cpp
C++
Backtracking/CountN-Queen.cpp
divyanshi23/CB-Algo
cd3702d715d2f269dacd065ad5fc300af86e55d8
[ "MIT" ]
null
null
null
Backtracking/CountN-Queen.cpp
divyanshi23/CB-Algo
cd3702d715d2f269dacd065ad5fc300af86e55d8
[ "MIT" ]
null
null
null
Backtracking/CountN-Queen.cpp
divyanshi23/CB-Algo
cd3702d715d2f269dacd065ad5fc300af86e55d8
[ "MIT" ]
null
null
null
/*You are given an empty chess board of size N*N. Find the number of ways to place N queens on the board, such that no two queens can kill each other in one move. A queen can move vertically, horizontally and diagonally. Input Format A single integer N, denoting the size of chess board. Constraints 1<=N<=11 Output Format A single integer denoting the count of solutions. Sample Input 4 Sample Output 2*/ #include <iostream> #include<bitset> using namespace std; bitset<11> d1,d2,col; void countNQueen(int r,int n,int &ans) { //Base case if(r==n) { ans++; return; } //Recursive case for(int c=0;c<n;c++) //try to place the queen in a particular column of the selected row { if(!col[c] && !d1[r-c+n-1] && !d2[r+c]) { col[c]=1; d1[r-c+n-1]=1; d2[r+c]=1; countNQueen(r+1,n,ans); col[c]=0; d1[r-c+n-1]=0; d2[r+c]=0; } } } int main() { int n; cin>>n; //chess board size int ans=0; int r=0; //starting row countNQueen(r,n,ans); cout<<ans; }
21.472727
221
0.546994
divyanshi23
32527ad159a454c0af64769e08a4aa0d978a048e
827
cpp
C++
src/Function.cpp
Deukhoofd/ELF_Reader
92b732ea3a351f88d9612293f8b9aa8349c7ec49
[ "MIT" ]
null
null
null
src/Function.cpp
Deukhoofd/ELF_Reader
92b732ea3a351f88d9612293f8b9aa8349c7ec49
[ "MIT" ]
null
null
null
src/Function.cpp
Deukhoofd/ELF_Reader
92b732ea3a351f88d9612293f8b9aa8349c7ec49
[ "MIT" ]
null
null
null
#include "Function.hpp" Function::Function(const File& file, Block* block) { _name = block->GetName(); _fileName = file.GetFileName(); _returnType = ((block->GetAtType() == 0) ? Type() : Type(file, file.GetBlock(block->GetAtType()))); auto c= block->GetNext(); while (c != nullptr){ if (c->GetLevel() == block->GetLevel()) break; if (c->GetType() == TagType::DW_TAG_formal_parameter && c->GetLevel() == block->GetLevel() + 1){ auto parameter = FunctionParameter(file, c); _parameters.push_back(parameter); } c = c->GetNext(); } } FunctionParameter::FunctionParameter(const File& file, Block* block) { _name = block->GetName(); _type = ((block->GetAtType() == 0) ? Type() : Type(file, file.GetBlock(block->GetAtType()))); }
34.458333
105
0.591294
Deukhoofd
325577c817ca18e1388cf980fdbde926192c8a0f
1,165
cpp
C++
mahbubul-hassan/0-Programming_Contest_DS_Algorithms/7-6-MCM.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
mahbubul-hassan/0-Programming_Contest_DS_Algorithms/7-6-MCM.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
mahbubul-hassan/0-Programming_Contest_DS_Algorithms/7-6-MCM.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
#include <bits/stdc++.h> using namespace std; #define si(x) scanf("%d",&x) #define sf(x) scanf("%f",&x) #define pi(x) printf("%d\n",x) #define pf(x) printf("%.4f\n",x) #define ll long long int #define sll(x) scanf("%I64d",&x); #define pll(x) printf("%-I64d\n",x); int *a; int n; int matrixChainMultiplication(){ int m[n][n]; for(int i=0; i<n; i++){ m[i][i] = 0; } for(int L=2; L<n; L++){ for(int i=1; i<n-L+1; i++){ int j=i+L-1; m[i][j] = INT_MAX; for(int k=i; k<=j-i; k++){ int q = m[i][k]+m[k+1][j]+a[i-1]*a[k]*a[j]; if(q<m[i][j]){ m[i][j] = q; } } } } return m[1][n-1]; } int main(int argc, char const *argv[]) { /* code */ /* Soln soln */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout<<"Enter # of matrices: \n"; cin>>n; a = new int[n+1]; for(int i=0; i<n; i++){ cin>>a[i]; } cout<<"Ans = "<<matrixChainMultiplication(); delete[] a; return 0; }
17.923077
59
0.453219
fahimfarhan
3255d0cc745c30166df6855a7bee475fa47f1bd8
1,473
cpp
C++
leetcode/0814_binary_tree_pruning.cpp
jacquerie/leetcode
a05e6b832eb0e0740aaff7b2eb3109038ad404bf
[ "MIT" ]
3
2018-05-10T09:56:49.000Z
2020-11-07T18:09:42.000Z
leetcode/0814_binary_tree_pruning.cpp
jacquerie/leetcode
a05e6b832eb0e0740aaff7b2eb3109038ad404bf
[ "MIT" ]
null
null
null
leetcode/0814_binary_tree_pruning.cpp
jacquerie/leetcode
a05e6b832eb0e0740aaff7b2eb3109038ad404bf
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Jacopo Notarstefano #include <cassert> #include <cstddef> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; explicit TreeNode(int x): val(x), left(NULL), right(NULL) {} }; bool operator==(TreeNode& p, TreeNode& q) { bool left, right; if (!p.left && !q.left) { left = true; } else if (!p.left || !q.left) { left = false; } else { left = *(p.left) == *(q.left); } if (!p.right && !q.right) { right = true; } else if (!p.right || !q.right) { right = false; } else { right = *(p.right) == *(q.right); } return p.val == q.val && left && right; } class Solution { public: TreeNode* pruneTree(TreeNode* root) { if (!root) { return NULL; } root->left = pruneTree(root->left); root->right = pruneTree(root->right); if (!root->left && !root->right && root->val == 0) { return NULL; } return root; } }; int main() { auto solution = Solution(); auto t0_0 = TreeNode(1); auto t0_1 = TreeNode(0); auto t0_2 = TreeNode(0); auto t0_3 = TreeNode(1); t0_1.right = &t0_3; t0_1.left = &t0_2; t0_0.right = &t0_1; auto t1_0 = TreeNode(1); auto t1_1 = TreeNode(0); auto t1_2 = TreeNode(1); t1_1.right = &t1_2; t1_0.right = &t1_1; assert(t1_0 == *(solution.pruneTree(&t0_0))); }
19.64
64
0.521385
jacquerie
3259e46a5834cf2b69b7d9c3b0c78188b4042656
683
cpp
C++
Mean Inequality.cpp
manu-karenite/Codeforces-Solutions
c963a0186c6530ea8a785780fc4d68ed539e8c6e
[ "MIT" ]
1
2021-04-07T05:13:21.000Z
2021-04-07T05:13:21.000Z
Mean Inequality.cpp
manu-karenite/Codeforces-Solutions
c963a0186c6530ea8a785780fc4d68ed539e8c6e
[ "MIT" ]
null
null
null
Mean Inequality.cpp
manu-karenite/Codeforces-Solutions
c963a0186c6530ea8a785780fc4d68ed539e8c6e
[ "MIT" ]
null
null
null
/* This code is written by Manavesh Narendra E-mail : manu.karenite@gmail.com LinkedIn : https://www.linkedin.com/in/manavesh-narendra-489833196/ */ #include <bits/stdc++.h> using namespace std; int main() { int test; cin>>test; while(test--) { int n; cin>>n; vector<int> num ; int entry; for(int i=0;i<2*n;i++) { cin>>entry; num.push_back(entry); } sort(num.begin(),num.end()); //orinting for(int p=0 , q = 2*n-1;p<=q;p++,q--) { cout<<num[p]<<" "<<num[q]<<" "; } cout<<endl; } }
17.512821
67
0.445095
manu-karenite
325b92c7534256bb162a8f8c5f5f99d688984ce2
2,778
cpp
C++
Common/util/src/encoding_ansi.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
4
2021-10-20T09:18:06.000Z
2022-03-27T05:08:26.000Z
Common/util/src/encoding_ansi.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
1
2021-11-05T03:28:41.000Z
2021-11-06T07:48:05.000Z
Common/util/src/encoding_ansi.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
1
2021-12-13T16:04:22.000Z
2021-12-13T16:04:22.000Z
/** * \file encoding_ansi.cpp * \brief ANSI 编码转换实现代码 */ #include "pch.h" #include "encoding_ansi.h" namespace dtutil { /** * \brief 获取编码实例 * \return 编码实例 */ Encoding & ANSIEncoding::GetInstance() { static ANSIEncoding ansi; return ansi; } /** * \brief 把 Unicode 字符串转换为指定编码的字符串 * \param wstr Unicode字符串 * \return 输出字符串 */ std::string ANSIEncoding::Transcode(const std::wstring &wstr) { return Convert(wstr.c_str()); } /** * \brief 把 Unicode 字符串转换为指定编码的字符串 * \param wstr Unicode字符串 * \return 输出字符串 */ std::string ANSIEncoding::Transcode(const wchar_t *wstr) { return Convert(wstr); } /** * \brief 把 Unicode 字符串转换为指定编码的字符串 * \param wstr Unicode字符串 * \return 输出字符串 */ std::string ANSIEncoding::Transcode(wchar_t *wstr) { return Convert(wstr); } /** * \brief 把指定编码的字符串转换为 Unicode 字符串 * \param str 输入字符串 * \return Unicode字符串 */ std::wstring ANSIEncoding::Transcode(const std::string &str) { return Convert(str.c_str()); } /** * \brief 把指定编码的字符串转换为 Unicode 字符串 * \param str 输入字符串 * \return Unicode字符串 */ std::wstring ANSIEncoding::Transcode(const char *str) { return Convert(str); } /** * \brief 把指定编码的字符串转换为 Unicode 字符串 * \param str 输入字符串 * \return Unicode字符串 */ std::wstring ANSIEncoding::Transcode(char *str) { return Convert(str); } /** * \brief 把指定编码的字符串转换为 Unicode 字符串 * \param str 输入字符串 * \return Unicode字符串 */ std::wstring ANSIEncoding::Convert(const char *str) { setlocale(LC_CTYPE, ""); // 使用系统默认编码 size_t size = strlen(str) + 1; wchar_t *buf = new wchar_t[size]; // wcs 的字符数要比 mbs 的字节数少 memset(buf, 0, sizeof(wchar_t) * size); size = mbstowcs(buf, str, size); if ((size_t)(-1) == size) { throw EncodingErrorException("invalid multibyte character"); } std::wstring wstr = buf; delete [] buf; return wstr; } /** * \brief 把 Unicode 字符串转换为特定编码的字符串 * \param wstr Unicode字符串 * \return 输出字符串 */ std::string ANSIEncoding::Convert(const wchar_t *wstr) { setlocale(LC_CTYPE, ""); // 使用系统默认编码 size_t size = wcstombs(NULL, wstr, 0) + 1; // 取得需要的尺寸 char *buf = new char[size]; memset(buf, 0, size); size = wcstombs(buf, wstr, size); if ((size_t)(-1) == size) { throw EncodingErrorException("some wide character cannot be convert to multibyte character."); } std::string str = buf; delete [] buf; return str; } }
21.369231
106
0.559755
deeptexas-ai
325db73319a6247366b8a74c6d1de425ad850af2
1,884
cc
C++
frc971/codelab/basic.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
39
2021-06-18T03:22:30.000Z
2022-03-21T15:23:43.000Z
frc971/codelab/basic.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
10
2021-06-18T03:22:19.000Z
2022-03-18T22:14:15.000Z
frc971/codelab/basic.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
4
2021-08-19T19:20:04.000Z
2022-03-08T07:33:18.000Z
#include "frc971/codelab/basic.h" namespace frc971 { namespace codelab { Basic::Basic(::aos::EventLoop *event_loop, const ::std::string &name) : frc971::controls::ControlLoop<Goal, Position, Status, Output>(event_loop, name) {} void Basic::RunIteration(const Goal *goal, const Position *position, aos::Sender<Output>::Builder *output, aos::Sender<Status>::Builder *status) { // FIX HERE: Set the intake_voltage to 12 Volts when // intake is requested (via intake in goal). Make sure not to set // the motor to anything but 0 V when the limit_sensor is pressed. // This line tells the compiler to to ignore the fact that goal and // position are not used in the code. You will need to read these messages // and use their values to determine the necessary output and status. (void)goal, (void)position; if (output) { Output::Builder builder = output->MakeBuilder<Output>(); // FIX HERE: As of now, this sets the intake voltage to 0 in // all circumstances. Add to this code to output a different // intake voltage depending on the circumstances to make the // tests pass. builder.add_intake_voltage(0.0); // Ignore the return value of Send (void)output->Send(builder.Finish()); } if (status) { Status::Builder builder = status->MakeBuilder<Status>(); // FIX HERE: Fill out the Status message! In order to fill the // information in the message, use the add_<name of the field>() method // on the builder, just like we do with the Output message above. // Look at the definition of Status in basic_status.fbs to find // the name of the field. // Ignore the return value of Send (void)status->Send(builder.Finish()); } } } // namespace codelab } // namespace frc971
36.941176
79
0.654459
AustinSchuh
325de760fb323573959be371c3c8d01d3044de2a
6,637
cc
C++
Bucatini.cc
EdoPro98/Bucatini
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
[ "MIT" ]
null
null
null
Bucatini.cc
EdoPro98/Bucatini
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
[ "MIT" ]
null
null
null
Bucatini.cc
EdoPro98/Bucatini
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
[ "MIT" ]
null
null
null
//************************************************** // \file Bucatini.cc // \brief: main() of Bucatini project // \author: Lorenzo Pezzotti (CERN EP-SFT-sim) @lopezzot // \start date: 7 July 2021 //************************************************** // Includers from project files // #include "BucatiniActionInitialization.hh" #include "BucatiniDetectorConstruction.hh" // Includers from Geant4 #include "G4FastSimulationPhysics.hh" #include "G4RunManagerFactory.hh" #include "G4UIExecutive.hh" #include "G4UIcommand.hh" #include "G4UImanager.hh" #include "G4VisExecutive.hh" #include "Randomize.hh" #include "G4PhysListFactoryAlt.hh" #include "G4PhysListRegistry.hh" #include "G4PhysicsConstructorFactory.hh" #include "G4PhysListStamper.hh" #include "G4VModularPhysicsList.hh" #include "G4OpticalParameters.hh" #include "G4StepLimiter.hh" #include "G4StepLimiterPhysics.hh" namespace PrintUsageError { void UsageError() { G4cerr << "->Bucatini usage: " << G4endl; G4cerr << "Bucatini [-m macro ] [-u UIsession] [-t nThreads] [-pl PhysicsList]" << G4endl; } } // namespace PrintUsageError namespace{ void PrintAvailable(G4int verbosity) { G4cout << G4endl; G4cout << "extensibleFactory: here are the available physics lists:" << G4endl; g4alt::G4PhysListFactory factory; factory.PrintAvailablePhysLists(); // if user asked for extra verbosity then print physics ctors as well if ( verbosity > 1 ) { G4cout << G4endl; G4cout << "extensibleFactory: " << "here are the available physics ctors that can be added:" << G4endl; G4PhysicsConstructorRegistry* g4pctorFactory = G4PhysicsConstructorRegistry::Instance(); g4pctorFactory->PrintAvailablePhysicsConstructors(); } } } // main() function // int main(int argc, char** argv) { // Error in argument numbers // if (argc > 11) { PrintUsageError::UsageError(); return 1; } // Convert arguments in G4string and G4int // G4String macro; G4String session; G4String physListName; int nThreads = 0; for (G4int i = 1; i < argc; i = i + 2) { if (G4String(argv[i]) == "-m") macro = argv[i + 1]; else if (G4String(argv[i]) == "-u") session = argv[i + 1]; else if (G4String(argv[i]) == "-pl") physListName = argv[i + 1]; #ifdef G4MULTITHREADED else if (G4String(argv[i]) == "-t") { nThreads = G4UIcommand::ConvertToInt(argv[i + 1]); } #endif else { PrintUsageError::UsageError(); return 1; } } #ifdef G4MULTITHREADED G4RunManager* runManager = G4RunManagerFactory::CreateRunManager(G4RunManagerType::Default, nThreads); #else G4RunManager* runManager = G4RunManagerFactory::CreateRunManager(G4RunManagerType::Serial); #endif G4Random::setTheEngine(new CLHEP::MTwistEngine()); // Detect interactive mode (if no macro provided) and define UI session // G4UIExecutive* ui = nullptr; if (!macro.size()) { // if macro card is none ui = new G4UIExecutive(argc, argv, session); } g4alt::G4PhysListFactory factory; G4VModularPhysicsList* physList = nullptr; factory.SetDefaultReferencePhysList("FTFP_BERT"); G4PhysListRegistry* plreg = G4PhysListRegistry::Instance(); plreg->AddPhysicsExtension("OPTICAL","G4OpticalPhysics"); plreg->AddPhysicsExtension("STEPLIMIT","G4StepLimiterPhysics"); if ( physListName.size() ) { if ( G4VisExecutive::Verbosity() > 0 ) { G4cout << "extensibleFactory: explicitly using '" << physListName << "'" << G4endl; } physList = factory.GetReferencePhysList(physListName); } else { if ( G4VisExecutive::Verbosity() > 0 ) { G4cout << "extensibleFactory: no -pl flag;" << " using ReferencePhysList() (FTFP_BERT)" << G4endl; } physList = factory.ReferencePhysList(); } if ( ! physList ) { G4cerr << "extensibleFactory: PhysicsList '" << physListName << "' was not available in g4alt::PhysListFactory." << G4endl; PrintAvailable(G4VisExecutive::Verbosity()); // if we can't get what the user asked for... // don't go on to use something else, that's confusing G4ExceptionDescription ED; ED << "The factory for the physicslist [" << physListName << "] does not exist!" << G4endl; G4Exception("Bucatini", "Buactini", FatalException, ED); exit(42); } G4FastSimulationPhysics* fastSimPhysics = new G4FastSimulationPhysics(); fastSimPhysics->ActivateFastSimulation("opticalphoton"); physList->RegisterPhysics(fastSimPhysics); G4OpticalParameters::Instance()->SetProcessActivation("Cerenkov", true); G4OpticalParameters::Instance()->SetProcessActivation("Scintillation", true); G4OpticalParameters::Instance()->SetProcessActivation("OpAbsorption", true); G4OpticalParameters::Instance()->SetProcessActivation("OpRayleigh", false); G4OpticalParameters::Instance()->SetProcessActivation("OpMieHG", false); G4OpticalParameters::Instance()->SetProcessActivation("OpWLS", false); G4OpticalParameters::Instance()->SetProcessActivation("OpWLS2", false); //G4OpticalParameters::Instance()->SetCerenkovStackPhotons(false); //G4OpticalParameters::Instance()->SetScintStackPhotons(false); G4OpticalParameters::Instance()->SetScintTrackInfo(false); G4OpticalParameters::Instance()->SetScintTrackSecondariesFirst(false); // only relevant if we actually stack and trace the optical photons G4OpticalParameters::Instance()->SetCerenkovTrackSecondariesFirst(false); // only relevant if we actually stack and trace the optical photons G4OpticalParameters::Instance()->SetCerenkovMaxPhotonsPerStep(100); G4OpticalParameters::Instance()->SetCerenkovMaxBetaChange(10.0); G4OpticalParameters::Instance()->Dump(); physList->DumpList(); // Set mandatory initialization classes runManager->SetUserInitialization(new BucatiniDetectorConstruction()); runManager->SetUserInitialization(physList); runManager->SetUserInitialization(new BucatiniActionInitialization()); // Initialize visualization auto visManager = new G4VisExecutive("Quiet"); visManager->Initialize(); // Get the pointer to the User Interface manager auto UImanager = G4UImanager::GetUIpointer(); // Process macro or start UI session // if (macro.size()) { // macro card mode G4String command = "/control/execute "; UImanager->ApplyCommand(command + macro); } else { // start UI session UImanager->ApplyCommand("/control/execute Bucatini_init_vis.mac"); if (ui->IsGUI()) { UImanager->ApplyCommand("/control/execute Bucatini_gui.mac"); } ui->SessionStart(); delete ui; } // Program termination (user actions deleted by run manager) delete visManager; delete runManager; } //**************************************************
32.694581
142
0.706645
EdoPro98
325ec08347b175f1da8ec0babebc75a39ff48c01
1,103
cpp
C++
source/common/xproto/framework/src/plugin/xplugin.cpp
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
98
2020-09-11T13:52:44.000Z
2022-03-23T11:52:02.000Z
source/common/xproto/framework/src/plugin/xplugin.cpp
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
8
2020-10-19T14:23:30.000Z
2022-03-16T01:00:07.000Z
source/common/xproto/framework/src/plugin/xplugin.cpp
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
28
2020-09-17T14:20:35.000Z
2022-01-10T16:26:00.000Z
/*! * ------------------------------------------- * Copyright (c) 2019, Horizon Robotics, Inc. * All rights reserved. * \File xplugin.cpp * \Author Songshan Gong * \Mail songshan.gong@horizon.ai * \Version 1.0.0.0 * \Date 2019-07-30 * \Brief implmentation of xplugin * \DO NOT MODIFY THIS COMMENT, \ * \WHICH IS AUTO GENERATED BY EDITOR * ------------------------------------------- */ #include "xproto/plugin/xplugin.h" #include "xproto/manager/msg_manager.h" #include "xproto/message/pluginflow/flowmsg.h" namespace horizon { namespace vision { namespace xproto { void XPlugin::RegisterMsg(const std::string& type) { XMsgQueue::Instance().RegisterPlugin(shared_from_this(), type); } void XPlugin::UnRegisterMsg(const std::string& type) { XMsgQueue::Instance().UnRegisterPlugin(shared_from_this(), type); } void XPlugin::PushMsg(XProtoMessagePtr msg) { XMsgQueue::Instance().PushMsg(msg); } int XPlugin::TryPushMsg(XProtoMessagePtr msg) { return XMsgQueue::Instance().TryPushMsg(msg); } } // namespace xproto } // namespace vision } // namespace horizon
25.068182
67
0.652765
robort-yuan
3260f431fd17186a0934bb7500142b1a27bef192
1,472
cpp
C++
test/Core/ListTest.cpp
anisimovsergey/gluino_test
7de141362cafb244841b13b7b86c17d00f550fba
[ "MIT" ]
5
2017-10-07T06:46:23.000Z
2018-12-10T07:14:47.000Z
test/Core/ListTest.cpp
anisimovsergey/gluino_test
7de141362cafb244841b13b7b86c17d00f550fba
[ "MIT" ]
8
2017-01-07T15:01:32.000Z
2017-07-16T20:18:10.000Z
test/Core/ListTest.cpp
anisimovsergey/gluino_test
7de141362cafb244841b13b7b86c17d00f550fba
[ "MIT" ]
4
2017-01-07T14:58:00.000Z
2019-10-30T09:38:53.000Z
#include "Utils/Testing.hpp" #include "Core/List.hpp" #include "Core/Memory.hpp" using namespace Core; namespace { class Content : public Core::IEntity { TYPE_INFO(Content, Core::IEntity, "content") public: explicit Content(int i):i(i) {} int i; }; class ContentList : public Core::List<Content> { TYPE_INFO(ContentList, Core::List<Content>, "contentList") }; } TEST_CASE("can add IEntity", "[List]") { ContentList list; list.addEntity(Content(1)); list.addEntity(Content(10)); int acc = 0; auto res = list.forEachEntity([&](const IEntity& element) { acc += static_cast<const Content&>(element).i; return Status::OK; }); REQUIRE(acc == 11); REQUIRE(res.getCode() == StatusCode::OK); } TEST_CASE("can add Content", "[List]") { ContentList list; list.add(Content(1)); list.add(Content(10)); int acc = 0; auto res = list.forEach([&](const Content& element) { acc += element.i; return Status::OK; }); REQUIRE(acc == 11); REQUIRE(res.getCode() == StatusCode::OK); } TEST_CASE("can abort forEach", "[List]") { ContentList list; list.add(Content(1)); list.add(Content(10)); list.add(Content(100)); int acc = 0; auto res = list.forEach([&](const Content& element) { if (element.i > 10) return Status(StatusCode::NotFound, "not found"); acc += element.i; return Status::OK; }); REQUIRE(acc == 11); REQUIRE(res.getCode() == StatusCode::NotFound); }
20.444444
62
0.629076
anisimovsergey
3263c76c159ab76eaf8c303bfdfb9de5f1a8fbb5
1,444
hpp
C++
cpp/include/manager/robinhood_bot.hpp
algo-trading-kjsce/trading
29a245a16512fd5803168064b45021cd508e7de0
[ "MIT" ]
2
2020-11-08T06:11:35.000Z
2021-09-18T01:44:45.000Z
cpp/include/manager/robinhood_bot.hpp
algo-trading-kjsce/trading
29a245a16512fd5803168064b45021cd508e7de0
[ "MIT" ]
null
null
null
cpp/include/manager/robinhood_bot.hpp
algo-trading-kjsce/trading
29a245a16512fd5803168064b45021cd508e7de0
[ "MIT" ]
1
2021-06-13T02:36:25.000Z
2021-06-13T02:36:25.000Z
/** * @file robinhood_bot.hpp * @author ashwinn76 * @brief * @version 0.1 * @date 2021-02-12 * * @copyright Copyright (c) 2021 * */ #pragma once #include "stock_data.hpp" #include "helper/py_object.hpp" namespace trading { class robinhood_bot { private: python::py_object m_bot{}; // Robinhood Bot python::py_object m_historyFunc{}; // Function to get history of prices python::py_object m_last_price_func{}; // Function to get latest price public: /** * @brief Construct a new robinhood bot object * */ robinhood_bot(); /** * @brief Get the historical prices for a stock/currency * * @param i_symbol Symbol to find info * @return csv_data Final historical result */ csv_data get_historical_prices( const std::string& i_symbol ); /** * @brief Get the latest price for a stock/currency * * @param i_symbol Symbol to find info * @return candle_s Candle for latest price */ candle_s get_latest_price( const std::string& i_symbol ); /** * @brief Buy a ticker * * @param i_ticker incoming ticker * @return number of shares and price per share bought */ std::pair<double, double> buy( const std::string& i_ticker ); /** * @brief sell a ticker * * @param i_ticker incoming ticker * @return sale price of ticker */ double sell( const std::string& i_ticker ); }; }
21.552239
76
0.631579
algo-trading-kjsce
32660093b2de2e07949a75a10b18c4a94b8dbb74
4,106
hpp
C++
include/item.hpp
hunter-land/humble-user-interface
2a6f9bf7f6c31e51061aa45fc1d0aa04e21b19e4
[ "Apache-2.0" ]
null
null
null
include/item.hpp
hunter-land/humble-user-interface
2a6f9bf7f6c31e51061aa45fc1d0aa04e21b19e4
[ "Apache-2.0" ]
null
null
null
include/item.hpp
hunter-land/humble-user-interface
2a6f9bf7f6c31e51061aa45fc1d0aa04e21b19e4
[ "Apache-2.0" ]
null
null
null
#pragma once #include "./element.hpp" #include "./itemHolder.hpp" extern "C" { #include <SDL2/SDL.h> } #include <vector> namespace lui { /** * \brief A draggable item which can be placed inside itemHolders * * \note Item template type must match the itemHolder's template type for the item to be held. */ template<typename T> class item : public element { protected: SDL_Texture *m_texture = nullptr; //!<The texture of the item bool m_beingMoved = false; //!<Is this item currently being moved by the user public: SDL_Rect *srcrect = nullptr; //!<Rectangle of the texture to draw itemHolder<T> *m_holder = nullptr; //!<The itemHolder to which we are assigned \warning This item should never be written to. T value; //!<Value, or ID, of this item /** * \brief Construct item with a texture and a value * * \param *texture The texture of the item. * \param val The value to assign to the item. */ item(SDL_Texture *texture, T val = T()) { value = val; } /** * \brief Construct item with a texture, position, size, angle, and value * * \param *texture The texture of the item. * \param dstrect The rectangle to draw the item in. * \param angle The angle the item will be at. * \param flip The flip the item will have. * \param val The value to assign to the item. */ item(SDL_Texture *texture, const SDL_FRect dstrect, const double angle = 0, const SDL_RendererFlip flip = SDL_FLIP_NONE, T val = T()) { setDstrect(dstrect); setAngle(angle); setTexture(texture); value = val; } /** * \brief Deconstruct item */ ~item() {} void render(SDL_Renderer *renderer) { SDL_RenderCopyExF(renderer, m_texture, srcrect, &m_dstrect, m_angle, &(zeroFPoint), m_flip); } void userLogic(std::vector<SDL_Event> &events, SDL_Renderer *renderer) { element::userLogic(events, renderer); for (SDL_Event &e : events) { if (m_hasFocus) { switch (e.type) { case SDL_MOUSEMOTION: if (m_beingMoved) { m_dstrect.x += e.motion.xrel; m_dstrect.y += e.motion.yrel; } break; case SDL_MOUSEBUTTONDOWN: if (e.button.button == SDL_BUTTON_LEFT) { //Start dragging item. pickup(); } break; case SDL_MOUSEBUTTONUP: if (e.button.button == SDL_BUTTON_LEFT) { //Release item release(); } break; } } } } void resetUserLogic() { element::resetUserLogic(); release(); } using element::loopLogic; using element::resetLoopLogic; using element::bind; using element::unbind; using element::setSet; using element::setFocus; void onFocusUpdated() { if (!m_hasFocus && m_beingMoved) { release(); } } using element::setDstrect; using element::getDstrect; using element::setAngle; using element::getAngle; /** * \brief Sets the item's texture * * \param *texture The texture for the item to use */ void setTexture(SDL_Texture *texture) { m_texture = texture; } /** * \brief Gets the item's texture * * \returns The texture of the item */ SDL_Texture* getTexture() { return m_texture; } /** * \brief Release/drop the item */ void release() { m_beingMoved = false; //Check if we were released on an itemHolder if (m_parentSet != nullptr) { std::array<element*, 2> focused = m_parentSet->getFocusedElements(); itemHolder<T>* focusedSub = dynamic_cast<itemHolder<T>*>(focused[1]); if (focused[0] == this && focusedSub != nullptr) { focusedSub->setChild(this); } } } /** * \brief Pickup the item and attach it to the user's mouse */ void pickup() { m_beingMoved = true; //Check if we are being taken from an itemHolder if (m_holder != nullptr) { m_holder->setChild((item<T>*)nullptr); m_holder = nullptr; m_callEventFunction(Event::ValueChanged); } } using element::pointInElement; }; };
26.836601
138
0.619338
hunter-land
3268d43a8df22768303d546e28afa48c87c0a62f
1,221
hpp
C++
include/common/color_utils.hpp
riscygeek/AntSimulator
b35d1b0e0a3601ec326eb2839fb7551672d036af
[ "MIT" ]
null
null
null
include/common/color_utils.hpp
riscygeek/AntSimulator
b35d1b0e0a3601ec326eb2839fb7551672d036af
[ "MIT" ]
null
null
null
include/common/color_utils.hpp
riscygeek/AntSimulator
b35d1b0e0a3601ec326eb2839fb7551672d036af
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> #include "common/math.hpp" #include "common/number_generator.hpp" struct ColorUtils { template<typename T> static sf::Color createColor(T r, T g, T b) { return sf::Color{ std::min(uint8_t{255}, std::max(uint8_t{0}, to<uint8_t>(r))), std::min(uint8_t{255}, std::max(uint8_t{0}, to<uint8_t>(g))), std::min(uint8_t{255}, std::max(uint8_t{0}, to<uint8_t>(b))) }; } static sf::Color getRainbow(float t) { const float r = sin(t); const float g = sin(t + 0.33f * 2.0f * Math::PI); const float b = sin(t + 0.66f * 2.0f * Math::PI); return createColor(255 * r * r, 255 * g * g, 255 * b * b); } static sf::Color getRandomColor() { return createColor(RNGf::getUnder(255.0f), RNGf::getUnder(255.0f), RNGf::getUnder(255.0f)); } static sf::Color getDesaturated(sf::Color color, float ratio) { const float l = 0.3f * color.r + 0.6f * color.g + 0.1f * color.b; float new_r = color.r + ratio * (l - color.r); float new_g = color.g + ratio * (l - color.g); float new_b = color.b + ratio * (l - color.b); return createColor(new_r, new_g, new_b); } };
30.525
99
0.581491
riscygeek
326a25b67e681e27ee9bc177f2a0f2babbb38cc9
4,041
hpp
C++
include/desola/profiling/ExpressionGraph.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
2
2021-12-17T10:46:20.000Z
2021-12-18T11:53:50.000Z
include/desola/profiling/ExpressionGraph.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
null
null
null
include/desola/profiling/ExpressionGraph.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
null
null
null
/****************************************************************************/ /* Copyright 2005-2006, Francis Russell */ /* */ /* 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. */ /* */ /****************************************************************************/ #ifndef DESOLA_PROFILING_EXPRESSION_GRAPH_HPP #define DESOLA_PROFILING_EXPRESSION_GRAPH_HPP #include "Desola_profiling_fwd.hpp" #include <boost/ptr_container/ptr_vector.hpp> #include <cstddef> #include <functional> #include <map> #include <algorithm> #include <cassert> namespace desola { namespace detail { template<typename T_element> class PExpressionGraph { private: PExpressionGraph(const PExpressionGraph&); PExpressionGraph& operator=(const PExpressionGraph&); boost::ptr_vector< PExpressionNode<T_element> > exprVector; mutable bool isHashCached; mutable std::size_t cachedHash; template<typename VisitorType> class ApplyVisitor : public std::unary_function< void, PExpressionNode<T_element> > { private: VisitorType& visitor; public: ApplyVisitor(VisitorType& v) : visitor(v) { } inline void operator()(PExpressionNode<T_element>& node) const { node.accept(visitor); } }; public: PExpressionGraph(ExpressionGraph<T_element>& expressionGraph) : isHashCached(false) { PExpressionNodeGenerator<T_element> generator(*this); expressionGraph.accept(generator); } inline std::size_t nodeCount() const { return exprVector.size(); } void addNode(PExpressionNode<T_element>* const node) { exprVector.push_back(node); } PExpressionNode<T_element>& nodeAt(const std::size_t index) { return exprVector[index]; } void accept(PExpressionNodeVisitor<T_element>& visitor) { std::for_each(exprVector.begin(), exprVector.end(), ApplyVisitor< PExpressionNodeVisitor<T_element> >(visitor)); } bool operator==(const PExpressionGraph& right) const { if(exprVector.size() != right.exprVector.size()) { return false; } else { std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*> mappings; for(std::size_t index = 0; index<exprVector.size(); ++index) { mappings[&exprVector[index]] = &right.exprVector[index]; } PEqualityCheckingVisitor<T_element> checker(mappings); const_cast<PExpressionGraph<T_element>&>(*this).accept(checker); return checker.isEqual(); } } friend std::size_t hash_value(const PExpressionGraph<T_element>& graph) { if(!graph.isHashCached) { graph.isHashCached = true; std::map<const PExpressionNode<T_element>*, int> nodeNumberings; for(std::size_t index=0; index<graph.exprVector.size(); ++index) { nodeNumberings[&graph.exprVector[index]] = index; } PHashingVisitor<T_element> hasher(nodeNumberings); const_cast<PExpressionGraph<T_element>&>(graph).accept(hasher); graph.cachedHash = hasher.getHash(); } return graph.cachedHash; } }; } } #endif
29.49635
116
0.592923
FrancisRussell
326a8bfdcdc201c13317a91c2fbb7621c50878c7
5,309
cpp
C++
src/cvm/defaults.cpp
thomas-pendragon/dablang
f8e1e0835138b6dc6a675da231e176ca20b1347a
[ "MIT" ]
2
2017-06-02T02:55:36.000Z
2017-06-02T22:15:46.000Z
src/cvm/defaults.cpp
thomas-pendragon/dablang
f8e1e0835138b6dc6a675da231e176ca20b1347a
[ "MIT" ]
1
2020-06-19T15:58:33.000Z
2020-06-19T15:58:33.000Z
src/cvm/defaults.cpp
thomas-pendragon/dablang
f8e1e0835138b6dc6a675da231e176ca20b1347a
[ "MIT" ]
1
2017-06-02T22:17:52.000Z
2017-06-02T22:17:52.000Z
#include "cvm.h" #ifndef DAB_PLATFORM_WINDOWS #include <dlfcn.h> #endif #define STR2(s) #s #define STR(s) STR2(s) #ifdef __linux__ #define DAB_LIBC_NAME "libc.so.6" // LINUX #else #define DAB_LIBC_NAME "libc.dylib" // APPLE #endif DabValue DabVM::merge_arrays(const DabValue &arg0, const DabValue &arg1) { auto & a0 = arg0.array(); auto & a1 = arg1.array(); DabValue array_class = classes[CLASS_ARRAY]; DabValue value = array_class.create_instance(); auto & array = value.array(); array.resize(a0.size() + a1.size()); fprintf(stderr, "vm: merge %d and %d items into new %d-sized array\n", (int)a0.size(), (int)a1.size(), (int)array.size()); size_t i = 0; for (auto &item : a0) { array[i++] = item; } for (auto &item : a1) { array[i++] = item; } return value; } dab_function_reg_t import_external_function(void *symbol, const DabFunctionReflection &reflection) { return [symbol, &reflection](DabValue, std::vector<DabValue> args) { const auto &arg_klasses = reflection.arg_klasses; const auto ret_klass = reflection.ret_klass; assert(args.size() == arg_klasses.size()); if (false) { } #include "ffi_signatures.h" else { fprintf(stderr, "vm: unsupported signature\n"); exit(1); } }; } void DabVM::define_defaults() { fprintf(stderr, "vm: define defaults\n"); define_default_classes(); fprintf(stderr, "vm: define default functions\n"); auto make_import_function = [this](const char *name) { return [this, name](DabValue, std::vector<DabValue> args) { #ifndef DAB_PLATFORM_WINDOWS assert(args.size() <= 2); std::string libc_name; if (args.size() == 2) { auto _libc_name = args[1]; libc_name = _libc_name.string(); } auto method = args[0]; assert(method.class_index() == CLASS_METHOD); auto method_name = method.string(); if (args.size() == 1) { libc_name = method_name; } fprintf(stderr, "vm: readjust '%s' to libc function '%s'\n", method_name.c_str(), libc_name.c_str()); auto handle = dlopen(name, RTLD_LAZY); if (!handle) { fprintf(stderr, "vm: dlopen error: %s", dlerror()); exit(1); } if (options.verbose) { fprintf(stderr, "vm: dlopen handle: %p\n", handle); } auto symbol = dlsym(handle, libc_name.c_str()); if (!symbol) { fprintf(stderr, "vm: dlsym error: %s", dlerror()); exit(1); } if (options.verbose) { fprintf(stderr, "vm: dlsym handle: %p\n", symbol); } auto func_index = get_or_create_symbol_index(method_name); auto &function = functions[func_index]; function.regular = false; function.address = -1; function.extra_reg = import_external_function(symbol, function.reflection); return DabValue(nullptr); #else (void)args; if (true) { throw DabRuntimeError("function import not supported on windows yet"); } return DabValue(nullptr); #endif }; }; { DabFunction fun; fun.name = "__import_libc"; fun.regular = false; fun.extra_reg = make_import_function(DAB_LIBC_NAME); auto func_index = get_or_create_symbol_index("__import_libc"); functions[func_index] = fun; } { DabFunction fun; fun.name = "__import_sdl"; fun.regular = false; fun.extra_reg = make_import_function("/usr/local/lib/libSDL2.dylib"); auto func_index = get_or_create_symbol_index("__import_sdl"); functions[func_index] = fun; } { DabFunction fun; fun.name = "__import_pq"; fun.regular = false; fun.extra_reg = make_import_function("/usr/local/lib/libpq.dylib"); auto func_index = get_or_create_symbol_index("__import_pq"); functions[func_index] = fun; } { DabFunction fun; fun.name = "||"; fun.regular = false; fun.extra_reg = [](DabValue, std::vector<DabValue> args) { assert(args.size() == 2); auto arg0 = args[0]; auto arg1 = args[1]; return arg0.truthy() ? arg0 : arg1; }; auto func_index = get_or_create_symbol_index("||"); functions[func_index] = fun; } { DabFunction fun; fun.name = "&&"; fun.regular = false; fun.extra_reg = [](DabValue, std::vector<DabValue> args) { assert(args.size() == 2); auto arg0 = args[0]; auto arg1 = args[1]; return arg0.truthy() ? arg1 : arg0; }; auto func_index = get_or_create_symbol_index("&&"); functions[func_index] = fun; } }
27.225641
98
0.531362
thomas-pendragon
326ed1406f7c711c77f356ff99e94ab70c1feb1f
2,636
cpp
C++
catkin_ws/src/srrg2_core/srrg2_core/src/examples/field_pack_example.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
5
2020-03-11T14:36:13.000Z
2021-09-09T09:01:15.000Z
catkin_ws/src/srrg2_core/srrg2_core/src/examples/field_pack_example.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
1
2020-06-07T17:25:04.000Z
2020-07-15T07:36:10.000Z
catkin_ws/src/srrg2_core/srrg2_core/src/examples/field_pack_example.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
2
2020-11-30T08:17:53.000Z
2021-06-19T05:07:07.000Z
#include <iostream> #include "srrg_data_structures/field_pack.h" #include <vector> #include <string> #include <sstream> #include "srrg_data_structures/generic_class_method_caller.h" using namespace srrg2_core; using namespace std; using MyFieldPack=FieldPack_<int, string, float>; using MyFieldPackDerived=FieldPackDerived_<MyFieldPack, float, float, string>; using MyFieldPackDerivedDerived=FieldPackDerived_<MyFieldPackDerived, string>; template <typename FieldPackType_, int i> struct PrintAt_ { static void print_(const FieldPackType_& pack) { PrintAt_<FieldPackType_, i-1>::print_(pack); std::cerr << pack.template field<i>() << ", "; } }; template <typename FieldPackType_> struct PrintAt_<FieldPackType_, 0> { static void print_(const FieldPackType_& pack) { std::cerr << pack.template field<0>() <<", "; } }; struct SimpleRunner { bool methodOne(int i , string s, float f) { std::cerr << "MethodOne" << i << " " << s << " " << f << std::endl; return true; } }; int main(int argc, char** argv) { MyFieldPack pack; pack.field<0>() = 5; pack.field<1>() = std::string("pack_test"); pack.field<2>() = 5.5; MyFieldPackDerived dpack; dpack.field<0>() = 50; dpack.field<1>() = std::string("dpack_test"); dpack.field<2>() = 55.5; dpack.field<3>() = 0.1; dpack.field<4>() = 0.7; dpack.field<5>() = std::string("dpack_test_final"); cerr << "num_fields: " << MyFieldPack::NumFields << endl; MyFieldPackDerivedDerived ddpack; ddpack.field<0>() = 500; ddpack.field<1>() = std::string("ddpack_test"); ddpack.field<2>() = 555.5; ddpack.field<3>() = 0.01; ddpack.field<4>() = 0.07; ddpack.field<5>() = std::string("ddpack_test_middle"); ddpack.field<6>() = std::string("ddpack_test_final"); std::cerr<< "base: " << endl; PrintAt_<MyFieldPack, MyFieldPack::NumFields-1>::print_(pack); cerr << endl; std::cerr<< "derived: " << endl; PrintAt_<MyFieldPackDerived, MyFieldPackDerived::NumFields-1>::print_(dpack); cerr << endl; std::cerr << "base=derived" << std::endl; pack=dpack; PrintAt_<MyFieldPack, MyFieldPack::NumFields-1>::print_(pack); cerr << endl; PrintAt_<MyFieldPack, MyFieldPack::NumFields-1>::print_(pack); SimpleRunner runner; GenericClassMethodCaller_<SimpleRunner, typeof(&SimpleRunner::methodOne), int, std::string, float> caller; std::vector<std::string> tokens; tokens.push_back("1"); tokens.push_back("i_am_a_string"); tokens.push_back("1.1"); caller.parsePackFromTokens<0>(tokens); caller.execute<0>(runner, &SimpleRunner::methodOne); }
28.042553
79
0.66692
laaners
326f8f201022daa2b16f257b0f344d04cfa2080d
6,668
cpp
C++
Gui/DataView/DirectConditionGenerator.cpp
WenjieXu/ogs
0cd1b72ec824833bf949a8bbce073c82158ee443
[ "BSD-4-Clause" ]
1
2021-11-21T17:29:38.000Z
2021-11-21T17:29:38.000Z
Gui/DataView/DirectConditionGenerator.cpp
WenjieXu/ogs
0cd1b72ec824833bf949a8bbce073c82158ee443
[ "BSD-4-Clause" ]
null
null
null
Gui/DataView/DirectConditionGenerator.cpp
WenjieXu/ogs
0cd1b72ec824833bf949a8bbce073c82158ee443
[ "BSD-4-Clause" ]
null
null
null
/** * \file * \author Karsten Rink * \date 2012-01-04 * \brief Implementation of the DirectConditionGenerator class. * * \copyright * Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include <fstream> // ThirdParty/logog #include "logog/include/logog.hpp" #include "DirectConditionGenerator.h" #include "Raster.h" #include "MeshSurfaceExtraction.h" #include "PointWithID.h" #include "Mesh.h" #include <cmath> #include <limits> const std::vector< std::pair<size_t,double> >& DirectConditionGenerator::directToSurfaceNodes(const MeshLib::Mesh &mesh, const std::string &filename) { if (_direct_values.empty()) { GeoLib::Raster* raster(GeoLib::Raster::getRasterFromASCFile(filename)); if (! raster) { ERR("Error in DirectConditionGenerator::directWithSurfaceIntegration() - could not load raster file."); return _direct_values; } double origin_x(raster->getOrigin()[0]); double origin_y(raster->getOrigin()[1]); double delta(raster->getRasterPixelDistance()); double no_data(raster->getNoDataValue()); unsigned imgwidth(raster->getNCols()), imgheight(raster->getNRows()); double const*const img(raster->begin()); const double dir[3] = {0,0,1}; const std::vector<GeoLib::PointWithID*> surface_nodes(MeshLib::MeshSurfaceExtraction::getSurfaceNodes(mesh, dir) ); const size_t nNodes(surface_nodes.size()); _direct_values.reserve(nNodes); for (size_t i=0; i<nNodes; i++) { const double* coords (surface_nodes[i]->getCoords()); if (coords[0]>=origin_x && coords[0]<(origin_x+(delta*imgwidth)) && coords[1]>=origin_y && coords[1]<(origin_y+(delta*imgheight))) { int cell_x = static_cast<int>(floor((coords[0] - origin_x)/delta)); int cell_y = static_cast<int>(floor((coords[1] - origin_y)/delta)); // if node outside of raster use raster boundary values cell_x = (cell_x < 0) ? 0 : ((cell_x > static_cast<int>(imgwidth )) ? (imgwidth-1) : cell_x); cell_y = (cell_y < 0) ? 0 : ((cell_y > static_cast<int>(imgheight)) ? (imgheight-1) : cell_y); size_t index = cell_y*imgwidth+cell_x; if (fabs(img[index] - no_data) > std::numeric_limits<float>::epsilon()) _direct_values.push_back( std::pair<size_t, double>(surface_nodes[i]->getID(),img[index]) ); } } delete raster; } else ERR("Error in DirectConditionGenerator::directToSurfaceNodes() - Data vector contains outdated values."); return _direct_values; } const std::vector< std::pair<size_t,double> >& DirectConditionGenerator::directWithSurfaceIntegration(MeshLib::Mesh &mesh, const std::string &filename, double scaling) { (void)mesh; (void)filename; (void)scaling; /* TODO6 double no_data_value (-9999); // TODO: get this from asc-reader! if (_direct_values.empty()) { //mesh.MarkInterface_mHM_Hydro_3D(); // mark element faces on the surface //---- const double dir[3] = {0,0,1}; MeshLib::Mesh* sfc_mesh (MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, dir)); std::vector<double> node_area_vec (sfc_mesh->getNNodes()); MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes(sfc_mesh, node_area_vec); //---- double origin_x(0), origin_y(0), delta(0); size_t imgwidth(0), imgheight(0); double node_val[8] = {0,0,0,0,0,0,0,0}; // maximum possible number of nodes per face (just in case ...) FiniteElement::CElement* fem ( new FiniteElement::CElement(mesh.GetCoordinateFlag()) ); float* img = 0; if (filename.substr(filename.length()-3,3).compare("asc") == 0) img = VtkRaster::loadDataFromASC(filename, origin_x, origin_y, imgwidth, imgheight, delta); else if (filename.substr(filename.length()-3,3).compare("grd") == 0) img = VtkRaster::loadDataFromSurfer(filename, origin_x, origin_y, imgwidth, imgheight, delta); if (img == 0) { std::cout << "Error in DirectConditionGenerator::directWithSurfaceIntegration() - could not load vtk raster." << std::endl; return _direct_values; } const size_t nNodes(mesh.nod_vector.size()); std::vector<double> val(nNodes, 0.0); for(size_t i = 0; i < nNodes; i++) mesh.nod_vector[i]->SetMark(false); // copied from CFEMesh::Precipitation2NeumannBC() by WW size_t nFaces = mesh.face_vector.size(); for(size_t i=0; i<nFaces; i++) { MeshLib::CElem* elem = mesh.face_vector[i]; if (!elem->GetMark()) continue; // if face is on the surface of the mesh size_t nElemNodes = elem->GetNodesNumber(false); for(size_t k=0; k<nElemNodes; k++) node_val[k] = 0.0; // get values from the raster for all nodes of the face for(size_t k=0; k<nElemNodes; k++) { double const* const pnt_k (elem->GetNode(k)->getData()); int cell_x = static_cast<int>(floor((pnt_k[0] - origin_x) / delta)); int cell_y = static_cast<int>(floor((pnt_k[1] - origin_y) / delta)); // if node outside of raster use raster boundary values cell_x = (cell_x < 0) ? 0 : ((static_cast<size_t>(cell_x) > imgwidth) ? (imgwidth-1) : cell_x); cell_y = (cell_y < 0) ? 0 : ((static_cast<size_t>(cell_y) > imgheight) ? (imgheight-1) : cell_y); node_val[k] = img[ 2 * (cell_y * imgwidth + cell_x) ]; if (fabs(node_val[k] - no_data_value) < std::numeric_limits<double>::epsilon()) node_val[k] = 0.; } // get area of the surface element face elem->ComputeVolume(); // do the actual surface integration fem->setOrder(mesh.getOrder() + 1); fem->ConfigElement(elem); fem->FaceIntegration(node_val); // add up the integrated values (nodes get values added for all faces they are part of) for(size_t k=0; k<elem->GetNodesNumber(false); k++) { MeshLib::CNode* node = elem->GetNode(k); node->SetMark(true); val[node->GetIndex()] += node_val[k]; } } _direct_values.reserve(nNodes); for(size_t k=0; k<nNodes; k++) { if (!mesh.nod_vector[k]->GetMark()) continue; // Assuming the unit of precipitation is mm/day _direct_values.push_back( std::pair<size_t, double>(k, val[k] / scaling) ); } } else std::cout << "Error in DirectConditionGenerator::directWithSurfaceIntegration() - Data vector contains outdated values..." << std::endl; */ return _direct_values; } int DirectConditionGenerator::writeToFile(const std::string &name) const { std::ofstream out( name.c_str(), std::ios::out ); if (out) { for (std::vector< std::pair<size_t,double> >::const_iterator it = _direct_values.begin(); it != _direct_values.end(); ++it) out << it->first << "\t" << it->second << "\n"; out.close(); } return 0; }
34.194872
167
0.678464
WenjieXu
32732877e7abe53c30f32eda347d067269fe883d
6,733
cxx
C++
STEER/ESD/AliESDMuonCluster.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/ESD/AliESDMuonCluster.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/ESD/AliESDMuonCluster.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ //----------------------------------------------------------------------------- /// \class AliESDMuonCluster /// /// Class to describe the MUON clusters in the Event Summary Data /// /// \author Philippe Pillot, Subatech //----------------------------------------------------------------------------- #include "AliESDEvent.h" #include "AliESDMuonCluster.h" #include "AliESDMuonPad.h" #include "AliLog.h" #include <TClonesArray.h> #include <Riostream.h> using std::endl; using std::cout; /// \cond CLASSIMP ClassImp(AliESDMuonCluster) /// \endcond //_____________________________________________________________________________ AliESDMuonCluster::AliESDMuonCluster() : TObject(), fCharge(0.), fChi2(0.), fPads(0x0), fNPads(0), fPadsId(0x0), fLabel(-1) { /// default constructor fXYZ[0] = fXYZ[1] = fXYZ[2] = 0.; fErrXY[0] = fErrXY[1] = 0.; } //_____________________________________________________________________________ AliESDMuonCluster::AliESDMuonCluster (const AliESDMuonCluster& cluster) : TObject(cluster), fCharge(cluster.fCharge), fChi2(cluster.fChi2), fPads(0x0), fNPads(cluster.fNPads), fPadsId(0x0), fLabel(cluster.fLabel) { /// Copy constructor fXYZ[0] = cluster.fXYZ[0]; fXYZ[1] = cluster.fXYZ[1]; fXYZ[2] = cluster.fXYZ[2]; fErrXY[0] = cluster.fErrXY[0]; fErrXY[1] = cluster.fErrXY[1]; if (cluster.fPads) { fPads = new TClonesArray("AliESDMuonPad",cluster.fPads->GetEntriesFast()); AliESDMuonPad *pad = (AliESDMuonPad*) cluster.fPads->First(); while (pad) { new ((*fPads)[fPads->GetEntriesFast()]) AliESDMuonPad(*pad); pad = (AliESDMuonPad*) cluster.fPads->After(pad); } } if (cluster.fPadsId) fPadsId = new TArrayI(*(cluster.fPadsId)); } //_____________________________________________________________________________ AliESDMuonCluster& AliESDMuonCluster::operator=(const AliESDMuonCluster& cluster) { /// Equal operator if (this == &cluster) return *this; TObject::operator=(cluster); // don't forget to invoke the base class' assignment operator fXYZ[0] = cluster.fXYZ[0]; fXYZ[1] = cluster.fXYZ[1]; fXYZ[2] = cluster.fXYZ[2]; fErrXY[0] = cluster.fErrXY[0]; fErrXY[1] = cluster.fErrXY[1]; fCharge = cluster.fCharge; fChi2 = cluster.fChi2; fLabel = cluster.fLabel; delete fPads; if (cluster.fPads) { fPads = new TClonesArray("AliESDMuonPad",cluster.fPads->GetEntriesFast()); AliESDMuonPad *pad = (AliESDMuonPad*) cluster.fPads->First(); while (pad) { new ((*fPads)[fPads->GetEntriesFast()]) AliESDMuonPad(*pad); pad = (AliESDMuonPad*) cluster.fPads->After(pad); } } else fPads = 0x0; SetPadsId(cluster.fNPads, cluster.GetPadsId()); return *this; } //_____________________________________________________________________________ void AliESDMuonCluster::Copy(TObject &obj) const { /// This overwrites the virtual TOBject::Copy() /// to allow run time copying without casting /// in AliESDEvent if(this==&obj)return; AliESDMuonCluster *robj = dynamic_cast<AliESDMuonCluster*>(&obj); if(!robj)return; // not an AliESDMuonCluster *robj = *this; } //__________________________________________________________________________ AliESDMuonCluster::~AliESDMuonCluster() { /// Destructor delete fPads; delete fPadsId; } //__________________________________________________________________________ void AliESDMuonCluster::Clear(Option_t* opt) { /// Clear arrays if (opt && opt[0] == 'C') { if (fPads) fPads->Clear("C"); } else { delete fPads; fPads = 0x0; } delete fPadsId; fPadsId = 0x0; fNPads = 0; } //_____________________________________________________________________________ void AliESDMuonCluster::AddPadId(UInt_t padId) { /// Add the given pad Id to the list associated to the cluster if (!fPadsId) fPadsId = new TArrayI(10); if (fPadsId->GetSize() <= fNPads) fPadsId->Set(fNPads+10); fPadsId->AddAt(static_cast<Int_t>(padId), fNPads++); } //_____________________________________________________________________________ void AliESDMuonCluster::SetPadsId(Int_t nPads, const UInt_t *padsId) { /// Fill the list pads'Id associated to the cluster with the given list if (nPads <= 0 || !padsId) { delete fPadsId; fPadsId = 0x0; fNPads = 0; return; } if (!fPadsId) fPadsId = new TArrayI(nPads, reinterpret_cast<const Int_t*>(padsId)); else fPadsId->Set(nPads, reinterpret_cast<const Int_t*>(padsId)); fNPads = nPads; } //_____________________________________________________________________________ void AliESDMuonCluster::MovePadsToESD(AliESDEvent &esd) { /// move the pads to the new ESD structure if (!fPads) return; for (Int_t i = 0; i < fPads->GetEntriesFast(); i++) { AliESDMuonPad *pad = static_cast<AliESDMuonPad*>(fPads->UncheckedAt(i)); AliESDMuonPad *newPad = esd.NewMuonPad(); *newPad = *pad; AddPadId(newPad->GetUniqueID()); } delete fPads; fPads = 0x0; } //_____________________________________________________________________________ void AliESDMuonCluster::Print(Option_t */*option*/) const { /// print cluster content UInt_t cId = GetUniqueID(); cout<<Form("clusterID=%u (ch=%d, det=%d, index=%d)", cId,GetChamberId(),GetDetElemId(),GetClusterIndex())<<endl; cout<<Form(" position=(%5.2f, %5.2f, %5.2f), sigma=(%5.2f, %5.2f, 0.0)", GetX(),GetY(),GetZ(),GetErrX(),GetErrY())<<endl; cout<<Form(" charge=%5.2f, chi2=%5.2f, MClabel=%d", GetCharge(), GetChi2(), GetLabel())<<endl; if (PadsStored()) { cout<<" pad infos:"<<endl; for (Int_t iPad=0; iPad<GetNPads(); iPad++) cout<<" "<<GetPadId(iPad)<<endl; } }
31.316279
97
0.65023
AllaMaevskaya
32761901f67e4dba8f0328a2acf39ee22b6902e2
889
cpp
C++
tests/source/test_tokenize_quoted_string.cpp
0lru/c2pcss
a641e58e4f8f681feedb5eaf06dc8374b3b24ed6
[ "MIT" ]
null
null
null
tests/source/test_tokenize_quoted_string.cpp
0lru/c2pcss
a641e58e4f8f681feedb5eaf06dc8374b3b24ed6
[ "MIT" ]
null
null
null
tests/source/test_tokenize_quoted_string.cpp
0lru/c2pcss
a641e58e4f8f681feedb5eaf06dc8374b3b24ed6
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <css/tokenizer/tokenize.h> namespace css::test { namespace { auto xy = R"()"; } TEST_CASE("can parse empty double quoted string", "[tokenize][detail]") { auto input = std::string(R"("")"); auto begin = input.data(); auto end = input.data() + input.size(); REQUIRE(detail::quoted_string(begin, end) == end); } TEST_CASE("can parse double quoted string with escaped quotes", "[tokenize][detail]") { auto input = std::string(R"("\"")"); auto begin = input.data(); auto end = input.data() + input.size(); REQUIRE(detail::quoted_string(begin, end) == end); } TEST_CASE("can escape newline in double quoted string", "[tokenize][detail]") { auto input = std::string("\"\\\n\""); auto begin = input.data(); auto end = input.data() + input.size(); REQUIRE(detail::quoted_string(begin, end) == end); } }
25.4
85
0.626547
0lru
3277ee831ccf791ce03e8d6d2b7ade4965d08192
2,544
cpp
C++
VisualStudio2013/WinSPP/WinSPP/WinSPPFrm.cpp
ma-laforge/WinSPP
7499a85d9872a2429c87aaa7d67806f2816c7407
[ "MIT" ]
null
null
null
VisualStudio2013/WinSPP/WinSPP/WinSPPFrm.cpp
ma-laforge/WinSPP
7499a85d9872a2429c87aaa7d67806f2816c7407
[ "MIT" ]
null
null
null
VisualStudio2013/WinSPP/WinSPP/WinSPPFrm.cpp
ma-laforge/WinSPP
7499a85d9872a2429c87aaa7d67806f2816c7407
[ "MIT" ]
null
null
null
#include <windows.h> #include "WinSPPFrm.h" #include <msclr/marshal_cppstd.h> namespace WinSPP { //In-elegant refresh all function to update control state: void WinSPPFrm::UpdateControlState() { tbFileName->Enabled = rbFromFile->Checked; } //UpdateControlState void WinSPPFrm::UpdateMetafile(bool displayErrors) { using namespace Runtime::InteropServices; using namespace GDIExt; bool compensateSObug = chkSOComp->Checked; std::string fileName = msclr::interop::marshal_as<std::string>(tbFileName->Text); if (plot) { delete plot; plot = 0; } try { plot = new SParamPlots::Plot(compensateSObug); if (rbEmptySmith->Checked) plot->CreateEmptySmith(); else if (rbEmptyPolar->Checked) plot->CreateEmptyPolar(); else plot->Open(fileName); } catch (std::exception &e) { if (plot) { delete plot; plot = 0; } RefreshPreview(); if (displayErrors) { System::String ^msg = gcnew System::String(e.what()); MessageBox::Show(msg, "ERROR", MessageBoxButtons::OK); } } } //UpdateMetafile void WinSPPFrm::RefreshPreview() { Drawing::Rectangle rect = pnlPreview->ClientRectangle; int maxdim = min(rect.Width, rect.Height); if (maxdim > 0) { pbPreview->SetBounds((rect.Width - maxdim) / 2, (rect.Height - maxdim) / 2, maxdim, maxdim); } try { using namespace Drawing; using Drawing::Pen; using Drawing::Rectangle; using Drawing::SolidBrush; Rectangle rect = pbPreview->ClientRectangle; SolidBrush ^brush = gcnew SolidBrush(Color::White); Bitmap ^bmp = gcnew Bitmap(rect.Width, rect.Height); Graphics ^g = Graphics::FromImage(bmp); //Use a white background: g->FillRectangle(brush, rect); if (plot) { HDC hdc = static_cast<HDC>(g->GetHdc().ToPointer()); plot->Draw(hdc, GDIExt::Rect(pbPreview->Width, pbPreview->Height)); g->ReleaseHdc(); } pbPreview->Image = bmp; } catch (...) {} } //RefreshPreview void WinSPPFrm::SaveMetafile() { try { System::String ^msg; std::string fileName = msclr::interop::marshal_as<std::string>(tbFileName->Text); fileName += ".emf"; if (!plot) throw(std::runtime_error("Nothing to save.")); if (rbEmptySmith->Checked) fileName = "Smith.emf"; else if (rbEmptyPolar->Checked) fileName = "Polar.emf"; plot->Save(fileName); msg = gcnew System::String(fileName.c_str()); MessageBox::Show(msg, "Saved to file:", MessageBoxButtons::OK); } catch (std::exception &e) { System::String ^msg = gcnew System::String(e.what()); MessageBox::Show(msg, "ERROR", MessageBoxButtons::OK); } } //SaveMetafile } //namespace WinSPP
28.909091
94
0.693396
ma-laforge
32792a931f60d8ebaf5e45311ac7a032bfcb33cc
776
hpp
C++
includes/Entity.hpp
LightCollective/OneLight
523678cacdc027efe3d4afa5d2558ad85b739d7f
[ "MIT" ]
null
null
null
includes/Entity.hpp
LightCollective/OneLight
523678cacdc027efe3d4afa5d2558ad85b739d7f
[ "MIT" ]
null
null
null
includes/Entity.hpp
LightCollective/OneLight
523678cacdc027efe3d4afa5d2558ad85b739d7f
[ "MIT" ]
null
null
null
#ifndef ONELIGHT_ENTITY_H #define ONELIGHT_ENTITY_H #include "FluxSprite.hpp" #include "FluxSpriteBatch.hpp" class Entity { public: Entity(); virtual ~Entity(); Flux::Vector2 getPosition(); virtual void setPosition(const Flux::Vector2 &position); std::shared_ptr<Flux::Sprite> getSprite(); Flux::Vector2 getVelocity(); void setVelocity(const Flux::Vector2 &velocity); float getSpeed(); void setSpeed(const float speed); virtual void update(); Flux::Rectangle2D getAABB(); protected: std::shared_ptr<Flux::Sprite> sprite; std::shared_ptr<Flux::SpriteBatch> sb; Flux::Vector2 velocity; Flux::Rectangle2D aabb; float speed; }; #endif
21.555556
64
0.628866
LightCollective
32794b2c3827699234606d4d93042d2cf9e8c940
8,017
cpp
C++
submodules/hal/maf/impl/halMafScanDimensions.cpp
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/maf/impl/halMafScanDimensions.cpp
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/maf/impl/halMafScanDimensions.cpp
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cassert> #include <iostream> #include <stdexcept> #include <sstream> #include <algorithm> #include "halMafScanDimensions.h" using namespace std; using namespace hal; MafScanDimensions::MafScanDimensions() : MafScanner() { assert(sizeof(ArrayInfo) == sizeof(hal_size_t)); } MafScanDimensions::~MafScanDimensions() { for (DimMap::iterator i = _dimMap.begin(); i != _dimMap.end(); ++i) { delete i->second; } } void MafScanDimensions::scan(const string& mafPath, const set<string>& targets) { for (DimMap::iterator i = _dimMap.begin(); i != _dimMap.end(); ++i) { delete i->second; } _dimMap.clear(); MafScanner::scan(mafPath, targets); updateArrayIndices(); } const MafScanDimensions::DimMap& MafScanDimensions::getDimensions() const { return _dimMap; } void MafScanDimensions::aLine() { assert(_rows <= _block.size()); if (_rows > 0) { updateDimensionsFromBlock(); } } void MafScanDimensions::sLine() { Row& row = _block[_rows - 1]; // this is the first pass. so we do a quick sanity check size_t dotPos = row._sequenceName.find('.'); if (dotPos == string::npos || dotPos == 0 || dotPos == row._sequenceName.length() - 1) { stringstream ss; ss << "illegal sequence name found: " << row._sequenceName << ". Sequence " "names must be in genomeName.sequenceName format."; throw hal_exception(ss.str()); } size_t numGaps = 0; for (size_t i = 0; i < row._line.length(); ++i) { if (row._line[i] == '-') { ++numGaps; } else { if (!isNucleotide(row._line[i])) { stringstream ss; ss << "problem reading line for sequence " << row._sequenceName << ": " " non-gap non-nucleotide character " << row._line[i] << " found at " << i << "th position"; throw hal_exception(ss.str()); } } } if (row._line.length() - numGaps != row._length) { stringstream ss; ss << "problem reading line for sequence " << row._sequenceName << ": " " length field was " << row._length << " but line contains " << row._line.length() - numGaps << " bases"; throw hal_exception(ss.str()); } if (row._startPosition + row._length > row._srcLength) { stringstream ss; ss << "problem reading line for sequence " << row._sequenceName << ": " " sequence length is" << row._srcLength << " but line starts at " << row._startPosition << " and contains " << row._length << " bases"; throw hal_exception(ss.str()); } } void MafScanDimensions::end() { assert(_rows <= _block.size()); if (_rows > 0) { updateDimensionsFromBlock(); } } void MafScanDimensions::updateDimensionsFromBlock() { assert(_rows > 0 && !_block.empty()); size_t length = _block[0]._line.length(); for (size_t i = 0; i < _rows; ++i) { Row& row = _block[i]; pair<string, Record*> newRec(row._sequenceName, NULL); pair<DimMap::iterator, bool> result = _dimMap.insert(newRec); Record*& rec = result.first->second; pair<hal_size_t, ArrayInfo> startIndex; startIndex.first = 0; startIndex.second._index = 0; startIndex.second._count = 1; startIndex.second._written = 0; startIndex.second._empty = 0; if (result.second == false && row._srcLength != rec->_length) { assert(rec != NULL); stringstream ss; ss << "conflicting length for sequence " << row._sequenceName << ": " << "was scanned once as " << row._srcLength << " then again as " << rec->_length; throw hal_exception(ss.str()); } else if (result.second == true) { rec = new Record(); startIndex.first = 0; startIndex.second._empty = 1; rec->_startMap.insert(startIndex); startIndex.second._empty = 0; rec->_numSegments = 0; } rec->_length = row._srcLength; if (row._length > 0) { // add the begnning of the line as a segment start position // also add the last + 1 segments as a start position if in range hal_size_t start = row._startPosition; hal_size_t end = start + row._length; if (row._strand == '-') { start = row._srcLength - 1 - (row._startPosition + row._length - 1); end = row._srcLength - row._startPosition; } startIndex.first = start; pair<StartMap::iterator, bool> smResult = rec->_startMap.insert(startIndex); StartMap::iterator smIt = smResult.first; bool bad = false; // check for duplication / inconsistency: // 1) new interval lands on start position of existing interval // existing is unchanged but we don't do anything else. if (smResult.second == false && smIt->second._empty == 0) { bad = true; } // 2) new interval overlaps with existing interval // set count to 0 if new, ignore otherwise StartMap::iterator next = smIt; ++next; while (next != rec->_startMap.end() && !bad) { if (next->second._count > 0) { if (smIt->first + row._length > next->first) { bad = true; } else { break; } } ++next; } // 3) new interval overlaps a previous interval that is not // empty if (!bad && smResult.second == true && smIt != rec->_startMap.begin()) { StartMap::iterator prev = smIt; --prev; while (!bad) { if (prev->second._count > 0) { if (prev->second._empty == 0) { bad = true; } else { break; } } if (prev == rec->_startMap.begin()) { break; } --prev; } } if (bad == true) { if (smResult.second == true) { rec->_startMap.erase(smIt); } rec->_badPosSet.insert(FilePosition(_mafFile.tellg(), i)); } else { smIt->second._empty = 0; assert(smIt->second._count == 1); if (end < row._srcLength) { startIndex.first = end; startIndex.second._empty = 1; startIndex.second._count = 1; pair<StartMap::iterator, bool> endResult = rec->_startMap.insert(startIndex); } size_t numGaps = 0; hal_size_t interiorStart; for (size_t j = 0; j < length; ++j) { if (row._line[j] == '-') { ++numGaps; } // valid segmentation between j-1 and j: // we add the start coordinate of the segment beginning at // j in forward segment coordinates. else if (_mask[j] == true && (row._line[j] != '-')) { interiorStart = start + j - numGaps; if (interiorStart > start) { ++smIt->second._count; } } } } } } } void MafScanDimensions::updateArrayIndices() { string curName, prevName; hal_size_t arrayIndex = 0; hal_size_t prevIndex = 0; for (DimMap::iterator i = _dimMap.begin(); i != _dimMap.end(); ++i) { assert(i->second != NULL); curName = genomeName(i->first); assert(!curName.empty()); if (curName != prevName) { arrayIndex = 0; prevIndex = 0; } // compute the array index for each start position in the map StartMap& startMap = i->second->_startMap; for (StartMap::iterator j = startMap.begin(); j != startMap.end(); ++j) { assert(j->second._count > 0); j->second._index = arrayIndex; arrayIndex += j->second._count; } i->second->_numSegments = arrayIndex - prevIndex; prevName = curName; prevIndex = arrayIndex; } }
26.458746
80
0.557939
pbasting
327a33491b966234533663c3aa20ceefa3cf84c4
2,980
cpp
C++
markup/mainwindow.cpp
rlbisbe/markup
03b8d706e9fc45586b54470bea9d324ab016020a
[ "MIT" ]
null
null
null
markup/mainwindow.cpp
rlbisbe/markup
03b8d706e9fc45586b54470bea9d324ab016020a
[ "MIT" ]
null
null
null
markup/mainwindow.cpp
rlbisbe/markup
03b8d706e9fc45586b54470bea9d324ab016020a
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "markdownparser.h" #include "document.h" #include "autosaveddocument.h" #include "wordcounter.h" #include <QFileDialog> #include <QTextStream> #include <QSettings> #include <QShortcut> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile())); connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile())); connect(ui->actionSave_file, SIGNAL(triggered()), this, SLOT(saveFile())); connect(ui->actionToggle_preview, SIGNAL(triggered()), this, SLOT(togglePreview())); connect(ui->editor, SIGNAL(textChanged()), this, SLOT(refreshRenderer())); QCoreApplication::setOrganizationName("Rlbisbe"); QCoreApplication::setOrganizationDomain("rlbisbe.net"); QCoreApplication::setApplicationName("MarkUp"); this->updatePreview(); } void MainWindow::reloadBuffer(){ if(m_settings.contains("currentFile")){ openFile(m_settings.value("currentFile").toString()); } } void MainWindow::newFile(){ m_settings.remove("currentFile"); this->m_document = new AutosavedDocument(); ui->editor->setPlainText(m_document->getContent()); } void MainWindow::openFile(){ //Get the new file name QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), nullptr, tr("Text files (*.md)")); openFile(fileName); } void MainWindow::openFile(QString fileName){ this->m_document = new AutosavedDocument(fileName); if(m_document->getContent() != nullptr){ ui->editor->setPlainText(m_document->getContent()); m_settings.setValue("currentFile", fileName); this->updateWindowTitle(); } } void MainWindow::refreshRenderer(){ m_document->setContent(ui->editor->toPlainText()); QString htmlContent = MarkdownParser().convertToHtml(m_document->getContent()); ui->preview->setText(htmlContent); this->updateWindowTitle(); WordCounter* wordCounter = new WordCounter(); ui->statusBar->showMessage(QString::number(wordCounter->count(m_document->getContent())) + " words"); } void MainWindow::saveFile(){ if(this->m_document->getPath() == nullptr){ this->m_document->setPath(QFileDialog::getSaveFileName(this, tr("Save File"), nullptr, tr("Text files (*.md)"))); } this->m_document->save(); this->updateWindowTitle(); } void MainWindow::togglePreview(){ m_settings.setValue("previewEnabled", !m_settings.value("previewEnabled", false).toBool()); this->updatePreview(); } void MainWindow::updatePreview(){ bool previewEnabled = m_settings.value("previewEnabled", false).toBool(); ui->preview->setVisible(previewEnabled); } void MainWindow::updateWindowTitle(){ setWindowTitle(this->m_document->getPathWithChanges() +" - " + "MarkUp text editor"); } MainWindow::~MainWindow() { delete ui; }
27.33945
105
0.692953
rlbisbe
3280832dbbd4ecaa3f1434e9f96c7f9d5e0917c1
7,720
cpp
C++
src/main.cpp
moonshadow565/fuckingmanifestdownloader
b362508c424567e76e74239bfed0c7fddfbbf17d
[ "MIT" ]
null
null
null
src/main.cpp
moonshadow565/fuckingmanifestdownloader
b362508c424567e76e74239bfed0c7fddfbbf17d
[ "MIT" ]
null
null
null
src/main.cpp
moonshadow565/fuckingmanifestdownloader
b362508c424567e76e74239bfed0c7fddfbbf17d
[ "MIT" ]
null
null
null
#include "manifest.hpp" #include "file.hpp" #include "error.hpp" #include "cli.hpp" #include "download.hpp" #include <iostream> #include <fstream> #include <set> using namespace rman; struct Main { CLI cli = {}; FileList manifest = {}; std::optional<FileList> upgrade = {}; std::unique_ptr<HttpClient> client = {}; void parse_args(int argc, char** argv) { cli.parse(argc, argv); } void parse_manifest() { rman_trace("Manifest file: %s", cli.manifest.c_str()); manifest = FileList::read(read_file(cli.manifest)); manifest.filter_langs(cli.langs); manifest.filter_path(cli.path); manifest.sanitize(); } void parse_upgrade() { if (!cli.upgrade.empty()) { rman_trace("Upgrade from manifest file: %s", cli.upgrade.c_str()); upgrade = FileList::read(read_file(cli.upgrade)); upgrade->filter_langs(cli.langs); upgrade->filter_path(cli.path); upgrade->sanitize(); manifest.remove_uptodate(*upgrade); } } void process() { switch(cli.action) { case Action::List: action_list(); break; case Action::ListBundles: action_list_bundles(); break; case Action::ListChunks: action_list_chunks(); break; case Action::Json: action_json(); break; case Action::Download: action_download(); break; } } void action_list() noexcept { for(auto& file: manifest.files) { if (cli.exist && file.remove_exist(cli.output)) { continue; } if (cli.verify && file.remove_verified(cli.output)) { continue; } std::cout << file.to_csv() << std::endl; } } void action_list_bundles() noexcept { auto visited = std::set<BundleID>{}; for (auto& file: manifest.files) { if (cli.exist && file.remove_exist(cli.output)) { continue; } if (cli.verify && file.remove_verified(cli.output)) { continue; } for (auto const& chunk: file.chunks) { auto const id = chunk.bundle_id; if (visited.find(id) != visited.end()) { continue; } visited.insert(id); std::cout << cli.download.prefix << "/bundles/" << to_hex(chunk.bundle_id) << ".bundle" << std::endl; } } for (auto const& id: manifest.unreferenced) { if (visited.find(id) != visited.end()) { continue; } visited.insert(id); std::cout << cli.download.prefix << "/bundles/" << to_hex(id) << ".bundle" << std::endl; } } void action_list_chunks() noexcept { auto visited = std::set<std::pair<BundleID, ChunkID>>{}; for (auto& file: manifest.files) { if (cli.exist && file.remove_exist(cli.output)) { continue; } if (cli.verify && file.remove_verified(cli.output)) { continue; } for (auto const& chunk: file.chunks) { auto const id = std::make_pair(chunk.bundle_id, chunk.id); if (visited.find(id) != visited.end()) { continue; } visited.insert(id); std::cout << to_hex(chunk.bundle_id) << '\t' << to_hex(chunk.id) << '\t' << to_hex(chunk.compressed_offset, 8) << '\t' << to_hex(chunk.compressed_size, 8) << '\t' << to_hex(chunk.uncompressed_size, 8) << std::endl;; } } } void action_json() noexcept { std::cout << '[' << std::endl; bool need_separator = false; for(auto& file: manifest.files) { if (cli.exist && file.remove_exist(cli.output)) { continue; } if (cli.verify && file.remove_verified(cli.output)) { continue; } if (!need_separator) { need_separator = true; std::cout << file.to_json(2) << std::endl; } else { std::cout << ',' << file.to_json(2) << std::endl; } } std::cout << ']' << std::endl; } void action_download() { client = std::make_unique<HttpClient>(cli.download); for (auto& file: manifest.files) { if (cli.exist && file.remove_exist(cli.output)) { std::cout << "SKIP: " << file.path << std::endl; continue; } if (cli.verify && file.remove_verified(cli.output)) { std::cout << "OK: " << file.path << std::endl; continue; } std::cout << "START: " << file.path << std::endl; download_file(file); } } void download_file(FileInfo& file) { std::unique_ptr<std::ofstream> outfile = {}; if (!cli.nowrite) { outfile = std::make_unique<std::ofstream>(file.create_file(cli.output)); } if (!cli.source_cache.empty()) { if (file.remove_cached(outfile.get(), cli.source_cache)) { std::cout << "OK: " << file.path << std::endl; return; } } auto bundles = BundleDownloadList::from_file_info(file, cli.download); client->set_outfile(outfile.get()); size_t total = bundles.unfinished.size(); for (uint32_t tried = 0; !bundles.unfinished.empty() && tried <= cli.download.retry; tried++) { std::cout << '\r' << "Try: " << tried << ' ' << "Bundles: " << bundles.good.size() << '/' << total << std::flush; bundles.queued = std::move(bundles.unfinished); for(;;) { client->push(bundles); client->perform(); client->pop(bundles); std::cout << '\r' << "Try: " << tried << ' ' << "Bundles: " << bundles.good.size() << '/' << total << std::flush; if (client->finished() && bundles.queued.empty()) { break; } client->poll(100); } } std::cout << ' ' << (bundles.unfinished.empty() ? "OK!" : "ERROR!") << std::endl; } static std::vector<char> read_file(std::string const& filename) { std::ifstream file(filename, std::ios::binary); rman_assert(file.good()); auto start = file.tellg(); file.seekg(0, std::ios::end); auto end = file.tellg(); file.seekg(start, std::ios::beg); auto size = end - start; rman_assert(size > 0 && size <= INT32_MAX); std::vector<char> data; data.resize((size_t)size); file.read(data.data(), size); return data; } }; int main(int argc, char ** argv) { auto main = Main{}; try { main.parse_args(argc, argv); main.parse_manifest(); main.parse_upgrade(); main.process(); } catch (std::exception const& e) { std::cerr << e.what() << std::endl; for(auto const& error: error_stack()) { std::cerr << error << std::endl; } error_stack().clear(); return EXIT_FAILURE; } return EXIT_SUCCESS; }
33.565217
117
0.479793
moonshadow565
3282e77067f5ccaa43f4158b1976bf25571752ef
1,826
cc
C++
src/main/songs.cc
hisahi/malpinx
3fd3630073d5abc6e53aa18e6672fb3265f5da94
[ "MIT" ]
null
null
null
src/main/songs.cc
hisahi/malpinx
3fd3630073d5abc6e53aa18e6672fb3265f5da94
[ "MIT" ]
null
null
null
src/main/songs.cc
hisahi/malpinx
3fd3630073d5abc6e53aa18e6672fb3265f5da94
[ "MIT" ]
null
null
null
/****************************************************************************/ /* */ /* MALPINX SOURCE CODE (C) 2020 SAMPO HIPPELAINEN (HISAHI). */ /* SEE THE LICENSE FILE IN THE SOURCE ROOT DIRECTORY FOR LICENSE INFO. */ /* */ /****************************************************************************/ // songs.cc: code for playing music #include <vector> #include "songs.hh" #include "gamedata.hh" #include "abase.hh" #include "config.hh" std::vector<std::string> songFiles; std::vector<int> songFileLoops; bool musicEnabled; bool sfxEnabled; void LoadSongList() { songFiles.clear(); auto songList = std::ifstream(GetDataPath("malpinx.sng")); if (!songList.fail()) { std::string line; int loop; while (std::getline(songList, line)) { loop = -1; if (!line.empty() && line.at(0) == '!') { loop = 1; line = line.substr(1); } songFiles.push_back(line); songFileLoops.push_back(loop); } } } void PlaySong(MusicTrack track) { int trackIndex = static_cast<int>(track); if (musicEnabled && trackIndex < songFiles.size()) abase_music_play(GetDataPath(songFiles[trackIndex]), songFileLoops[trackIndex]); } bool IsSongPlaying() { return abase_song_playing(); } void PauseSound() { abase_pause(); } void ResumeSound() { abase_resume(); } void FadeOutSong(int fadeMs /*= S_FADEOUT_MS*/) { abase_music_fadeout(fadeMs); } void StopSong() { abase_music_stop(); }
24.675676
79
0.467141
hisahi
32845211cfd38ea90ce0f84eb9f9d322d94569b4
187
hpp
C++
projects/codility/niobium2019/include/Niobium.hpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
2
2021-06-24T21:46:56.000Z
2021-09-24T07:51:04.000Z
projects/codility/niobium2019/include/Niobium.hpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
null
null
null
projects/codility/niobium2019/include/Niobium.hpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace Niobium { // https://app.codility.com/programmers/task/flipping_matrix/ int solution(std::vector<std::vector<int>> &A); } // namespace Niobium
18.7
61
0.73262
antaljanosbenjamin
3289f377ad108943861e878e6b115b570172d5f8
5,022
cpp
C++
gui/shared/importers/image_importer.cpp
sadisutikku/engine_libs
b9d8aea6218e043162850c092fd32eb930120e15
[ "MIT" ]
null
null
null
gui/shared/importers/image_importer.cpp
sadisutikku/engine_libs
b9d8aea6218e043162850c092fd32eb930120e15
[ "MIT" ]
null
null
null
gui/shared/importers/image_importer.cpp
sadisutikku/engine_libs
b9d8aea6218e043162850c092fd32eb930120e15
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////// //! MIT License //! Copyright (c) 2022 sadisutikku //! Part of https://github.com/sadisutikku/engine_libs.git ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// //! Includes ////////////////////////////////////////////////////////////////////// #include "gui/shared/importers/image_importer.h" #include "gui/platforms/graphics/RHI/windows/d3d11/texture2d_d3d11.h" #include "gui/shared/graphics/renderer/renderer.h" #include "gui/shared/graphics/storage/render_storage.h" #include <fstream> #include <vector> #define STBI_NO_PSD #define STBI_NO_TGA #define STBI_NO_HDR #define STBI_NO_PIC #define STBI_NO_PNM #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_STATIC #define STBI_NO_STDIO //#define STBI_MALLOC(sz) sicore::MEMORY::allocate(sz) //#define STBI_REALLOC(p,newsz) sicore::MEMORY::reallocate(p,newsz) //#define STBI_FREE(p) sicore::MEMORY::free(p) //#define STBI_REALLOC_SIZED(p,oldsz,newsz) sicore::MEMORY::reallocate(p,newsz); SICORE_UNUSED(oldsz) #include <gui/thirdparty/stb/stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_STATIC #define STBI_WRITE_NO_STDIO //#define STBIW_MALLOC(sz) sicore::MEMORY::allocate(sz) //#define STBIW_REALLOC(p,newsz) sicore::MEMORY::reallocate(p,newsz) //#define STBIW_FREE(p) sicore::MEMORY::free(p) #include <gui/thirdparty/stb/stb_image_write.h> #define STB_IMAGE_RESIZE_IMPLEMENTATION #define STB_IMAGE_RESIZE_STATIC // There is scope here to use the c (context) parameter to reuse temp buffers //#define STBIR_MALLOC(sz,c) ((void)(c), sicore::MEMORY::allocate(sz)) //#define STBIR_FREE(p,c) ((void)(c), sicore::MEMORY::free(p)) #include <gui/thirdparty/stb/stb_image_resize.h> namespace { struct CALLBACK_USER_DATA { std::vector<char>& data; uint32_t position{}; bool is_eof{}; }; inline gui::RHI_Format get_rhi_format( const uint32_t bytes_per_channel, const uint32_t channel_count ) { const uint32_t bits_per_channel = bytes_per_channel * 8; if ( channel_count == 1 ) { if ( bits_per_channel == 8 ) return gui::RHI_Format_R8_Unorm; } else if ( channel_count == 2 ) { if ( bits_per_channel == 8 ) return gui::RHI_Format_R8G8_Unorm; } else if ( channel_count == 3 ) { if ( bits_per_channel == 32 ) return gui::RHI_Format_R32G32B32A32_Float; } else if ( channel_count == 4 ) { if ( bits_per_channel == 8 ) return gui::RHI_Format_R8G8B8A8_Unorm; if ( bits_per_channel == 16 ) return gui::RHI_Format_R16G16B16A16_Float; if ( bits_per_channel == 32 ) return gui::RHI_Format_R32G32B32A32_Float; } ASSERT_FAILED( "Could not deduce format" ); return gui::RHI_Format_Undefined; } } namespace gui { int stream_read_callback( void *user, char *data, int size ) { CALLBACK_USER_DATA* user_data = static_cast<CALLBACK_USER_DATA*>(user); memcpy( data, static_cast<const void*>(&user_data->data[user_data->position]), size ); user_data->position += size; return size; } void stream_skip_callback( void *user, int size ) { CALLBACK_USER_DATA* user_data = static_cast<CALLBACK_USER_DATA*>(user); user_data->position += size; } int stream_eof_callback( void *user ) { const CALLBACK_USER_DATA* user_data = static_cast<CALLBACK_USER_DATA*>(user); return user_data->is_eof; } TEXTURE2D_BASE* IMAGE_IMPORTER::load_from_file( const std::string& filepath ) { if ( auto existing_texture = RENDER_STORAGE::get_singleton()->get_texture( filepath ); existing_texture ) { return existing_texture; } std::ifstream file_for_read( filepath, std::ios::binary ); // Stop eating new lines in binary mode file_for_read.unsetf( std::ios::skipws ); // get its size: std::streampos file_size; file_for_read.seekg( 0, std::ios::end ); file_size = file_for_read.tellg(); file_for_read.seekg( 0, std::ios::beg ); std::vector<char> vec; vec.reserve( file_size ); std::copy( std::istream_iterator<char>( file_for_read ), std::istream_iterator<char>(), std::back_inserter( vec ) ); stbi_io_callbacks callbacks{ stream_read_callback, stream_skip_callback, stream_eof_callback }; CALLBACK_USER_DATA user_data{ vec }; int32_t width{}; int32_t height{}; int32_t channels{}; if ( stbi_uc* ptr = stbi_load_from_callbacks( &callbacks, &user_data, &width, &height, &channels, STBI_rgb_alpha ) ) { const int32_t num_bytes{ width * height * channels }; auto byte_data{ reinterpret_cast<std::byte*>(ptr) }; std::vector<std::byte> image_data{ byte_data, byte_data + num_bytes }; const RHI_Format image_format = get_rhi_format( 1, channels ); auto texture = RENDERER::get_singleton()->create_texture2d( width, height, image_format, RHI_Texture_Sampled, image_data ); RENDER_STORAGE::get_singleton()->cache_texture( filepath, texture ); return texture; } else { return nullptr; } } }
30.436364
126
0.686181
sadisutikku
328c535c4b8b2d2bdfc307728a04565b5615aa19
5,153
cpp
C++
software/protoDUNE/rceData/dtm_src/lib/PpiDmaMap.cpp
slaclab/proto-dune
e487ee6d40359b40776098410d7fd302b9631448
[ "BSD-3-Clause-LBNL" ]
null
null
null
software/protoDUNE/rceData/dtm_src/lib/PpiDmaMap.cpp
slaclab/proto-dune
e487ee6d40359b40776098410d7fd302b9631448
[ "BSD-3-Clause-LBNL" ]
2
2017-05-11T04:22:27.000Z
2018-09-18T16:10:29.000Z
software/protoDUNE/rceData/dtm_src/lib/PpiDmaMap.cpp
slaclab/proto-dune
e487ee6d40359b40776098410d7fd302b9631448
[ "BSD-3-Clause-LBNL" ]
2
2017-04-03T21:59:53.000Z
2020-12-13T00:14:20.000Z
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <string> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <iostream> #include <iomanip> #include <queue> #include <sys/stat.h> #include "PpiDmaMap.h" using namespace std; PpiDmaMap::PpiDmaMap (uint idx) { _channel = idx; int fd; fd = ::open("/dev/mem", O_RDWR | O_SYNC); if (fd == -1) { _regMap = NULL; _ocmMap = NULL; } else { _regMap = (volatile char *)mmap(0, RegMemoryMapSize, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_SHARED, fd, RegMemoryBase); if (_regMap == (void *) -1) _regMap = NULL; _ocmMap = (volatile char *)mmap(0, OcmMemoryMapSize, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_SHARED, fd, OcmMemoryBase); if (_ocmMap == (void *) -1) _ocmMap = NULL; } _baseAddr[0] = 0x50000000; _baseAddr[1] = 0x50020000; _baseAddr[2] = 0x50040000; _baseAddr[3] = 0x50060000; printf("Write to ob free list : 0x%08x\n",_obHdrAddr); regWrite(_baseAddr[idx]+_obWork,_obHdrAddr); printf("Write to ib free list : 0x%08x\n",_ibHdrAddr); regWrite(_baseAddr[idx]+_ibWork,_ibHdrAddr); } PpiDmaMap::~PpiDmaMap () { } // Write a block of data int PpiDmaMap::write(unsigned char *data, uint hdrSize, uint paySize, uint type) { uint addr; uint desc; uint uintPtr; uint ucharPtr; addr = regRead(_baseAddr[_channel]+_obFree); if ((addr & 0x1) != 0 ) return(0); printf("Got free outbound address : 0x%08x\n",addr); uintPtr = addr; ucharPtr = addr + 24; ocmWrite(uintPtr,addr + 24 + hdrSize); ocmWrite(uintPtr+0x4,paySize); ocmWrite(uintPtr+0x8,_channel*2); ocmWrite(uintPtr+0xc,0x5a5a5a5a); ocmWrite(uintPtr+0x10,hdrSize); ocmWrite(uintPtr+0x14,paySize); ocmBlockWrite(ucharPtr,data,hdrSize+paySize); desc = addr | (((hdrSize/8)+3) << 18) | (type << 26); if ( paySize > 0 ) desc |= 0xC0000000; else desc |= 0x40000000; printf("Writing to outbound work\n"); regWrite(_baseAddr[_channel]+_obWork,desc); if ( paySize > 0 ) { printf("Waiting for outbound completion\n"); do { desc = regRead(_compFifos+(_channel*8)); usleep(100); } while ( (desc & 0x1) != 0); printf("Got write completion : 0x%08x\n",desc); desc = regRead(_compFifos+(_channel*8)); printf("Second write completion read : 0x%08x\n",desc); } return(hdrSize+paySize); } // Read a block of data, return -1 on error, 0 if no data, size if data int PpiDmaMap::read(unsigned char *data, uint maxSize, uint *type, uint *err, uint *hdrSize, uint *paySize) { uint uintPtr; uint ucharPtr; uint desc; uint pay; uint addr; desc = regRead(_baseAddr[_channel]+_ibPend); if ((desc & 0x1) != 0 ) return(0); addr = desc & 0x3FFFF; *type = (desc >> 26) & 0xF; *err = (desc >> 30) & 0x1; pay = (desc >> 31) & 0x1; uintPtr = addr; ucharPtr = addr + 24; *hdrSize = ocmRead(uintPtr+0x10); *paySize = ocmRead(uintPtr+0x14); printf("Got inbound header Addr: 0x%08x, Type: %i, Err: %i, Pay: %i, HSize: %i, PSize: %i\n", addr,*type,*err,pay,*hdrSize,*paySize); ocmBlockRead(ucharPtr,data,*hdrSize); if ( pay == 0 ) { printf("Write to ib free list : 0x%08x\n",addr); regWrite(_baseAddr[_channel]+_ibWork,addr); return(*hdrSize); } ocmWrite(uintPtr,addr + 24 + *hdrSize); ocmWrite(uintPtr+0x4,*paySize); ocmWrite(uintPtr+0x8,(_channel*2)+1); ocmWrite(uintPtr+0xc,0x5a5a5a5a); printf("Writing to inbound work\n"); desc = 0x60000000 | addr; regWrite(_baseAddr[_channel]+_ibWork,desc); printf("Waiting for inbound completion\n"); do { desc = regRead(_compFifos+((_channel*8)+4)); usleep(100); } while ( (desc & 0x1) != 0); printf("Got read completion : 0x%08x\n",desc); desc = regRead(_compFifos+((_channel*8)+4)); printf("Second read completion read : 0x%08x\n",desc); ocmBlockRead(ucharPtr,data,*hdrSize+*paySize); return(*hdrSize+*paySize); } // Write to OCM void PpiDmaMap::ocmBlockWrite ( uint addr, unsigned char *data, uint size) { uint diff = addr - OcmMemoryBase; uint x; for (x=0; x < size; x++) _ocmMap[diff+x] = data[x]; } // Read from OCM void PpiDmaMap::ocmBlockRead ( uint addr, unsigned char *data, uint size) { uint diff = addr - OcmMemoryBase; uint x; for (x=0; x < size; x++) data[x] = _ocmMap[diff+x]; } // Write to OCM void PpiDmaMap::ocmWrite ( uint addr, uint value) { uint diff = addr - OcmMemoryBase; volatile uint * ptr = (uint *)(_ocmMap + diff); *ptr = value; } // Read from OCM uint PpiDmaMap::ocmRead ( uint addr) { uint diff = addr - OcmMemoryBase; volatile uint * ptr = (uint *)(_ocmMap + diff); return(*ptr); } // Write to register void PpiDmaMap::regWrite (uint addr, uint value) { uint diff = addr - RegMemoryBase; volatile uint * ptr = (uint *)(_regMap + diff); *ptr = value; } // Read from register uint PpiDmaMap::regRead (uint addr) { uint diff = addr - RegMemoryBase; volatile uint * ptr = (uint *)(_regMap + diff); return(*ptr); }
25.259804
126
0.632835
slaclab
3295b0730366a18035aa155b35d551cb60075ea1
1,962
cpp
C++
Problems/geeksforgeeks/first-repeating-element/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
Problems/geeksforgeeks/first-repeating-element/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
1
2019-05-09T19:17:00.000Z
2019-05-09T19:17:00.000Z
Problems/geeksforgeeks/first-repeating-element/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
#include <iostream> #include <map> using namespace std; const int MAX_VAL = 1000100; int countApp[MAX_VAL + 1]; int arr[MAX_VAL + 1]; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); #endif int t; cin >> t; for (int i = 0; i < t; i++) { map<int, int> positions; int n; cin >> n; for (int j = 0; j < n; j++) { cin >> arr[j]; if (positions.find(arr[j]) == positions.end()) { positions[arr[j]] = j; countApp[arr[j]] = 1; } else countApp[arr[j]]++; } int lowestPos = n; for (int j = 0; j < n; j++) { if (countApp[arr[j]] > 1) { //it means value `originalValue` appeared more then 2 times starting at position if (positions[arr[j]] < lowestPos) lowestPos = positions[arr[j]]; } } /* int j = 0; for (; j < n; j++) { const int originalValue = arr[j] % MAX_VAL; if (arr[originalValue] >= MAX_VAL) { countApp[originalValue]++; } else { pos[originalValue] = j; countApp[originalValue] = 1; arr[originalValue] += MAX_VAL; } } // need to find element which has 2 or more in the pos with lowest index int lowestPos = n; for (j = 0; j < n; j++) { const int originalValue = arr[j] % MAX_VAL; if (countApp[originalValue] >= 2) { //it means value `originalValue` appeared more then 2 times starting at position if (pos[originalValue] < lowestPos) lowestPos = pos[originalValue]; } } */ if (lowestPos == n) { cout << -1 << endl; } else cout << lowestPos + 1 << endl; } return 0; }
26.876712
96
0.453619
grand87
32996bfaec9335f6b2f29e28da28ded7a2b9e1e7
324
cpp
C++
Sources/Graphics/Picture/qt4main/origin.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
27
2017-12-19T09:15:36.000Z
2021-07-30T13:02:00.000Z
Sources/Graphics/Picture/qt4main/origin.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
null
null
null
Sources/Graphics/Picture/qt4main/origin.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
29
2018-04-10T13:25:54.000Z
2021-12-24T01:51:03.000Z
#include <QApplication> #include <QLabel> #include <QPixmap> int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel label; //C++11 //string path = R"(test.jpg)"; //QPixmap pix(path.c_str()); QPixmap pix(argv[1]); //图片路径 label.setPixmap(pix); label.show(); label.resize(640,480); return a.exec(); }
19.058824
32
0.657407
wurui1994
3299c337d5c45106d83004e7bb91ae6c4f89d1e3
32,774
cc
C++
farmhash_golden_test.cc
dietmarkuehl/hashing-demo
006f61c4221c2119c893fcfda8c505c08ed5b006
[ "Apache-2.0" ]
35
2015-03-26T03:38:41.000Z
2022-01-03T04:32:53.000Z
farmhash_golden_test.cc
dietmarkuehl/hashing-demo
006f61c4221c2119c893fcfda8c505c08ed5b006
[ "Apache-2.0" ]
null
null
null
farmhash_golden_test.cc
dietmarkuehl/hashing-demo
006f61c4221c2119c893fcfda8c505c08ed5b006
[ "Apache-2.0" ]
16
2015-03-26T02:53:23.000Z
2021-07-12T12:31:07.000Z
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Golden tests of farmhash, based on tests in original FarmHash source. #include <cassert> #include <iostream> #include "farmhash.h" #include "std.h" namespace farmhashna { uint64_t HashLen16(uint64_t u, uint64_t v) { static constexpr uint64_t kMul = 0x9ddfea08eb382d69ULL; uint64_t a = (u ^ v) * kMul; a ^= (a >> 47); uint64_t b = (v ^ a) * kMul; b ^= (b >> 47); b *= kMul; return b; } // Adapt our API to the one the test fixture expects uint64_t Hash64(const char* str, size_t len) { hashing::farmhash::state_type state; return static_cast<size_t>( hash_combine_range(hashing::farmhash(&state), str, str + len)); } uint64_t Hash64WithSeeds(const char *s, size_t len, uint64_t seed0, uint64_t seed1) { return HashLen16(Hash64(s, len) - seed0, seed1); } uint64_t Hash64WithSeed(const char *s, size_t len, uint64_t seed) { static constexpr uint64_t k2 = 0x9ae16a3b2f90404fULL; return Hash64WithSeeds(s, len, k2, seed); } } // namespace farmhashna using std::cout; using std::cerr; using std::endl; using std::hex; constexpr int kDataSize = 1 << 20; static const int kTestSize = 300; char data[kDataSize]; int errors = 0; template <typename T> constexpr bool IsNonZero(T x) { return x != 0; } // Initialize data to pseudorandom values. void Setup() { static constexpr uint64_t k0 = 0xc3a5c85c97cb3127ULL; uint64_t a = 9; uint64_t b = 777; for (int i = 0; i < kDataSize; i++) { a += b; b += a; a = (a ^ (a >> 41)) * k0; b = (b ^ (b >> 41)) * k0 + i; uint8_t u = b >> 37; memcpy(data + i, &u, 1); // uint8_t -> char } } uint32_t CreateSeed(int offset, int salt) { static constexpr uint32_t c1 = 0xcc9e2d51; uint32_t h = static_cast<uint32_t>(salt & 0xffffffff); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); h += static_cast<uint32_t>(offset & 0xffffffff); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); return h; } #undef SEED #undef SEED1 #undef SEED0 #define SEED CreateSeed(offset, -1) #define SEED0 CreateSeed(offset, 0) #define SEED1 CreateSeed(offset, 1) uint32_t expected[] = { 1140953930u, 861465670u, 3277735313u, 2681724312u, 2598464059u, 797982799u, 890626835u, 800175912u, 2603993599u, 921001710u, 1410420968u, 2134990486u, 3283896453u, 1867689945u, 2914424215u, 2244477846u, 255297188u, 2992121793u, 1110588164u, 4186314283u, 161451183u, 3943596029u, 4019337850u, 452431531u, 283198166u, 2741341286u, 3379021470u, 2557197665u, 299850021u, 2532580744u, 452473466u, 1706958772u, 1298374911u, 3099673830u, 2199864459u, 3696623795u, 236935126u, 2976578695u, 4055299123u, 3281581178u, 1053458494u, 1882212500u, 2305012065u, 2169731866u, 3456121707u, 275903667u, 458884671u, 3033004529u, 3058973506u, 2379411653u, 1898235244u, 1402319660u, 2700149065u, 2699376854u, 147814787u, 720739346u, 2433714046u, 4222949502u, 4220361840u, 1712034059u, 3425469811u, 3690733394u, 4148372108u, 1330324210u, 594028478u, 2921867846u, 1635026870u, 192883107u, 780716741u, 1728752234u, 3280331829u, 326029180u, 3969463346u, 1436364519u, 393215742u, 3349570000u, 3824583307u, 1612122221u, 2859809759u, 3808705738u, 1379537552u, 1646032583u, 2233466664u, 1432476832u, 4023053163u, 2650381482u, 2052294713u, 3552092450u, 1628777059u, 1499109081u, 3476440786u, 3829307897u, 2960536756u, 1554038301u, 1145519619u, 3190844552u, 2902102606u, 3600725550u, 237495366u, 540224401u, 65721842u, 489963606u, 1448662590u, 397635823u, 1596489240u, 1562872448u, 1790705123u, 2128624475u, 180854224u, 2604346966u, 1435705557u, 1262831810u, 155445229u, 1672724608u, 1669465176u, 1341975128u, 663607706u, 2077310004u, 3610042449u, 1911523866u, 1043692997u, 1454396064u, 2563776023u, 294527927u, 1099072299u, 1389770549u, 703505868u, 678706990u, 2952353448u, 2026137563u, 3603803785u, 629449419u, 1933894405u, 3043213226u, 226132789u, 2489287368u, 1552847036u, 645684964u, 3828089804u, 3632594520u, 187883449u, 230403464u, 3151491850u, 3272648435u, 3729087873u, 1303930448u, 2002861219u, 165370827u, 916494250u, 1230085527u, 3103338579u, 3064290191u, 3807265751u, 3628174014u, 231181488u, 851743255u, 2295806711u, 1781190011u, 2988893883u, 1554380634u, 1142264800u, 3667013118u, 1968445277u, 315203929u, 2638023604u, 2290487377u, 732137533u, 1909203251u, 440398219u, 1891630171u, 1380301172u, 1498556724u, 4072067757u, 4165088768u, 4204318635u, 441430649u, 3931792696u, 197618179u, 956300927u, 914413116u, 3010839769u, 2837339569u, 2148126371u, 1913303225u, 3074915312u, 3117299654u, 4139181436u, 2993479124u, 3178848746u, 1357272220u, 1438494951u, 507436733u, 667183474u, 2084369203u, 3854939912u, 1413396341u, 126024219u, 146044391u, 1016656857u, 3022024459u, 3254014218u, 429095991u, 165589978u, 1578546616u, 985653208u, 1718653828u, 623071693u, 366414107u, 249776086u, 1207522198u, 3047342438u, 2991127487u, 3120876698u, 1684583131u, 46987739u, 1157614300u, 863214540u, 1087193030u, 199124911u, 520792961u, 3614377032u, 586863115u, 3331828431u, 1013201099u, 1716848157u, 4033596884u, 1164298657u, 4140791139u, 1146169032u, 1434258493u, 3824360466u, 3242407770u, 3725511003u, 232064808u, 872586426u, 762243036u, 2736953692u, 816692935u, 512845449u, 3748861010u, 2266795890u, 3781899767u, 4290630595u, 517646945u, 22638523u, 648000590u, 959214578u, 558910384u, 1283799121u, 3047062993u, 1024246061u, 4027776454u, 3544509313u, 622325861u, 834785312u, 382936554u, 411505255u, 1973395102u, 1825135056u, 2725923798u, 580988377u, 2826990641u, 3474970689u, 1029055034u, 812546227u, 2506885666u, 2584372201u, 1758123094u, 589567754u, 325737734u, 345313518u, 2022370576u, 3886113119u, 3338548567u, 257578986u, 3698087965u, 1776047957u, 1771384107u, 3604937815u, 3198590202u, 2305332220u, 191910725u, 4232136669u, 427759438u, 4244322689u, 542201663u, 3315355162u, 2135941665u, 556609672u, 45845311u, 1175961330u, 3948351189u, 23075771u, 3252374102u, 1634635545u, 4151937410u, 713127376u, 1467786451u, 663013031u, 3444053918u, 2638154051u, 810082938u, 3077742128u, 1062268187u, 2115441882u, 4081398201u, 3735739145u, 2794294783u, 2335576331u, 2560479831u, 1379288194u, 4225182569u, 2442302747u, 3948961926u, 3958366652u, 3067277639u, 3667516477u, 1709989541u, 1516711748u, 2339636583u, 4188504038u, 59581167u, 2725013602u, 3639843023u, 2658147000u, 2643979752u, 3758739543u, 4189944477u, 2470483982u, 877580602u, 2995362413u, 118817200u, 3252925478u, 2062343506u, 3981838403u, 3762572073u, 1231633714u, 4168280671u, 2931588131u, 3284356565u, 1129162571u, 732225574u, 4173605289u, 1407328702u, 1677744031u, 3532596884u, 3232041815u, 1652884780u, 2256541290u, 3459463480u, 3740979556u, 259034107u, 2227121257u, 1426140634u, 3606709555u, 3424793077u, 315836068u, 3200749877u, 1386256573u, 24035717u, 2982018998u, 1811050648u, 234531934u, 1115203611u, 1598686658u, 3146815575u, 1603559457u, 323296368u, 2632963283u, 1778459926u, 739944537u, 579625482u, 3486330348u, 492621815u, 1231665285u, 2457048126u, 3903349120u, 389846205u, 3355404249u, 3275550588u, 1052645068u, 862072556u, 2834153464u, 1481069623u, 2657392572u, 4279236653u, 1688445808u, 701920051u, 3740748788u, 3388062747u, 1873358321u, 2152785640u, 883382081u, 1005815394u, 1020177209u, 734239551u, 2371453141u, 100326520u, 3488500412u, 1279682138u, 2610427744u, 49703572u, 3026361211u, 605900428u, 302392721u, 2509302188u, 1416453607u, 2815915291u, 1862819968u, 519710058u, 2450888314u, 4017598378u, 937074653u, 3035635454u, 1590230729u, 3268013438u, 2710029305u, 12886044u, 3711259084u, 2627383582u, 3895772404u, 648534979u, 260307902u, 855990313u, 3669691805u, 263366740u, 2938543471u, 414331688u, 3080542944u, 3405007814u, 3565059103u, 1190977418u, 390836981u, 1606450012u, 2649808239u, 2514169310u, 2747519432u, 4129538640u, 1721522849u, 492099164u, 792990594u, 3625507637u, 2271095827u, 2993032712u, 2302363854u, 4013112951u, 1111617969u, 2183845740u, 795918276u, 1116991810u, 3110898804u, 3963062126u, 2737064702u, 462795667u, 937372240u, 1343017609u, 1091041189u, 2790555455u, 277024217u, 25485284u, 1166522068u, 1623631848u, 241727183u, 2836158787u, 3112996740u, 573836428u, 2721658101u, 1937681565u, 4175169209u, 3190765433u, 1970000788u, 1668258120u, 114616703u, 954762543u, 199237753u, 4094644498u, 2522281978u, 732086117u, 1756889687u, 2936126607u, 2437031370u, 4103143808u, 3883389541u, 3171090854u, 2483004780u, 1927385370u, 2360538162u, 2740855009u, 4241185118u, 1492209542u, 1672737098u, 2148675559u, 1789864670u, 2434313103u, 2319172611u, 2760941207u, 2636210123u, 1338083267u, 1128080590u, 822806371u, 1199583556u, 314727461u, 1335160250u, 2084630531u, 1156261526u, 316766066u, 112090465u, 3129033323u, 2746885618u, 636616055u, 2582210744u, 1721064910u, 3468394263u, 470463518u, 2076016059u, 408721884u, 2121041886u, 378460278u, 1915948002u, 357324860u, 2301682622u, 2691859523u, 1869756364u, 2429314418u, 2193146527u, 1185564327u, 2614088922u, 1975527044u, 919067651u, 2855948894u, 3662539576u, 1943802836u, 3529473373u, 1490330107u, 366036094u, 3384241033u, 4276268604u, 448403661u, 4271796078u, 1910401882u, 3077107698u, 299427366u, 2035665349u, 3201262636u, 3738454258u, 2554452696u, 3588997135u, 3363895827u, 1267505995u, 1852004679u, 2237827073u, 2803250686u, 3468044908u, 2143572850u, 1728158656u, 1022551180u, 1996680960u, 839529273u, 2400647871u, 2201096054u, 3606433628u, 2597259793u, 3544595875u, 3909443124u, 819278607u, 3447346709u, 806136613u, 2711436388u, 3656063205u, 837475154u, 694525336u, 4070212073u, 4011303412u, 1068395209u, 438095290u, 484603494u, 2673730227u, 737767009u, 642310823u, 3914002299u, 308425103u, 268427550u, 1334387085u, 4069797497u, 4280783219u, 2914011058u, 4243643405u, 2849988118u, 2504230175u, 1817156623u, 2804200483u, 3406991497u, 2948254999u, 2102063419u, 1071272117u, 514889942u, 571972433u, 1246595599u, 1735616066u, 1539151988u, 1230831543u, 277987182u, 4269526481u, 991511607u, 95237878u, 2005032160u, 1291113144u, 626619670u, 3560835907u, 164940926u, 1433635018u, 116647396u, 3039097112u, 2868163232u, 1141645918u, 1764165478u, 881378302u, 2159170082u, 2953647681u, 1011320066u, 184856151u, 1723308975u, 336034862u, 2017579106u, 1476681709u, 147523618u, 3896252223u, 2264728166u, 944743644u, 1694443528u, 2690700128u, 1947321519u, 735478508u, 4058183171u, 260177668u, 505662155u, 2391691262u, 1920739747u, 3216960415u, 1898176786u, 3722741628u, 1511077569u, 449636564u, 983350414u, 2580237367u, 2055059789u, 1103819072u, 2089123665u, 3873755579u, 2718467458u, 3124338704u, 3204250304u, 2475035432u, 1120017626u, 3873758287u, 1982999824u, 2950794582u, 780634378u, 2842141483u, 4029205195u, 1656892865u, 3330993377u, 80890710u, 1953796601u, 3873078673u, 136118734u, 2317676604u, 4199091610u, 1864448181u, 3063437608u, 1699452298u, 1403506686u, 1513069466u, 2348491299u, 4273657745u, 4055855649u, 1805475756u, 2562064338u, 973124563u, 4197091358u, 172861513u, 2858726767u, 4271866024u, 3071338162u, 3590386266u, 2328277259u, 1096050703u, 1189614342u, 459509140u, 771592405u, 817999971u, 3740825152u, 520400189u, 1941874618u, 185232757u, 4032960199u, 3928245258u, 3527721294u, 1301118856u, 752188080u, 3512945009u, 308584855u, 2105373972u, 752872278u, 3823368815u, 3760952096u, 4250142168u, 2565680167u, 3646354146u, 1259957455u, 1085857127u, 3471066607u, 38924274u, 3770488806u, 1083869477u, 3312508103u, 71956383u, 3738784936u, 3099963860u, 1255084262u, 4286969992u, 3621849251u, 1190908967u, 1831557743u, 2363435042u, 54945052u, 4059585566u, 4023974274u, 1788578453u, 3442180039u, 2534883189u, 2432427547u, 3909757989u, 731996369u, 4168347425u, 1356028512u, 2741583197u, 1280920000u, 312887059u, 3259015297u, 3946278527u, 4135481831u, 1281043691u, 1121403845u, 3312292477u, 1819941269u, 1741932545u, 3293015483u, 2127558730u, 713121337u, 2635469238u, 486003418u, 4015067527u, 2976737859u, 2108187161u, 927011680u, 1970188338u, 4177613234u, 1799789551u, 2118505126u, 4134691985u, 1958963937u, 1929210029u, 2555835851u, 2768832862u, 910892050u, 2567532373u, 4075249328u, 86689814u, 3726640307u, 1392137718u, 1240000030u, 4104757832u, 3026358429u, 313797689u, 1435798509u, 3101500919u, 1241665335u, 3573008472u, 3615577014u, 3767659003u, 3134294021u, 4063565523u, 2296824134u, 1541946015u, 3087190425u, 2693152531u, 2199672572u, 2123763822u, 1034244398u, 857839960u, 2515339233u, 2228007483u, 1628096047u, 2116502287u, 2502657424u, 2809830736u, 460237542u, 450205998u, 3646921704u, 3818199357u, 1808504491u, 1950698961u, 2069753399u, 3657033172u, 3734547671u, 4067859590u, 3292597295u, 1106466069u, 356742959u, 2469567432u, 3495418823u, 183440071u, 3248055817u, 3662626864u, 1750561299u, 3926138664u, 4088592524u, 567122118u, 3810297651u, 992181339u, 3384018814u, 3272124369u, 3177596743u, 320086295u, 2316548367u, 100741310u, 451656820u, 4086604273u, 3759628395u, 2553391092u, 1745659881u, 3650357479u, 2390172694u, 330172533u, 767377322u, 526742034u, 4102497288u, 2088767754u, 164402616u, 2482632320u, 2352347393u, 1873658044u, 3861555476u, 2751052984u, 1767810825u, 20037241u, 545143220u, 2594532522u, 472304191u, 3441135892u, 3323383489u, 258785117u, 2977745165u, 2781737565u, 2963590112u, 2756998822u, 207428029u, 2581558559u, 3824717027u, 1258619503u, 3472047571u, 2648427775u, 2360400900u, 2393763818u, 2332399088u, 3932701729u, 884421165u, 1396468647u, 1377764574u, 4061795938u, 1559119087u, 3343596838u, 3604258095u, 1435134775u, 1099809675u, 908163739u, 1418405656u, 368446627u, 3741651161u, 3374512975u, 3542220540u, 3244772570u, 200009340u, 3198975081u, 2521038253u, 4081637863u, 337070226u, 3235259030u, 3897262827u, 736956644u, 641040550u, 644850146u, 1306761320u, 4219448634u, 193750500u, 3293278106u, 1383997679u, 1242645122u, 4109252858u, 450747727u, 3716617561u, 362725793u, 2252520167u, 3377483696u, 1788337208u, 8130777u, 3226734120u, 759239140u, 1012411364u, 1658628529u, 2911512007u, 1002580201u, 1681898320u, 3039016929u, 4294520281u, 367022558u, 3071359622u, 3205848570u, 152989999u, 3839042136u, 2357687350u, 4273132307u, 3898950547u, 1176841812u, 1314157485u, 75443951u, 1027027239u, 1858986613u, 2040551642u, 36574105u, 2603059541u, 3456147251u, 2137668425u, 4077477194u, 3565689036u, 491832241u, 363703593u, 2579177168u, 3589545214u, 265993036u, 1864569342u, 4149035573u, 3189253455u, 1072259310u, 3153745937u, 923017956u, 490608221u, 855846773u, 845706553u, 1018226240u, 1604548872u, 3833372385u, 3287246572u, 2757959551u, 2452872151u, 1553870564u, 1713154780u, 2649450292u, 500120236u, 84251717u, 661869670u, 1444911517u, 2489716881u, 2810524030u, 1561519055u, 3884088359u, 2509890699u, 4247155916u, 1005636939u, 3224066062u, 2774151984u, 2035978240u, 2514910366u, 1478837908u, 3144450144u, 2107011431u, 96459446u, 3587732908u, 2389230590u, 3287635953u, 250533792u, 1235983679u, 4237425634u, 3704645833u, 3882376657u, 2976369049u, 1187061987u, 276949224u, 4100839753u, 1698347543u, 1629662314u, 1556151829u, 3784939568u, 427484362u, 4246879223u, 3155311770u, 4285163791u, 1693376813u, 124492786u, 1858777639u, 3476334357u, 1941442701u, 1121980173u, 3485932087u, 820852908u, 358032121u, 2511026735u, 1873607283u, 2556067450u, 2248275536u, 1528632094u, 1535473864u, 556796152u, 1499201704u, 1472623890u, 1526518503u, 3692729434u, 1476438092u, 2913077464u, 335109599u, 2167614601u, 4121131078u, 3158127917u, 3051522276u, 4046477658u, 2857717851u, 1863977403u, 1341023343u, 692059110u, 1802040304u, 990407433u, 3285847572u, 319814144u, 561105582u, 1540183799u, 4052924496u, 2926590471u, 2244539806u, 439121871u, 3317903224u, 3178387550u, 4265214507u, 82077489u, 1978918971u, 4279668976u, 128732476u, 2853224222u, 464407878u, 4190838199u, 997819001u, 3250520802u, 2330081301u, 4095846095u, 733509243u, 1583801700u, 722314527u, 3552883023u, 1403784280u, 432327540u, 1877837196u, 3912423882u, 505219998u, 696031431u, 908238873u, 4189387259u, 8759461u, 2540185277u, 3385159748u, 381355877u, 2519951681u, 1679786240u, 2019419351u, 4051584612u, 1933923923u, 3768201861u, 1670133081u, 3454981037u, 700836153u, 1675560450u, 371560700u, 338262316u, 847351840u, 2222395828u, 3130433948u, 405251683u, 3037574880u, 184098830u, 453340528u, 1385561439u, 2224044848u, 4071581802u, 1431235296u, 5570097u, 570114376u, 2287305551u, 2272418128u, 803575837u, 3943113491u, 414959787u, 708083137u, 2452657767u, 4019147902u, 3841480082u, 3791794715u, 2965956183u, 2763690963u, 2350937598u, 3424361375u, 779434428u, 1274947212u, 686105485u, 3426668051u, 3692865672u, 3057021940u, 2285701422u, 349809124u, 1379278508u, 3623750518u, 215970497u, 1783152480u, 823305654u, 216118434u, 1787189830u, 3692048450u, 2272612521u, 3032187389u, 4159715581u, 1388133148u, 1611772864u, 2544383526u, 552925303u, 3420960112u, 3198900547u, 3503230228u, 2603352423u, 2318375898u, 4064071435u, 3006227299u, 4194096960u, 1283392422u, 1510460996u, 174272138u, 3671038966u, 1775955687u, 1719108984u, 1763892006u, 1385029063u, 4083790740u, 406757708u, 684087286u, 531310503u, 3329923157u, 3492083607u, 1059031410u, 3037314475u, 3105682208u, 3382290593u, 2292208503u, 426380557u, 97373678u, 3842309471u, 777173623u, 3241407531u, 303065016u, 1477104583u, 4234905200u, 2512514774u, 2649684057u, 1397502982u, 1802596032u, 3973022223u, 2543566442u, 3139578968u, 3193669211u, 811750340u, 4013496209u, 567361887u, 4169410406u, 3622282782u, 3403136990u, 2540585554u, 895210040u, 3862229802u, 1145435213u, 4146963980u, 784952939u, 943914610u, 573034522u, 464420660u, 2356867109u, 3054347639u, 3985088434u, 1911188923u, 583391304u, 176468511u, 2990150068u, 2338031599u, 519948041u, 3181425568u, 496106033u, 4110294665u, 2736756930u, 1196757691u, 1089679033u, 240953857u, 3399092928u, 4040779538u, 2843673626u, 240495962u, 3017658263u, 3828377737u, 4243717901u, 2448373688u, 2759616657u, 2246245780u, 308018483u, 4262383425u, 2731780771u, 328023017u, 2884443148u, 841480070u, 3188015819u, 4051263539u, 2298178908u, 2944209234u, 1372958390u, 4164532914u, 4074952232u, 1683612329u, 2155036654u, 1872815858u, 2041174279u, 2368092311u, 206775997u, 2283918569u, 645945606u, 115406202u, 4206471368u, 3923500892u, 2217060665u, 350160869u, 706531239u, 2824302286u, 509981657u, 1469342315u, 140980u, 1891558063u, 164887091u, 3094962711u, 3437115622u, 13327420u, 422986366u, 330624974u, 3630863408u, 2425505046u, 824008515u, 3543885677u, 918718096u, 376390582u, 3224043675u, 3724791476u, 1837192976u, 2968738516u, 3424344721u, 3187805406u, 1550978788u, 1743089918u, 4251270061u, 645016762u, 3855037968u, 1928519266u, 1373803416u, 2289007286u, 1889218686u, 1610271373u, 3059200728u, 2108753646u, 582042641u, 812347242u, 3188172418u, 191994904u, 1343511943u, 2247006571u, 463291708u, 2697254095u, 1534175504u, 1106275740u, 622521957u, 917121602u, 4095777215u, 3955972648u, 3852234638u, 2845309942u, 3299763344u, 2864033668u, 2554947496u, 799569078u, 2551629074u, 1102873346u, 2661022773u, 2006922227u, 2900438444u, 1448194126u, 1321567432u, 1983773590u, 1237256330u, 3449066284u, 1691553115u, 3274671549u, 4271625619u, 2741371614u, 3285899651u, 786322314u, 1586632825u, 564385522u, 2530557509u, 2974240289u, 1244759631u, 3263135197u, 3592389776u, 3570296884u, 2749873561u, 521432811u, 987586766u, 3206261120u, 1327840078u, 4078716491u, 1753812954u, 976892272u, 1827135136u, 1781944746u, 1328622957u, 1015377974u, 3439601008u, 2209584557u, 2482286699u, 1109175923u, 874877499u, 2036083451u, 483570344u, 1091877599u, 4190721328u, 1129462471u, 640035849u, 1867372700u, 920761165u, 3273688770u, 1623777358u, 3389003793u, 3241132743u, 2734783008u, 696674661u, 2502161880u, 1646071378u, 1164309901u, 350411888u, 1978005963u, 2253937037u, 7371540u, 989577914u, 3626554867u, 3214796883u, 531343826u, 398899695u, 1145247203u, 1516846461u, 3656006011u, 529303412u, 3318455811u, 3062828129u, 1696355359u, 3698796465u, 3155218919u, 1457595996u, 3191404246u, 1395609912u, 2917345728u, 1237411891u, 1854985978u, 1091884675u, 3504488111u, 3109924189u, 1628881950u, 3939149151u, 878608872u, 778235395u, 1052990614u, 903730231u, 2069566979u, 2437686324u, 3163786257u, 2257884264u, 2123173186u, 939764916u, 2933010098u, 1235300371u, 1256485167u, 1950274665u, 2180372319u, 2648400302u, 122035049u, 1883344352u, 2083771672u, 3712110541u, 321199441u, 1896357377u, 508560958u, 3066325351u, 2770847216u, 3177982504u, 296902736u, 1486926688u, 456842861u, 601221482u, 3992583643u, 2794121515u, 1533934172u, 1706465470u, 4281971893u, 2557027816u, 900741486u, 227175484u, 550595824u, 690918144u, 2825943628u, 90375300u, 300318232u, 1985329734u, 1440763373u, 3670603707u, 2533900859u, 3253901179u, 542270815u, 3677388841u, 307706478u, 2570910669u, 3320103693u, 1273768482u, 1216399252u, 1652924805u, 1043647584u, 1120323676u, 639941430u, 325675502u, 3652676161u, 4241680335u, 1545838362u, 1991398008u, 4100211814u, 1097584090u, 3262252593u, 2254324292u, 1765019121u, 4060211241u, 2315856188u, 3704419305u, 411263051u, 238929055u, 3540688404u, 3094544537u, 3250435765u, 3460621305u, 1967599860u, 2016157366u, 847389916u, 1659615591u, 4020453639u, 901109753u, 2682611693u, 1661364280u, 177155177u, 3210561911u, 3802058181u, 797089608u, 3286110054u, 2110358240u, 1353279028u, 2479975820u, 471725410u, 2219863904u, 3623364733u, 3167128228u, 1052188336u, 3656587111u, 721788662u, 3061255808u, 1615375832u, 924941453u, 2547780700u, 3328169224u, 1310964134u, 2701956286u, 4145497671u, 1421461094u, 1221397398u, 1589183618u, 1492533854u, 449740816u, 2686506989u, 3035198924u, 1682886232u, 2529760244u, 3342031659u, 1235084019u, 2151665147u, 2315686577u, 3282027660u, 1140138691u, 2754346599u, 2091754612u, 1178454681u, 4226896579u, 2942520471u, 2122168506u, 3751680858u, 3213794286u, 2601416506u, 4142747914u, 3951404257u, 4243249649u, 748595836u, 4004834921u, 238887261u, 1927321047u, 2217148444u, 205977665u, 1885975275u, 186020771u, 2367569534u, 2941662631u, 2608559272u, 3342096731u, 741809437u, 1962659444u, 3539886328u, 3036596491u, 2282550094u, 2366462727u, 2748286642u, 2144472852u, 1390394371u, 1257385924u, 2205425874u, 2119055686u, 46865323u, 3597555910u, 3188438773u, 2372320753u, 3641116924u, 3116286108u, 2680722658u, 3371014971u, 2058751609u, 2966943726u, 2345078707u, 2330535244u, 4013841927u, 1169588594u, 857915866u, 1875260989u, 3175831309u, 3193475664u, 1955181430u, 923161569u, 4068653043u, 776445899u, 954196929u, 61509556u, 4248237857u, 3808667664u, 581227317u, 2893240187u, 4159497403u, 4212264930u, 3973886195u, 2077539039u, 851579036u, 2957587591u, 772351886u, 1173659554u, 946748363u, 2794103714u, 2094375930u, 4234750213u, 3671645488u, 2614250782u, 2620465358u, 3122317317u, 2365436865u, 3393973390u, 523513960u, 3645735309u, 2766686992u, 2023960931u, 2312244996u, 1875932218u, 3253711056u, 3622416881u, 3274929205u, 612094988u, 1555465129u, 2114270406u, 3553762793u, 1832633644u, 1087551556u, 3306195841u, 1702313921u, 3675066046u, 1735998785u, 1690923980u, 1482649756u, 1171351291u, 2043136409u, 1962596992u, 461214626u, 3278253346u, 1392428048u, 3744621107u, 1028502697u, 3991171462u, 1014064003u, 3642345425u, 3186995039u, 6114625u, 3359104346u, 414856965u, 2814387514u, 3583605071u, 2497896367u, 1024572712u, 1927582962u, 2892797583u, 845302635u, 328548052u, 1523379748u, 3392622118u, 1347167673u, 1012316581u, 37767602u, 2647726017u, 1070326065u, 2075035198u, 4202817168u, 2502924707u, 2612406822u, 2187115553u, 1180137213u, 701024148u, 1481965992u, 3223787553u, 2083541843u, 203230202u, 3876887380u, 1334816273u, 2870251538u, 2186205850u, 3985213979u, 333533378u, 806507642u, 1010064531u, 713520765u, 3084131515u, 2637421459u, 1703168933u, 1517562266u, 4089081247u, 3231042924u, 3079916123u, 3154574447u, 2253948262u, 1725190035u, 2452539325u, 1343734533u, 213706059u, 2519409656u, 108055211u, 2916327746u, 587001593u, 1917607088u, 4202913084u, 926304016u, 469255411u, 4042080256u, 3498936874u, 246692543u, 495780578u, 438717281u, 2259272650u, 4011324645u, 2836854664u, 2317249321u, 946828752u, 1280403658u, 1905648354u, 2034241661u, 774652981u, 1285694082u, 2200307766u, 2158671727u, 1135162148u, 232040752u, 397012087u, 1717527689u, 1720414106u, 918797022u, 2580119304u, 3568069742u, 2904461070u, 3893453420u, 973817938u, 667499332u, 3785870412u, 2088861715u, 1565179401u, 600903026u, 591806775u, 3512242245u, 997964515u, 2339605347u, 1134342772u, 3234226304u, 4084179455u, 302315791u, 2445626811u, 2590372496u, 345572299u, 2274770442u, 3600587867u, 3706939009u, 1430507980u, 2656330434u, 1079209397u, 2122849632u, 1423705223u, 3826321888u, 3683385276u, 1057038163u, 1242840526u, 3987000643u, 2398253089u, 1538190921u, 1295898647u, 3570196893u, 3065138774u, 3111336863u, 2524949549u, 4203895425u, 3025864372u, 968800353u, 1023721001u, 3763083325u, 526350786u, 635552097u, 2308118370u, 2166472723u, 2196937373u, 2643841788u, 3040011470u, 4010301879u, 2782379560u, 3474682856u, 4201389782u, 4223278891u, 1457302296u, 2251842132u, 1090062008u, 3188219189u, 292733931u, 1424229089u, 1590782640u, 1365212370u, 3975957073u, 3982969588u, 2927147928u, 1048291071u, 2766680094u, 884908196u, 35237839u, 2221180633u, 2490333812u, 4098360768u, 4029081103u, 3490831871u, 2392516272u, 3455379186u, 3948800722u, 335456628u, 2105117968u, 4181629008u, 1044201772u, 3335754111u, 540133451u, 3313113759u, 3786107905u, 2627207327u, 3540337875u, 3473113388u, 3430536378u, 2514123129u, 2124531276u, 3872633376u, 3272957388u, 3501994650u, 2418881542u, 487365389u, 3877672368u, 1512866656u, 3486531087u, 2102955203u, 1136054817u, 3004241477u, 1549075351u, 1302002008u, 3936430045u, 2258587644u, 4109233936u, 3679809321u, 3467083076u, 2484463221u, 1594979755u, 529218470u, 3527024461u, 1147434678u, 106799023u, 1823161970u, 1704656738u, 1675883700u, 3308746763u, 1875093248u, 1352868568u, 1898561846u, 2508994984u, 3177750780u, 4217929592u, 400784472u, 80090315u, 3564414786u, 3841585648u, 3379293868u, 160353261u, 2413172925u, 2378499279u, 673436726u, 1505702418u, 1330977363u, 1853298225u, 3201741245u, 2135714208u, 4069554166u, 3715612384u, 3692488887u, 3680311316u, 4274382900u, 914186796u, 2264886523u, 3869634032u, 1254199592u, 1131020455u, 194781179u, 429923922u, 2763792336u, 2052895198u, 3997373194u, 3440090658u, 2165746386u, 1575500242u, 3463310191u, 2064974716u, 3779513671u, 3106421434u, 880320527u, 3281914119u, 286569042u, 3909096631u, 122359727u, 1429837716u, 252230074u, 4111461225u, 762273136u, 93658514u, 2766407143u, 3623657004u, 3869801679u, 3925695921u, 2390397316u, 2499025338u, 2741806539u, 2507199021u, 1659221866u, 361292116u, 4048761557u, 3797133396u, 1517903247u, 3121647246u, 3884308578u, 1697201500u, 1558800262u, 4150812360u, 3161302278u, 2610217849u, 641564641u, 183814518u, 2075245419u, 611996508u, 2223461433u, 329123979u, 121860586u, 860985829u, 1137889144u, 4018949439u, 2904348960u, 947795261u, 1992594155u, 4255427501u, 2281583851u, 2892637604u, 1478186924u, 3050771207u, 2767035539u, 373510582u, 1963520320u, 3763848370u, 3756817798u, 627269409u, 1806905031u, 1814444610u, 3646665053u, 1822693920u, 278515794u, 584050483u, 4142579188u, 2149745808u, 3193071606u, 1179706341u, 2693495182u, 3259749808u, 644172091u, 880509048u, 3340630542u, 3365160815u, 2384445068u, 3053081915u, 2840648309u, 1986990122u, 1084703471u, 2370410550u, 1627743573u, 2244943480u, 4057483496u, 2611595995u, 2470013639u, 4024732359u, 3987190386u, 873421687u, 2447660175u, 3226583022u, 767655877u, 2528024413u, 1962070688u, 1233635843u, 2163464207u, 659054446u, 854207134u, 258410943u, 4197831420u, 2515400215u, 3100476924u, 1961549594u, 2219491151u, 3997658851u, 163850514u, 470325051u, 2598261204u, 3052145580u, 59836528u, 1376188597u, 966733415u, 850667549u, 3622479237u, 1083731990u, 1525777459u, 4005126532u, 1428155540u, 2781907007u, 943739431u, 1493961005u, 2839096988u, 2000057832u, 1941829603u, 1901484772u, 939810041u, 3377407371u, 3090115837u, 3310840540u, 2068409688u, 3261383939u, 2212130277u, 2594774045u, 2912652418u, 4179816101u, 3534504531u, 3349254805u, 2796552902u, 1385421283u, 4259908631u, 3714780837u, 3070073945u, 3372846298u, 3835884044u, 3047965714u, 3009018735u, 744091167u, 1861124263u, 2764936304u, 1338171648u, 4222019554u, 1395200692u, 1371426007u, 3338031581u, 2525665319u, 4196233786u, 2332743921u, 1474702008u, 2274266301u, 4255175517u, 2290169528u, 1793910997u, 2188254024u, 354202001u, 3864458796u, 4280290498u, 1554419340u, 1733094688u, 2010552302u, 1561807039u, 664313606u, 2548990879u, 1084699349u, 3233936866u, 973895284u, 2386881969u, 1831995860u, 2961465052u, 1428704144u, 3269904970u, 231648253u, 2602483763u, 4125013173u, 3319187387u, 3347011944u, 1892898231u, 4019114049u, 868879116u, 4085937045u, 2378411019u, 1072588531u, 3547435717u, 2208070766u, 1069899078u, 3142980597u, 2337088907u, 1593338562u, 919414554u, 688077849u, 3625708135u, 1472447348u, 1947711896u, 3953006207u, 877438080u, 845995820u, 3150361443u, 3053496713u, 2484577841u, 224271045u, 2914958001u, 2682612949u, 806655563u, 2436224507u, 1907729235u, 2920583824u, 1251814062u, 2070814520u, 4034325578u, 497847539u, 2714317144u, 385182008u, 640855184u, 1327075087u, 1062468773u, 1757405994u, 1374270191u, 4263183176u, 3041193150u, 1037871524u, 3633173991u, 4231821821u, 2830131945u, 3505072908u, 2830570613u, 4195208715u, 575398021u, 3992840257u, 3691788221u, 1949847968u, 2999344380u, 3183782163u, 3723754342u, 759716128u, 3284107364u, 1714496583u, 15918244u, 820509475u, 2553936299u, 2201876606u, 4237151697u, 2605688266u, 3253705097u, 1008333207u, 712158730u, 1722280252u, 1933868287u, 4152736859u, 2097020806u, 584426382u, 2836501956u, 2522777566u, 1996172430u, 2122199776u, 1069285218u, 1474209360u, 690831894u, 107482532u, 3695525410u, 670591796u, 768977505u, 2412057331u, 3647886687u, 3110327607u, 1072658422u, 379861934u, 1557579480u, 4124127129u, 2271365865u, 3880613089u, 739218494u, 547346027u, 388559045u, 3147335977u, 176230425u, 3094853730u, 2554321205u, 1495176194u, 4093461535u, 3521297827u, 4108148413u, 1913727929u, 1177947623u, 1911655402u, 1053371241u, 3265708874u, 1266515850u, 1045540427u, 3194420196u, 3717104621u, 1144474110u, 1464392345u, 52070157u, 4144237690u, 3350490823u, 4166253320u, 2747410691u, }; // Return false only if offset is -1 and a spot check of 3 hashes all yield 0. bool Test(int offset, int len = 0) { #undef Check #undef IsAlive #define Check(x) do { \ const uint32_t actual = (x), e = expected[index++]; \ bool ok = actual == e; \ if (!ok) { \ cerr << "expected " << hex << e << " but got " << actual << endl; \ ++errors; \ } \ assert(ok); \ } while (0) #define IsAlive(x) do { alive += IsNonZero(x); } while (0) // After the following line is where the uses of "Check" and such will go. static int index = 0; if (offset == -1) { int alive = 0; { uint64_t h = farmhashna::Hash64WithSeeds(data, len++, SEED0, SEED1); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64WithSeed(data, len++, SEED); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64(data, len++); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } len -= 3; return alive > 0; } { uint64_t h = farmhashna::Hash64WithSeeds(data + offset, len, SEED0, SEED1); Check(h >> 32); Check((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64WithSeed(data + offset, len, SEED); Check(h >> 32); Check((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64(data + offset, len); Check(h >> 32); Check((h << 32) >> 32); } return true; #undef Check #undef IsAlive } int RunTest() { Setup(); int i = 0; cout << "Running farmhashnaTest"; if (!Test(-1)) { cout << "... Unavailable\n"; return errors; } // Good. The function is attempting to hash, so run the full test. int errors_prior_to_test = errors; for ( ; i < kTestSize - 1; i++) { Test(i * i, i); } for ( ; i < kDataSize; i += i / 7) { Test(0, i); } Test(0, kDataSize); cout << (errors == errors_prior_to_test ? "... OK\n" : "... Failed\n"); return errors; } #undef SEED #undef SEED1 #undef SEED0 int main(int argc, char* argv[]) { return RunTest(); }
26.052464
383
0.801947
dietmarkuehl
3299c5a5c960b8e0e3a203a2fd5acd556c37ff53
18,489
cpp
C++
src/configator.cpp
MickaelBlet/Configator
e5679106d9946885e88b18430562ea4a6b47dbd4
[ "MIT" ]
null
null
null
src/configator.cpp
MickaelBlet/Configator
e5679106d9946885e88b18430562ea4a6b47dbd4
[ "MIT" ]
null
null
null
src/configator.cpp
MickaelBlet/Configator
e5679106d9946885e88b18430562ea4a6b47dbd4
[ "MIT" ]
1
2020-07-14T02:26:16.000Z
2020-07-14T02:26:16.000Z
/** * configator.cpp * * Licensed under the MIT License <http://opensource.org/licenses/MIT>. * Copyright (c) 2020 BLET Mickaël. * * 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 <list> #include "configator.hpp" namespace mblet { Configator::Configator(): _mapConfig(Configator::Map()), _filename(std::string()), _isRead(false) { return ; } Configator::Configator(const char* filename): _mapConfig(Configator::Map()), _filename(std::string()), _isRead(false) { readFile(filename); return ; } Configator::Configator(const Configator& src): _mapConfig(src._mapConfig), _filename(src._filename), _isRead(src._isRead) { return ; } Configator::~Configator() { return ; } Configator& Configator::operator=(const Configator& rhs) { _mapConfig = rhs._mapConfig; _filename = rhs._filename; _isRead = rhs._isRead; return *this; } const Configator::Map& Configator::operator[](std::size_t index) const { return _mapConfig[index]; } const Configator::Map& Configator::operator[](const std::string& str) const { return _mapConfig[str]; } bool Configator::readFile(const char* filename) { _mapConfig.clear(); _filename = ""; _isRead = false; std::ifstream fileStream(filename); // open file if (fileStream.is_open()) { _filename = filename; _isRead = true; readStream(fileStream); // parse file fileStream.close(); } return _isRead; } void Configator::setConfig(const Configator::Map& mapConfig) { _mapConfig.clear(); _mapConfig = mapConfig; } const Configator::Map& Configator::getConfig() const { return _mapConfig; } const std::string& Configator::getFilename() const { return _filename; } bool Configator::isRead() const { return _isRead; } // ============================================================================= // dump static void s_printCommentDump(std::ostream& oss, const std::string& str) { if (!str.empty()) { oss << " ; " << str; } } static void s_printDump(std::ostream& oss, const std::string& str) { unsigned int i; for (i = 0; i < str.size(); ++i) { if (str[i] == ' ' || str[i] == '"' || str[i] == '#' || str[i] == ';' || str[i] == '\\' || str[i] == '[' || str[i] == ']') { break; } } if (i < str.size()) { oss << '"'; for (i = 0; i < str.size(); ++i) { if (str[i] == '"' || str[i] == '\\') { oss << '\\' << str[i]; } else { oss << str[i]; } } oss << '"'; } else { oss << str; } } static void s_sectionCommentDump(std::ostream& oss, const std::string& str) { if (!str.empty()) { oss << "; "; unsigned int i; for (i = 0; i < str.size(); ++i) { oss << str[i]; if (str[i] == '\n') { oss << "; "; } } oss << '\n'; } } static void s_sectionDump(std::ostream& oss, const std::string& str, std::size_t sectionIndex) { oss << std::string(sectionIndex + 1, '['); s_printDump(oss, str); oss << std::string(sectionIndex + 1, ']'); } static void s_recurseDump(std::ostream& oss, const Configator::Map& map, std::size_t sectionIndex = 0) { Configator::Map::const_iterator itSection; for (itSection = map.begin(); itSection != map.end(); ++itSection) { if (itSection->second.size() > 0) { if (!itSection->second.value.empty()) { s_printDump(oss, itSection->first); oss << " = "; s_printDump(oss, itSection->second.value); oss << '\n'; } s_sectionDump(oss, itSection->first, sectionIndex); oss << '\n'; s_sectionCommentDump(oss, itSection->second.comment); s_recurseDump(oss, itSection->second, sectionIndex + 1); } else { s_printDump(oss, itSection->first); oss << " = "; s_printDump(oss, itSection->second.value); s_printCommentDump(oss, itSection->second.comment); oss << '\n'; } } } std::ostream& Configator::dump(std::ostream& oss) const { s_recurseDump(oss, _mapConfig); return oss; } // ============================================================================= // parse /** * @brief check if character is comment * * @param c * @return true : c is comment character * @return false : c is not comment character */ static bool s_isComment(const char& c) { if (c == ';' || c == '#') { return true; } else { return false; } } /** * @brief move index to character after spaces * * @param str * @param index */ static void s_stringJumpSpace(const std::string& str, std::size_t& index) { while (::isspace(str[index])) { ++index; } } /** * @brief detect if line is empty or comment * * @param line * @return true : line is empty or comment * @return false : line is not empty or comment */ static bool s_emptyOrComment(const std::string& line, std::string* retComment) { std::size_t start; std::size_t end; std::size_t i = 0; s_stringJumpSpace(line, i); if (line[i] != '\0' && !s_isComment(line[i])) { return false; } ++i; // jump character ';' or '#' s_stringJumpSpace(line, i); start = i; while (line[i] != '\0') { ++i; } --i; // revert jump '\0' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; *retComment = line.substr(start, end - start); return true; } /** * @brief parse section name * * @param line * @param retSection * @param retComment * @return true * @return false */ static bool s_parseSections(std::string line, std::list<std::string>* retSection, std::string* retComment) { char quote; std::size_t start; std::size_t end; std::size_t last; std::size_t level = 0; std::size_t i = 0; s_stringJumpSpace(line, i); // if not begin section if (line[i] != '[') { return false; } while (line[i] == '[') { ++i; // jump character '[' ++level; s_stringJumpSpace(line, i); if (line[i] == '[') { return false; } // start section name if (line[i] == '\"' || line[i] == '\'') { // get quote character quote = line[i]; ++i; // jump quote start = i; // search end quote while (line[i] != quote) { if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) { line.erase(i, 1); } if (line[i] == '\0') { return false; } ++i; } end = i; ++i; // jump quote s_stringJumpSpace(line, i); } else { start = i; while (line[i] != ']') { if (line[i] == '\0') { return false; } ++i; } last = i; --i; // revert jump ']' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; i = last; } if (line[i] != ']') { return false; } ++i; // jump ] if (level == 1) { retSection->clear(); } retSection->push_back(line.substr(start, end - start)); s_stringJumpSpace(line, i); } if (line[i] != '\0' && !s_isComment(line[i])) { retSection->pop_back(); return false; } if (s_isComment(line[i])) { ++i; // jump character ';' or '#' s_stringJumpSpace(line, i); start = i; while (line[i] != '\0') { ++i; } --i; // revert jump '\0' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; *retComment = line.substr(start, end - start); } return true; } /** * @brief parse section name * * @param line * @param retSection * @param retComment * @return true * @return false */ static bool s_parseSectionLevel(std::string line, std::list<std::string>* retSection, std::string* retComment) { char quote; std::size_t start; std::size_t end; std::size_t last; std::size_t level = 0; std::size_t saveLevel = 0; std::size_t i = 0; s_stringJumpSpace(line, i); // if not begin section if (line[i] != '[') { return false; } while (line[i] == '[') { ++i; // jump character '[' ++level; s_stringJumpSpace(line, i); } // start section name if (line[i] == '\"' || line[i] == '\'') { // get quote character quote = line[i]; ++i; // jump quote start = i; // search end quote while (line[i] != quote) { if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) { line.erase(i, 1); } if (line[i] == '\0') { return false; } ++i; } end = i; ++i; // jump quote s_stringJumpSpace(line, i); } else { start = i; while (line[i] != ']') { if (line[i] == '\0') { return false; } ++i; } last = i; --i; // revert jump ']' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; i = last; } saveLevel = level; while (line[i] == ']') { ++i; // jump character ']' --level; s_stringJumpSpace(line, i); } if (level != 0) { return false; } --saveLevel; while (retSection->size() > saveLevel) { retSection->pop_back(); } if (saveLevel == retSection->size()) { retSection->push_back(line.substr(start, end - start)); } else { return false; } s_stringJumpSpace(line, i); if (line[i] != '\0' && !s_isComment(line[i])) { return false; } if (s_isComment(line[i])) { ++i; // jump character ';' or '#' s_stringJumpSpace(line, i); start = i; while (line[i] != '\0') { ++i; } --i; // revert jump '\0' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; *retComment = line.substr(start, end - start); } return true; } /** * @brief parse key * * @param line * @param retKey * @param retValue * @param retComment * @return true * @return false */ static bool s_parseKey(std::string line, std::list<std::string>* retKey, std::string* retValue, std::string* retComment) { char quote; std::size_t start; std::size_t end; std::size_t last; std::size_t i = 0; s_stringJumpSpace(line, i); if (line[i] == '=') { return false; // not key element } // start key name if (line[i] == '\"' || line[i] == '\'') { // get quote character quote = line[i]; ++i; // jump quote start = i; // search end quote while (line[i] != quote) { if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) { line.erase(i, 1); } if (line[i] == '\0') { return false; } ++i; } end = i; ++i; // jump quote s_stringJumpSpace(line, i); if (line[i] != '=' && line[i] != '[') { return false; // not valid key } } else { start = i; while (line[i] != '=' && line[i] != '[') { if (line[i] == '\0') { return false; } ++i; } last = i; --i; // revert jump '=' or '[' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; i = last; } retKey->push_back(line.substr(start, end - start)); // check table key while (line[i] == '[') { ++i; // jump '[' s_stringJumpSpace(line, i); // start key name if (line[i] == '\"' || line[i] == '\'') { // get quote character quote = line[i]; ++i; // jump quote start = i; // search end quote while (line[i] != quote) { if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) { line.erase(i, 1); } if (line[i] == '\0') { return false; } ++i; } end = i; ++i; // jump quote s_stringJumpSpace(line, i); if (line[i] != ']') { return false; // not valid key } } else { start = i; while (line[i] != ']') { if (line[i] == '\0') { return false; } ++i; } last = i; --i; // revert jump '=' or '[' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; i = last; } ++i; // jump ']' s_stringJumpSpace(line, i); retKey->push_back(line.substr(start, end - start)); } s_stringJumpSpace(line, i); if (line[i] != '=') { return false; } ++i; // jump '=' s_stringJumpSpace(line, i); // start value if (line[i] == '\"' || line[i] == '\'') { // get quote character quote = line[i]; ++i; // jump quote start = i; // search end quote while (line[i] != quote) { if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) { line.erase(i, 1); } if (line[i] == '\0') { return false; } ++i; } end = i; ++i; // jump quote s_stringJumpSpace(line, i); if (line[i] != '\0' && !s_isComment(line[i])) { return false; // not valid value } } else { start = i; while (line[i] != '\0' && !s_isComment(line[i])) { ++i; } last = i; --i; // revert jump '\0' or ';' or '#' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; i = last; } *retValue = line.substr(start, end - start); if (s_isComment(line[i])) { ++i; // jump character ';' or '#' s_stringJumpSpace(line, i); start = i; while (line[i] != '\0') { ++i; } --i; // revert jump '\0' while (i > 0 && isspace(line[i])) { --i; } ++i; // last character end = i; *retComment = line.substr(start, end - start); } return true; } /** * @brief get map of section * * @param map * @param sections * @return Configator::Map& */ static Configator::Map& s_section(Configator::Map& map, const std::list<std::string>& sections) { std::list<std::string>::const_iterator itSection; Configator::Map* pMap = &map; for (itSection = sections.begin(); itSection != sections.end(); ++itSection) { pMap = &((*pMap)[*itSection]); } return *pMap; } void Configator::readStream(std::istream& stream) { std::string line(""); std::list<std::string> sections; sections.push_back(""); while (std::getline(stream, line)) { std::list<std::string> keys; std::string comment = ""; std::string value = ""; if (s_emptyOrComment(line, &comment)) { Configator::Map& map = s_section(_mapConfig, sections); if (!map.comment.empty()) { map.comment.append("\n"); } map.comment.append(comment); } else if (s_parseSections(line, &sections, &comment)) { Configator::Map& map = s_section(_mapConfig, sections); map.comment = comment; } else if (s_parseSectionLevel(line, &sections, &comment)) { Configator::Map& map = s_section(_mapConfig, sections); map.comment = comment; } else if (s_parseKey(line, &keys, &value, &comment)) { Configator::Map& map = s_section(_mapConfig, sections); Configator::Map* tmpMap = &(map); std::list<std::string>::iterator it; for (it = keys.begin(); it != keys.end() ; ++it) { if (it->empty()) { std::ostringstream oss(""); oss << tmpMap->size(); tmpMap = &((*tmpMap)[oss.str()]); } else { tmpMap = &((*tmpMap)[*it]); } } *tmpMap = value; tmpMap->comment = comment; } } } }
26.679654
112
0.467683
MickaelBlet
329fe9fec81dd232d8f5d189629999932344b660
12,190
cpp
C++
src/select/tcpsocket_impl.cpp
tempbottle/zsummerX
b5a6b306329d6877cb53c1f30b586a2363c7682a
[ "MIT" ]
1
2021-07-14T01:42:21.000Z
2021-07-14T01:42:21.000Z
src/select/tcpsocket_impl.cpp
tempbottle/zsummerX
b5a6b306329d6877cb53c1f30b586a2363c7682a
[ "MIT" ]
null
null
null
src/select/tcpsocket_impl.cpp
tempbottle/zsummerX
b5a6b306329d6877cb53c1f30b586a2363c7682a
[ "MIT" ]
1
2021-07-14T01:42:25.000Z
2021-07-14T01:42:25.000Z
/* * zsummerX License * ----------- * * zsummerX is licensed under the terms of the MIT license reproduced below. * This means that zsummerX is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2015 YaweiZhang <yawei.zhang@foxmail.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. * * =============================================================================== * * (end of COPYRIGHT) */ #include <zsummerX/select/tcpsocket_impl.h> using namespace zsummer::network; TcpSocket::TcpSocket() { g_appEnvironment.addCreatedSocketCount(); _register._type = tagRegister::REG_TCP_SOCKET; } TcpSocket::~TcpSocket() { g_appEnvironment.addClosedSocketCount(); if (_onRecvHandler || _onSendHandler || _onConnectHandler) { LCT("TcpSocket::~TcpSocket[this0x" << this << "] Handler status error. " << logSection()); } if (_register._fd != InvalideFD) { closesocket(_register._fd); _register._fd = InvalideFD; } } std::string TcpSocket::logSection() { std::stringstream os; os << ";; Status: summer.user_count()=" << _summer.use_count() << ", remoteIP=" << _remoteIP << ", remotePort=" << _remotePort << ", _onConnectHandler = " << (bool)_onConnectHandler << ", _onRecvHandler = " << (bool)_onRecvHandler << ", _pRecvBuf=" << (void*)_pRecvBuf << ", _iRecvLen=" << _iRecvLen << ", _onSendHandler = " << (bool)_onSendHandler << ", _pSendBuf=" << (void*)_pSendBuf << ", _iSendLen=" << _iSendLen << "; _register=" << _register; return os.str(); } bool TcpSocket::initialize(const EventLoopPtr & summer) { _summer = summer; if (_register._linkstat != LS_UNINITIALIZE) { if (!_summer->registerEvent(0, _register)) { LCE("TcpSocket::initialize[this0x" << this << "] socket already used or not initilize." << logSection()); return false; } _register._linkstat = LS_ESTABLISHED; } else { if (_register._fd != -1) { LCE("TcpSocket::doConnect[this0x" << this << "] fd aready used!" << logSection()); return false; } _register._fd = socket(AF_INET, SOCK_STREAM, 0); if (_register._fd == -1) { LCE("TcpSocket::doConnect[this0x" << this << "] fd create failed!" << logSection()); return false; } setNonBlock(_register._fd); setNoDelay(_register._fd); _register._linkstat = LS_WAITLINK; } return true; } bool TcpSocket::attachSocket(SOCKET s, const std::string& remoteIP, unsigned short remotePort) { _register._fd = s; _remoteIP = remoteIP; _remotePort = remotePort; _register._linkstat = LS_WAITLINK; return true; } bool TcpSocket::doConnect(const std::string & remoteIP, unsigned short remotePort, _OnConnectHandler && handler) { if (!_summer) { LCE("TcpSocket::doConnect[this0x" << this << "] summer not bind!" << logSection()); return false; } if (_register._linkstat != LS_WAITLINK) { LCE("TcpSocket::doConnect[this0x" << this << "] _linkstat not LS_WAITLINK!" << logSection()); return false; } _register._wt = true; _remoteIP = remoteIP; _remotePort = remotePort; sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(_remoteIP.c_str()); addr.sin_port = htons(_remotePort); int ret = connect(_register._fd, (sockaddr *) &addr, sizeof(addr)); #ifndef WIN32 if (ret != 0 && errno != EINPROGRESS) #else if (ret != 0 && WSAGetLastError() != WSAEWOULDBLOCK) #endif { LCT("TcpSocket::doConnect[this0x" << this << "] ::connect error. " << OSTREAM_GET_LASTERROR << logSection()); closesocket(_register._fd); _register._fd = InvalideFD; return false; } _register._tcpSocketConnectPtr = shared_from_this(); if (!_summer->registerEvent(0, _register)) { LCE("TcpSocket::doConnect[this0x" << this << "] registerEvent Error" << logSection()); closesocket(_register._fd); _register._fd = InvalideFD; _register._tcpSocketConnectPtr.reset(); return false; } _onConnectHandler = std::move(handler); return true; } bool TcpSocket::doSend(char * buf, unsigned int len, _OnSendHandler && handler) { if (_register._linkstat != LS_ESTABLISHED) { LCT("TcpSocket::doSend[this0x" << this << "] _linkstat not REG_ESTABLISHED_TCP!" << logSection()); return false; } if (!_summer) { LCE("TcpSocket::doSend[this0x" << this << "] _summer not bind!" << logSection()); return false; } if (len == 0) { LCE("TcpSocket::doSend[this0x" << this << "] argument err! len ==0" << logSection()); return false; } if (_pSendBuf != NULL || _iSendLen != 0) { LCE("TcpSocket::doSend[this0x" << this << "] _pSendBuf =" << (void *) _pSendBuf << " _iSendLen =" << _iSendLen<< logSection()); return false; } if (_onSendHandler) { LCE("TcpSocket::doSend[this0x" << this << "] _onSendHandler == TRUE" << logSection()); return false; } _pSendBuf = buf; _iSendLen = len; _register._wt = true; _register._tcpSocketSendPtr = shared_from_this(); if (!_summer->registerEvent(1, _register)) { LCT("TcpSocket::doSend[this0x" << this << "] registerEvent Error" << logSection()); _pSendBuf = nullptr; _iSendLen = 0; _register._tcpSocketSendPtr.reset(); doClose(); return false; } _onSendHandler = std::move(handler); return true; } bool TcpSocket::doRecv(char * buf, unsigned int len, _OnRecvHandler && handler) { if (_register._linkstat != LS_ESTABLISHED) { LCT("TcpSocket::doRecv[this0x" << this << "] type not REG_ESTABLISHED_TCP!" << logSection()); return false; } if (!_summer) { LCE("TcpSocket::doRecv[this0x" << this << "] _summer not bind!" << logSection()); return false; } if (len == 0 ) { LCE("TcpSocket::doRecv[this0x" << this << "] argument err !!! len==0" << logSection()); return false; } if (_pRecvBuf != NULL || _iRecvLen != 0) { LCE("TcpSocket::doRecv[this0x" << this << "] (_pRecvBuf != NULL || _iRecvLen != 0) == TRUE" << logSection()); return false; } if (_onRecvHandler) { LCE("TcpSocket::doRecv[this0x" << this << "] (_onRecvHandler) == TRUE" << logSection()); return false; } _pRecvBuf = buf; _iRecvLen = len; _register._rd = true; _register._tcpSocketRecvPtr = shared_from_this(); if (!_summer->registerEvent(1, _register)) { LCT("TcpSocket::doRecv[this0x" << this << "] registerEvent Error" << logSection()); _pRecvBuf = nullptr; _iRecvLen = 0; _register._tcpSocketRecvPtr.reset(); return false; } _onRecvHandler = std::move(handler); return true; } void TcpSocket::onSelectMessage(bool rd, bool wt, bool err) { unsigned char linkstat = _register._linkstat; NetErrorCode ec = NEC_ERROR; if (!_onRecvHandler && !_onSendHandler && !_onConnectHandler) { LCE("TcpSocket::onSelectMessage[this0x" << this << "] unknown error. " << OSTREAM_GET_LASTERROR << logSection()); return ; } if (linkstat == LS_WAITLINK) { std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketConnectPtr)); _OnConnectHandler onConnect(std::move(_onConnectHandler)); int errCode = 0; socklen_t len = sizeof(int); if (err || getsockopt(_register._fd, SOL_SOCKET, SO_ERROR, (char*)&errCode, &len) != 0 || errCode != 0) { LOGT("onConnect False. " << OSTREAM_GET_LASTERROR); _register._linkstat = LS_WAITLINK; _summer->registerEvent(2, _register); onConnect(NEC_ERROR); return; } else { _register._wt = 0; _summer->registerEvent(1, _register); _register._linkstat = LS_ESTABLISHED; onConnect(NEC_SUCCESS); return; } return ; } if (rd && _onRecvHandler) { std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketRecvPtr)); int ret = recv(_register._fd, _pRecvBuf, _iRecvLen, 0); _register._rd = false; if (!_summer->registerEvent(1, _register)) { LCF("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLLMod error. " << OSTREAM_GET_LASTERROR << logSection()); } if (ret == 0 || (ret == -1 && !IS_WOULDBLOCK)) { ec = NEC_ERROR; _register._linkstat = LS_CLOSED; if (rd && _onRecvHandler) { _OnRecvHandler onRecv(std::move(_onRecvHandler)); onRecv(ec, 0); } if (!_onSendHandler && !_onRecvHandler) { if (!_summer->registerEvent(2, _register)) { LCW("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLL DEL error. " << OSTREAM_GET_LASTERROR << logSection()); } } return ; } else if (ret != -1) { _OnRecvHandler onRecv(std::move(_onRecvHandler)); _pRecvBuf = NULL; _iRecvLen = 0; onRecv(NEC_SUCCESS,ret); } return; } else if (wt && _onSendHandler) { std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketSendPtr)); int ret = send(_register._fd, _pSendBuf, _iSendLen, 0); _register._wt = false; if (!_summer->registerEvent(1, _register)) { LCF("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLLMod error. " << OSTREAM_GET_LASTERROR << logSection()); } if ((ret == -1 && !IS_WOULDBLOCK) || _register._linkstat == LS_CLOSED) { ec = NEC_ERROR; _register._linkstat = LS_CLOSED; _onSendHandler = nullptr; if (!_onSendHandler && !_onRecvHandler) { if (!_summer->registerEvent(2, _register)) { LCW("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLL DEL error. " << OSTREAM_GET_LASTERROR << logSection()); } } return ; } else if (ret != -1) { _OnSendHandler onSend(std::move(_onSendHandler)); _pSendBuf = NULL; _iSendLen = 0; onSend(NEC_SUCCESS, ret); } } return ; } bool TcpSocket::doClose() { if (_register._fd != InvalideFD) { shutdown(_register._fd, SHUT_RDWR); } return true; }
30.860759
151
0.579655
tempbottle
32a0a7fba84f4162d3de29e78fc6b8c5121fc1a1
5,967
cpp
C++
src/isodata/isodata.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/isodata/isodata.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/isodata/isodata.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
#include "tkdCmdParser.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImage.h" #include "itkTimeProbe.h" #include "IsoDataImage.cpp" /** * ISODATA. */ class IsoData { protected: // Split function; return true if we should split... bool split( IsoDataImage& img, double STDV, unsigned int minPointsPerCluster ) { bool split = false; //STEP 7: img.calculateSTDVector(); //STEP 8: img.calculateVmax(); // STEP 9: // the vector to_split will contain integers that // represent the cluster numbers that need to be split. std::vector< unsigned int > to_split = img.shouldSplit( STDV, minPointsPerCluster ); if ( to_split.size() != 0 ) { img.split( to_split ); split = true; } return split; } // Merge... void merge( IsoDataImage& img, double LUMP, int MAXPAIR ) { // STEP 11: std::vector< IsoDataImage::PairDistanceNode > centerDistances = img.computeCenterDistances(); // STEP 12: std::vector< IsoDataImage::PairDistanceNode > to_lump = img.findLumpCandidates( centerDistances, LUMP, MAXPAIR ); // STEP 13: if ( to_lump.size() != 0 ) { img.lump( to_lump ); } } // ************************************************************************************************ public: /** * Run. */ void run( const std::vector< std::string >& inputs, const std::string& output, const std::string& mask, unsigned int NUMCLUS, unsigned int SAMPRM, unsigned int MAXITER, double STDV, double LUMP, int MAXPAIR, bool normalize ) { itk::TimeProbe probe; probe.Start(); // initialize raw data... IsoDataImage img = IsoDataImage( inputs, output, mask, normalize ); // STEP 1: arbitrarily choose k and init clusters... img.initClusters( NUMCLUS ); for ( unsigned int i = 0; i < MAXITER; i++ ) { std::cout << "Iter: " << i << std::endl; // STEP 2: assign each point to the clostest cluster center... img.assignPointsToClosestClusterCenter(); // STEP 3: discard clusters with less than min. samples per cluster... // If any clusters were deleted, then go back to STEP 2... if ( img.discardSmallClusters( SAMPRM ) ) { continue; } // STEP 4: update each remaining cluster center... img.updateClusters(); // STEP 5: compute the average distance of points in clusters from // their corresponding cluster center... // also compute overall average distance... img.computeAverageDistance(); img.computeOverallAverageDistance(); // STEP 6: if ( i == MAXITER ) { LUMP = 0.0; // goto STEP 9: merge( img, LUMP, MAXPAIR ); } else if ( ( i % 2 == 0 ) || ( img.getNumCenters() >= 2 * NUMCLUS ) ) { // goto STEP 9: merge( img, LUMP, MAXPAIR ); } else if ( img.getNumCenters() <= ( NUMCLUS / 2 ) ) { // goto STEP 7: // if we are in last iteration and split is performed, we need to rerun from STEP 2 again // as cluster centers need to be updated before final run... if ( ( split( img, STDV, SAMPRM ) ) && ( i == MAXITER ) ) { i--; } } } img.writeOutput( output ); probe.Stop(); std::cout << "Total runtime: " << probe.GetMeanTime() << " s." << std::endl; } }; /** * Main. */ int main( int argc, char * argv[] ) { // arguments... std::vector< std::string > inputs; std::string output; std::string mask; int numberOfClusters = 10; // kinit int minNumberOfClusterPoints = 30; // nmin 1/5 average kluster size -> nmin = n/5 kinit. int maxNumberOfIter = 20; // Imax default 20 double maxStdev = 0.1; // STDV default 2 * sigma double minRequiredDistance = 0.001; // Lmin default 0.001 int maxPair = 4; // MAXPAIR bool normalize = false; // normalize input images... tkd::CmdParser parser( argv[0], "Isodata" ); parser.AddArgument( inputs, "inputs" ) -> AddAlias( "i" ) -> SetInput( "<strings>" ) -> SetDescription( "Input images" ) -> SetRequired( true ) -> SetMinMax( 1, 10000 ); parser.AddArgument( output, "output" ) -> AddAlias( "o" ) -> SetInput( "<string>" ) -> SetDescription( "Output cluster image file" ) -> SetRequired( true ) -> SetMinMax( 1, 1 ); parser.AddArgument( mask, "mask" ) -> AddAlias( "m" ) -> SetInput( "<string>" ) -> SetDescription( "Mask image" ) -> SetRequired( false ) -> SetMinMax( 0, 1 ); parser.AddArgument( numberOfClusters, "clusters" ) -> AddAlias( "c" ) -> SetInput( "<int>" ) -> SetDescription( "Initial number of clusters (NUMCLUS)" ) -> SetMinMax( 1, 1 ); parser.AddArgument( minNumberOfClusterPoints, "min-clusters" ) -> AddAlias( "m" ) -> SetInput( "<int>" ) -> SetDescription( "Minimum number of points that can form a cluster (SAMPRM)" ) -> SetMinMax( 1, 1 ); parser.AddArgument( maxNumberOfIter, "max-itererations" ) -> AddAlias( "it" ) -> SetInput( "<int>" ) -> SetDescription( "Maximum number of iterations (MAXITER)" ) -> SetMinMax( 1, 1 ); parser.AddArgument( maxStdev, "standard-deviation" ) -> AddAlias( "s" ) -> SetInput( "<double>" ) -> SetDescription( "Maximum standard deviation of points from their cluster center along each axis (STDV)" ) -> SetMinMax( 1, 1 ); parser.AddArgument( minRequiredDistance, "min-distance" ) -> AddAlias( "d" ) -> SetInput( "<double>" ) -> SetDescription( " Minimum required distance between two cluster centers (LUMP)" ) -> SetMinMax( 1, 1 ); parser.AddArgument( maxPair, "max-pairs" ) -> AddAlias( "p" ) -> SetInput( "<int>" ) -> SetDescription( "Maximum number of cluster pairs that can be merged per iteration (MAXPAIR)" ) -> SetMinMax( 1, 1 ); parser.AddArgument( normalize, "normalize" ) -> AddAlias( "n" ) -> SetInput( "<bool>" ) -> SetDescription( "Normalize input images before clustering (default: false)" ); if ( !parser.Parse( argc, argv ) ) { parser.PrintUsage( std::cout ); return EXIT_FAILURE; } IsoData isoData = IsoData(); isoData.run( inputs, output, mask, numberOfClusters, minNumberOfClusterPoints, maxNumberOfIter, maxStdev, minRequiredDistance, maxPair, normalize ); }
33.335196
149
0.64002
wmotte
32a2a7171e1f335a70241b41cb2874d2ec40de69
457
hpp
C++
v3/include/AsyncWatchResponse.hpp
chijinxina/etcd-cpp-api
70946a5d4eff340a821096d247031d083fd0148e
[ "BSD-3-Clause" ]
null
null
null
v3/include/AsyncWatchResponse.hpp
chijinxina/etcd-cpp-api
70946a5d4eff340a821096d247031d083fd0148e
[ "BSD-3-Clause" ]
null
null
null
v3/include/AsyncWatchResponse.hpp
chijinxina/etcd-cpp-api
70946a5d4eff340a821096d247031d083fd0148e
[ "BSD-3-Clause" ]
1
2021-07-13T07:19:37.000Z
2021-07-13T07:19:37.000Z
#ifndef __ASYNC_WATCH_HPP__ #define __ASYNC_WATCH_HPP__ #include <grpc++/grpc++.h> #include "proto/rpc.grpc.pb.h" #include "proto/rpc.pb.h" #include "v3/include/V3Response.hpp" using etcdserverpb::WatchRequest; using etcdserverpb::WatchResponse; using etcdserverpb::KV; namespace etcdv3 { class AsyncWatchResponse : public etcdv3::V3Response { public: AsyncWatchResponse(){}; void ParseResponse(WatchResponse& resp); }; } #endif
17.576923
54
0.73523
chijinxina