commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
5eb7b97a72571877b364129e698ad7aeb6ff1c76
src/native/tchclient/cefclient/tch_add/TchErrorHandler.cc
src/native/tchclient/cefclient/tch_add/TchErrorHandler.cc
#include "TchErrorHandler.h" #include <stdio.h> #ifdef OS_WIN #include <Windows.h> #endif // OS_WIN namespace Tnelab{ TchErrorHandler::TchErrorDelegate TchErrorHandler::_tch_error_delegate = 0; void TchErrorHandler::OnTchError(int error_code, std::string error_msg) { if (_tch_error_delegate != 0) { _tch_error_delegate(error_code, error_msg); return; } #ifdef OS_WIN if (!error_msg.empty()) { char msg[1024] = { 0 }; sprintf(msg, "TCH_ERROR:%d,%s\r\n", error_code, error_msg.c_str()); AllocConsole(); HANDLE hd = GetStdHandle(STD_OUTPUT_HANDLE); WriteConsoleA(hd, msg, strlen(msg), NULL, NULL); system("pause"); CloseHandle(hd); } #else if (!error_msg.empty()) printf("TCH_ERROR:%d,%s\r\n", error_code, error_msg.c_str()); #endif // OS_WIN } int TchErrorHandler::SetTchErrorDelegate(TchErrorDelegate delegate) { _tch_error_delegate = delegate; return 0; } }
#include "TchErrorHandler.h" #include <stdio.h> #ifdef OS_WIN #include <Windows.h> #endif // OS_WIN namespace Tnelab{ TchErrorHandler::TchErrorDelegate TchErrorHandler::_tch_error_delegate = 0; void TchErrorHandler::OnTchError(int error_code, std::string error_msg) { if (_tch_error_delegate != 0) { _tch_error_delegate(error_code, error_msg); return; } #ifdef OS_WIN if (!error_msg.empty()) { // ϢԭʹAllocConsoleǵĿ̨ڲܵر char msg[1024] = { 0 }; sprintf(msg, "TCH_ERROR:%d,%s\r\n", error_code, error_msg.c_str()); MessageBoxA(NULL, error_msg.c_str(), "Error, press Ctrl+C to copy the details", MB_ICONERROR | MB_OK); } #else if (!error_msg.empty()) printf("TCH_ERROR:%d,%s\r\n", error_code, error_msg.c_str()); #endif // OS_WIN } int TchErrorHandler::SetTchErrorDelegate(TchErrorDelegate delegate) { _tch_error_delegate = delegate; return 0; } }
修复#3,使用MessageBoxA代替AllocConsole
修复#3,使用MessageBoxA代替AllocConsole
C++
mit
tnelab/tchapp,tnelab/tchapp,tnelab/tchapp,tnelab/tchapp,tnelab/tchapp,tnelab/tchapp
d57b0306681f9405d222a0c1199b11469198d2c0
src/target_detection/src/usbCamera.cpp
src/target_detection/src/usbCamera.cpp
#include "usbCamera.h" enum Default { DEFAULT_CAMERA_INDEX = 0, DEFAULT_FPS = 1 }; USBCamera::USBCamera(int frameRate, int cameraIndex, string hostname): it(nh), videoStream(cameraIndex) { nh.param<int>("cameraIndex", cameraIndex, DEFAULT_CAMERA_INDEX); nh.param<int>("fps", fps, frameRate); if (not videoStream.isOpened()) { ROS_ERROR_STREAM("Failed to open camera device!"); ros::shutdown(); } ros::Duration period = ros::Duration(1. / fps); rawImgPublish = it.advertise((hostname + "/camera/image"), 2); rosImage = boost::make_shared<cv_bridge::CvImage>(); rosImage->encoding = sensor_msgs::image_encodings::RGB8; timer = nh.createTimer(period, &USBCamera::capture, this); } void USBCamera::capture(const ros::TimerEvent& te) { videoStream >> cvImageColor; cv::resize(cvImageColor, cvImageLR, cv::Size(320,240), cv::INTER_LINEAR); rosImage->image = cvImageLR; if (not rosImage->image.empty()) { rosImage->header.stamp = ros::Time::now(); rawImgPublish.publish(rosImage->toImageMsg()); } } USBCamera::~USBCamera(){ videoStream.release(); }
#include "usbCamera.h" enum Default { DEFAULT_CAMERA_INDEX = 0, DEFAULT_FPS = 1 }; USBCamera::USBCamera(int frameRate, int cameraIndex, string hostname): it(nh), videoStream(cameraIndex) { nh.param<int>("cameraIndex", cameraIndex, DEFAULT_CAMERA_INDEX); nh.param<int>("fps", fps, frameRate); if (not videoStream.isOpened()) { ROS_ERROR_STREAM("Failed to open camera device!"); ros::shutdown(); } ros::Duration period = ros::Duration(1. / fps); rawImgPublish = it.advertise((hostname + "/camera/image"), 2); rosImage = boost::make_shared<cv_bridge::CvImage>(); rosImage->encoding = sensor_msgs::image_encodings::BGR8; timer = nh.createTimer(period, &USBCamera::capture, this); } void USBCamera::capture(const ros::TimerEvent& te) { videoStream >> cvImageColor; cv::resize(cvImageColor, cvImageLR, cv::Size(320,240), cv::INTER_LINEAR); rosImage->image = cvImageLR; if (not rosImage->image.empty()) { rosImage->header.stamp = ros::Time::now(); rawImgPublish.publish(rosImage->toImageMsg()); } } USBCamera::~USBCamera(){ videoStream.release(); }
Revert to BGR color on camera to accommodate OpenCV
Revert to BGR color on camera to accommodate OpenCV
C++
mit
BCLab-UNM/SwarmBaseCode-ROS,BCLab-UNM/SwarmBaseCode-ROS,BCLab-UNM/SwarmBaseCode-ROS,BCLab-UNM/SwarmBaseCode-ROS,BCLab-UNM/SwarmBaseCode-ROS,BCLab-UNM/SwarmBaseCode-ROS
32e1ed107beffb688a351d5c3d061061d47b2076
Lia/list/zip.hpp
Lia/list/zip.hpp
#ifndef LIA_ZIP_LIST_COMP_HPP #define LIA_ZIP_LIST_COMP_HPP #include "../detail/type_traits.hpp" #include <tuple> #include <vector> namespace lia { namespace detail { template<template<typename...> class Cont, typename T> const T& forward_index(const Cont<T>& cont, unsigned i) { return cont[i]; } template<template<typename...> class Cont, typename T> T&& forward_index(Cont<T>&& cont, unsigned i) { return std::move(cont[i]); } } // detail template<typename... Args> std::vector<std::tuple<ValueType<Args>...>> zip(Args&&... args) { auto size = min(args.size()...); std::vector<std::tuple<ValueType<Args>...>> result; result.reserve(size); for(unsigned i = 0; i < size; ++i) { result.emplace_back(detail::forward_index(std::forward<Args>(args), i)...); } return result; } } // lia #endif // LIA_ZIP_LIST_COMP_HPP
#ifndef LIA_ZIP_LIST_COMP_HPP #define LIA_ZIP_LIST_COMP_HPP #include "../detail/type_traits.hpp" #include <tuple> #include <vector> namespace lia { namespace detail { template<template<typename...> class Cont, typename T> const T& forward_index(const Cont<T>& cont, unsigned i) { return cont[i]; } template<template<typename...> class Cont, typename T> T&& forward_index(Cont<T>&& cont, unsigned i) { return std::move(cont[i]); } } // detail template<typename... Args> std::vector<std::tuple<BareValueType<Args>...>> zip(Args&&... args) { auto size = min(args.size()...); std::vector<std::tuple<BareValueType<Args>...>> result; result.reserve(size); for(unsigned i = 0; i < size; ++i) { result.emplace_back(detail::forward_index(std::forward<Args>(args), i)...); } return result; } } // lia #endif // LIA_ZIP_LIST_COMP_HPP
Fix zip
Fix zip
C++
mit
Rapptz/Lia
414469854072121a2e91aeed25a049005fb9d1ea
Library/OSRM.cpp
Library/OSRM.cpp
/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "OSRM.h" OSRM::OSRM( const ServerPaths & server_paths, const bool use_shared_memory ) : use_shared_memory(use_shared_memory) { if( !use_shared_memory ) { SimpleLogger().Write() << "loading data into internal memory"; query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>( server_paths ); } else { SimpleLogger().Write() << "loading data from shared memory"; query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>( ); } //The following plugins handle all requests. RegisterPlugin( new HelloWorldPlugin() ); RegisterPlugin( new LocatePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new NearestPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new TimestampPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new ViaRoutePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); } OSRM::~OSRM() { BOOST_FOREACH(PluginMap::value_type & plugin_pointer, plugin_map) { delete plugin_pointer.second; } } void OSRM::RegisterPlugin(BasePlugin * plugin) { SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor(); if( plugin_map.find(plugin->GetDescriptor()) != plugin_map.end() ) { delete plugin_map.find(plugin->GetDescriptor())->second; } plugin_map.emplace(plugin->GetDescriptor(), plugin); } void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { SimpleLogger().Write() << "running query"; const PluginMap::const_iterator & iter = plugin_map.find( route_parameters.service ); if(plugin_map.end() != iter) { reply.status = http::Reply::ok; if( use_shared_memory ) { SimpleLogger().Write() << "shared memory handling"; // lock update pending boost::interprocess::scoped_lock< boost::interprocess::named_mutex > pending_lock(barrier.pending_update_mutex); SimpleLogger().Write() << "got pending lock"; // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier.query_mutex); SimpleLogger().Write() << "got query lock"; // unlock update pending pending_lock.unlock(); SimpleLogger().Write() << "released pending lock"; // increment query count ++(barrier.number_of_queries); (static_cast<SharedDataFacade<QueryEdge::EdgeData>* >(query_data_facade))->CheckAndReloadFacade(); } iter->second->HandleRequest(route_parameters, reply ); SimpleLogger().Write() << "finished request"; if( use_shared_memory ) { // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier.query_mutex); SimpleLogger().Write() << "got query lock"; // decrement query count --(barrier.number_of_queries); BOOST_ASSERT_MSG( 0 <= barrier.number_of_queries, "invalid number of queries" ); if (0 == barrier.number_of_queries) { // notify all processes that were waiting for this condition barrier.no_running_queries_condition.notify_all(); SimpleLogger().Write() << "sent notification"; } } } else { reply = http::Reply::stockReply(http::Reply::badRequest); } }
/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "OSRM.h" OSRM::OSRM( const ServerPaths & server_paths, const bool use_shared_memory ) : use_shared_memory(use_shared_memory) { if( !use_shared_memory ) { SimpleLogger().Write() << "loading data into internal memory"; query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>( server_paths ); } else { SimpleLogger().Write() << "loading data from shared memory"; query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>( ); } //The following plugins handle all requests. RegisterPlugin( new HelloWorldPlugin() ); RegisterPlugin( new LocatePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new NearestPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new TimestampPlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); RegisterPlugin( new ViaRoutePlugin<BaseDataFacade<QueryEdge::EdgeData> >( query_data_facade ) ); } OSRM::~OSRM() { BOOST_FOREACH(PluginMap::value_type & plugin_pointer, plugin_map) { delete plugin_pointer.second; } } void OSRM::RegisterPlugin(BasePlugin * plugin) { SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor(); if( plugin_map.find(plugin->GetDescriptor()) != plugin_map.end() ) { delete plugin_map.find(plugin->GetDescriptor())->second; } plugin_map.emplace(plugin->GetDescriptor(), plugin); } void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) { const PluginMap::const_iterator & iter = plugin_map.find( route_parameters.service ); if(plugin_map.end() != iter) { reply.status = http::Reply::ok; if( use_shared_memory ) { // lock update pending boost::interprocess::scoped_lock< boost::interprocess::named_mutex > pending_lock(barrier.pending_update_mutex); // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier.query_mutex); // unlock update pending pending_lock.unlock(); // increment query count ++(barrier.number_of_queries); (static_cast<SharedDataFacade<QueryEdge::EdgeData>* >(query_data_facade))->CheckAndReloadFacade(); } iter->second->HandleRequest(route_parameters, reply ); if( use_shared_memory ) { // lock query boost::interprocess::scoped_lock< boost::interprocess::named_mutex > query_lock(barrier.query_mutex); // decrement query count --(barrier.number_of_queries); BOOST_ASSERT_MSG( 0 <= barrier.number_of_queries, "invalid number of queries" ); // notify all processes that were waiting for this condition if (0 == barrier.number_of_queries) { barrier.no_running_queries_condition.notify_all(); } } } else { reply = http::Reply::stockReply(http::Reply::badRequest); } }
make data store less verbose in release mode
make data store less verbose in release mode
C++
bsd-2-clause
jpizarrom/osrm-backend,felixguendling/osrm-backend,yuryleb/osrm-backend,alex85k/Project-OSRM,arnekaiser/osrm-backend,ammeurer/osrm-backend,KnockSoftware/osrm-backend,oxidase/osrm-backend,bjtaylor1/Project-OSRM-Old,prembasumatary/osrm-backend,alex85k/Project-OSRM,antoinegiret/osrm-geovelo,antoinegiret/osrm-backend,Conggge/osrm-backend,hydrays/osrm-backend,ramyaragupathy/osrm-backend,antoinegiret/osrm-backend,alex85k/Project-OSRM,neilbu/osrm-backend,agruss/osrm-backend,tkhaxton/osrm-backend,arnekaiser/osrm-backend,Project-OSRM/osrm-backend,felixguendling/osrm-backend,bitsteller/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,raymond0/osrm-backend,ammeurer/osrm-backend,hydrays/osrm-backend,deniskoronchik/osrm-backend,raymond0/osrm-backend,prembasumatary/osrm-backend,KnockSoftware/osrm-backend,nagyistoce/osrm-backend,bjtaylor1/Project-OSRM-Old,ammeurer/osrm-backend,beemogmbh/osrm-backend,Conggge/osrm-backend,antoinegiret/osrm-geovelo,stevevance/Project-OSRM,stevevance/Project-OSRM,beemogmbh/osrm-backend,neilbu/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,bjtaylor1/osrm-backend,Conggge/osrm-backend,chaupow/osrm-backend,frodrigo/osrm-backend,jpizarrom/osrm-backend,ramyaragupathy/osrm-backend,nagyistoce/osrm-backend,jpizarrom/osrm-backend,Project-OSRM/osrm-backend,arnekaiser/osrm-backend,duizendnegen/osrm-backend,bjtaylor1/Project-OSRM-Old,ammeurer/osrm-backend,arnekaiser/osrm-backend,agruss/osrm-backend,nagyistoce/osrm-backend,stevevance/Project-OSRM,oxidase/osrm-backend,yuryleb/osrm-backend,skyborla/osrm-backend,ramyaragupathy/osrm-backend,deniskoronchik/osrm-backend,Carsten64/OSRM-aux-git,duizendnegen/osrm-backend,atsuyim/osrm-backend,Tristramg/osrm-backend,tkhaxton/osrm-backend,skyborla/osrm-backend,atsuyim/osrm-backend,bitsteller/osrm-backend,Carsten64/OSRM-aux-git,oxidase/osrm-backend,ammeurer/osrm-backend,atsuyim/osrm-backend,frodrigo/osrm-backend,ammeurer/osrm-backend,felixguendling/osrm-backend,KnockSoftware/osrm-backend,chaupow/osrm-backend,neilbu/osrm-backend,bjtaylor1/osrm-backend,hydrays/osrm-backend,frodrigo/osrm-backend,antoinegiret/osrm-backend,prembasumatary/osrm-backend,Tristramg/osrm-backend,deniskoronchik/osrm-backend,duizendnegen/osrm-backend,stevevance/Project-OSRM,bjtaylor1/Project-OSRM-Old,bitsteller/osrm-backend,frodrigo/osrm-backend,Conggge/osrm-backend,oxidase/osrm-backend,Carsten64/OSRM-aux-git,yuryleb/osrm-backend,tkhaxton/osrm-backend,hydrays/osrm-backend,raymond0/osrm-backend,agruss/osrm-backend,skyborla/osrm-backend,duizendnegen/osrm-backend,bjtaylor1/osrm-backend,antoinegiret/osrm-geovelo,KnockSoftware/osrm-backend,chaupow/osrm-backend,Tristramg/osrm-backend,deniskoronchik/osrm-backend,beemogmbh/osrm-backend,Project-OSRM/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,neilbu/osrm-backend,Carsten64/OSRM-aux-git
0c6d72796a186812850be3cab5322afd238151b4
paramset.hpp
paramset.hpp
/* paramset: A Parameter Management Utility for C++ https://github.com/tuem/paramset Copyright 2017 Takashi Uemura 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 __PARAMSET_HPP__ #define __PARAMSET_HPP__ #include <string> #include <vector> #include <map> #include <fstream> #include <sstream> #include "cmdline.h" #include "json.hpp" namespace paramset{ // internal representation of parameters struct parameter{ std::string value; parameter(){} parameter(const char* value): value(value){} parameter(const std::string& value): value(value){} template<typename T> parameter(const T& t): value(std::to_string(t)){} operator std::string() const{ return value; } operator int() const{ return std::stoi(value); } operator double() const{ return std::stod(value); } operator bool() const{ if(value.empty() || value == "0") return false; std::string lower; std::transform(std::begin(value), std::end(value), std::back_inserter(lower), ::tolower); return lower != "false"; } template<typename T> T as() const{ return static_cast<T>(*this); } template<typename T> parameter& operator=(const T& t){ value = parameter(t).value; return *this; } }; // parameter definitions struct definition{ std::string name; parameter default_value; std::vector<std::string> json_path; std::string long_option; char short_option; std::string description; bool required; definition(const std::string& name, const parameter& default_value): name(name), default_value(default_value){} definition(const std::string& name, const parameter& default_value, const std::vector<std::string>& json_path): name(name), default_value(default_value), json_path(json_path){} definition(const std::string& name, const parameter& default_value, const std::string& long_option, char short_option, const std::string& description, bool required = false): name(name), default_value(default_value), long_option(long_option), short_option(short_option), description(description), required(required){} definition(const std::string& name, const parameter& default_value, const std::vector<std::string>& json_path, const std::string& long_option, char short_option, const std::string& description, bool required = false): name(name), default_value(default_value), json_path(json_path), long_option(long_option), short_option(short_option), description(description), required(required){} }; using definitions = std::vector<definition>; // main class for managing parameters class manager{ const definitions defs; std::map<std::string, parameter> params; public: // command line arguments without option names std::vector<parameter> rest; manager(const definitions& defs): defs(defs){ for(const auto& def: defs) params[def.name] = def.default_value; } // load parameters from command line arguments and config file void load(int argc, char* argv[], const std::string conf_option = "", size_t min_unnamed_argc = 0){ // parse command line arguments cmdline::parser parser; for(const auto& def: defs) if(!def.long_option.empty()) parser.add(def.long_option, def.short_option, def.description, def.required, def.default_value.as<std::string>()); if(!parser.parse(argc, argv)) throw std::invalid_argument(parser.error_full() + parser.usage()); // overwrite parameters with config file if(!conf_option.empty() && parser.exist(conf_option)){ nlohmann::json json; std::ifstream(parser.get<std::string>(conf_option)) >> json; for(const auto& def: defs) if(!def.json_path.empty()) load_parameter_from_json(&json, def); } // overwrite parameters with command line arguments for(const auto& def: defs) if(!def.long_option.empty() && parser.exist(def.long_option)) params[def.name] = parser.get<std::string>(def.long_option); // store rest of command line arguments for(const auto& r: parser.rest()) rest.push_back(r); if(rest.size() < min_unnamed_argc) throw std::invalid_argument("requires " + std::to_string(min_unnamed_argc) + " unnamed option" + (min_unnamed_argc > 1 ? "s" : "") + '\n' + parser.usage()); } // returns parameter value parameter& operator[](const std::string& name){ return params[name]; } // returns parameter value as a specific type template<typename T> T get(const std::string& name) const{ return params.at(name).as<T>(); } private: // find def.json_path from json and overwrite params[def.name] if exists void load_parameter_from_json(const nlohmann::json* j, const definition& def){ for(auto i = std::begin(def.json_path); i != std::end(def.json_path); j = &(j->at(*i++))) if(j->count(*i) == 0) return; try{ params[def.name] = j->get<std::string>(); } catch(const std::exception&){ // if failed to get as string, convert non-string value to string params[def.name] = static_cast<std::stringstream&>(std::stringstream() << *j).str(); } } }; }; #endif
/* paramset: A Parameter Management Utility for C++ https://github.com/tuem/paramset Copyright 2017 Takashi Uemura 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 __PARAMSET_HPP__ #define __PARAMSET_HPP__ #include <string> #include <vector> #include <map> #include <fstream> #include <sstream> #include "cmdline.h" #include "json.hpp" namespace paramset{ // internal representation of parameters struct parameter{ std::string value; parameter(){} parameter(const char* value): value(value){} parameter(const std::string& value): value(value){} template<typename T> parameter(const T& t): value(std::to_string(t)){} operator std::string() const{ return value; } operator int() const{ return std::stoi(value); } operator double() const{ return std::stod(value); } operator bool() const{ if(value.empty() || value == "0") return false; std::string lower; std::transform(std::begin(value), std::end(value), std::back_inserter(lower), ::tolower); return lower != "false"; } template<typename T> T as() const{ return static_cast<T>(*this); } template<typename T> parameter& operator=(const T& t){ value = parameter(t).value; return *this; } }; // parameter definitions struct definition{ std::string name; parameter default_value; std::vector<std::string> json_path; std::string long_option; char short_option; std::string description; bool required; definition(const std::string& name, const parameter& default_value): name(name), default_value(default_value){} definition(const std::string& name, const parameter& default_value, const std::vector<std::string>& json_path): name(name), default_value(default_value), json_path(json_path){} definition(const std::string& name, const parameter& default_value, const std::string& long_option, char short_option, const std::string& description, bool required = false): name(name), default_value(default_value), long_option(long_option), short_option(short_option), description(description), required(required){} definition(const std::string& name, const parameter& default_value, const std::vector<std::string>& json_path, const std::string& long_option, char short_option, const std::string& description, bool required = false): name(name), default_value(default_value), json_path(json_path), long_option(long_option), short_option(short_option), description(description), required(required){} }; using definitions = std::vector<definition>; // main class for managing parameters class manager{ const definitions defs; std::map<std::string, parameter> params; public: // command line arguments without option names std::vector<parameter> rest; manager(const definitions& defs): defs(defs){ for(const auto& def: defs) params[def.name] = def.default_value; } // load parameters from command line arguments and config file void load(int argc, char* argv[], const std::string conf_option = "", size_t min_unnamed_argc = 0){ // parse command line arguments cmdline::parser parser; for(const auto& def: defs) if(!def.long_option.empty()) parser.add(def.long_option, def.short_option, def.description, def.required, def.default_value.as<std::string>()); if(!parser.parse(argc, argv)) throw std::invalid_argument(parser.error_full() + parser.usage()); // overwrite parameters with config file if(!conf_option.empty() && parser.exist(conf_option)){ nlohmann::json json; std::ifstream(parser.get<std::string>(conf_option)) >> json; for(const auto& def: defs) if(!def.json_path.empty()) load_parameter_from_json(&json, def); } // overwrite parameters with command line arguments for(const auto& def: defs) if(!def.long_option.empty() && parser.exist(def.long_option)) params[def.name] = parser.get<std::string>(def.long_option); // store rest of command line arguments for(const auto& r: parser.rest()) rest.push_back(r); if(rest.size() < min_unnamed_argc) throw std::invalid_argument("requires " + std::to_string(min_unnamed_argc) + " unnamed option" + (min_unnamed_argc > 1 ? "s" : "") + '\n' + parser.usage()); } // returns parameter value parameter& operator[](const std::string& name){ return params[name]; } // returns parameter value as a specific type template<typename T> T get(const std::string& name) const{ return params.at(name).as<T>(); } private: // find def.json_path from json and overwrite params[def.name] if exists void load_parameter_from_json(const nlohmann::json* j, const definition& def){ for(auto i = std::begin(def.json_path); i != std::end(def.json_path); j = &(j->at(*i++))) if(j->count(*i) == 0) return; try{ params[def.name] = j->get<std::string>(); } catch(const std::exception&){ // if failed to get as string, convert non-string value to string std::stringstream ss; ss << *j; params[def.name] = ss.str(); } } }; }; #endif
fix compilation error with clang
fix compilation error with clang
C++
apache-2.0
tuem/paramset
17d5a82102fd7ca11009465866eb3db1ccd0b7a6
code/rtkCudaForwardProjectionImageFilter.cxx
code/rtkCudaForwardProjectionImageFilter.cxx
/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkCudaForwardProjectionImageFilter.h" #include "rtkCudaUtilities.hcu" #include "rtkCudaForwardProjectionImageFilter.hcu" #include <itkImageRegionConstIterator.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkLinearInterpolateImageFunction.h> #include <itkMacro.h> namespace rtk { CudaForwardProjectionImageFilter ::CudaForwardProjectionImageFilter() { m_DeviceVolume = NULL; m_DeviceProjection = NULL; m_DeviceMatrix = NULL; } void CudaForwardProjectionImageFilter ::InitDevice() { // Dimension arguments in CUDA format for volume m_VolumeDimension[0] = this->GetInput(1)->GetRequestedRegion().GetSize()[0]; m_VolumeDimension[1] = this->GetInput(1)->GetRequestedRegion().GetSize()[1]; m_VolumeDimension[2] = this->GetInput(1)->GetRequestedRegion().GetSize()[2]; // Dimension arguments in CUDA format for projections m_ProjectionDimension[0] = this->GetInput(0)->GetRequestedRegion().GetSize()[0]; m_ProjectionDimension[1] = this->GetInput(0)->GetRequestedRegion().GetSize()[1]; // Cuda initialization std::vector<int> devices = GetListOfCudaDevices(); if(devices.size()>1) { cudaThreadExit(); cudaSetDevice(devices[0]); } const float *host_volume = this->GetInput(1)->GetBufferPointer(); CUDA_forward_project_init (m_ProjectionDimension, m_VolumeDimension, m_DeviceVolume, m_DeviceProjection, m_DeviceMatrix, host_volume); } void CudaForwardProjectionImageFilter ::CleanUpDevice() { if(this->GetOutput()->GetRequestedRegion() != this->GetOutput()->GetBufferedRegion() ) itkExceptionMacro(<< "Can't handle different requested and buffered regions " << this->GetOutput()->GetRequestedRegion() << this->GetOutput()->GetBufferedRegion() ); CUDA_forward_project_cleanup (m_ProjectionDimension, m_DeviceVolume, m_DeviceProjection, m_DeviceMatrix); m_DeviceVolume = NULL; m_DeviceProjection = NULL; m_DeviceMatrix = NULL; } void CudaForwardProjectionImageFilter ::GenerateData() { this->AllocateOutputs(); this->InitDevice(); const Superclass::GeometryType::Pointer geometry = this->GetGeometry(); const unsigned int Dimension = ImageType::ImageDimension; const unsigned int iFirstProj = this->GetInput(0)->GetRequestedRegion().GetIndex(Dimension-1); const unsigned int nProj = this->GetInput(0)->GetRequestedRegion().GetSize(Dimension-1); const unsigned int nPixelsPerProj = this->GetOutput()->GetBufferedRegion().GetSize(0) * this->GetOutput()->GetBufferedRegion().GetSize(1); float t_step = 1; // Step in mm int blockSize[3] = {16,16,1}; itk::Vector<double, 4> source_position; // Setting BoxMin and BoxMax // SR: we are using cuda textures where the pixel definition is not center but corner. // Therefore, we set the box limits from index to index+size instead of, for ITK, // index-0.5 to index+size-0.5. float boxMin[3]; float boxMax[3]; for(unsigned int i=0; i<3; i++) { boxMin[i] = this->GetInput(1)->GetBufferedRegion().GetIndex()[i]; boxMax[i] = boxMin[i] + this->GetInput(1)->GetBufferedRegion().GetSize()[i]; } // Getting Spacing float spacing[3]; for(unsigned int i=0; i<3; i++) spacing[i] = this->GetInput(1)->GetSpacing()[i]; // Go over each projection for(unsigned int iProj=iFirstProj; iProj<iFirstProj+nProj; iProj++) { // Account for system rotations Superclass::GeometryType::ThreeDHomogeneousMatrixType volPPToIndex; volPPToIndex = GetPhysicalPointToIndexMatrix( this->GetInput(1) ); // Adding 0.5 offset to change from the centered pixel convention (ITK) // to the corner pixel convention (CUDA). for(unsigned int i=0; i<3; i++) volPPToIndex[i][3]+=0.5; // Compute matrix to transform projection index to volume index Superclass::GeometryType::ThreeDHomogeneousMatrixType d_matrix; d_matrix = volPPToIndex.GetVnlMatrix() * geometry->GetProjectionCoordinatesToFixedSystemMatrix(iProj).GetVnlMatrix() * GetIndexToPhysicalPointMatrix( this->GetInput() ).GetVnlMatrix(); float matrix[4][4]; for (int j=0; j<4; j++) for (int k=0; k<4; k++) matrix[j][k] = (float)d_matrix[j][k]; // Set source position in volume indices source_position = volPPToIndex * geometry->GetSourcePosition(iProj); CUDA_forward_project(blockSize, this->GetOutput()->GetBufferPointer()+iProj*nPixelsPerProj, m_DeviceProjection, (double*)&(source_position[0]), m_ProjectionDimension, t_step, m_DeviceMatrix, (float*)&(matrix[0][0]), boxMin, boxMax, spacing); } this->CleanUpDevice(); } } // end namespace rtk
/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkCudaForwardProjectionImageFilter.h" #include "rtkCudaUtilities.hcu" #include "rtkCudaForwardProjectionImageFilter.hcu" #include <itkImageRegionConstIterator.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkLinearInterpolateImageFunction.h> #include <itkMacro.h> namespace rtk { CudaForwardProjectionImageFilter ::CudaForwardProjectionImageFilter() { m_DeviceVolume = NULL; m_DeviceProjection = NULL; m_DeviceMatrix = NULL; } void CudaForwardProjectionImageFilter ::InitDevice() { // Dimension arguments in CUDA format for volume m_VolumeDimension[0] = this->GetInput(1)->GetRequestedRegion().GetSize()[0]; m_VolumeDimension[1] = this->GetInput(1)->GetRequestedRegion().GetSize()[1]; m_VolumeDimension[2] = this->GetInput(1)->GetRequestedRegion().GetSize()[2]; // Dimension arguments in CUDA format for projections m_ProjectionDimension[0] = this->GetInput(0)->GetRequestedRegion().GetSize()[0]; m_ProjectionDimension[1] = this->GetInput(0)->GetRequestedRegion().GetSize()[1]; // Cuda initialization std::vector<int> devices = GetListOfCudaDevices(); if(devices.size()>1) { cudaThreadExit(); cudaSetDevice(devices[0]); } const float *host_volume = this->GetInput(1)->GetBufferPointer(); CUDA_forward_project_init (m_ProjectionDimension, m_VolumeDimension, m_DeviceVolume, m_DeviceProjection, m_DeviceMatrix, host_volume); } void CudaForwardProjectionImageFilter ::CleanUpDevice() { if(this->GetOutput()->GetRequestedRegion() != this->GetOutput()->GetBufferedRegion() ) itkExceptionMacro(<< "Can't handle different requested and buffered regions " << this->GetOutput()->GetRequestedRegion() << this->GetOutput()->GetBufferedRegion() ); CUDA_forward_project_cleanup (m_ProjectionDimension, m_DeviceVolume, m_DeviceProjection, m_DeviceMatrix); m_DeviceVolume = NULL; m_DeviceProjection = NULL; m_DeviceMatrix = NULL; } void CudaForwardProjectionImageFilter ::GenerateData() { this->AllocateOutputs(); this->InitDevice(); const Superclass::GeometryType::Pointer geometry = this->GetGeometry(); const unsigned int Dimension = ImageType::ImageDimension; const unsigned int iFirstProj = this->GetInput(0)->GetRequestedRegion().GetIndex(Dimension-1); const unsigned int nProj = this->GetInput(0)->GetRequestedRegion().GetSize(Dimension-1); const unsigned int nPixelsPerProj = this->GetOutput()->GetBufferedRegion().GetSize(0) * this->GetOutput()->GetBufferedRegion().GetSize(1); float t_step = 1; // Step in mm int blockSize[3] = {16,16,1}; itk::Vector<double, 4> source_position; // Setting BoxMin and BoxMax // SR: we are using cuda textures where the pixel definition is not center but corner. // Therefore, we set the box limits from index to index+size instead of, for ITK, // index-0.5 to index+size-0.5. float boxMin[3]; float boxMax[3]; for(unsigned int i=0; i<3; i++) { boxMin[i] = this->GetInput(1)->GetBufferedRegion().GetIndex()[i]; boxMax[i] = boxMin[i] + this->GetInput(1)->GetBufferedRegion().GetSize()[i]; } // Getting Spacing float spacing[3]; for(unsigned int i=0; i<3; i++) spacing[i] = this->GetInput(1)->GetSpacing()[i]; // Go over each projection for(unsigned int iProj=iFirstProj; iProj<iFirstProj+nProj; iProj++) { // Account for system rotations Superclass::GeometryType::ThreeDHomogeneousMatrixType volPPToIndex; volPPToIndex = GetPhysicalPointToIndexMatrix( this->GetInput(1) ); // Adding 0.5 offset to change from the centered pixel convention (ITK) // to the corner pixel convention (CUDA). for(unsigned int i=0; i<3; i++) volPPToIndex[i][3] += 0.5; // Compute matrix to transform projection index to volume index Superclass::GeometryType::ThreeDHomogeneousMatrixType d_matrix; d_matrix = volPPToIndex.GetVnlMatrix() * geometry->GetProjectionCoordinatesToFixedSystemMatrix(iProj).GetVnlMatrix() * GetIndexToPhysicalPointMatrix( this->GetInput() ).GetVnlMatrix(); float matrix[4][4]; for (int j=0; j<4; j++) for (int k=0; k<4; k++) matrix[j][k] = (float)d_matrix[j][k]; // Set source position in volume indices source_position = volPPToIndex * geometry->GetSourcePosition(iProj); CUDA_forward_project(blockSize, this->GetOutput()->GetBufferPointer()+iProj*nPixelsPerProj, m_DeviceProjection, (double*)&(source_position[0]), m_ProjectionDimension, t_step, m_DeviceMatrix, (float*)&(matrix[0][0]), boxMin, boxMax, spacing); } this->CleanUpDevice(); } } // end namespace rtk
Fix style
Fix style
C++
apache-2.0
ldqcarbon/RTK,ipsusila/RTK,dsarrut/RTK,fabienmomey/RTK,ipsusila/RTK,fabienmomey/RTK,fabienmomey/RTK,dsarrut/RTK,ipsusila/RTK,ldqcarbon/RTK,SimonRit/RTK,ldqcarbon/RTK,dsarrut/RTK,ipsusila/RTK,fabienmomey/RTK,SimonRit/RTK,SimonRit/RTK,ipsusila/RTK,SimonRit/RTK,ldqcarbon/RTK,dsarrut/RTK,fabienmomey/RTK,ldqcarbon/RTK,ldqcarbon/RTK,dsarrut/RTK,ipsusila/RTK,dsarrut/RTK,ldqcarbon/RTK,fabienmomey/RTK,dsarrut/RTK,fabienmomey/RTK,ipsusila/RTK
678a71414586ec0c1c9a3acbdf535ecdc2077ad3
Metafuck/Interpreter/ConvenienceFuck.cpp
Metafuck/Interpreter/ConvenienceFuck.cpp
#include "ConvenienceFuck.h" #include <iostream> #include <fstream> void BinaryInput::get(char& c) { if (front_) { c = data_.front(); data_.pop_front(); } else { c = data_.back(); data_.pop_back(); } } BinaryInput& BinaryInput::operator << (char c) { data_.push_back(c); return *this; } BinaryInput& BinaryInput::operator << (const char* str) { for (char const* c = str; *c != '\0'; ++c) { data_.push_back(*c); } return *this; } BinaryInput& BinaryInput::operator << (std::string str) { for (auto const& c : str) { data_.push_back(c); } return *this; } BinaryInput& BinaryInput::operator << (std::vector <char> data) { for (auto const& c : data) { data_.push_back(c); } return *this; } BinaryInput& BinaryInput::operator << (std::deque <char> data) { for (auto const& c : data) { data_.push_back(c); } return *this; } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, std::size_t memorySize) { return RunBrainfuckProgram<decltype(std::cin), decltype(std::cout)> (program, std::cin, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, std::stringstream& input, std::size_t memorySize) { return RunBrainfuckProgram<std::stringstream, decltype(std::cout)> (program, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, BinaryInput& input, std::size_t memorySize) { return RunBrainfuckProgram<BinaryInput, decltype(std::cout)> (program, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, std::string& input, std::size_t memorySize) { std::stringstream sstr; sstr << input; return RunBrainfuckProgram<std::stringstream, decltype(std::cout)> (program, sstr, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_NullOutput(std::string program, std::size_t memorySize) { NullOutput NullOut; return RunBrainfuckProgram<decltype(std::cin), NullOutput> (program, std::cin, NullOut, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_NullInput(std::string program, std::size_t memorySize) { NullInput NullIn; return RunBrainfuckProgram<NullInput, decltype(std::cout)> (program, NullIn, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_NullIO(std::string program, std::size_t memorySize) { NullOutput NullOut; NullInput NullIn; return RunBrainfuckProgram<NullInput, NullOutput> (program, NullIn, NullOut, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, std::size_t memorySize) { return RunBrainfuckProgram_FromFile<decltype(std::cin), decltype(std::cout)>(path, std::cin, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, std::string& input, std::size_t memorySize) { std::stringstream sstr; sstr << input; return RunBrainfuckProgram_FromFile<std::stringstream, decltype(std::cout)>(path, sstr, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, std::stringstream& input, std::size_t memorySize) { return RunBrainfuckProgram_FromFile<std::stringstream, decltype(std::cout)>(path, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, BinaryInput& input, std::size_t memorySize) { return RunBrainfuckProgram_FromFile<BinaryInput, decltype(std::cout)> (path, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile_NullInput(std::string path, std::size_t memorySize) { NullInput NullIn; return RunBrainfuckProgram_FromFile<NullInput, decltype(std::cout)> (path, NullIn, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile_NullOutput(std::string path, std::size_t memorySize) { NullOutput NullOut; return RunBrainfuckProgram_FromFile<decltype(std::cin), NullOutput> (path, std::cin, NullOut, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile_NullIO(std::string path, std::size_t memorySize) { NullOutput NullOut; NullInput NullIn; return RunBrainfuckProgram_FromFile<NullInput, NullOutput> (path, NullIn, NullOut, memorySize); }
#include "ConvenienceFuck.h" #include <iostream> #include <fstream> // test void BinaryInput::get(char& c) { if (front_) { c = data_.front(); data_.pop_front(); } else { c = data_.back(); data_.pop_back(); } } BinaryInput& BinaryInput::operator << (char c) { data_.push_back(c); return *this; } BinaryInput& BinaryInput::operator << (const char* str) { for (char const* c = str; *c != '\0'; ++c) { data_.push_back(*c); } return *this; } BinaryInput& BinaryInput::operator << (std::string str) { for (auto const& c : str) { data_.push_back(c); } return *this; } BinaryInput& BinaryInput::operator << (std::vector <char> data) { for (auto const& c : data) { data_.push_back(c); } return *this; } BinaryInput& BinaryInput::operator << (std::deque <char> data) { for (auto const& c : data) { data_.push_back(c); } return *this; } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, std::size_t memorySize) { return RunBrainfuckProgram<decltype(std::cin), decltype(std::cout)> (program, std::cin, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, std::stringstream& input, std::size_t memorySize) { return RunBrainfuckProgram<std::stringstream, decltype(std::cout)> (program, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, BinaryInput& input, std::size_t memorySize) { return RunBrainfuckProgram<BinaryInput, decltype(std::cout)> (program, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram(std::string program, std::string& input, std::size_t memorySize) { std::stringstream sstr; sstr << input; return RunBrainfuckProgram<std::stringstream, decltype(std::cout)> (program, sstr, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_NullOutput(std::string program, std::size_t memorySize) { NullOutput NullOut; return RunBrainfuckProgram<decltype(std::cin), NullOutput> (program, std::cin, NullOut, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_NullInput(std::string program, std::size_t memorySize) { NullInput NullIn; return RunBrainfuckProgram<NullInput, decltype(std::cout)> (program, NullIn, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_NullIO(std::string program, std::size_t memorySize) { NullOutput NullOut; NullInput NullIn; return RunBrainfuckProgram<NullInput, NullOutput> (program, NullIn, NullOut, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, std::size_t memorySize) { return RunBrainfuckProgram_FromFile<decltype(std::cin), decltype(std::cout)>(path, std::cin, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, std::string& input, std::size_t memorySize) { std::stringstream sstr; sstr << input; return RunBrainfuckProgram_FromFile<std::stringstream, decltype(std::cout)>(path, sstr, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, std::stringstream& input, std::size_t memorySize) { return RunBrainfuckProgram_FromFile<std::stringstream, decltype(std::cout)>(path, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile(std::string path, BinaryInput& input, std::size_t memorySize) { return RunBrainfuckProgram_FromFile<BinaryInput, decltype(std::cout)> (path, input, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile_NullInput(std::string path, std::size_t memorySize) { NullInput NullIn; return RunBrainfuckProgram_FromFile<NullInput, decltype(std::cout)> (path, NullIn, std::cout, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile_NullOutput(std::string path, std::size_t memorySize) { NullOutput NullOut; return RunBrainfuckProgram_FromFile<decltype(std::cin), NullOutput> (path, std::cin, NullOut, memorySize); } BrainfuckCompiler::CompilerErrorCode RunBrainfuckProgram_FromFile_NullIO(std::string path, std::size_t memorySize) { NullOutput NullOut; NullInput NullIn; return RunBrainfuckProgram_FromFile<NullInput, NullOutput> (path, NullIn, NullOut, memorySize); }
Test Commit 5cript
Test Commit 5cript
C++
mit
leMaik/Metafuck,leMaik/Metafuck
d4ee239aed58cc207ce3c1a5c9b48a287ec0ec15
src/CNewton.cpp
src/CNewton.cpp
/** * CNewton.cpp * Note: modified by Yongqun He from GepasiDoc class of the gepasi. * */ #include "CNewton.h" //default constructor CNewton::CNewton() { mModel = NULL; mNewtonLimit = DefaultNewtonLimit; mSs_nfunction=0; mSs_solution = 0; mSs_x = NULL; mSs_xnew = NULL; mSs_dxdt = NULL; mSs_h = NULL; mSs_jacob = NULL; mSs_ipvt = NULL; } // constructor CNewton::CNewton(C_INT32 anInt) { mModel = NULL; mNewtonLimit = anInt; mSs_nfunction = 0; mSs_solution = 0; initialize(); } //Y.H. //set up mSs_x and mSs_x's default values //they should come from steady state class, though void CNewton::init_Ss_x_new(void) { // we start with initial concentrations as the guess (modify from Gepasi) for( C_INT32 i=0; i<mModel->getTotMetab(); i++ ) // mSs_x[i+1] = mSs_xnew[i+1] = mModel->Metabolite[mModel.Row[i]].IConc * // mModel->Compartment[mModel.Metabolite[mModel.Row[i]].Compart].Volume; //YH mSs_x[i+1] = mSs_xnew[i+1] = mModel->getMetabolitesInd()[i]->getInitialNumber(); } // copy constructor CNewton::CNewton(const CNewton& source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } //Object assignment overloading CNewton& CNewton::operator=(const CNewton& source) { if(this != &source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } return *this; } //destructor CNewton::~CNewton() { cout << "~CNewton " << endl; } //set mModel void CNewton::setModel(CModel * aModel) { mModel = aModel; } //get mModel CModel * CNewton::getModel() const { return mModel; } // set mSSRes void CNewton::setSSRes(C_FLOAT64 aDouble) { mSSRes = aDouble; } //get mSSRes C_FLOAT64 CNewton::getSSRes() const { return mSSRes; } // get mSs_xnew C_FLOAT64 * CNewton::getSs_xnew() const { return mSs_xnew; } // get mSs_dxdt C_FLOAT64 * CNewton::getSs_dxdt() const { return mSs_dxdt; } // finds out if current state is a valid steady state C_INT32 CNewton::isSteadyState( void ) { int i; double maxrate; mSs_solution = SS_NOT_FOUND; for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) return SS_NOT_FOUND; //FEval( 0, 0, mSs_x, ss_dxdt ); mModel->lSODAEval( 0, 0, mSs_xnew, mSs_dxdt ); mSs_nfunction++; // maxrate = SS_XNorn( ss_dxdt ); maxrate = xNorm(mModel->getIntMetab(),mSs_dxdt, 1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; return mSs_solution; } // set mDerivFactor void CNewton::setDerivFactor(C_FLOAT64 aDouble) { mDerivFactor = aDouble; } // get mDerivFactor C_FLOAT64 CNewton::getDerivFactor() const { return mDerivFactor; } // set mSs_nfunction void CNewton::setSs_nfunction(C_INT32 aInt) { mSs_nfunction = aInt; } // get mDerivFactor C_INT32 CNewton::getSs_nfunction() const { return mSs_nfunction; } // initialize pointers void CNewton::initialize() { cleanup(); mSs_x = new double[mModel->getTotMetab()+1]; mSs_xnew = new double[mModel->getTotMetab()+1]; mSs_dxdt = new double[mModel->getTotMetab()+1]; mSs_h = new double[mModel->getTotMetab()+1]; mSs_ipvt = new C_INT32[mModel->getIndMetab()+1]; mSs_jacob = new double *[mModel->getTotMetab()+1]; for( int i=0; i<mModel->getTotMetab()+1; i++ ) mSs_jacob[i] = new double[mModel->getTotMetab()+1]; } //similar to SS_Newton() in gepasi except a few modification // void CNewton::process(void) { int i,j,k,l,m; C_FLOAT64 maxrate, nmaxrate; C_INT32 info; mSs_solution = SS_NOT_FOUND; //by Yongqun He //get the dimensions of the matrix int dim = mModel->getIndMetab(); // try // { // mModel->lSODAEval(0, 0, mSs_x, mSs_dxdt ); //changed by Yongqun He mModel->lSODAEval(dim, 0, mSs_x, mSs_dxdt ); mSs_nfunction++; maxrate =xNorm(mModel->getIntMetab(), mSs_dxdt,1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; if( mSs_solution == SS_FOUND ) { for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } } // } // finally // { //} if( mSs_solution==SS_FOUND ) return; for( k=0; k<mNewtonLimit; k++ ) { // try //{ JEval( mSs_x, mSs_jacob ); // LU decomposition of Jacobian dgefa( mSs_jacob, mModel->getIndMetab(), mSs_ipvt, &info); if( info!=0 ) { // jacobian is singular mSs_solution = SS_SINGULAR_JACOBIAN; return; } // solve mSs_jacob . x = mSs_h for x (result in mSs_dxdt) dgesl( mSs_jacob, mModel->getIndMetab(), mSs_ipvt, mSs_dxdt, 0 ); // } //finally //{ //} nmaxrate = maxrate * 1.001; // copy values of increment to mSs_h for(i=0;i<mModel->getIndMetab();i++) mSs_h[i+1] = mSs_dxdt[i+1]; for( i=0; (i<32) && (nmaxrate>maxrate) ; i++ ) { for( j=0; j<mModel->getIndMetab(); j++ ) { mSs_xnew[j+1] = mSs_x[j+1] - mSs_h[j+1]; mSs_h[j+1] /= 2; } mModel->setConcentrations(mSs_xnew); // update the dependent metabolites // try //{ //FEval( 0, 0, mSs_xnew, mSs_dxdt ); mModel->lSODAEval( 0, 0, mSs_xnew, mSs_dxdt ); mSs_nfunction++; nmaxrate = xNorm(mModel->getIntMetab(), mSs_dxdt,1); //} //finally //{ //} } if( i==32 ) { if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_DAMPING_LIMIT; return; } } for(i=0;i<mModel->getIntMetab();i++) mSs_x[i+1] = mSs_xnew[i+1]; maxrate = nmaxrate; } if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_ITERATION_LIMIT; return; } } // Clean up internal pointer variables void CNewton::cleanup(void) { if(mSs_jacob) delete [] mSs_jacob; mSs_jacob = NULL; mSs_x = NULL; mSs_xnew = NULL; mSs_dxdt = NULL; mSs_h = NULL; mSs_ipvt = NULL; } // evaluates the Jacobian matrix void CNewton::JEval( double *y, double **ydot ) { register int i, j; double store, temp, *f1, *f2; double K1, K2, K3; // constants for differentiation by finite differences K1 = 1 + mDerivFactor; K2 = 1 - mDerivFactor; K3 = 2 * mDerivFactor; // arrays to store function values f1 = new double[mModel->getIntMetab()+1]; f2 = new double[mModel->getIntMetab()+1]; // iterate over all metabolites for( i=1; i<mModel->getIndMetab()+1; i++ ) { // if y[i] is zero, the derivative will be calculated at a small // positive value (no point in considering negative values!). // let's stick with mSSRes*(1.0+mDerivFactor) store = y[i]; if( store < mSSRes ) temp = mSSRes*K1; else temp = store; y[i] = temp*K1; //FEval( 0, 0, y, f1 ); mModel->lSODAEval(0, 0, y, f1); mSs_nfunction++; y[i] = temp*K2; //FEval( 0, 0, y, f2 ); mModel->lSODAEval(0, 0, y, f2); mSs_nfunction++; for( j=1; j<mModel->getIndMetab()+1; j++ ) ydot[j][i] = (f1[j]-f2[j])/(temp*K3); y[i] = store; } delete [] f1; delete [] f2; //Yongqun He: no plan to count the JEval() yet. Maybe later. //ss_njacob++; }
/** * CNewton.cpp * Note: modified by Yongqun He from GepasiDoc class of the gepasi. * */ #include "CNewton.h" //default constructor CNewton::CNewton() { mModel = NULL; mNewtonLimit = DefaultNewtonLimit; mSs_nfunction=0; mSs_solution = 0; mSs_x = NULL; mSs_xnew = NULL; mSs_dxdt = NULL; mSs_h = NULL; mSs_jacob = NULL; mSs_ipvt = NULL; // initialize(); } // constructor CNewton::CNewton(C_INT32 anInt) { mModel = NULL; mNewtonLimit = anInt; mSs_nfunction = 0; mSs_solution = 0; //initialize(); } // copy constructor CNewton::CNewton(const CNewton& source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } // initialize pointers void CNewton::initialize() { cleanup(); mSs_x = new double[mModel->getTotMetab()+1]; mSs_xnew = new double[mModel->getTotMetab()+1]; mSs_dxdt = new double[mModel->getTotMetab()+1]; mSs_h = new double[mModel->getTotMetab()+1]; mSs_ipvt = new C_INT32[mModel->getIndMetab()+1]; mSs_jacob = new double *[mModel->getTotMetab()+1]; for( int i=0; i<mModel->getTotMetab()+1; i++ ) mSs_jacob[i] = new double[mModel->getTotMetab()+1]; } //Y.H. //set up mSs_x and mSs_x's default values //they should come from steady state class, though void CNewton::init_Ss_x_new(void) { // we start with initial concentrations as the guess (modify from Gepasi) for( int i=0; i<mModel->getTotMetab(); i++ ) // mSs_x[i+1] = mSs_xnew[i+1] = mModel->Metabolite[mModel.Row[i]].IConc * // mModel->Compartment[mModel.Metabolite[mModel.Row[i]].Compart].Volume; //YH { double tmp = mModel->getMetabolitesInd()[i]->getInitialNumber(); mSs_x[i+1] = tmp; mSs_xnew[i+1] = tmp; } } //Object assignment overloading CNewton& CNewton::operator=(const CNewton& source) { if(this != &source) { mModel = source.mModel; mNewtonLimit = source.mNewtonLimit; mSs_nfunction = source.mSs_nfunction; mSs_solution = source.mSs_solution; mSs_x = source.mSs_x; mSs_xnew = source.mSs_xnew; mSs_dxdt =source.mSs_dxdt; mSs_h = source.mSs_h; mSs_jacob = source.mSs_jacob; mSs_ipvt = source.mSs_ipvt; } return *this; } //destructor CNewton::~CNewton() { cout << "~CNewton " << endl; } //set mModel void CNewton::setModel(CModel * aModel) { mModel = aModel; } //get mModel CModel * CNewton::getModel() const { return mModel; } // set mSSRes void CNewton::setSSRes(C_FLOAT64 aDouble) { mSSRes = aDouble; } //get mSSRes C_FLOAT64 CNewton::getSSRes() const { return mSSRes; } // get mSs_xnew C_FLOAT64 * CNewton::getSs_xnew() const { return mSs_xnew; } // get mSs_dxdt C_FLOAT64 * CNewton::getSs_dxdt() const { return mSs_dxdt; } // set mDerivFactor void CNewton::setDerivFactor(C_FLOAT64 aDouble) { mDerivFactor = aDouble; } // get mDerivFactor C_FLOAT64 CNewton::getDerivFactor() const { return mDerivFactor; } // set mSs_nfunction void CNewton::setSs_nfunction(C_INT32 aInt) { mSs_nfunction = aInt; } // get mDerivFactor C_INT32 CNewton::getSs_nfunction() const { return mSs_nfunction; } // finds out if current state is a valid steady state C_INT32 CNewton::isSteadyState( void ) { int i; double maxrate; mSs_solution = SS_NOT_FOUND; for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) return SS_NOT_FOUND; //FEval( 0, 0, mSs_x, ss_dxdt ); mModel->lSODAEval( 0, 0, mSs_xnew, mSs_dxdt ); mSs_nfunction++; // maxrate = SS_XNorn( ss_dxdt ); maxrate = xNorm(mModel->getIntMetab(),mSs_dxdt, 1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; return mSs_solution; } //similar to SS_Newton() in gepasi except a few modification // void CNewton::process(void) { int i,j,k,l,m; C_FLOAT64 maxrate, nmaxrate; C_INT32 info; mSs_solution = SS_NOT_FOUND; //by Yongqun He //get the dimensions of the matrix int dim = mModel->getIndMetab(); // try // { // mModel->lSODAEval(0, 0, mSs_x, mSs_dxdt ); //changed by Yongqun He mModel->lSODAEval(dim, 0, mSs_x, mSs_dxdt ); mSs_nfunction++; maxrate =xNorm(mModel->getIntMetab(), mSs_dxdt,1); if( maxrate < mSSRes ) mSs_solution = SS_FOUND; if( mSs_solution == SS_FOUND ) { for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } } // } // finally // { //} if( mSs_solution==SS_FOUND ) return; for( k=0; k<mNewtonLimit; k++ ) { // try //{ JEval( mSs_x, mSs_jacob ); // LU decomposition of Jacobian dgefa( mSs_jacob, mModel->getIndMetab(), mSs_ipvt, &info); if( info!=0 ) { // jacobian is singular mSs_solution = SS_SINGULAR_JACOBIAN; return; } // solve mSs_jacob . x = mSs_h for x (result in mSs_dxdt) dgesl( mSs_jacob, mModel->getIndMetab(), mSs_ipvt, mSs_dxdt, 0 ); // } //finally //{ //} nmaxrate = maxrate * 1.001; // copy values of increment to mSs_h for(i=0;i<mModel->getIndMetab();i++) mSs_h[i+1] = mSs_dxdt[i+1]; for( i=0; (i<32) && (nmaxrate>maxrate) ; i++ ) { for( j=0; j<mModel->getIndMetab(); j++ ) { mSs_xnew[j+1] = mSs_x[j+1] - mSs_h[j+1]; mSs_h[j+1] /= 2; } mModel->setConcentrations(mSs_xnew); // update the dependent metabolites // try //{ //FEval( 0, 0, mSs_xnew, mSs_dxdt ); mModel->lSODAEval( 0, 0, mSs_xnew, mSs_dxdt ); mSs_nfunction++; nmaxrate = xNorm(mModel->getIntMetab(), mSs_dxdt,1); //} //finally //{ //} } if( i==32 ) { if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_DAMPING_LIMIT; return; } } for(i=0;i<mModel->getIntMetab();i++) mSs_x[i+1] = mSs_xnew[i+1]; maxrate = nmaxrate; } if( maxrate < mSSRes ) { mSs_solution = SS_FOUND; // check if solution is valid for( i=0; i<mModel->getIntMetab(); i++ ) if( mSs_x[i+1] < 0.0 ) { mSs_solution = SS_NOT_FOUND; break; } return; } else { mSs_solution = SS_ITERATION_LIMIT; return; } } // Clean up internal pointer variables void CNewton::cleanup(void) { if(mSs_jacob) delete [] mSs_jacob; mSs_jacob = NULL; mSs_x = NULL; mSs_xnew = NULL; mSs_dxdt = NULL; mSs_h = NULL; mSs_ipvt = NULL; } // evaluates the Jacobian matrix void CNewton::JEval( double *y, double **ydot ) { register int i, j; double store, temp, *f1, *f2; double K1, K2, K3; // constants for differentiation by finite differences K1 = 1 + mDerivFactor; K2 = 1 - mDerivFactor; K3 = 2 * mDerivFactor; // arrays to store function values f1 = new double[mModel->getIntMetab()+1]; f2 = new double[mModel->getIntMetab()+1]; // iterate over all metabolites for( i=1; i<mModel->getIndMetab()+1; i++ ) { // if y[i] is zero, the derivative will be calculated at a small // positive value (no point in considering negative values!). // let's stick with mSSRes*(1.0+mDerivFactor) store = y[i]; if( store < mSSRes ) temp = mSSRes*K1; else temp = store; y[i] = temp*K1; //FEval( 0, 0, y, f1 ); mModel->lSODAEval(0, 0, y, f1); mSs_nfunction++; y[i] = temp*K2; //FEval( 0, 0, y, f2 ); mModel->lSODAEval(0, 0, y, f2); mSs_nfunction++; for( j=1; j<mModel->getIndMetab()+1; j++ ) ydot[j][i] = (f1[j]-f2[j])/(temp*K3); y[i] = store; } delete [] f1; delete [] f2; //Yongqun He: no plan to count the JEval() yet. Maybe later. //ss_njacob++; }
fix bugs in init_x_new(), modify constructors
fix bugs in init_x_new(), modify constructors
C++
artistic-2.0
jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI
3c8870a1d81ebe8ffb250f11d2189fa708327da9
src/tests/perf_tests/ANGLEPerfTest.cpp
src/tests/perf_tests/ANGLEPerfTest.cpp
// // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "ANGLEPerfTest.h" #include "third_party/perf/perf_test.h" #include <iostream> #include <cassert> ANGLEPerfTest::ANGLEPerfTest(const std::string &name, const std::string &suffix) : mName(name), mSuffix(suffix), mRunning(false), mTimer(nullptr), mNumFrames(0) { mTimer = CreateTimer(); } ANGLEPerfTest::~ANGLEPerfTest() { SafeDelete(mTimer); } void ANGLEPerfTest::run() { mTimer->start(); double prevTime = 0.0; while (mRunning) { double elapsedTime = mTimer->getElapsedTime(); double deltaTime = elapsedTime - prevTime; ++mNumFrames; step(static_cast<float>(deltaTime), elapsedTime); if (!mRunning) { break; } prevTime = elapsedTime; } } void ANGLEPerfTest::printResult(const std::string &trace, double value, const std::string &units, bool important) const { perf_test::PrintResult(mName, mSuffix, trace, value, units, important); } void ANGLEPerfTest::printResult(const std::string &trace, size_t value, const std::string &units, bool important) const { perf_test::PrintResult(mName, mSuffix, trace, value, units, important); } void ANGLEPerfTest::SetUp() { mRunning = true; } void ANGLEPerfTest::TearDown() { printResult("score", static_cast<size_t>(mNumFrames), "frames", true); } std::string RenderTestParams::suffix() const { switch (requestedRenderer) { case EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE: return "_d3d11"; case EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE: return "_d3d9"; default: assert(0); return "_unk"; } } ANGLERenderTest::ANGLERenderTest(const std::string &name, const RenderTestParams &testParams) : ANGLEPerfTest(name, testParams.suffix()), mTestParams(testParams), mDrawIterations(10), mRunTimeSeconds(5.0), mEGLWindow(nullptr), mOSWindow(nullptr) { } ANGLERenderTest::~ANGLERenderTest() { SafeDelete(mOSWindow); SafeDelete(mEGLWindow); } void ANGLERenderTest::SetUp() { EGLPlatformParameters platformParams(mTestParams.requestedRenderer, EGL_DONT_CARE, EGL_DONT_CARE, mTestParams.deviceType); mOSWindow = CreateOSWindow(); mEGLWindow = new EGLWindow(mTestParams.widowWidth, mTestParams.windowHeight, mTestParams.glesMajorVersion, platformParams); mEGLWindow->setSwapInterval(0); if (!mOSWindow->initialize(mName, mEGLWindow->getWidth(), mEGLWindow->getHeight())) { FAIL() << "Failed initializing OSWindow"; return; } if (!mEGLWindow->initializeGL(mOSWindow)) { FAIL() << "Failed initializing EGLWindow"; return; } initializeBenchmark(); ANGLEPerfTest::SetUp(); } void ANGLERenderTest::TearDown() { ANGLEPerfTest::TearDown(); destroyBenchmark(); mEGLWindow->destroyGL(); mOSWindow->destroy(); } void ANGLERenderTest::step(float dt, double totalTime) { stepBenchmark(dt, totalTime); // Clear events that the application did not process from this frame Event event; while (popEvent(&event)) { // If the application did not catch a close event, close now if (event.Type == Event::EVENT_CLOSED) { mRunning = false; } } if (mRunning) { draw(); mEGLWindow->swap(); mOSWindow->messageLoop(); } } void ANGLERenderTest::draw() { if (mTimer->getElapsedTime() > mRunTimeSeconds) { mRunning = false; return; } ++mNumFrames; beginDrawBenchmark(); for (unsigned int iteration = 0; iteration < mDrawIterations; ++iteration) { drawBenchmark(); } endDrawBenchmark(); } bool ANGLERenderTest::popEvent(Event *event) { return mOSWindow->popEvent(event); } OSWindow *ANGLERenderTest::getWindow() { return mOSWindow; }
// // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "ANGLEPerfTest.h" #include "third_party/perf/perf_test.h" #include <iostream> #include <cassert> ANGLEPerfTest::ANGLEPerfTest(const std::string &name, const std::string &suffix) : mName(name), mSuffix(suffix), mRunning(false), mTimer(nullptr), mNumFrames(0) { mTimer = CreateTimer(); } ANGLEPerfTest::~ANGLEPerfTest() { SafeDelete(mTimer); } void ANGLEPerfTest::run() { mTimer->start(); double prevTime = 0.0; while (mRunning) { double elapsedTime = mTimer->getElapsedTime(); double deltaTime = elapsedTime - prevTime; ++mNumFrames; step(static_cast<float>(deltaTime), elapsedTime); if (!mRunning) { break; } prevTime = elapsedTime; } } void ANGLEPerfTest::printResult(const std::string &trace, double value, const std::string &units, bool important) const { perf_test::PrintResult(mName, mSuffix, trace, value, units, important); } void ANGLEPerfTest::printResult(const std::string &trace, size_t value, const std::string &units, bool important) const { perf_test::PrintResult(mName, mSuffix, trace, value, units, important); } void ANGLEPerfTest::SetUp() { mRunning = true; } void ANGLEPerfTest::TearDown() { printResult("score", static_cast<size_t>(mNumFrames), "score", true); } std::string RenderTestParams::suffix() const { switch (requestedRenderer) { case EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE: return "_d3d11"; case EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE: return "_d3d9"; default: assert(0); return "_unk"; } } ANGLERenderTest::ANGLERenderTest(const std::string &name, const RenderTestParams &testParams) : ANGLEPerfTest(name, testParams.suffix()), mTestParams(testParams), mDrawIterations(10), mRunTimeSeconds(5.0), mEGLWindow(nullptr), mOSWindow(nullptr) { } ANGLERenderTest::~ANGLERenderTest() { SafeDelete(mOSWindow); SafeDelete(mEGLWindow); } void ANGLERenderTest::SetUp() { EGLPlatformParameters platformParams(mTestParams.requestedRenderer, EGL_DONT_CARE, EGL_DONT_CARE, mTestParams.deviceType); mOSWindow = CreateOSWindow(); mEGLWindow = new EGLWindow(mTestParams.widowWidth, mTestParams.windowHeight, mTestParams.glesMajorVersion, platformParams); mEGLWindow->setSwapInterval(0); if (!mOSWindow->initialize(mName, mEGLWindow->getWidth(), mEGLWindow->getHeight())) { FAIL() << "Failed initializing OSWindow"; return; } if (!mEGLWindow->initializeGL(mOSWindow)) { FAIL() << "Failed initializing EGLWindow"; return; } initializeBenchmark(); ANGLEPerfTest::SetUp(); } void ANGLERenderTest::TearDown() { ANGLEPerfTest::TearDown(); destroyBenchmark(); mEGLWindow->destroyGL(); mOSWindow->destroy(); } void ANGLERenderTest::step(float dt, double totalTime) { stepBenchmark(dt, totalTime); // Clear events that the application did not process from this frame Event event; while (popEvent(&event)) { // If the application did not catch a close event, close now if (event.Type == Event::EVENT_CLOSED) { mRunning = false; } } if (mRunning) { draw(); mEGLWindow->swap(); mOSWindow->messageLoop(); } } void ANGLERenderTest::draw() { if (mTimer->getElapsedTime() > mRunTimeSeconds) { mRunning = false; return; } ++mNumFrames; beginDrawBenchmark(); for (unsigned int iteration = 0; iteration < mDrawIterations; ++iteration) { drawBenchmark(); } endDrawBenchmark(); } bool ANGLERenderTest::popEvent(Event *event) { return mOSWindow->popEvent(event); } OSWindow *ANGLERenderTest::getWindow() { return mOSWindow; }
Use 'score' units.
perf_tests: Use 'score' units. The dashboard automatically marks 'frames' as 'lower is better', while 'score' is automatically marked as 'higher is better'. Hence, use score instead of frames. BUG=468852 Change-Id: I02b3a9e4b74989793d4bfbf21a94e43670b3e028 Reviewed-on: https://chromium-review.googlesource.com/266522 Tested-by: Jamie Madill <[email protected]> Reviewed-by: Geoff Lang <[email protected]>
C++
bsd-3-clause
csa7mdm/angle,crezefire/angle,mybios/angle,larsbergstrom/angle,crezefire/angle,bsergean/angle,mybios/angle,csa7mdm/angle,domokit/waterfall,ppy/angle,mrobinson/rust-angle,ghostoy/angle,MSOpenTech/angle,mlfarrell/angle,mybios/angle,ghostoy/angle,crezefire/angle,vvuk/angle,mikolalysenko/angle,MSOpenTech/angle,csa7mdm/angle,ecoal95/angle,mybios/angle,vvuk/angle,MSOpenTech/angle,ppy/angle,mikolalysenko/angle,ppy/angle,bsergean/angle,bsergean/angle,mlfarrell/angle,mlfarrell/angle,mrobinson/rust-angle,MSOpenTech/angle,mikolalysenko/angle,ecoal95/angle,ecoal95/angle,mrobinson/rust-angle,mrobinson/rust-angle,ecoal95/angle,domokit/waterfall,ppy/angle,mikolalysenko/angle,vvuk/angle,ecoal95/angle,mrobinson/rust-angle,larsbergstrom/angle,mlfarrell/angle,crezefire/angle,larsbergstrom/angle,csa7mdm/angle,larsbergstrom/angle,ghostoy/angle,vvuk/angle,ghostoy/angle,bsergean/angle
0d8deae65ed07b4a89d5a6b4a9f04201db07809a
qmljs_value.cpp
qmljs_value.cpp
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the V4VM module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qmljs_engine.h> #include <qmljs_objects.h> #include <qv4ecmaobjects_p.h> namespace QQmlJS { namespace VM { int Value::toUInt16(ExecutionContext *ctx) { return __qmljs_to_uint16(*this, ctx); } Bool Value::toBoolean(ExecutionContext *ctx) const { return __qmljs_to_boolean(*this, ctx); } double Value::toInteger(ExecutionContext *ctx) const { return __qmljs_to_integer(*this, ctx); } double Value::toNumber(ExecutionContext *ctx) const { return __qmljs_to_number(*this, ctx); } String *Value::toString(ExecutionContext *ctx) const { Value v = __qmljs_to_string(*this, ctx); assert(v.isString()); return v.stringValue(); } Value Value::toObject(ExecutionContext *ctx) const { return __qmljs_to_object(*this, ctx); } bool Value::sameValue(Value other) { if (val == other.val) return true; if (isString() && other.isString()) return stringValue()->isEqualTo(other.stringValue()); return false; } Value Value::fromString(ExecutionContext *ctx, const QString &s) { return fromString(ctx->engine->newString(s)); } int Value::toInt32(double number) { const double D32 = 4294967296.0; const double D31 = D32 / 2.0; if ((number >= -D31 && number < D31)) return static_cast<int>(number); if (!std::isfinite(number)) return 0; double d = ::floor(::fabs(number)); if (std::signbit(number)) d = -d; number = ::fmod(d , D32); if (number < -D31) number += D32; else if (number >= D31) number -= D32; return int(number); } unsigned int Value::toUInt32(double number) { const double D32 = 4294967296.0; if ((number >= 0 && number < D32)) return static_cast<uint>(number); if (!std::isfinite(number)) return +0; double d = ::floor(::fabs(number)); if (std::signbit(number)) d = -d; number = ::fmod(d , D32); if (number < 0) number += D32; return unsigned(number); } double Value::toInteger(double number) { if (std::isnan(number)) return +0; else if (! number || std::isinf(number)) return number; const double v = floor(fabs(number)); return std::signbit(number) ? -v : v; } Object *Value::asObject() const { return isObject() ? objectValue() : 0; } FunctionObject *Value::asFunctionObject() const { return isObject() ? objectValue()->asFunctionObject() : 0; } BooleanObject *Value::asBooleanObject() const { return isObject() ? objectValue()->asBooleanObject() : 0; } NumberObject *Value::asNumberObject() const { return isObject() ? objectValue()->asNumberObject() : 0; } StringObject *Value::asStringObject() const { return isObject() ? objectValue()->asStringObject() : 0; } DateObject *Value::asDateObject() const { return isObject() ? objectValue()->asDateObject() : 0; } RegExpObject *Value::asRegExpObject() const { return isObject() ? objectValue()->asRegExpObject() : 0; } ArrayObject *Value::asArrayObject() const { return isObject() ? objectValue()->asArrayObject() : 0; } ErrorObject *Value::asErrorObject() const { return isObject() ? objectValue()->asErrorObject() : 0; } Value Value::property(ExecutionContext *ctx, String *name) const { return isObject() ? objectValue()->__get__(ctx, name) : undefinedValue(); } } // namespace VM } // namespace QQmlJS
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the V4VM module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qmljs_engine.h> #include <qmljs_objects.h> #include <qv4ecmaobjects_p.h> namespace QQmlJS { namespace VM { int Value::toUInt16(ExecutionContext *ctx) { return __qmljs_to_uint16(*this, ctx); } Bool Value::toBoolean(ExecutionContext *ctx) const { return __qmljs_to_boolean(*this, ctx); } double Value::toInteger(ExecutionContext *ctx) const { return __qmljs_to_integer(*this, ctx); } double Value::toNumber(ExecutionContext *ctx) const { return __qmljs_to_number(*this, ctx); } String *Value::toString(ExecutionContext *ctx) const { Value v = __qmljs_to_string(*this, ctx); assert(v.isString()); return v.stringValue(); } Value Value::toObject(ExecutionContext *ctx) const { return __qmljs_to_object(*this, ctx); } bool Value::sameValue(Value other) { if (val == other.val) return true; if (isString() && other.isString()) return stringValue()->isEqualTo(other.stringValue()); if (isInteger() && int_32 == 0 && other.dbl == 0) return true; if (dbl == 0 && other.isInteger() && other.int_32 == 0) return true; return false; } Value Value::fromString(ExecutionContext *ctx, const QString &s) { return fromString(ctx->engine->newString(s)); } int Value::toInt32(double number) { const double D32 = 4294967296.0; const double D31 = D32 / 2.0; if ((number >= -D31 && number < D31)) return static_cast<int>(number); if (!std::isfinite(number)) return 0; double d = ::floor(::fabs(number)); if (std::signbit(number)) d = -d; number = ::fmod(d , D32); if (number < -D31) number += D32; else if (number >= D31) number -= D32; return int(number); } unsigned int Value::toUInt32(double number) { const double D32 = 4294967296.0; if ((number >= 0 && number < D32)) return static_cast<uint>(number); if (!std::isfinite(number)) return +0; double d = ::floor(::fabs(number)); if (std::signbit(number)) d = -d; number = ::fmod(d , D32); if (number < 0) number += D32; return unsigned(number); } double Value::toInteger(double number) { if (std::isnan(number)) return +0; else if (! number || std::isinf(number)) return number; const double v = floor(fabs(number)); return std::signbit(number) ? -v : v; } Object *Value::asObject() const { return isObject() ? objectValue() : 0; } FunctionObject *Value::asFunctionObject() const { return isObject() ? objectValue()->asFunctionObject() : 0; } BooleanObject *Value::asBooleanObject() const { return isObject() ? objectValue()->asBooleanObject() : 0; } NumberObject *Value::asNumberObject() const { return isObject() ? objectValue()->asNumberObject() : 0; } StringObject *Value::asStringObject() const { return isObject() ? objectValue()->asStringObject() : 0; } DateObject *Value::asDateObject() const { return isObject() ? objectValue()->asDateObject() : 0; } RegExpObject *Value::asRegExpObject() const { return isObject() ? objectValue()->asRegExpObject() : 0; } ArrayObject *Value::asArrayObject() const { return isObject() ? objectValue()->asArrayObject() : 0; } ErrorObject *Value::asErrorObject() const { return isObject() ? objectValue()->asErrorObject() : 0; } Value Value::property(ExecutionContext *ctx, String *name) const { return isObject() ? objectValue()->__get__(ctx, name) : undefinedValue(); } } // namespace VM } // namespace QQmlJS
Fix sameValue() for integer vs double 0
Fix sameValue() for integer vs double 0 Change-Id: Id56699a3e3624c644b14c6ece847a91da0ea7004 Reviewed-by: Simon Hausmann <[email protected]>
C++
lgpl-2.1
mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,qmlc/qtdeclarative,qmlc/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,qmlc/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d
dde900e8a350db4baeb6b0ffb3bb65672fbc5e31
qterm/qterm.cpp
qterm/qterm.cpp
#include <QPainter> #include <QAbstractEventDispatcher> #include <QApplication> #include <QPaintEvent> #include <QFontMetrics> #include <qterm.h> #include <stdio.h> #include <QKeyEvent> #include <QTimer> #include <sys/select.h> #include <errno.h> #ifdef __QNX__ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <bbsupport/Keyboard> #include <bbsupport/Notification> #endif #define WIDTH 80 #define HEIGHT 17 #define BLINK_SPEED 1000 QTerm::QTerm(QWidget *parent) : QWidget(parent) { term_create( &terminal ); term_begin( terminal, WIDTH, HEIGHT, 0 ); init(); } QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent) { this->terminal = terminal; init(); } void QTerm::init() { char_width = 0; char_height = 0; cursor_x = -1; cursor_y = -1; cursor_on = 1; resize(1024, 600); term_set_user_data( terminal, this ); term_register_update( terminal, term_update ); term_register_cursor( terminal, term_update_cursor ); term_register_bell( terminal, term_bell ); notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read ); exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception ); cursor_timer = new QTimer( this ); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data())); QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate())); QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor())); #ifdef __QNX__ BlackBerry::Keyboard::instance().show(); #endif cursor_timer->start(BLINK_SPEED); } QTerm::~QTerm() { delete notifier; delete exit_notifier; term_free( terminal ); } void QTerm::term_bell(term_t handle) { #ifdef __QNX__ char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}"; int f = open("/pps/services/multimedia/sound/control", O_RDWR); write(f, command, sizeof(command)); ::close(f); #else QApplication::beep(); #endif } void QTerm::term_update(term_t handle, int x, int y, int width, int height) { QTerm *term = (QTerm *)term_get_user_data( handle ); term->update( x * term->char_width, y * term->char_height, width * term->char_width, height * term->char_height + term->char_descent ); } void QTerm::term_update_cursor(term_t handle, int x, int y) { QTerm *term = (QTerm *)term_get_user_data( handle ); // Update old cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); term->cursor_x = x; term->cursor_y = y; // Update new cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); } void QTerm::terminal_data() { if( !term_process_child( terminal ) ) { exit(0); } } void QTerm::terminate() { exit(0); } void QTerm::blink_cursor() { cursor_on ^= 1; update( cursor_x * char_width, cursor_y * char_height, char_width, char_height ); } void QTerm::paintEvent(QPaintEvent *event) { int i, j, color; int new_width; int new_height; const uint32_t **grid; const uint32_t **attribs; const uint32_t **colors; QPainter painter(this); QFont font; font.setStyleHint(QFont::TypeWriter); font.setFamily("Monospace"); font.setFixedPitch(true); font.setKerning(false); painter.setBackgroundMode(Qt::TransparentMode); painter.setBrush(QColor(8, 0, 0)); painter.setFont(font); // First erase the grid with its current dimensions painter.drawRect(event->rect()); new_width = painter.fontMetrics().maxWidth(); // Workaround for a bug in OSX - Dave reports that maxWidth returns 0, // when width of different characters returns the correct value if( new_width == 0 ) { new_width = painter.fontMetrics().width(QChar('X')); } new_height = painter.fontMetrics().lineSpacing(); if( char_width != new_width || char_height != new_height ) { char_width = new_width; char_height = new_height; char_descent = painter.fontMetrics().descent(); #ifdef __QNX__ { int kbd_height; virtualkeyboard_get_height( &kbd_height ); term_resize( terminal, contentsRect().width() / char_width, (contentsRect().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, contentsRect().width() / char_width, contentsRect().height() / char_height, 0 ); #endif update( contentsRect() ); return; } painter.setPen(QColor(255, 255, 255)); painter.setBrush(QColor(255, 255, 255)); grid = term_get_grid( terminal ); attribs = term_get_attribs( terminal ); colors = term_get_colours( terminal ); for( i = 0; i < term_get_height( terminal ); i ++ ) { for( j = 0; j < term_get_width( terminal ); j ++ ) { if( cursor_on && j == cursor_x && i == cursor_y ) { painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2); painter.setPen(QColor(0, 0, 0)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); painter.setPen(QColor(255, 255, 255)); } else { color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] ); painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); } } } } void QTerm::keyPressEvent(QKeyEvent *event) { switch(event->key()) { // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed case Qt::Key_CapsLock: case Qt::Key_Shift: break; case Qt::Key_Up: term_send_special( terminal, TERM_KEY_UP ); break; case Qt::Key_Down: term_send_special( terminal, TERM_KEY_DOWN ); break; case Qt::Key_Right: term_send_special( terminal, TERM_KEY_RIGHT ); break; case Qt::Key_Left: term_send_special( terminal, TERM_KEY_LEFT ); break; default: term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() ); break; } } void QTerm::resizeEvent(QResizeEvent *event) { if( char_width != 0 && char_height != 0 ) { #ifdef __QNX__ { int kbd_height; virtualkeyboard_get_height( &kbd_height ); term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 ); #endif } } int main(int argc, char *argv[]) { term_t terminal; if( !term_create( &terminal ) ) { fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) ); exit(1); } if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) { fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) ); exit(1); } { QCoreApplication::addLibraryPath("app/native/lib"); QApplication app(argc, argv); QTerm term(NULL, terminal); term.show(); return app.exec(); } }
#include <QPainter> #include <QAbstractEventDispatcher> #include <QApplication> #include <QPaintEvent> #include <QFontMetrics> #include <qterm.h> #include <stdio.h> #include <QKeyEvent> #include <QTimer> #include <sys/select.h> #include <errno.h> #ifdef __QNX__ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <bbsupport/Keyboard> #include <bbsupport/Notification> #endif #define WIDTH 80 #define HEIGHT 17 #define BLINK_SPEED 1000 QTerm::QTerm(QWidget *parent) : QWidget(parent) { term_create( &terminal ); term_begin( terminal, WIDTH, HEIGHT, 0 ); init(); } QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent) { this->terminal = terminal; init(); } void QTerm::init() { char_width = 0; char_height = 0; cursor_x = -1; cursor_y = -1; cursor_on = 1; resize(1024, 600); term_set_user_data( terminal, this ); term_register_update( terminal, term_update ); term_register_cursor( terminal, term_update_cursor ); term_register_bell( terminal, term_bell ); notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read ); exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception ); cursor_timer = new QTimer( this ); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data())); QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate())); QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor())); #ifdef __QNX__ BlackBerry::Keyboard::instance().show(); #endif cursor_timer->start(BLINK_SPEED); } QTerm::~QTerm() { delete notifier; delete exit_notifier; term_free( terminal ); } void QTerm::term_bell(term_t handle) { #ifdef __QNX__ char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}"; int f = open("/pps/services/multimedia/sound/control", O_RDWR); write(f, command, sizeof(command)); ::close(f); #else QApplication::beep(); #endif } void QTerm::term_update(term_t handle, int x, int y, int width, int height) { QTerm *term = (QTerm *)term_get_user_data( handle ); term->update( x * term->char_width, y * term->char_height, width * term->char_width, height * term->char_height + term->char_descent ); } void QTerm::term_update_cursor(term_t handle, int x, int y) { QTerm *term = (QTerm *)term_get_user_data( handle ); // Update old cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); term->cursor_x = x; term->cursor_y = y; // Update new cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); } void QTerm::terminal_data() { if( !term_process_child( terminal ) ) { exit(0); } } void QTerm::terminate() { exit(0); } void QTerm::blink_cursor() { cursor_on ^= 1; update( cursor_x * char_width, cursor_y * char_height, char_width, char_height ); } void QTerm::paintEvent(QPaintEvent *event) { int i, j, color; int new_width; int new_height; const uint32_t **grid; const uint32_t **attribs; const uint32_t **colors; QPainter painter(this); QFont font; font.setStyleHint(QFont::TypeWriter); font.setFamily("Monospace"); font.setFixedPitch(true); font.setKerning(false); painter.setBackgroundMode(Qt::TransparentMode); painter.setBrush(QColor(8, 0, 0)); painter.setFont(font); // First erase the grid with its current dimensions painter.drawRect(event->rect()); new_width = painter.fontMetrics().maxWidth(); // Workaround for a bug in OSX - Dave reports that maxWidth returns 0, // when width of different characters returns the correct value if( new_width == 0 ) { new_width = painter.fontMetrics().width(QChar('X')); } new_height = painter.fontMetrics().lineSpacing(); if( char_width != new_width || char_height != new_height ) { char_width = new_width; char_height = new_height; char_descent = painter.fontMetrics().descent(); #ifdef __QNX__ { int kbd_height; kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); term_resize( terminal, contentsRect().width() / char_width, (contentsRect().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, contentsRect().width() / char_width, contentsRect().height() / char_height, 0 ); #endif update( contentsRect() ); return; } painter.setPen(QColor(255, 255, 255)); painter.setBrush(QColor(255, 255, 255)); grid = term_get_grid( terminal ); attribs = term_get_attribs( terminal ); colors = term_get_colours( terminal ); for( i = 0; i < term_get_height( terminal ); i ++ ) { for( j = 0; j < term_get_width( terminal ); j ++ ) { if( cursor_on && j == cursor_x && i == cursor_y ) { painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2); painter.setPen(QColor(0, 0, 0)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); painter.setPen(QColor(255, 255, 255)); } else { color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] ); painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); } } } } void QTerm::keyPressEvent(QKeyEvent *event) { switch(event->key()) { // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed case Qt::Key_CapsLock: case Qt::Key_Shift: break; case Qt::Key_Up: term_send_special( terminal, TERM_KEY_UP ); break; case Qt::Key_Down: term_send_special( terminal, TERM_KEY_DOWN ); break; case Qt::Key_Right: term_send_special( terminal, TERM_KEY_RIGHT ); break; case Qt::Key_Left: term_send_special( terminal, TERM_KEY_LEFT ); break; default: term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() ); break; } } void QTerm::resizeEvent(QResizeEvent *event) { if( char_width != 0 && char_height != 0 ) { #ifdef __QNX__ { int kbd_height; kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 ); #endif } } int main(int argc, char *argv[]) { term_t terminal; if( !term_create( &terminal ) ) { fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) ); exit(1); } if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) { fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) ); exit(1); } { QCoreApplication::addLibraryPath("app/native/lib"); QApplication app(argc, argv); QTerm term(NULL, terminal); term.show(); return app.exec(); } }
Subtract keyboard size in the way appropriate to bbndk1.0
Subtract keyboard size in the way appropriate to bbndk1.0
C++
apache-2.0
absmall/libterm,absmall/libterm
64d0563872b7727b1e61fa56c72b1df510304edb
Runtime/World/CTeamAiMgr.hpp
Runtime/World/CTeamAiMgr.hpp
#pragma once #include "Runtime/RetroTypes.hpp" #include "Runtime/World/CEntity.hpp" #include <zeus/CVector3f.hpp> namespace urde { class CStateManager; class CAi; class CTeamAiRole { friend class CTeamAiMgr; public: enum class ETeamAiRole { Invalid = -1, Initial, Melee, Ranged, Unknown, Unassigned }; private: TUniqueId x0_ownerId; ETeamAiRole x4_roleA = ETeamAiRole::Invalid; ETeamAiRole x8_roleB = ETeamAiRole::Invalid; ETeamAiRole xc_roleC = ETeamAiRole::Invalid; ETeamAiRole x10_curRole = ETeamAiRole::Invalid; s32 x14_roleIndex = -1; s32 x18_captainPriority = 0; zeus::CVector3f x1c_position; public: CTeamAiRole(TUniqueId ownerId, ETeamAiRole a, ETeamAiRole b, ETeamAiRole c) : x0_ownerId(ownerId), x4_roleA(a), x8_roleB(b), xc_roleC(c) {} TUniqueId GetOwnerId() const { return x0_ownerId; } bool HasTeamAiRole() const { return false; } ETeamAiRole GetTeamAiRole() const { return x10_curRole; } void SetTeamAiRole(ETeamAiRole role) { x10_curRole = role; } s32 GetRoleIndex() const { return x14_roleIndex; } void SetRoleIndex(s32 idx) { x14_roleIndex = idx; } const zeus::CVector3f& GetTeamPosition() const { return x1c_position; } void SetTeamPosition(const zeus::CVector3f& pos) { x1c_position = pos; } bool operator<(const CTeamAiRole& other) const { return x0_ownerId < other.x0_ownerId; } }; class CTeamAiData { friend class CTeamAiMgr; u32 x0_aiCount; u32 x4_meleeCount; u32 x8_rangedCount; u32 xc_unknownCount; u32 x10_maxMeleeAttackerCount; u32 x14_maxRangedAttackerCount; u32 x18_positionMode; float x1c_meleeTimeInterval; float x20_rangedTimeInterval; public: CTeamAiData(CInputStream& in, s32 propCount); }; class CTeamAiMgr : public CEntity { public: enum class EAttackType { Melee, Ranged }; private: CTeamAiData x34_data; std::vector<CTeamAiRole> x58_roles; std::vector<TUniqueId> x68_meleeAttackers; std::vector<TUniqueId> x78_rangedAttackers; float x88_timeDirty = 0.f; TUniqueId x8c_teamCaptainId = kInvalidUniqueId; float x90_timeSinceMelee; float x94_timeSinceRanged; void UpdateTeamCaptain(); bool ShouldUpdateRoles(float dt); void ResetRoles(CStateManager& mgr); void AssignRoles(CTeamAiRole::ETeamAiRole role, s32 count); void UpdateRoles(CStateManager& mgr); void SpacingSort(CStateManager& mgr, const zeus::CVector3f& pos); void PositionTeam(CStateManager& mgr); public: CTeamAiMgr(TUniqueId uid, std::string_view name, const CEntityInfo& info, const CTeamAiData& data); void Accept(IVisitor&) override; void Think(float dt, CStateManager& mgr) override; void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) override; CTeamAiRole* GetTeamAiRole(TUniqueId aiId); bool IsPartOfTeam(TUniqueId aiId) const; bool HasTeamAiRole(TUniqueId aiId) const; bool AssignTeamAiRole(const CAi& ai, CTeamAiRole::ETeamAiRole roleA, CTeamAiRole::ETeamAiRole roleB, CTeamAiRole::ETeamAiRole roleC); void RemoveTeamAiRole(TUniqueId aiId); void ClearTeamAiRole(TUniqueId aiId); s32 GetNumAssignedOfRole(CTeamAiRole::ETeamAiRole role) const; s32 GetNumAssignedAiRoles() const; bool IsMeleeAttacker(TUniqueId aiId) const; bool CanAcceptMeleeAttacker(TUniqueId aiId) const; bool AddMeleeAttacker(TUniqueId aiId); void RemoveMeleeAttacker(TUniqueId aiId); bool IsRangedAttacker(TUniqueId aiId) const; bool CanAcceptRangedAttacker(TUniqueId aiId) const; bool AddRangedAttacker(TUniqueId aiId); void RemoveRangedAttacker(TUniqueId aiId); bool HasMeleeAttackers() const { return !x68_meleeAttackers.empty(); } bool HasRangedAttackers() const { return !x78_rangedAttackers.empty(); } s32 GetNumRoles() const { return x58_roles.size(); } const std::vector<CTeamAiRole>& GetRoles() const { return x58_roles; } s32 GetMaxMeleeAttackerCount() const { return x34_data.x10_maxMeleeAttackerCount; } s32 GetMaxRangedAttackerCount() const { return x34_data.x14_maxRangedAttackerCount; } static CTeamAiRole* GetTeamAiRole(CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId); static void ResetTeamAiRole(EAttackType type, CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId, bool clearRole); static bool CanAcceptAttacker(EAttackType type, CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId); static bool AddAttacker(EAttackType type, CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId); static TUniqueId GetTeamAiMgr(CAi& ai, CStateManager& mgr); }; } // namespace urde
#pragma once #include "Runtime/RetroTypes.hpp" #include "Runtime/World/CEntity.hpp" #include <zeus/CVector3f.hpp> namespace urde { class CStateManager; class CAi; class CTeamAiRole { friend class CTeamAiMgr; public: enum class ETeamAiRole { Invalid = -1, Initial, Melee, Ranged, Unknown, Unassigned }; private: TUniqueId x0_ownerId; ETeamAiRole x4_roleA = ETeamAiRole::Invalid; ETeamAiRole x8_roleB = ETeamAiRole::Invalid; ETeamAiRole xc_roleC = ETeamAiRole::Invalid; ETeamAiRole x10_curRole = ETeamAiRole::Invalid; s32 x14_roleIndex = -1; s32 x18_captainPriority = 0; zeus::CVector3f x1c_position; public: CTeamAiRole(TUniqueId ownerId, ETeamAiRole a, ETeamAiRole b, ETeamAiRole c) : x0_ownerId(ownerId), x4_roleA(a), x8_roleB(b), xc_roleC(c) {} TUniqueId GetOwnerId() const { return x0_ownerId; } bool HasTeamAiRole() const { return false; } ETeamAiRole GetTeamAiRole() const { return x10_curRole; } void SetTeamAiRole(ETeamAiRole role) { x10_curRole = role; } s32 GetRoleIndex() const { return x14_roleIndex; } void SetRoleIndex(s32 idx) { x14_roleIndex = idx; } const zeus::CVector3f& GetTeamPosition() const { return x1c_position; } void SetTeamPosition(const zeus::CVector3f& pos) { x1c_position = pos; } bool operator<(const CTeamAiRole& other) const { return x0_ownerId < other.x0_ownerId; } }; class CTeamAiData { friend class CTeamAiMgr; u32 x0_aiCount; u32 x4_meleeCount; u32 x8_rangedCount; u32 xc_unknownCount; u32 x10_maxMeleeAttackerCount; u32 x14_maxRangedAttackerCount; u32 x18_positionMode; float x1c_meleeTimeInterval; float x20_rangedTimeInterval; public: CTeamAiData(CInputStream& in, s32 propCount); }; class CTeamAiMgr : public CEntity { public: enum class EAttackType { Melee, Ranged }; private: CTeamAiData x34_data; std::vector<CTeamAiRole> x58_roles; std::vector<TUniqueId> x68_meleeAttackers; std::vector<TUniqueId> x78_rangedAttackers; float x88_timeDirty = 0.0f; TUniqueId x8c_teamCaptainId = kInvalidUniqueId; float x90_timeSinceMelee = 0.0f; float x94_timeSinceRanged = 0.0f; void UpdateTeamCaptain(); bool ShouldUpdateRoles(float dt); void ResetRoles(CStateManager& mgr); void AssignRoles(CTeamAiRole::ETeamAiRole role, s32 count); void UpdateRoles(CStateManager& mgr); void SpacingSort(CStateManager& mgr, const zeus::CVector3f& pos); void PositionTeam(CStateManager& mgr); public: CTeamAiMgr(TUniqueId uid, std::string_view name, const CEntityInfo& info, const CTeamAiData& data); void Accept(IVisitor&) override; void Think(float dt, CStateManager& mgr) override; void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) override; CTeamAiRole* GetTeamAiRole(TUniqueId aiId); bool IsPartOfTeam(TUniqueId aiId) const; bool HasTeamAiRole(TUniqueId aiId) const; bool AssignTeamAiRole(const CAi& ai, CTeamAiRole::ETeamAiRole roleA, CTeamAiRole::ETeamAiRole roleB, CTeamAiRole::ETeamAiRole roleC); void RemoveTeamAiRole(TUniqueId aiId); void ClearTeamAiRole(TUniqueId aiId); s32 GetNumAssignedOfRole(CTeamAiRole::ETeamAiRole role) const; s32 GetNumAssignedAiRoles() const; bool IsMeleeAttacker(TUniqueId aiId) const; bool CanAcceptMeleeAttacker(TUniqueId aiId) const; bool AddMeleeAttacker(TUniqueId aiId); void RemoveMeleeAttacker(TUniqueId aiId); bool IsRangedAttacker(TUniqueId aiId) const; bool CanAcceptRangedAttacker(TUniqueId aiId) const; bool AddRangedAttacker(TUniqueId aiId); void RemoveRangedAttacker(TUniqueId aiId); bool HasMeleeAttackers() const { return !x68_meleeAttackers.empty(); } bool HasRangedAttackers() const { return !x78_rangedAttackers.empty(); } s32 GetNumRoles() const { return x58_roles.size(); } const std::vector<CTeamAiRole>& GetRoles() const { return x58_roles; } s32 GetMaxMeleeAttackerCount() const { return x34_data.x10_maxMeleeAttackerCount; } s32 GetMaxRangedAttackerCount() const { return x34_data.x14_maxRangedAttackerCount; } static CTeamAiRole* GetTeamAiRole(CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId); static void ResetTeamAiRole(EAttackType type, CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId, bool clearRole); static bool CanAcceptAttacker(EAttackType type, CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId); static bool AddAttacker(EAttackType type, CStateManager& mgr, TUniqueId mgrId, TUniqueId aiId); static TUniqueId GetTeamAiMgr(CAi& ai, CStateManager& mgr); }; } // namespace urde
Initialize x90_timeSinceMelee and x90_timeSinceRanged to 0.0f in constructor
CTeamAiMgr: Initialize x90_timeSinceMelee and x90_timeSinceRanged to 0.0f in constructor Makes all class members have a deterministic initial state.
C++
mit
AxioDL/PathShagged,AxioDL/PathShagged,AxioDL/PathShagged
e5a66e1160796359d0c0264655b9af21ccfa5cbc
src/nostalgia/player/main.cpp
src/nostalgia/player/main.cpp
/* * Copyright 2016 - 2019 [email protected] * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <ox/fs/fs.hpp> #include <ox/std/units.hpp> #include <nostalgia/world/world.hpp> using namespace nostalgia::common; using namespace nostalgia::core; using namespace nostalgia::world; ox::Error run(ox::FileSystem *fs) { Context ctx; ctx.rom = fs; oxReturnError(init(&ctx)); //Zone zone; //oxReturnError(zone.init(&ctx, Bounds{0, 0, 40, 40}, "/TileSheets/Charset.ng", "/Palettes/Charset.npal")); //zone.draw(&ctx); oxReturnError(initConsole(&ctx)); puts(&ctx, 10, 9, "DOPENESS!!!"); oxReturnError(run()); oxReturnError(shutdownGfx()); return OxError(0); } #ifndef OX_USE_STDLIB int main() { auto rom = loadRom(); if (!rom) { return 1; } ox::FileSystem32 fs(ox::FileStore32(rom, 32 * ox::units::MB)); run(&fs); return 0; } #else #include <vector> #include <stdio.h> std::vector<uint8_t> loadFileBuff(const char *path) { auto file = fopen(path, "r"); if (file) { fseek(file, 0, SEEK_END); const auto size = ftell(file); rewind(file); std::vector<uint8_t> buff(size); fread(buff.data(), size, 1, file); fclose(file); return buff; } else { return {}; } } int main(int argc, const char **argv) { if (argc > 1) { std::unique_ptr<ox::FileSystem> fs; std::vector<uint8_t> rom; std::string path = argv[1]; const std::string fsExt = path.substr(path.find_last_of('.')); if (fsExt == ".oxfs") { rom = loadFileBuff(path.c_str()); if (!rom.size()) { return 1; } fs = std::make_unique<ox::FileSystem32>(ox::FileStore32(rom.data(), 32 * ox::units::MB)); } else { fs = std::make_unique<ox::PassThroughFS>(path.c_str()); } auto err = run(fs.get()); oxAssert(err, "Something went wrong..."); return err; } return 2; } #endif
/* * Copyright 2016 - 2019 [email protected] * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <ox/fs/fs.hpp> #include <ox/std/units.hpp> #include <nostalgia/world/world.hpp> using namespace nostalgia::common; using namespace nostalgia::core; using namespace nostalgia::world; ox::Error run(ox::FileSystem *fs) { Context ctx; ctx.rom = fs; oxReturnError(init(&ctx)); //Zone zone; //oxReturnError(zone.init(&ctx, Bounds{0, 0, 40, 40}, "/TileSheets/Charset.ng", "/Palettes/Charset.npal")); //zone.draw(&ctx); oxReturnError(initConsole(&ctx)); puts(&ctx, 10, 9, "DOPENESS!!!"); oxReturnError(run()); oxReturnError(shutdownGfx()); return OxError(0); } #ifndef OX_USE_STDLIB int main() { auto rom = loadRom(); if (!rom) { return 1; } ox::FileSystem32 fs(ox::FileStore32(rom, 32 * ox::units::MB)); run(&fs); return 0; } #else #include <vector> #include <stdio.h> std::vector<uint8_t> loadFileBuff(const char *path) { auto file = fopen(path, "r"); if (file) { fseek(file, 0, SEEK_END); const auto size = ftell(file); rewind(file); std::vector<uint8_t> buff(size); fread(buff.data(), size, 1, file); fclose(file); return buff; } else { return {}; } } int main(int argc, const char **argv) { if (argc > 1) { std::unique_ptr<ox::FileSystem> fs; std::vector<uint8_t> rom; std::string path = argv[1]; const auto lastDot = path.find_last_of('.'); const std::string fsExt = lastDot != std::string::npos ? path.substr(lastDot) : ""; if (fsExt == ".oxfs") { rom = loadFileBuff(path.c_str()); if (!rom.size()) { return 1; } fs = std::make_unique<ox::FileSystem32>(ox::FileStore32(rom.data(), 32 * ox::units::MB)); } else { fs = std::make_unique<ox::PassThroughFS>(path.c_str()); } auto err = run(fs.get()); oxAssert(err, "Something went wrong..."); return err; } return 2; } #endif
Fix loading from directory
[nostalgia/player] Fix loading from directory
C++
mpl-2.0
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
23e5c82014fe2e080e5ded018fa99b8a6c2134fd
virvo/tools/vserver/vvserver.cpp
virvo/tools/vserver/vvserver.cpp
// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <iostream> using std::cerr; using std::endl; using std::ios; #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #ifdef FREEGLUT // For glutInitContextFlags(GLUT_DEBUG), needed for GL_ARB_debug_output #include <GL/freeglut.h> #endif #endif #ifdef VV_DEBUG_MEMORY #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__, __LINE__) #endif #include <virvo/vvvirvo.h> #include <virvo/vvtoolshed.h> #include <virvo/vvibrserver.h> #include <virvo/vvimageserver.h> #include <virvo/vvimage.h> #include <virvo/vvremoteserver.h> #include <virvo/vvrendererfactory.h> #include <virvo/vvvoldesc.h> #include <virvo/vvdebugmsg.h> #include <virvo/vvsocketio.h> #include <virvo/vvtexrend.h> #include <virvo/vvcuda.h> /** * Virvo Server main class. * * Server unit for remote rendering. * * Options -port: set port, else default will be used. * * @author Juergen Schulze ([email protected]) * @author Stavros Delisavas ([email protected]) */ class vvServer { private: /// Remote rendering type enum { RR_NONE = 0, RR_CLUSTER, RR_IMAGE, RR_IBR }; static const int DEFAULTSIZE; ///< default window size (width and height) in pixels static const int DEFAULT_PORT; ///< default port for socket connections static vvServer* ds; ///< one instance of vvServer is always present int winWidth, winHeight; ///< window size in pixels int rrMode; ///< memory remote rendering mode int port; ///< port the server renderer uses to listen for incoming connections public: vvServer(); ~vvServer(); int run(int, char**); static void cleanup(); private: static void reshapeCallback(int, int); static void displayCallback(); static void timerCallback(int); void initGraphics(int argc, char *argv[]); void displayHelpInfo(); bool parseCommandLine(int argc, char *argv[]); void mainLoop(int argc, char *argv[]); void serverLoop(); }; const int vvServer::DEFAULTSIZE = 512; const int vvServer::DEFAULT_PORT = 31050; vvServer* vvServer::ds = NULL; //---------------------------------------------------------------------------- /// Constructor vvServer::vvServer() { winWidth = winHeight = DEFAULTSIZE; ds = this; rrMode = RR_NONE; port = vvServer::DEFAULT_PORT; } //---------------------------------------------------------------------------- /// Destructor. vvServer::~vvServer() { ds = NULL; } void vvServer::serverLoop() { vvGLTools::enableGLErrorBacktrace(); while (1) { cerr << "Listening on port " << port << endl; vvSocketIO *sock = new vvSocketIO(port, vvSocket::VV_TCP); sock->set_debuglevel(vvDebugMsg::getDebugLevel()); if(sock->init() != vvSocket::VV_OK) { std::cerr << "Failed to initialize server socket on port " << port << std::endl; delete sock; break; } vvRemoteServer* server = NULL; int type; sock->getInt32(type); switch(type) { case vvRenderer::REMOTE_IMAGE: rrMode = RR_IMAGE; server = new vvImageServer(sock); break; case vvRenderer::REMOTE_IBR: rrMode = RR_IBR; server = new vvIbrServer(sock); break; default: std::cerr << "Unknown remote rendering type " << type << std::endl; delete sock; break; } if(!server) { break; } vvVolDesc *vd = NULL; if (server->initData(vd) != vvRemoteServer::VV_OK) { cerr << "Could not initialize volume data" << endl; cerr << "Continuing with next client..." << endl; goto cleanup; } if (vd != NULL) { if (server->getLoadVolumeFromFile()) { vd->printInfoLine(); } // Set default color scheme if no TF present: if (vd->tf.isEmpty()) { vd->tf.setDefaultAlpha(0, 0.0, 1.0); vd->tf.setDefaultColors((vd->chan==1) ? 0 : 2, 0.0, 1.0); } vvRenderState rs; vvRenderer *renderer = vvRendererFactory::create(vd, rs, rrMode==RR_IBR ? "rayrend" : "default", ""); if(rrMode == RR_IBR) renderer->setParameter(vvRenderer::VV_USE_IBR, 1.f); server->renderLoop(renderer); delete renderer; } // Frames vector with bricks is deleted along with the renderer. // Don't free them here. // see setRenderer(). cleanup: delete server; server = NULL; delete vd; vd = NULL; } } //---------------------------------------------------------------------------- /** Virvo server main loop. @param filename volume file to display */ void vvServer::mainLoop(int argc, char *argv[]) { vvDebugMsg::msg(2, "vvServer::mainLoop()"); initGraphics(argc, argv); vvCuda::initGlInterop(); glutTimerFunc(1, timerCallback, 0); glutMainLoop(); } //---------------------------------------------------------------------------- /** Callback method for window resizes. @param w,h new window width and height */ void vvServer::reshapeCallback(int w, int h) { vvDebugMsg::msg(2, "vvServer::reshapeCallback(): ", w, h); ds->winWidth = w; ds->winHeight = h; // Resize OpenGL viewport: glViewport(0, 0, ds->winWidth, ds->winHeight); glDrawBuffer(GL_FRONT_AND_BACK); // select all buffers // set clear color glClearColor(0., 0., 0., 0.); // clear window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------------------------- /// Callback method for window redraws. void vvServer::displayCallback() { vvDebugMsg::msg(3, "vvServer::displayCallback()"); vvGLTools::printGLError("enter vvServer::displayCallback()"); glDrawBuffer(GL_BACK); glClearColor(0., 0., 0., 0.); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw volume: glMatrixMode(GL_MODELVIEW); glDrawBuffer(GL_BACK); glutSwapBuffers(); vvGLTools::printGLError("leave vvServer::displayCallback()"); } //---------------------------------------------------------------------------- /** Timer callback method, triggered by glutTimerFunc(). */ void vvServer::timerCallback(int) { vvDebugMsg::msg(3, "vvServer::timerCallback()"); ds->serverLoop(); exit(0); } //---------------------------------------------------------------------------- /// Initialize the GLUT window and the OpenGL graphics context. void vvServer::initGraphics(int argc, char *argv[]) { vvDebugMsg::msg(1, "vvServer::initGraphics()"); cerr << "Number of CPUs found: " << vvToolshed::getNumProcessors() << endl; cerr << "Initializing GLUT." << endl; glutInit(&argc, argv); // initialize GLUT // Other glut versions than freeglut currently don't support // debug context flags. #if defined(FREEGLUT) && defined(GLUT_INIT_MAJOR_VERSION) glutInitContextFlags(GLUT_DEBUG); #endif // FREEGLUT glutInitWindowSize(winWidth, winHeight); // set initial window size // Create window title. // Don't use sprintf, it won't work with macros on Irix! char title[1024]; // window title sprintf(title, "Virvo Server V%s.%s (Port %d)", virvo::getVersionMajor(), virvo::getReleaseCounter(), port); glutCreateWindow(title); // open window and set window title glutSetWindowTitle(title); // Set GL state: glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glEnable(GL_DEPTH_TEST); // Set Glut callbacks: glutDisplayFunc(displayCallback); glutReshapeFunc(reshapeCallback); const char *version = (const char *)glGetString(GL_VERSION); cerr << "Found OpenGL version: " << version << endl; if (strncmp(version,"1.0",3)==0) { cerr << "Virvo server requires OpenGL version 1.1 or greater." << endl; } vvGLTools::checkOpenGLextensions(); if (vvDebugMsg::isActive(2)) { cerr << "\nSupported OpenGL extensions:" << endl; vvGLTools::displayOpenGLextensions(vvGLTools::ONE_BY_ONE); } } //---------------------------------------------------------------------------- /// Display command usage help on the command line. void vvServer::displayHelpInfo() { vvDebugMsg::msg(1, "vvServer::displayHelpInfo()"); cerr << "Syntax:" << endl; cerr << endl; cerr << " vserver [options]" << endl; cerr << endl; cerr << "Available options:" << endl; cerr << endl; cerr << "-port (-p)" << endl; cerr << " Don't use the default port (" << DEFAULT_PORT << "), but the specified one" << endl; cerr << endl; cerr << "-size <width> <height>" << endl; cerr << " Set the window size to <width> * <height> pixels." << endl; cerr << " The default window size is " << DEFAULTSIZE << " * " << DEFAULTSIZE << " pixels" << endl; } //---------------------------------------------------------------------------- /** Parse command line arguments. @param argc,argv command line arguments @return true if parsing ok, false on error */ bool vvServer::parseCommandLine(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::parseCommandLine()"); for (int arg=1; arg<argc; ++arg) { if (vvToolshed::strCompare(argv[arg], "-help")==0 || vvToolshed::strCompare(argv[arg], "-h")==0 || vvToolshed::strCompare(argv[arg], "-?")==0 || vvToolshed::strCompare(argv[arg], "/?")==0) { displayHelpInfo(); return false; } else if (vvToolshed::strCompare(argv[arg], "-size")==0) { if ((++arg)>=argc) { cerr << "Window width missing." << endl; return false; } winWidth = atoi(argv[arg]); if ((++arg)>=argc) { cerr << "Window height missing." << endl; return false; } winHeight = atoi(argv[arg]); if (winWidth<1 || winHeight<1) { cerr << "Invalid window size." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-port")==0) { if ((++arg)>=argc) { cerr << "No port specified, defaulting to: " << vvServer::DEFAULT_PORT << endl; port = vvServer::DEFAULT_PORT; return false; } else { cerr << "test----------------------"<<endl; port = atoi(argv[arg]); } } else if (vvToolshed::strCompare(argv[arg], "-display")==0 || vvToolshed::strCompare(argv[arg], "-geometry")==0) { // handled by GLUT if ((++arg)>=argc) { cerr << "Required argument unspecified" << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-iconic")==0 || vvToolshed::strCompare(argv[arg], "-direct")==0 || vvToolshed::strCompare(argv[arg], "-indirect")==0 || vvToolshed::strCompare(argv[arg], "-gldebug")==0 || vvToolshed::strCompare(argv[arg], "-sync")==0) { // handled by GLUT } else { cerr << "Unknown option/parameter: \"" << argv[arg] << "\", use -help for instructions" << endl; return false; } } return true; } //---------------------------------------------------------------------------- /** Main Virvo server routine. @param argc,argv command line arguments @return 0 if the program finished ok, 1 if an error occurred */ int vvServer::run(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::run()"); cerr << "Virvo server " << virvo::getVersionMajor() << "." << virvo::getReleaseCounter() << endl; cerr << "(c) " << virvo::getYearOfRelease() << " Juergen Schulze ([email protected])" << endl; cerr << "Brown University" << endl << endl; if (parseCommandLine(argc, argv) == false) return 1; mainLoop(argc, argv); return 0; } void vvServer::cleanup() { delete ds; ds = NULL; } //---------------------------------------------------------------------------- /// Main entry point. int main(int argc, char** argv) { #ifdef VV_DEBUG_MEMORY int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);// Get current flag flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit flag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flag); // Set flag to the new value #endif #ifdef VV_DEBUG_MEMORY _CrtMemState s1, s2, s3; _CrtCheckMemory(); _CrtMemCheckpoint( &s1 ); #endif // do stuff to test memory difference for #ifdef VV_DEBUG_MEMORY _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); _CrtCheckMemory(); #endif // do stuff to verify memory status after #ifdef VV_DEBUG_MEMORY _CrtCheckMemory(); #endif atexit(vvServer::cleanup); //vvDebugMsg::setDebugLevel(vvDebugMsg::NO_MESSAGES); int error = (new vvServer())->run(argc, argv); #ifdef VV_DEBUG_MEMORY _CrtDumpMemoryLeaks(); // display memory leaks, if any #endif return error; } //============================================================================ // End of File //============================================================================ // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <iostream> using std::cerr; using std::endl; using std::ios; #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #ifdef FREEGLUT // For glutInitContextFlags(GLUT_DEBUG), needed for GL_ARB_debug_output #include <GL/freeglut.h> #endif #endif #ifdef VV_DEBUG_MEMORY #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__, __LINE__) #endif #include <virvo/vvvirvo.h> #include <virvo/vvtoolshed.h> #include <virvo/vvibrserver.h> #include <virvo/vvimageserver.h> #include <virvo/vvimage.h> #include <virvo/vvremoteserver.h> #include <virvo/vvrendererfactory.h> #include <virvo/vvvoldesc.h> #include <virvo/vvdebugmsg.h> #include <virvo/vvsocketio.h> #include <virvo/vvtexrend.h> #include <virvo/vvcuda.h> /** * Virvo Server main class. * * Server unit for remote rendering. * * Options -port: set port, else default will be used. * * @author Juergen Schulze ([email protected]) * @author Stavros Delisavas ([email protected]) */ class vvServer { private: /// Remote rendering type enum { RR_NONE = 0, RR_CLUSTER, RR_IMAGE, RR_IBR }; static const int DEFAULTSIZE; ///< default window size (width and height) in pixels static const int DEFAULT_PORT; ///< default port for socket connections static vvServer* ds; ///< one instance of vvServer is always present int winWidth, winHeight; ///< window size in pixels int rrMode; ///< memory remote rendering mode int port; ///< port the server renderer uses to listen for incoming connections public: vvServer(); ~vvServer(); int run(int, char**); static void cleanup(); private: static void reshapeCallback(int, int); static void displayCallback(); static void timerCallback(int); void initGraphics(int argc, char *argv[]); void displayHelpInfo(); bool parseCommandLine(int argc, char *argv[]); void mainLoop(int argc, char *argv[]); void serverLoop(); }; const int vvServer::DEFAULTSIZE = 512; const int vvServer::DEFAULT_PORT = 31050; vvServer* vvServer::ds = NULL; //---------------------------------------------------------------------------- /// Constructor vvServer::vvServer() { winWidth = winHeight = DEFAULTSIZE; ds = this; rrMode = RR_NONE; port = vvServer::DEFAULT_PORT; } //---------------------------------------------------------------------------- /// Destructor. vvServer::~vvServer() { ds = NULL; } void vvServer::serverLoop() { vvGLTools::enableGLErrorBacktrace(); while (1) { cerr << "Listening on port " << port << endl; vvSocketIO *sock = new vvSocketIO(port, vvSocket::VV_TCP); sock->set_debuglevel(vvDebugMsg::getDebugLevel()); if(sock->init() != vvSocket::VV_OK) { std::cerr << "Failed to initialize server socket on port " << port << std::endl; delete sock; break; } vvRemoteServer* server = NULL; int type; sock->getInt32(type); switch(type) { case vvRenderer::REMOTE_IMAGE: rrMode = RR_IMAGE; server = new vvImageServer(sock); break; case vvRenderer::REMOTE_IBR: rrMode = RR_IBR; server = new vvIbrServer(sock); break; default: std::cerr << "Unknown remote rendering type " << type << std::endl; delete sock; break; } if(!server) { break; } vvVolDesc *vd = NULL; if (server->initData(vd) != vvRemoteServer::VV_OK) { cerr << "Could not initialize volume data" << endl; cerr << "Continuing with next client..." << endl; goto cleanup; } if (vd != NULL) { if (server->getLoadVolumeFromFile()) { vd->printInfoLine(); } // Set default color scheme if no TF present: if (vd->tf.isEmpty()) { vd->tf.setDefaultAlpha(0, 0.0, 1.0); vd->tf.setDefaultColors((vd->chan==1) ? 0 : 2, 0.0, 1.0); } vvRenderState rs; vvRenderer *renderer = vvRendererFactory::create(vd, rs, rrMode==RR_IBR ? "rayrend" : "default", ""); if(rrMode == RR_IBR) renderer->setParameter(vvRenderer::VV_USE_IBR, 1.f); server->renderLoop(renderer); delete renderer; } // Frames vector with bricks is deleted along with the renderer. // Don't free them here. // see setRenderer(). cleanup: delete server; server = NULL; delete vd; vd = NULL; } } //---------------------------------------------------------------------------- /** Virvo server main loop. @param filename volume file to display */ void vvServer::mainLoop(int argc, char *argv[]) { vvDebugMsg::msg(2, "vvServer::mainLoop()"); initGraphics(argc, argv); vvCuda::initGlInterop(); glutTimerFunc(1, timerCallback, 0); glutMainLoop(); } //---------------------------------------------------------------------------- /** Callback method for window resizes. @param w,h new window width and height */ void vvServer::reshapeCallback(int w, int h) { vvDebugMsg::msg(2, "vvServer::reshapeCallback(): ", w, h); ds->winWidth = w; ds->winHeight = h; // Resize OpenGL viewport: glViewport(0, 0, ds->winWidth, ds->winHeight); glDrawBuffer(GL_FRONT_AND_BACK); // select all buffers // set clear color glClearColor(0., 0., 0., 0.); // clear window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------------------------- /// Callback method for window redraws. void vvServer::displayCallback() { vvDebugMsg::msg(3, "vvServer::displayCallback()"); vvGLTools::printGLError("enter vvServer::displayCallback()"); glDrawBuffer(GL_BACK); glClearColor(0., 0., 0., 0.); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw volume: glMatrixMode(GL_MODELVIEW); glDrawBuffer(GL_BACK); glutSwapBuffers(); vvGLTools::printGLError("leave vvServer::displayCallback()"); } //---------------------------------------------------------------------------- /** Timer callback method, triggered by glutTimerFunc(). */ void vvServer::timerCallback(int) { vvDebugMsg::msg(3, "vvServer::timerCallback()"); ds->serverLoop(); exit(0); } //---------------------------------------------------------------------------- /// Initialize the GLUT window and the OpenGL graphics context. void vvServer::initGraphics(int argc, char *argv[]) { vvDebugMsg::msg(1, "vvServer::initGraphics()"); cerr << "Number of CPUs found: " << vvToolshed::getNumProcessors() << endl; cerr << "Initializing GLUT." << endl; glutInit(&argc, argv); // initialize GLUT // Other glut versions than freeglut currently don't support // debug context flags. #if defined(FREEGLUT) && defined(GLUT_INIT_MAJOR_VERSION) glutInitContextFlags(GLUT_DEBUG); #endif // FREEGLUT // create double buffering context glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); if (!glutGet(GLUT_DISPLAY_MODE_POSSIBLE)) { cerr << "Error: Virvo server needs a double buffering OpenGL context with alpha channel." << endl; exit(1); } glutInitWindowSize(winWidth, winHeight); // set initial window size // Create window title. // Don't use sprintf, it won't work with macros on Irix! char title[1024]; // window title sprintf(title, "Virvo Server V%s.%s (Port %d)", virvo::getVersionMajor(), virvo::getReleaseCounter(), port); glutCreateWindow(title); // open window and set window title glutSetWindowTitle(title); // Set GL state: glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glEnable(GL_DEPTH_TEST); // Set Glut callbacks: glutDisplayFunc(displayCallback); glutReshapeFunc(reshapeCallback); const char *version = (const char *)glGetString(GL_VERSION); cerr << "Found OpenGL version: " << version << endl; if (strncmp(version,"1.0",3)==0) { cerr << "Virvo server requires OpenGL version 1.1 or greater." << endl; } vvGLTools::checkOpenGLextensions(); if (vvDebugMsg::isActive(2)) { cerr << "\nSupported OpenGL extensions:" << endl; vvGLTools::displayOpenGLextensions(vvGLTools::ONE_BY_ONE); } } //---------------------------------------------------------------------------- /// Display command usage help on the command line. void vvServer::displayHelpInfo() { vvDebugMsg::msg(1, "vvServer::displayHelpInfo()"); cerr << "Syntax:" << endl; cerr << endl; cerr << " vserver [options]" << endl; cerr << endl; cerr << "Available options:" << endl; cerr << endl; cerr << "-port (-p)" << endl; cerr << " Don't use the default port (" << DEFAULT_PORT << "), but the specified one" << endl; cerr << endl; cerr << "-size <width> <height>" << endl; cerr << " Set the window size to <width> * <height> pixels." << endl; cerr << " The default window size is " << DEFAULTSIZE << " * " << DEFAULTSIZE << " pixels" << endl; } //---------------------------------------------------------------------------- /** Parse command line arguments. @param argc,argv command line arguments @return true if parsing ok, false on error */ bool vvServer::parseCommandLine(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::parseCommandLine()"); for (int arg=1; arg<argc; ++arg) { if (vvToolshed::strCompare(argv[arg], "-help")==0 || vvToolshed::strCompare(argv[arg], "-h")==0 || vvToolshed::strCompare(argv[arg], "-?")==0 || vvToolshed::strCompare(argv[arg], "/?")==0) { displayHelpInfo(); return false; } else if (vvToolshed::strCompare(argv[arg], "-size")==0) { if ((++arg)>=argc) { cerr << "Window width missing." << endl; return false; } winWidth = atoi(argv[arg]); if ((++arg)>=argc) { cerr << "Window height missing." << endl; return false; } winHeight = atoi(argv[arg]); if (winWidth<1 || winHeight<1) { cerr << "Invalid window size." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-port")==0) { if ((++arg)>=argc) { cerr << "No port specified, defaulting to: " << vvServer::DEFAULT_PORT << endl; port = vvServer::DEFAULT_PORT; return false; } else { cerr << "test----------------------"<<endl; port = atoi(argv[arg]); } } else if (vvToolshed::strCompare(argv[arg], "-display")==0 || vvToolshed::strCompare(argv[arg], "-geometry")==0) { // handled by GLUT if ((++arg)>=argc) { cerr << "Required argument unspecified" << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-iconic")==0 || vvToolshed::strCompare(argv[arg], "-direct")==0 || vvToolshed::strCompare(argv[arg], "-indirect")==0 || vvToolshed::strCompare(argv[arg], "-gldebug")==0 || vvToolshed::strCompare(argv[arg], "-sync")==0) { // handled by GLUT } else { cerr << "Unknown option/parameter: \"" << argv[arg] << "\", use -help for instructions" << endl; return false; } } return true; } //---------------------------------------------------------------------------- /** Main Virvo server routine. @param argc,argv command line arguments @return 0 if the program finished ok, 1 if an error occurred */ int vvServer::run(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::run()"); cerr << "Virvo server " << virvo::getVersionMajor() << "." << virvo::getReleaseCounter() << endl; cerr << "(c) " << virvo::getYearOfRelease() << " Juergen Schulze ([email protected])" << endl; cerr << "Brown University" << endl << endl; if (parseCommandLine(argc, argv) == false) return 1; mainLoop(argc, argv); return 0; } void vvServer::cleanup() { delete ds; ds = NULL; } //---------------------------------------------------------------------------- /// Main entry point. int main(int argc, char** argv) { #ifdef VV_DEBUG_MEMORY int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);// Get current flag flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit flag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flag); // Set flag to the new value #endif #ifdef VV_DEBUG_MEMORY _CrtMemState s1, s2, s3; _CrtCheckMemory(); _CrtMemCheckpoint( &s1 ); #endif // do stuff to test memory difference for #ifdef VV_DEBUG_MEMORY _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); _CrtCheckMemory(); #endif // do stuff to verify memory status after #ifdef VV_DEBUG_MEMORY _CrtCheckMemory(); #endif atexit(vvServer::cleanup); //vvDebugMsg::setDebugLevel(vvDebugMsg::NO_MESSAGES); int error = (new vvServer())->run(argc, argv); #ifdef VV_DEBUG_MEMORY _CrtDumpMemoryLeaks(); // display memory leaks, if any #endif return error; } //============================================================================ // End of File //============================================================================ // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
create an appropriate visual
create an appropriate visual git-svn-id: a0a066a1d7ce87c7a04dae20f169ad0cd8bda35d@1488 04231f92-3938-0410-9931-e931ac552b4f
C++
lgpl-2.1
deskvox/deskvox,deskvox/deskvox,deskvox/deskvox,deskvox/deskvox,deskvox/deskvox
bee8b41205320a2c5673566fd1f75810b34f0f75
src/algorithm/rnea.hpp
src/algorithm/rnea.hpp
// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_rnea_hpp__ #define __se3_rnea_hpp__ #include "pinocchio/multibody/visitor.hpp" #include "pinocchio/multibody/model.hpp" namespace se3 { inline const Eigen::VectorXd& rnea(const Model & model, Data& data, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Eigen::VectorXd & a); } // namespace se3 /* --- Details -------------------------------------------------------------------- */ namespace se3 { struct RneaForwardStep : public fusion::JointVisitor<RneaForwardStep> { typedef boost::fusion::vector< const se3::Model&, se3::Data&, const int&, const Eigen::VectorXd &, const Eigen::VectorXd &, const Eigen::VectorXd & > ArgsType; JOINT_VISITOR_INIT(RneaForwardStep); template<typename JointModel> static int algo(const se3::JointModelBase<JointModel> & jmodel, se3::JointDataBase<typename JointModel::JointData> & jdata, const se3::Model& model, se3::Data& data, const int &i, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Eigen::VectorXd & a) { using namespace Eigen; using namespace se3; jmodel.calc(jdata.derived(),q,v); const Model::Index & parent = model.parents[(Model::Index)i]; data.liMi[(Model::Index)i] = model.jointPlacements[(Model::Index)i]*jdata.M(); data.v[(Model::Index)i] = jdata.v(); if(parent>0) data.v[(Model::Index)i] += data.liMi[(Model::Index)i].actInv(data.v[parent]); data.a_gf[(Model::Index)i] = jdata.S()*jmodel.jointVelocitySelector(a) + jdata.c() + (data.v[(Model::Index)i] ^ jdata.v()) ; data.a_gf[(Model::Index)i] += data.liMi[(Model::Index)i].actInv(data.a_gf[parent]); data.f[(Model::Index)i] = model.inertias[(Model::Index)i]*data.a_gf[(Model::Index)i] + model.inertias[(Model::Index)i].vxiv(data.v[(Model::Index)i]); // -f_ext return 0; } }; struct RneaBackwardStep : public fusion::JointVisitor<RneaBackwardStep> { typedef boost::fusion::vector<const Model&, Data&, const int &> ArgsType; JOINT_VISITOR_INIT(RneaBackwardStep); template<typename JointModel> static void algo(const JointModelBase<JointModel> & jmodel, JointDataBase<typename JointModel::JointData> & jdata, const Model& model, Data& data, int i) { const Model::Index & parent = model.parents[(Model::Index)i]; jmodel.jointVelocitySelector(data.tau) = jdata.S().transpose()*data.f[(Model::Index)i]; if(parent>0) data.f[(Model::Index)parent] += data.liMi[(Model::Index)i].act(data.f[(Model::Index)i]); } }; inline const Eigen::VectorXd& rnea(const Model & model, Data& data, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Eigen::VectorXd & a) { data.v[0].setZero(); data.a_gf[0] = -model.gravity; for( int i=1;i<model.nbody;++i ) { RneaForwardStep::run(model.joints[(Model::Index)i],data.joints[(Model::Index)i], RneaForwardStep::ArgsType(model,data,i,q,v,a)); } for( int i=model.nbody-1;i>0;--i ) { RneaBackwardStep::run(model.joints[(Model::Index)i],data.joints[(Model::Index)i], RneaBackwardStep::ArgsType(model,data,i)); } return data.tau; } } // namespace se3 #endif // ifndef __se3_rnea_hpp__
// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_rnea_hpp__ #define __se3_rnea_hpp__ #include "pinocchio/multibody/visitor.hpp" #include "pinocchio/multibody/model.hpp" namespace se3 { inline const Eigen::VectorXd& rnea(const Model & model, Data& data, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Eigen::VectorXd & a); } // namespace se3 /* --- Details -------------------------------------------------------------------- */ namespace se3 { struct RneaForwardStep : public fusion::JointVisitor<RneaForwardStep> { typedef boost::fusion::vector< const se3::Model&, se3::Data&, const int&, const Eigen::VectorXd &, const Eigen::VectorXd &, const Eigen::VectorXd & > ArgsType; JOINT_VISITOR_INIT(RneaForwardStep); template<typename JointModel> static void algo(const se3::JointModelBase<JointModel> & jmodel, se3::JointDataBase<typename JointModel::JointData> & jdata, const se3::Model& model, se3::Data& data, const int &i, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Eigen::VectorXd & a) { using namespace Eigen; using namespace se3; jmodel.calc(jdata.derived(),q,v); const Model::Index & parent = model.parents[(Model::Index)i]; data.liMi[(Model::Index)i] = model.jointPlacements[(Model::Index)i]*jdata.M(); data.v[(Model::Index)i] = jdata.v(); if(parent>0) data.v[(Model::Index)i] += data.liMi[(Model::Index)i].actInv(data.v[parent]); data.a_gf[(Model::Index)i] = jdata.S()*jmodel.jointVelocitySelector(a) + jdata.c() + (data.v[(Model::Index)i] ^ jdata.v()) ; data.a_gf[(Model::Index)i] += data.liMi[(Model::Index)i].actInv(data.a_gf[parent]); data.f[(Model::Index)i] = model.inertias[(Model::Index)i]*data.a_gf[(Model::Index)i] + model.inertias[(Model::Index)i].vxiv(data.v[(Model::Index)i]); // -f_ext } }; struct RneaBackwardStep : public fusion::JointVisitor<RneaBackwardStep> { typedef boost::fusion::vector<const Model&, Data&, const int &> ArgsType; JOINT_VISITOR_INIT(RneaBackwardStep); template<typename JointModel> static void algo(const JointModelBase<JointModel> & jmodel, JointDataBase<typename JointModel::JointData> & jdata, const Model& model, Data& data, int i) { const Model::Index & parent = model.parents[(Model::Index)i]; jmodel.jointVelocitySelector(data.tau) = jdata.S().transpose()*data.f[(Model::Index)i]; if(parent>0) data.f[(Model::Index)parent] += data.liMi[(Model::Index)i].act(data.f[(Model::Index)i]); } }; inline const Eigen::VectorXd& rnea(const Model & model, Data& data, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const Eigen::VectorXd & a) { data.v[0].setZero(); data.a_gf[0] = -model.gravity; for( int i=1;i<model.nbody;++i ) { RneaForwardStep::run(model.joints[(Model::Index)i],data.joints[(Model::Index)i], RneaForwardStep::ArgsType(model,data,i,q,v,a)); } for( int i=model.nbody-1;i>0;--i ) { RneaBackwardStep::run(model.joints[(Model::Index)i],data.joints[(Model::Index)i], RneaBackwardStep::ArgsType(model,data,i)); } return data.tau; } } // namespace se3 #endif // ifndef __se3_rnea_hpp__
Correct return type
[C++] Correct return type
C++
bsd-2-clause
fvalenza/pinocchio,fvalenza/pinocchio,fvalenza/pinocchio,fvalenza/pinocchio
a9c71d620d173815f4ef9a3c74837021143dc117
OVR_SDL2_nav.cpp
OVR_SDL2_nav.cpp
// Copyright (c) 2014 Robert Kooima // // 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 "OVR_SDL2_nav.hpp" //------------------------------------------------------------------------------ OVR_SDL2_nav::OVR_SDL2_nav() : rotation(0), drotation(0), move_L(false), move_R(false), move_D(false), move_U(false), move_F(false), move_B(false) { } OVR_SDL2_nav::~OVR_SDL2_nav() { } /// Animate the camera position. void OVR_SDL2_nav::step() { mat3 N = normal(inverse(yrotation(to_radians(rotation)))); vec3 v = dposition; if (move_L) v = v + vec3(-1, 0, 0); if (move_R) v = v + vec3(+1, 0, 0); if (move_D) v = v + vec3(0, -1, 0); if (move_U) v = v + vec3(0, +1, 0); if (move_F) v = v + vec3(0, 0, -1); if (move_B) v = v + vec3(0, 0, +1); if (length(v) > 1.0) v = normalize(v); position = position + N * v / 30.0; rotation = rotation + drotation; } /// Handle a key press or release. void OVR_SDL2_nav::keyboard(int key, bool down, bool repeat) { OVR_SDL2_app::keyboard(key, down, repeat); if (!repeat) { switch (key) { case SDL_SCANCODE_A: move_L = down; return; case SDL_SCANCODE_D: move_R = down; return; case SDL_SCANCODE_C: move_D = down; return; case SDL_SCANCODE_SPACE: move_U = down; return; case SDL_SCANCODE_W: move_F = down; return; case SDL_SCANCODE_S: move_B = down; return; } } } /// Handle mouse pointer motion. void OVR_SDL2_nav::mouse_motion(int dx, int dy) { rotation += 0.5 * dx; } /// Handle gamepad button press or release. void OVR_SDL2_nav::game_button(int device, int button, bool down) { switch (button) { case SDL_CONTROLLER_BUTTON_DPAD_LEFT: move_L = down; break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: move_R = down; break; case SDL_CONTROLLER_BUTTON_B: move_D = down; break; case SDL_CONTROLLER_BUTTON_A: move_U = down; break; case SDL_CONTROLLER_BUTTON_DPAD_UP: move_F = down; break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: move_B = down; break; } } /// Handle gamepad axis motion. void OVR_SDL2_nav::game_axis(int device, int axis, float value) { double k = copysign(value * value, value); switch (axis) { case SDL_CONTROLLER_AXIS_LEFTX: dposition[0] = (fabs(k) > 0.1f) ? k : 0.0f; break; case SDL_CONTROLLER_AXIS_LEFTY: dposition[2] = (fabs(k) > 0.1f) ? k : 0.0f; break; case SDL_CONTROLLER_AXIS_RIGHTX: drotation = (fabs(k) > 0.1f) ? k : 0.0f; break; } } //------------------------------------------------------------------------------ /// Return the current view matrix. mat4 OVR_SDL2_nav::view() const { return OVR_SDL2_app::view() * yrotation(to_radians(rotation)) * translation(-position); } //------------------------------------------------------------------------------
// Copyright (c) 2014 Robert Kooima // // 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 "OVR_SDL2_nav.hpp" //------------------------------------------------------------------------------ OVR_SDL2_nav::OVR_SDL2_nav() : rotation(0), drotation(0), move_L(false), move_R(false), move_D(false), move_U(false), move_F(false), move_B(false) { // FPS-style mouselook requires relative mouse motion. SDL_SetRelativeMouseMode(SDL_TRUE); } OVR_SDL2_nav::~OVR_SDL2_nav() { } /// Animate the camera position. void OVR_SDL2_nav::step() { mat3 N = normal(inverse(yrotation(to_radians(rotation)))); vec3 v = dposition; if (move_L) v = v + vec3(-1, 0, 0); if (move_R) v = v + vec3(+1, 0, 0); if (move_D) v = v + vec3(0, -1, 0); if (move_U) v = v + vec3(0, +1, 0); if (move_F) v = v + vec3(0, 0, -1); if (move_B) v = v + vec3(0, 0, +1); if (length(v) > 1.0) v = normalize(v); position = position + N * v / 30.0; rotation = rotation + drotation; } /// Handle a key press or release. void OVR_SDL2_nav::keyboard(int key, bool down, bool repeat) { OVR_SDL2_app::keyboard(key, down, repeat); if (!repeat) { switch (key) { case SDL_SCANCODE_A: move_L = down; return; case SDL_SCANCODE_D: move_R = down; return; case SDL_SCANCODE_C: move_D = down; return; case SDL_SCANCODE_SPACE: move_U = down; return; case SDL_SCANCODE_W: move_F = down; return; case SDL_SCANCODE_S: move_B = down; return; } } } /// Handle mouse pointer motion. void OVR_SDL2_nav::mouse_motion(int dx, int dy) { rotation += 0.5 * dx; } /// Handle gamepad button press or release. void OVR_SDL2_nav::game_button(int device, int button, bool down) { switch (button) { case SDL_CONTROLLER_BUTTON_DPAD_LEFT: move_L = down; break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: move_R = down; break; case SDL_CONTROLLER_BUTTON_B: move_D = down; break; case SDL_CONTROLLER_BUTTON_A: move_U = down; break; case SDL_CONTROLLER_BUTTON_DPAD_UP: move_F = down; break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: move_B = down; break; } } /// Handle gamepad axis motion. void OVR_SDL2_nav::game_axis(int device, int axis, float value) { double k = copysign(value * value, value); switch (axis) { case SDL_CONTROLLER_AXIS_LEFTX: dposition[0] = (fabs(k) > 0.1f) ? k : 0.0f; break; case SDL_CONTROLLER_AXIS_LEFTY: dposition[2] = (fabs(k) > 0.1f) ? k : 0.0f; break; case SDL_CONTROLLER_AXIS_RIGHTX: drotation = (fabs(k) > 0.1f) ? k : 0.0f; break; } } //------------------------------------------------------------------------------ /// Return the current view matrix. mat4 OVR_SDL2_nav::view() const { return OVR_SDL2_app::view() * yrotation(to_radians(rotation)) * translation(-position); } //------------------------------------------------------------------------------
Move relative mouse mode setting from app to nav
Move relative mouse mode setting from app to nav
C++
mit
rlk/OVR_SDL2,rlk/OVR_SDL2
e6d7539ee84fb600a96a04113d6bf0e9a64b8ccb
src/opt/array_split_rdata.cpp
src/opt/array_split_rdata.cpp
#include "opt/array_split_rdata.h" #include "design/design_util.h" #include "iroha/i_design.h" #include "iroha/resource_class.h" namespace iroha { namespace opt { namespace { class TableConverter { public: TableConverter(ITable *tab); void Convert(); private: IResource *GetRDataResource(IResource *a); bool IsArrayRead(IInsn *insn); ITable *tab_; map<IResource *, IResource *> array_to_rdata_; }; TableConverter::TableConverter(ITable *tab) : tab_(tab) { } void TableConverter::Convert() { for (IState *st : tab_->states_) { vector<IInsn *> new_insns; for (IInsn *insn : st->insns_) { if (!IsArrayRead(insn)) { new_insns.push_back(insn); continue; } // Replaces insn with rd_insn. IResource *rd = GetRDataResource(insn->GetResource()); IInsn *rd_insn = new IInsn(rd); rd_insn->inputs_ = insn->inputs_; rd_insn->outputs_ = insn->outputs_; new_insns.push_back(rd_insn); } st->insns_ = new_insns; } // TODO: Set rd_insn->depending_insns_. } bool TableConverter::IsArrayRead(IInsn *insn) { IResource *res = insn->GetResource(); auto *klass = res->GetClass(); if (!resource::IsArray(*klass)) { return false; } if (insn->inputs_.size() == 0 && insn->outputs_.size() == 1) { return true; } return false; } IResource *TableConverter::GetRDataResource(IResource *a) { auto it = array_to_rdata_.find(a); IResource *r = nullptr; if (it == array_to_rdata_.end()) { r = DesignUtil::CreateResource(tab_, resource::kArrayRData); tab_->resources_.push_back(r); array_to_rdata_[a] = r; } else { r = it->second; } return r; } } // namespace ArraySplitRData::~ArraySplitRData() { } Phase *ArraySplitRData::Create() { return new ArraySplitRData(); } bool ArraySplitRData::ApplyForTable(const string &key, ITable *table) { TableConverter cv(table); cv.Convert(); return true; } } // namespace opt } // namespace iroha
#include "opt/array_split_rdata.h" #include "design/design_util.h" #include "iroha/i_design.h" #include "iroha/resource_class.h" namespace iroha { namespace opt { namespace { class TableConverter { public: TableConverter(ITable *tab); void Convert(); private: IResource *GetRDataResource(IResource *a); bool IsArrayRAddress(IInsn *insn); bool IsArrayRData(IInsn *insn); ITable *tab_; map<IResource *, IResource *> array_to_rdata_; }; TableConverter::TableConverter(ITable *tab) : tab_(tab) { } void TableConverter::Convert() { map<IResource *, IInsn *> raddr_insn; for (IState *st : tab_->states_) { vector<IInsn *> new_insns; for (IInsn *insn : st->insns_) { if (IsArrayRAddress(insn)) { raddr_insn[insn->GetResource()] = insn; } if (!IsArrayRData(insn)) { new_insns.push_back(insn); continue; } // Replaces insn with rd_insn. IResource *rd = GetRDataResource(insn->GetResource()); IInsn *rd_insn = new IInsn(rd); rd_insn->inputs_ = insn->inputs_; rd_insn->outputs_ = insn->outputs_; IInsn *a_insn = raddr_insn[insn->GetResource()]; rd_insn->depending_insns_.push_back(a_insn); new_insns.push_back(rd_insn); } st->insns_ = new_insns; } } bool TableConverter::IsArrayRAddress(IInsn *insn) { IResource *res = insn->GetResource(); auto *klass = res->GetClass(); if (!resource::IsArray(*klass)) { return false; } if (insn->inputs_.size() == 1 && insn->outputs_.size() == 0) { return true; } return false; } bool TableConverter::IsArrayRData(IInsn *insn) { IResource *res = insn->GetResource(); auto *klass = res->GetClass(); if (!resource::IsArray(*klass)) { return false; } if (insn->inputs_.size() == 0 && insn->outputs_.size() == 1) { return true; } return false; } IResource *TableConverter::GetRDataResource(IResource *a) { auto it = array_to_rdata_.find(a); IResource *r = nullptr; if (it == array_to_rdata_.end()) { r = DesignUtil::CreateResource(tab_, resource::kArrayRData); r->SetParentResource(a); tab_->resources_.push_back(r); array_to_rdata_[a] = r; } else { r = it->second; } return r; } } // namespace ArraySplitRData::~ArraySplitRData() { } Phase *ArraySplitRData::Create() { return new ArraySplitRData(); } bool ArraySplitRData::ApplyForTable(const string &key, ITable *table) { TableConverter cv(table); cv.Convert(); return true; } } // namespace opt } // namespace iroha
Add depending_insn_ and parent resource to array-rdata.
Add depending_insn_ and parent resource to array-rdata.
C++
bsd-3-clause
nlsynth/iroha,nlsynth/iroha
35f466404e4b61cfa9a2c1961669b190c739ca70
c++/connection.cpp
c++/connection.cpp
#include <assert.h> #include <string.h> #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #define SHUT_RDWR SD_BOTH #else // WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #endif // !WIN32 #include <unordered_map> #include <set> #include "connection.h" #include "utils.h" class GlobalNetProcess { public: std::mutex fd_map_mutex; std::unordered_map<int, Connection*> fd_map; #ifndef WIN32 int pipe_write; #endif static void do_net_process(GlobalNetProcess* me) { fd_set fd_set_read, fd_set_write; struct timeval timeout; #ifndef WIN32 int pipefd[2]; ALWAYS_ASSERT(!pipe(pipefd)); fcntl(pipefd[1], F_SETFL, fcntl(pipefd[1], F_GETFL) | O_NONBLOCK); fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK); me->pipe_write = pipefd[1]; #endif while (true) { #ifndef WIN32 timeout.tv_sec = 86400; timeout.tv_usec = 20 * 1000; #else timeout.tv_sec = 0; timeout.tv_usec = 1000; #endif FD_ZERO(&fd_set_read); FD_ZERO(&fd_set_write); #ifndef WIN32 int max = pipefd[0]; FD_SET(pipefd[0], &fd_set_read); #else int max = 0; #endif auto now = std::chrono::steady_clock::now(); { std::lock_guard<std::mutex> lock(me->fd_map_mutex); for (const auto& e : me->fd_map) { ALWAYS_ASSERT(e.first < FD_SETSIZE); if (e.second->total_inbound_size < 65536) FD_SET(e.first, &fd_set_read); if (e.second->total_waiting_size > 0) { if (now < e.second->earliest_next_write) { timeout.tv_sec = 0; timeout.tv_usec = std::min((long unsigned)timeout.tv_usec, to_micros_lu(e.second->earliest_next_write - now)); } else FD_SET(e.first, &fd_set_write); } max = std::max(e.first, max); } } ALWAYS_ASSERT(select(max + 1, &fd_set_read, &fd_set_write, NULL, &timeout) >= 0); now = std::chrono::steady_clock::now(); unsigned char buf[4096]; { std::set<int> remove_set; std::lock_guard<std::mutex> lock(me->fd_map_mutex); for (const auto& e : me->fd_map) { Connection* conn = e.second; if (FD_ISSET(e.first, &fd_set_read)) { ssize_t count = recv(conn->sock, (char*)buf, 4096, 0); std::lock_guard<std::mutex> lock(conn->read_mutex); if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) { remove_set.insert(e.first); conn->sock_errno = errno; } else { conn->inbound_queue.emplace_back(new std::vector<unsigned char>(buf, buf + count)); conn->total_inbound_size += count; conn->read_cv.notify_all(); } } if (FD_ISSET(e.first, &fd_set_write)) { if (now < conn->earliest_next_write) continue; std::lock_guard<std::mutex> lock(conn->send_mutex); if (!conn->secondary_writepos && conn->outbound_primary_queue.size()) { auto& msg = conn->outbound_primary_queue.front(); ssize_t count = send(conn->sock, (char*) &(*msg)[conn->primary_writepos], msg->size() - conn->primary_writepos, MSG_NOSIGNAL); if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) { remove_set.insert(e.first); conn->sock_errno = errno; } else { conn->primary_writepos += count; if (conn->primary_writepos == msg->size()) { conn->primary_writepos = 0; conn->total_waiting_size -= msg->size(); conn->outbound_primary_queue.pop_front(); } } } else { assert(conn->outbound_secondary_queue.size() && !conn->primary_writepos); auto& msg = conn->outbound_secondary_queue.front(); ssize_t count = send(conn->sock, (char*) &(*msg)[conn->secondary_writepos], msg->size() - conn->secondary_writepos, MSG_NOSIGNAL); if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) { remove_set.insert(e.first); conn->sock_errno = errno; } else { conn->secondary_writepos += count; if (conn->secondary_writepos == msg->size()) { conn->secondary_writepos = 0; conn->total_waiting_size -= msg->size(); conn->outbound_secondary_queue.pop_front(); } } } if (!conn->total_waiting_size) conn->initial_outbound_throttle = false; else if (!conn->primary_writepos && !conn->secondary_writepos && conn->initial_outbound_throttle) conn->earliest_next_write = std::chrono::steady_clock::now() + std::chrono::milliseconds(20); // Limit outbound to avg 5Mbps worst-case } } for (const int fd : remove_set) { Connection* conn = me->fd_map[fd]; std::lock_guard<std::mutex> lock(conn->read_mutex); conn->inbound_queue.emplace_back((std::nullptr_t)NULL); conn->read_cv.notify_all(); conn->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE; me->fd_map.erase(fd); } } #ifndef WIN32 if (FD_ISSET(pipefd[0], &fd_set_read)) while (read(pipefd[0], buf, 4096) > 0); #endif } } GlobalNetProcess() { std::thread(do_net_process, this).detach(); } }; static GlobalNetProcess processor; Connection::~Connection() { assert(disconnectFlags & DISCONNECT_COMPLETE); user_thread->join(); close(sock); delete user_thread; } void Connection::do_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) { if (!send_mutex_token) send_mutex.lock(); else ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token); if (initial_outbound_throttle && send_mutex_token) initial_outbound_bytes += bytes->size(); if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) { if (!send_mutex_token) send_mutex.unlock(); return disconnect_from_outside("total_waiting_size blew up :("); } outbound_primary_queue.push_back(bytes); total_waiting_size += bytes->size(); #ifndef WIN32 if (total_waiting_size > (ssize_t)bytes->size()) write(processor.pipe_write, "1", 1); #endif if (!send_mutex_token) send_mutex.unlock(); } void Connection::maybe_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) { if (!send_mutex_token) { if (!send_mutex.try_lock()) return; } else ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token); if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) { if (!send_mutex_token) send_mutex.unlock(); return disconnect_from_outside("total_waiting_size blew up :("); } outbound_secondary_queue.push_back(bytes); total_waiting_size += bytes->size(); #ifndef WIN32 if (total_waiting_size > (ssize_t)bytes->size()) write(processor.pipe_write, "1", 1); #endif if (!send_mutex_token) send_mutex.unlock(); } void Connection::disconnect_from_outside(const char* reason) { if (disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE) return; printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(errno)); shutdown(sock, SHUT_RDWR); } void Connection::disconnect(const char* reason) { if (disconnectFlags.fetch_or(DISCONNECT_STARTED) & DISCONNECT_STARTED) return; if (!(disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE)) { printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(sock_errno)); shutdown(sock, SHUT_RDWR); } assert(std::this_thread::get_id() == user_thread->get_id()); std::unique_lock<std::mutex> lock(read_mutex); while (!(disconnectFlags & DISCONNECT_GLOBAL_THREAD_DONE)) read_cv.wait(lock); outbound_secondary_queue.clear(); outbound_primary_queue.clear(); inbound_queue.clear(); disconnectFlags |= DISCONNECT_COMPLETE; if (on_disconnect) std::thread(on_disconnect).detach(); } void Connection::do_setup_and_read(Connection* me) { #ifdef WIN32 unsigned long nonblocking = 1; ioctlsocket(me->sock, FIONBIO, &nonblocking); #else fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) | O_NONBLOCK); #endif #ifdef X86_BSD int nosigpipe = 1; setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int)); #endif int nodelay = 1; setsockopt(me->sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay)); if (errno) { me->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE; return me->disconnect("error during connect"); } { std::lock_guard<std::mutex> lock(processor.fd_map_mutex); processor.fd_map[me->sock] = me; #ifndef WIN32 write(processor.pipe_write, "1", 1); #endif } me->net_process([&](const char* reason) { me->disconnect(reason); }); } ssize_t Connection::read_all(char *buf, size_t nbyte) { size_t total = 0; while (total < nbyte) { std::unique_lock<std::mutex> lock(read_mutex); while (!inbound_queue.size()) read_cv.wait(lock); if (!inbound_queue.front()) return -1; size_t readamt = std::min(nbyte - total, inbound_queue.front()->size() - readpos); memcpy(buf + total, &(*inbound_queue.front())[readpos], readamt); if (readpos + readamt == inbound_queue.front()->size()) { #ifndef WIN32 int32_t old_size = total_inbound_size; #endif total_inbound_size -= inbound_queue.front()->size(); #ifndef WIN32 // If the old size is >= 64k, we may need to wakeup the select thread to get it to read more if (old_size >= 65536) write(processor.pipe_write, "1", 1); #endif readpos = 0; inbound_queue.pop_front(); } else readpos += readamt; total += readamt; } assert(total == nbyte); return nbyte; } void OutboundPersistentConnection::reconnect(std::string disconnectReason) { OutboundConnection* old = (OutboundConnection*) connection.fetch_and(0); if (old) old->disconnect_from_outside(disconnectReason.c_str()); on_disconnect(); std::this_thread::sleep_for(std::chrono::seconds(1)); while (old && !(old->getDisconnectFlags() & DISCONNECT_COMPLETE)) { printf("Disconnect of outbound connection still not complete (status is %d)\n", old->getDisconnectFlags()); std::this_thread::sleep_for(std::chrono::seconds(1)); } std::thread(do_connect, this).detach(); delete old; } void OutboundPersistentConnection::do_connect(OutboundPersistentConnection* me) { int sock = socket(AF_INET6, SOCK_STREAM, 0); if (sock <= 0) return me->reconnect("unable to create socket"); sockaddr_in6 addr; if (!lookup_address(me->serverHost.c_str(), &addr)) { close(sock); return me->reconnect("unable to lookup host"); } int v6only = 0; setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only)); addr.sin6_port = htons(me->serverPort); if (connect(sock, (struct sockaddr*)&addr, sizeof(addr))) { close(sock); return me->reconnect("failed to connect()"); } OutboundConnection* new_conn = new OutboundConnection(sock, me); #ifndef NDEBUG unsigned long old_val = #endif me->connection.exchange((unsigned long)new_conn); assert(old_val == 0); new_conn->construction_done(); }
#include <assert.h> #include <string.h> #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #define SHUT_RDWR SD_BOTH #else // WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #endif // !WIN32 #include <unordered_map> #include <set> #include "connection.h" #include "utils.h" class GlobalNetProcess { public: std::mutex fd_map_mutex; std::unordered_map<int, Connection*> fd_map; #ifndef WIN32 int pipe_write; #endif static void do_net_process(GlobalNetProcess* me) { fd_set fd_set_read, fd_set_write; struct timeval timeout; #ifndef WIN32 int pipefd[2]; ALWAYS_ASSERT(!pipe(pipefd)); fcntl(pipefd[1], F_SETFL, fcntl(pipefd[1], F_GETFL) | O_NONBLOCK); fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK); me->pipe_write = pipefd[1]; #endif while (true) { #ifndef WIN32 timeout.tv_sec = 86400; timeout.tv_usec = 20 * 1000; #else timeout.tv_sec = 0; timeout.tv_usec = 1000; #endif FD_ZERO(&fd_set_read); FD_ZERO(&fd_set_write); #ifndef WIN32 int max = pipefd[0]; FD_SET(pipefd[0], &fd_set_read); #else int max = 0; #endif auto now = std::chrono::steady_clock::now(); { std::lock_guard<std::mutex> lock(me->fd_map_mutex); for (const auto& e : me->fd_map) { ALWAYS_ASSERT(e.first < FD_SETSIZE); if (e.second->total_inbound_size < 65536) FD_SET(e.first, &fd_set_read); if (e.second->total_waiting_size > 0) { if (now < e.second->earliest_next_write) { timeout.tv_sec = 0; timeout.tv_usec = std::min((long unsigned)timeout.tv_usec, to_micros_lu(e.second->earliest_next_write - now)); } else FD_SET(e.first, &fd_set_write); } max = std::max(e.first, max); } } ALWAYS_ASSERT(select(max + 1, &fd_set_read, &fd_set_write, NULL, &timeout) >= 0); now = std::chrono::steady_clock::now(); unsigned char buf[4096]; { std::set<int> remove_set; std::lock_guard<std::mutex> lock(me->fd_map_mutex); for (const auto& e : me->fd_map) { Connection* conn = e.second; if (FD_ISSET(e.first, &fd_set_read)) { ssize_t count = recv(conn->sock, (char*)buf, 4096, 0); std::lock_guard<std::mutex> lock(conn->read_mutex); if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) { remove_set.insert(e.first); conn->sock_errno = errno; } else { conn->inbound_queue.emplace_back(new std::vector<unsigned char>(buf, buf + count)); conn->total_inbound_size += count; conn->read_cv.notify_all(); } } if (FD_ISSET(e.first, &fd_set_write)) { if (now < conn->earliest_next_write) continue; std::lock_guard<std::mutex> lock(conn->send_mutex); if (!conn->secondary_writepos && conn->outbound_primary_queue.size()) { auto& msg = conn->outbound_primary_queue.front(); ssize_t count = send(conn->sock, (char*) &(*msg)[conn->primary_writepos], msg->size() - conn->primary_writepos, MSG_NOSIGNAL); if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) { remove_set.insert(e.first); conn->sock_errno = errno; } else { conn->primary_writepos += count; if (conn->primary_writepos == msg->size()) { conn->primary_writepos = 0; conn->total_waiting_size -= msg->size(); conn->outbound_primary_queue.pop_front(); } } } else { assert(conn->outbound_secondary_queue.size() && !conn->primary_writepos); auto& msg = conn->outbound_secondary_queue.front(); ssize_t count = send(conn->sock, (char*) &(*msg)[conn->secondary_writepos], msg->size() - conn->secondary_writepos, MSG_NOSIGNAL); if (count <= 0 && errno != EAGAIN && errno != EWOULDBLOCK) { remove_set.insert(e.first); conn->sock_errno = errno; } else { conn->secondary_writepos += count; if (conn->secondary_writepos == msg->size()) { conn->secondary_writepos = 0; conn->total_waiting_size -= msg->size(); conn->outbound_secondary_queue.pop_front(); } } } if (!conn->total_waiting_size) conn->initial_outbound_throttle = false; else if (!conn->primary_writepos && !conn->secondary_writepos && conn->initial_outbound_throttle) conn->earliest_next_write = std::chrono::steady_clock::now() + std::chrono::milliseconds(20); // Limit outbound to avg 5Mbps worst-case } } for (const int fd : remove_set) { Connection* conn = me->fd_map[fd]; std::lock_guard<std::mutex> lock(conn->read_mutex); conn->inbound_queue.emplace_back((std::nullptr_t)NULL); conn->read_cv.notify_all(); conn->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE; me->fd_map.erase(fd); } } #ifndef WIN32 if (FD_ISSET(pipefd[0], &fd_set_read)) while (read(pipefd[0], buf, 4096) > 0); #endif } } GlobalNetProcess() { std::thread(do_net_process, this).detach(); } }; static GlobalNetProcess processor; Connection::~Connection() { assert(disconnectFlags & DISCONNECT_COMPLETE); user_thread->join(); close(sock); delete user_thread; } void Connection::do_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) { if (!send_mutex_token) send_mutex.lock(); else ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token); if (initial_outbound_throttle && send_mutex_token) initial_outbound_bytes += bytes->size(); if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) { if (!send_mutex_token) send_mutex.unlock(); return disconnect_from_outside("total_waiting_size blew up :("); } outbound_primary_queue.push_back(bytes); total_waiting_size += bytes->size(); #ifndef WIN32 if (total_waiting_size > (ssize_t)bytes->size()) ALWAYS_ASSERT(write(processor.pipe_write, "1", 1) == 1); #endif if (!send_mutex_token) send_mutex.unlock(); } void Connection::maybe_send_bytes(const std::shared_ptr<std::vector<unsigned char> >& bytes, int send_mutex_token) { if (!send_mutex_token) { if (!send_mutex.try_lock()) return; } else ALWAYS_ASSERT(send_mutex_token == outside_send_mutex_token); if (total_waiting_size - (initial_outbound_throttle ? initial_outbound_bytes : 0) > 4000000) { if (!send_mutex_token) send_mutex.unlock(); return disconnect_from_outside("total_waiting_size blew up :("); } outbound_secondary_queue.push_back(bytes); total_waiting_size += bytes->size(); #ifndef WIN32 if (total_waiting_size > (ssize_t)bytes->size()) ALWAYS_ASSERT(write(processor.pipe_write, "1", 1) == 1); #endif if (!send_mutex_token) send_mutex.unlock(); } void Connection::disconnect_from_outside(const char* reason) { if (disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE) return; printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(errno)); shutdown(sock, SHUT_RDWR); } void Connection::disconnect(const char* reason) { if (disconnectFlags.fetch_or(DISCONNECT_STARTED) & DISCONNECT_STARTED) return; if (!(disconnectFlags.fetch_or(DISCONNECT_PRINT_AND_CLOSE) & DISCONNECT_PRINT_AND_CLOSE)) { printf("%s Disconnect: %s (%s)\n", host.c_str(), reason, strerror(sock_errno)); shutdown(sock, SHUT_RDWR); } assert(std::this_thread::get_id() == user_thread->get_id()); std::unique_lock<std::mutex> lock(read_mutex); while (!(disconnectFlags & DISCONNECT_GLOBAL_THREAD_DONE)) read_cv.wait(lock); outbound_secondary_queue.clear(); outbound_primary_queue.clear(); inbound_queue.clear(); disconnectFlags |= DISCONNECT_COMPLETE; if (on_disconnect) std::thread(on_disconnect).detach(); } void Connection::do_setup_and_read(Connection* me) { #ifdef WIN32 unsigned long nonblocking = 1; ioctlsocket(me->sock, FIONBIO, &nonblocking); #else fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) | O_NONBLOCK); #endif #ifdef X86_BSD int nosigpipe = 1; setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int)); #endif int nodelay = 1; setsockopt(me->sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay)); if (errno) { me->disconnectFlags |= DISCONNECT_GLOBAL_THREAD_DONE; return me->disconnect("error during connect"); } { std::lock_guard<std::mutex> lock(processor.fd_map_mutex); processor.fd_map[me->sock] = me; #ifndef WIN32 ALWAYS_ASSERT(write(processor.pipe_write, "1", 1) == 1); #endif } me->net_process([&](const char* reason) { me->disconnect(reason); }); } ssize_t Connection::read_all(char *buf, size_t nbyte) { size_t total = 0; while (total < nbyte) { std::unique_lock<std::mutex> lock(read_mutex); while (!inbound_queue.size()) read_cv.wait(lock); if (!inbound_queue.front()) return -1; size_t readamt = std::min(nbyte - total, inbound_queue.front()->size() - readpos); memcpy(buf + total, &(*inbound_queue.front())[readpos], readamt); if (readpos + readamt == inbound_queue.front()->size()) { #ifndef WIN32 int32_t old_size = total_inbound_size; #endif total_inbound_size -= inbound_queue.front()->size(); #ifndef WIN32 // If the old size is >= 64k, we may need to wakeup the select thread to get it to read more if (old_size >= 65536) ALWAYS_ASSERT(write(processor.pipe_write, "1", 1) == 1); #endif readpos = 0; inbound_queue.pop_front(); } else readpos += readamt; total += readamt; } assert(total == nbyte); return nbyte; } void OutboundPersistentConnection::reconnect(std::string disconnectReason) { OutboundConnection* old = (OutboundConnection*) connection.fetch_and(0); if (old) old->disconnect_from_outside(disconnectReason.c_str()); on_disconnect(); std::this_thread::sleep_for(std::chrono::seconds(1)); while (old && !(old->getDisconnectFlags() & DISCONNECT_COMPLETE)) { printf("Disconnect of outbound connection still not complete (status is %d)\n", old->getDisconnectFlags()); std::this_thread::sleep_for(std::chrono::seconds(1)); } std::thread(do_connect, this).detach(); delete old; } void OutboundPersistentConnection::do_connect(OutboundPersistentConnection* me) { int sock = socket(AF_INET6, SOCK_STREAM, 0); if (sock <= 0) return me->reconnect("unable to create socket"); sockaddr_in6 addr; if (!lookup_address(me->serverHost.c_str(), &addr)) { close(sock); return me->reconnect("unable to lookup host"); } int v6only = 0; setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only)); addr.sin6_port = htons(me->serverPort); if (connect(sock, (struct sockaddr*)&addr, sizeof(addr))) { close(sock); return me->reconnect("failed to connect()"); } OutboundConnection* new_conn = new OutboundConnection(sock, me); #ifndef NDEBUG unsigned long old_val = #endif me->connection.exchange((unsigned long)new_conn); assert(old_val == 0); new_conn->construction_done(); }
Fix compile warnings
Fix compile warnings
C++
mit
TheBlueMatt/RelayNode,TheBlueMatt/RelayNode,martindale/RelayNode,danoctavian/RelayNode,arnuschky/RelayNode,danoctavian/RelayNode,BitcoinRelayNetwork/RelayNode,arnuschky/RelayNode,BitcoinRelayNetwork/RelayNode,martindale/RelayNode,BitcoinRelayNetwork/RelayNode
ae428292bc1680db6b80302385f3971bdf26fefe
1v1_neckbeard_server/Server.cpp
1v1_neckbeard_server/Server.cpp
// // Server.cpp // 1v1_server // // Created by Filip Peterek on 12/12/2016. // Copyright © 2016 Filip Peterek. All rights reserved. // #include "Server.hpp" Server::Server(unsigned short clientPort, unsigned short serverPort) : _clientPort(clientPort), _serverPort(serverPort), _player1(_world), _player2(_world) { if (_socket.bind(_serverPort) != sf::Socket::Done) { std::stringstream ss; ss << "Error binding UDP socket to port " << _serverPort; throw std::runtime_error(ss.str()); } _response.addEntity(_player1); _response.addEntity(_player2); _response.addEntity(_player1.getDorito()); _response.addEntity(_player2.getDorito()); resetPlayers(); waitForConnection(); /* Restart clock before doing anything else */ _clock.restart(); mainLoop(); } void Server::resetPlayers() { /* Player sprite is 10 pixels wide without hair (hitbox is 10 pixels wide) */ /* Player sprite is scaled up by 3, therefor the hitbox is 10 * 3 */ /* Width of player is 30 */ _player1.position().x = 110; _player1.position().y = 150; _player1.direction() = direction::right; _player2.position().x = 690 - 30; #ifdef TEMPORARY_MOVE_PLAYER2 _player2.position().x -= 200; #endif _player2.position().y = 150; _player2.direction() = direction::left; auto init = [&] (Player & player) -> void { player.resetAttack(); player.resetDorito(); player.getHitbox().setPosition(player.position().x, player.position().y); player.hp() = 6; }; init(_player1); init(_player2); } sf::IpAddress Server::playerConnection() { char input[8]; size_t received = 0; sf::IpAddress address; unsigned short port; while (true) { _socket.receive(input, 8, received, address, port); std::cout << "Received " << received << " bytes from " << address.toString() << ":" << port << " - " << input << std::endl; if (port != _clientPort) { continue; } if (strcmp(input, "connect")) { continue; } break; } std::cout << "Received " << received << " bytes from " << address.toString() << std::endl; char response[10] = { 'c', 'o', 'n', 'n', 'e', 'c', 't', 'e', 'd', '\0' }; _socket.send(response, 10, address, port); return address; } void Server::waitForConnection() { std::cout << "IP Address: " << sf::IpAddress::getLocalAddress() << "\n" << std::endl; std::cout << "Waiting for connection...\n" << "IP Address 1: None \n" << "IP Address 2: None" << std::endl; _addr1 = playerConnection(); #ifndef NO_2_PLAYERS std::cout << "Waiting for connection... \n" << "IP Address 1: " << _addr1.toString() << "\nIP Address 2: None" << std::endl; _addr2 = playerConnection(); #endif std::cout << "\u001b[2J\u001b[1;1H" << std::endl; std::cout << "2 players connected, running server... \n"; std::cout << "Player 1: " << _addr1.toString() << ":" << _clientPort << "\n"; std::cout << "Player 2: " << _addr2.toString() << ":" << _clientPort << std::endl; } void Server::acceptRequest(sf::IpAddress & targetIP) { size_t received; sf::IpAddress remoteAddress; unsigned short remotePort; Player & player = (targetIP == _addr1) ? _player1 : _player2; sf::Socket::Status status = _socket.receive(_receivedData, 255, received, remoteAddress, remotePort); if (status != sf::Socket::Done or not player.canPerformAction()) { return player.update(); } if (remoteAddress == targetIP and remotePort == _clientPort) { parseRequest(player); } } void Server::parseRequest(Player & player) { std::string data(_receivedData); /* Request won't be greater than 255 bytes, so I can use an unsigned char, because it will never overflow */ unsigned char iter = 1; char action = data[iter]; while (action != '}') { switch (action) { case LEFT: case RIGHT: player.move(direction(action)); break; case JUMP: player.jump(); break; case ATTACK: player.attack(); break; case DORITO: player.throwDorito(); break; default: break; } action = data[++iter]; } } void Server::sendData() { std::string dataStr = _response.generateResponse(); const char * data = dataStr.c_str(); size_t dataLen = dataStr.length(); _socket.send(data, dataLen, _addr1, _clientPort); #ifndef NO_2_PLAYERS _socket.send(data, dataLen, _addr2, _clientPort); #endif } void Server::sleep(const unsigned int milliseconds) { static int timeSlept = 0; int timeToSleep = milliseconds - _clock.restart().asMilliseconds() + (timeSlept < 0 ? timeSlept : 0); std::this_thread::sleep_for( std::chrono::milliseconds(timeToSleep) ); timeSlept = timeToSleep; // std::cout << "Time slept: " << timeSlept << std::endl; } void Server::updatePlayers() { _player1.applyForce(); _player1.updateDorito(); _player2.applyForce(); _player2.updateDorito(); if ( _player1.collidesWith(_player2.getSwordHitbox()) ) { _player1.takeDamage(); _player2.resetAttackHitbox(); } else if ( _player1.collidesWith(_player2.getDorito().getHitbox()) ) { _player1.takeDamage(); _player2.resetDorito(); } if (_player2.collidesWith(_player1.getSwordHitbox())) { _player2.takeDamage(); _player1.resetAttackHitbox(); } else if ( _player2.collidesWith(_player1.getDorito().getHitbox()) ) { _player2.takeDamage(); _player1.resetDorito(); } if (_player1.hp() <= 0) { _player2.incrementVictoryCounter(); resetPlayers(); } else if (_player2.hp() <= 0) { _player1.incrementVictoryCounter(); resetPlayers(); } } void Server::mainLoop() { /* Probably don't want a blocking socket anymore, so the server doesn't stop to wait for */ /* packet if one client loses connection */ _socket.setBlocking(false); while (true) { /* Accept and parse requests from both clients */ acceptRequest(_addr1); #ifndef NO_2_PLAYERS /* Trying to accept a request from 0.0.0.0 is probably pointless */ /* Gotta save the 5 cycles */ acceptRequest(_addr2); #endif updatePlayers(); sendData(); /* I hope I can just make the thread sleep */ sleep(15); } }
// // Server.cpp // 1v1_server // // Created by Filip Peterek on 12/12/2016. // Copyright © 2016 Filip Peterek. All rights reserved. // #include "Server.hpp" Server::Server(unsigned short clientPort, unsigned short serverPort) : _clientPort(clientPort), _serverPort(serverPort), _player1(_world), _player2(_world) { if (_socket.bind(_serverPort) != sf::Socket::Done) { std::stringstream ss; ss << "Error binding UDP socket to port " << _serverPort; throw std::runtime_error(ss.str()); } _response.addEntity(_player1); _response.addEntity(_player2); _response.addEntity(_player1.getDorito()); _response.addEntity(_player2.getDorito()); resetPlayers(); waitForConnection(); /* Restart clock before doing anything else */ _clock.restart(); mainLoop(); } void Server::resetPlayers() { /* Player sprite is 10 pixels wide without hair (hitbox is 10 pixels wide) */ /* Player sprite is scaled up by 3, therefor the hitbox is 10 * 3 */ /* Width of player is 30 */ _player1.position().x = 110; _player1.position().y = 150; _player1.getDirection() = direction::right; _player2.position().x = 690 - 30; #ifdef TEMPORARY_MOVE_PLAYER2 _player2.position().x -= 200; #endif _player2.position().y = 150; _player2.getDirection() = direction::left; auto init = [&] (Player & player) -> void { player.resetAttack(); player.resetDorito(); player.getHitbox().setPosition(player.position().x, player.position().y); player.hp() = 6; }; init(_player1); init(_player2); } sf::IpAddress Server::playerConnection() { char input[8]; size_t received = 0; sf::IpAddress address; unsigned short port; while (true) { _socket.receive(input, 8, received, address, port); std::cout << "Received " << received << " bytes from " << address.toString() << ":" << port << " - " << input << std::endl; if (port != _clientPort) { continue; } if (strcmp(input, "connect")) { continue; } break; } std::cout << "Received " << received << " bytes from " << address.toString() << std::endl; char response[10] = { 'c', 'o', 'n', 'n', 'e', 'c', 't', 'e', 'd', '\0' }; _socket.send(response, 10, address, port); return address; } void Server::waitForConnection() { std::cout << "IP Address: " << sf::IpAddress::getLocalAddress() << "\n" << std::endl; std::cout << "Waiting for connection...\n" << "IP Address 1: None \n" << "IP Address 2: None" << std::endl; _addr1 = playerConnection(); #ifndef NO_2_PLAYERS std::cout << "Waiting for connection... \n" << "IP Address 1: " << _addr1.toString() << "\nIP Address 2: None" << std::endl; _addr2 = playerConnection(); #endif std::cout << "\u001b[2J\u001b[1;1H" << std::endl; std::cout << "2 players connected, running server... \n"; std::cout << "Player 1: " << _addr1.toString() << ":" << _clientPort << "\n"; std::cout << "Player 2: " << _addr2.toString() << ":" << _clientPort << std::endl; } void Server::acceptRequest(sf::IpAddress & targetIP) { size_t received; sf::IpAddress remoteAddress; unsigned short remotePort; Player & player = (targetIP == _addr1) ? _player1 : _player2; sf::Socket::Status status = _socket.receive(_receivedData, 255, received, remoteAddress, remotePort); if (status != sf::Socket::Done or not player.canPerformAction()) { return player.update(); } if (remoteAddress == targetIP and remotePort == _clientPort) { parseRequest(player); } } void Server::parseRequest(Player & player) { std::string data(_receivedData); /* Request won't be greater than 255 bytes, so I can use an unsigned char, because it will never overflow */ unsigned char iter = 1; char action = data[iter]; while (action != '}') { switch (action) { case LEFT: case RIGHT: player.move(direction(action)); break; case JUMP: player.jump(); break; case ATTACK: player.attack(); break; case DORITO: player.throwDorito(); break; default: break; } action = data[++iter]; } } void Server::sendData() { std::string dataStr = _response.generateResponse(); const char * data = dataStr.c_str(); size_t dataLen = dataStr.length(); _socket.send(data, dataLen, _addr1, _clientPort); #ifndef NO_2_PLAYERS _socket.send(data, dataLen, _addr2, _clientPort); #endif } void Server::sleep(const unsigned int milliseconds) { static int timeSlept = 0; int timeToSleep = milliseconds - _clock.restart().asMilliseconds() + (timeSlept < 0 ? timeSlept : 0); std::this_thread::sleep_for( std::chrono::milliseconds(timeToSleep) ); timeSlept = timeToSleep; // std::cout << "Time slept: " << timeSlept << std::endl; } void Server::updatePlayers() { _player1.applyForce(); _player1.updateDorito(); _player2.applyForce(); _player2.updateDorito(); if ( _player1.collidesWith(_player2.getSwordHitbox()) ) { _player1.takeDamage(); _player2.resetAttackHitbox(); } else if ( _player1.collidesWith(_player2.getDorito().getHitbox()) ) { _player1.takeDamage(); _player2.resetDorito(); } if (_player2.collidesWith(_player1.getSwordHitbox())) { _player2.takeDamage(); _player1.resetAttackHitbox(); } else if ( _player2.collidesWith(_player1.getDorito().getHitbox()) ) { _player2.takeDamage(); _player1.resetDorito(); } if (_player1.hp() <= 0) { _player2.incrementVictoryCounter(); resetPlayers(); } else if (_player2.hp() <= 0) { _player1.incrementVictoryCounter(); resetPlayers(); } } void Server::mainLoop() { /* Probably don't want a blocking socket anymore, so the server doesn't stop to wait for */ /* packet if one client loses connection */ _socket.setBlocking(false); while (true) { /* Accept and parse requests from both clients */ acceptRequest(_addr1); #ifndef NO_2_PLAYERS /* Trying to accept a request from 0.0.0.0 is probably pointless */ /* Gotta save the 5 cycles */ acceptRequest(_addr2); #endif updatePlayers(); sendData(); /* I hope I can just make the thread sleep */ sleep(15); } }
Update Server.cpp
Update Server.cpp
C++
apache-2.0
fpeterek/1v1-game-server,fpeterek/1v1-game-server
cb051a976bf3160df9292a55dc60cfe87932afda
src/engine/core/src/api/halley_api.cpp
src/engine/core/src/api/halley_api.cpp
#include <utility> #include "api/halley_api.h" #include <halley/plugin/plugin.h> #include "halley/audio/audio_facade.h" #include "halley/support/logger.h" #include "entry/entry_point.h" using namespace Halley; void HalleyAPI::assign() { Expects(coreInternal != nullptr); Expects(systemInternal != nullptr); core = coreInternal; system = systemInternal.get(); if (videoInternal) { video = videoInternal.get(); } if (inputInternal) { input = inputInternal.get(); } if (audioInternal) { audio = audioInternal.get(); } if (platformInternal) { platform = platformInternal.get(); } if (networkInternal) { network = networkInternal.get(); } if (movieInternal) { movie = movieInternal.get(); } } void HalleyAPI::init() { if (systemInternal) { systemInternal->init(); } if (videoInternal) { videoInternal->init(); } if (inputInternal) { inputInternal->init(); } if (audioOutputInternal) { audioOutputInternal->init(); } if (audioInternal) { audioInternal->init(); } if (platformInternal) { platformInternal->init(); } if (networkInternal) { networkInternal->init(); } if (movieInternal) { movieInternal->init(); } } void HalleyAPI::deInit() { if (movieInternal) { movieInternal->deInit(); } if (networkInternal) { networkInternal->deInit(); } if (platformInternal) { platformInternal->deInit(); } if (audioInternal) { audioInternal->deInit(); } if (audioOutputInternal) { audioOutputInternal->deInit(); } if (inputInternal) { inputInternal->deInit(); } if (videoInternal) { videoInternal->deInit(); } if (systemInternal) { systemInternal->deInit(); } } std::unique_ptr<HalleyAPI> HalleyAPI::create(CoreAPIInternal* core, int flags) { auto api = std::make_unique<HalleyAPI>(); api->coreInternal = core; HalleyAPIFlags::Flags flagList[] = { HalleyAPIFlags::System, HalleyAPIFlags::Video, HalleyAPIFlags::Input, HalleyAPIFlags::Audio, HalleyAPIFlags::Network, HalleyAPIFlags::Platform, HalleyAPIFlags::Movie }; PluginType pluginTypes[] = { PluginType::SystemAPI, PluginType::GraphicsAPI, PluginType::InputAPI, PluginType::AudioOutputAPI, PluginType::NetworkAPI, PluginType::PlatformAPI, PluginType::MovieAPI }; String names[] = { "System", "Graphics", "Input", "AudioOutput", "Network", "Platform", "Movie" }; constexpr size_t n = std::end(flagList) - std::begin(flagList); for (size_t i = 0; i < n; ++i) { if (flags & flagList[i] || flagList[i] == HalleyAPIFlags::System) { auto plugins = core->getPlugins(pluginTypes[i]); if (!plugins.empty()) { Logger::logInfo(names[i] + " plugin: " + plugins[0]->getName()); api->setAPI(pluginTypes[i], plugins[0]->createAPI(api->systemInternal.get())); } else { throw Exception("No suitable " + names[i] + " plugins found.", HalleyExceptions::Core); } } } api->assign(); return api; } void HalleyAPI::setAPI(PluginType pluginType, HalleyAPIInternal* api) { switch (pluginType) { case PluginType::SystemAPI: systemInternal.reset(dynamic_cast<SystemAPIInternal*>(api)); return; case PluginType::InputAPI: inputInternal.reset(dynamic_cast<InputAPIInternal*>(api)); return; case PluginType::GraphicsAPI: videoInternal.reset(dynamic_cast<VideoAPIInternal*>(api)); return; case PluginType::AudioOutputAPI: audioOutputInternal.reset(dynamic_cast<AudioOutputAPIInternal*>(api)); audioInternal = std::make_unique<AudioFacade>(*audioOutputInternal, *systemInternal); return; case PluginType::PlatformAPI: platformInternal.reset(dynamic_cast<PlatformAPIInternal*>(api)); return; case PluginType::NetworkAPI: networkInternal.reset(dynamic_cast<NetworkAPIInternal*>(api)); return; case PluginType::MovieAPI: movieInternal.reset(dynamic_cast<MovieAPIInternal*>(api)); return; } } HalleyAPI& HalleyAPI::operator=(const HalleyAPI& other) = default; std::unique_ptr<HalleyAPI> HalleyAPI::clone() const { auto api = std::make_unique<HalleyAPI>(); *api = *this; return api; } void HalleyAPI::replaceCoreAPI(CoreAPIInternal* coreAPI) { coreInternal = coreAPI; core = coreAPI; } uint32_t Halley::getHalleyDLLAPIVersion() { return 252; }
#include <utility> #include "api/halley_api.h" #include <halley/plugin/plugin.h> #include "halley/audio/audio_facade.h" #include "halley/support/logger.h" #include "entry/entry_point.h" using namespace Halley; void HalleyAPI::assign() { Expects(coreInternal != nullptr); Expects(systemInternal != nullptr); core = coreInternal; system = systemInternal.get(); if (videoInternal) { video = videoInternal.get(); } if (inputInternal) { input = inputInternal.get(); } if (audioInternal) { audio = audioInternal.get(); } if (platformInternal) { platform = platformInternal.get(); } if (networkInternal) { network = networkInternal.get(); } if (movieInternal) { movie = movieInternal.get(); } } void HalleyAPI::init() { if (systemInternal) { systemInternal->init(); } if (videoInternal) { videoInternal->init(); } if (inputInternal) { inputInternal->init(); } if (audioOutputInternal) { audioOutputInternal->init(); } if (audioInternal) { audioInternal->init(); } if (platformInternal) { platformInternal->init(); } if (networkInternal) { networkInternal->init(); } if (movieInternal) { movieInternal->init(); } } void HalleyAPI::deInit() { if (movieInternal) { movieInternal->deInit(); } if (networkInternal) { networkInternal->deInit(); } if (platformInternal) { platformInternal->deInit(); } if (audioInternal) { audioInternal->deInit(); } if (audioOutputInternal) { audioOutputInternal->deInit(); } if (inputInternal) { inputInternal->deInit(); } if (videoInternal) { videoInternal->deInit(); } if (systemInternal) { systemInternal->deInit(); } } std::unique_ptr<HalleyAPI> HalleyAPI::create(CoreAPIInternal* core, int flags) { auto api = std::make_unique<HalleyAPI>(); api->coreInternal = core; HalleyAPIFlags::Flags flagList[] = { HalleyAPIFlags::System, HalleyAPIFlags::Video, HalleyAPIFlags::Input, HalleyAPIFlags::Audio, HalleyAPIFlags::Network, HalleyAPIFlags::Platform, HalleyAPIFlags::Movie }; PluginType pluginTypes[] = { PluginType::SystemAPI, PluginType::GraphicsAPI, PluginType::InputAPI, PluginType::AudioOutputAPI, PluginType::NetworkAPI, PluginType::PlatformAPI, PluginType::MovieAPI }; String names[] = { "System", "Graphics", "Input", "AudioOutput", "Network", "Platform", "Movie" }; constexpr size_t n = std::end(flagList) - std::begin(flagList); for (size_t i = 0; i < n; ++i) { if (flags & flagList[i] || flagList[i] == HalleyAPIFlags::System) { auto plugins = core->getPlugins(pluginTypes[i]); if (!plugins.empty()) { Logger::logInfo(names[i] + " plugin: " + plugins[0]->getName()); api->setAPI(pluginTypes[i], plugins[0]->createAPI(api->systemInternal.get())); } else { throw Exception("No suitable " + names[i] + " plugins found.", HalleyExceptions::Core); } } } api->assign(); return api; } void HalleyAPI::setAPI(PluginType pluginType, HalleyAPIInternal* api) { switch (pluginType) { case PluginType::SystemAPI: systemInternal.reset(dynamic_cast<SystemAPIInternal*>(api)); return; case PluginType::InputAPI: inputInternal.reset(dynamic_cast<InputAPIInternal*>(api)); return; case PluginType::GraphicsAPI: videoInternal.reset(dynamic_cast<VideoAPIInternal*>(api)); return; case PluginType::AudioOutputAPI: audioOutputInternal.reset(dynamic_cast<AudioOutputAPIInternal*>(api)); audioInternal = std::make_unique<AudioFacade>(*audioOutputInternal, *systemInternal); return; case PluginType::PlatformAPI: platformInternal.reset(dynamic_cast<PlatformAPIInternal*>(api)); return; case PluginType::NetworkAPI: networkInternal.reset(dynamic_cast<NetworkAPIInternal*>(api)); return; case PluginType::MovieAPI: movieInternal.reset(dynamic_cast<MovieAPIInternal*>(api)); return; } } HalleyAPI& HalleyAPI::operator=(const HalleyAPI& other) = default; std::unique_ptr<HalleyAPI> HalleyAPI::clone() const { auto api = std::make_unique<HalleyAPI>(); *api = *this; return api; } void HalleyAPI::replaceCoreAPI(CoreAPIInternal* coreAPI) { coreInternal = coreAPI; core = coreAPI; } uint32_t Halley::getHalleyDLLAPIVersion() { return 253; }
Bump halley api version
Bump halley api version
C++
apache-2.0
amzeratul/halley,amzeratul/halley,amzeratul/halley
65c4b1abaf40e4f6dbd6d15a29f94322c17eaa2d
src/platform/lpc17xx/uart.cpp
src/platform/lpc17xx/uart.cpp
#include <string.h> #include "lpc17xx_pinsel.h" #include "lpc17xx_uart.h" #include "interface/uart.h" #include "pipeline.h" #include "config.h" #include "util/bytebuffer.h" #include "util/log.h" #include "gpio.h" // Only UART1 supports hardware flow control, so this has to be UART1 #define UART1_DEVICE (LPC_UART_TypeDef*)LPC_UART1 #define UART_STATUS_PORT 0 #define UART_STATUS_PIN 18 #ifdef BLUEBOARD #define UART1_FUNCNUM 2 #define UART1_PORTNUM 2 #define UART1_TX_PINNUM 0 #define UART1_RX_PINNUM 1 #define UART1_FLOW_PORTNUM UART1_PORTNUM #define UART1_FLOW_FUNCNUM UART1_FUNCNUM #define UART1_CTS1_PINNUM 2 #define UART1_RTS1_PINNUM 7 #else // Ford OpenXC VI Prototype #define UART1_FUNCNUM 1 #define UART1_PORTNUM 0 #define UART1_TX_PINNUM 15 #define UART1_RX_PINNUM 16 #define UART1_FLOW_PORTNUM 2 #define UART1_FLOW_FUNCNUM 2 #define UART1_RTS1_PINNUM 2 #define UART1_CTS1_PINNUM 7 #endif namespace gpio = openxc::gpio; using openxc::config::getConfiguration; using openxc::util::log::debug; using openxc::pipeline::Pipeline; using openxc::util::bytebuffer::processQueue; using openxc::gpio::GpioValue; using openxc::gpio::GpioDirection; __IO int32_t RTS_STATE; __IO FlagStatus TRANSMIT_INTERRUPT_STATUS; /* Disable request to send through RTS line. We cannot handle any more data * right now. */ void pauseReceive() { if(RTS_STATE == ACTIVE) { // Disable request to send through RTS line UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, INACTIVE); RTS_STATE = INACTIVE; } } /* Enable request to send through RTS line. We can handle more data now. */ void resumeReceive() { if (RTS_STATE == INACTIVE) { // Enable request to send through RTS line UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, ACTIVE); RTS_STATE = ACTIVE; } } void disableTransmitInterrupt() { UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, DISABLE); } void enableTransmitInterrupt() { TRANSMIT_INTERRUPT_STATUS = SET; UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, ENABLE); } void handleReceiveInterrupt() { while(!QUEUE_FULL(uint8_t, &getConfiguration()->uart.receiveQueue)) { uint8_t byte; uint32_t received = UART_Receive(UART1_DEVICE, &byte, 1, NONE_BLOCKING); if(received > 0) { QUEUE_PUSH(uint8_t, &getConfiguration()->uart.receiveQueue, byte); if(QUEUE_FULL(uint8_t, &getConfiguration()->uart.receiveQueue)) { pauseReceive(); } } else { break; } } } void handleTransmitInterrupt() { disableTransmitInterrupt(); while(UART_CheckBusy(UART1_DEVICE) == SET); while(!QUEUE_EMPTY(uint8_t, &getConfiguration()->uart.sendQueue)) { uint8_t byte = QUEUE_PEEK(uint8_t, &getConfiguration()->uart.sendQueue); if(UART_Send(UART1_DEVICE, &byte, 1, NONE_BLOCKING)) { QUEUE_POP(uint8_t, &getConfiguration()->uart.sendQueue); } else { break; } } if(QUEUE_EMPTY(uint8_t, &getConfiguration()->uart.sendQueue)) { disableTransmitInterrupt(); TRANSMIT_INTERRUPT_STATUS = RESET; } else { enableTransmitInterrupt(); } } extern "C" { void UART1_IRQHandler() { uint32_t interruptSource = UART_GetIntId(UART1_DEVICE) & UART_IIR_INTID_MASK; switch(interruptSource) { case UART1_IIR_INTID_MODEM: { // Check Modem status uint8_t modemStatus = UART_FullModemGetStatus(LPC_UART1); // Check CTS status change flag if (modemStatus & UART1_MODEM_STAT_DELTA_CTS) { // if CTS status is active, continue to send data if (modemStatus & UART1_MODEM_STAT_CTS) { UART_TxCmd(UART1_DEVICE, ENABLE); } else { // Otherwise, Stop current transmission immediately UART_TxCmd(UART1_DEVICE, DISABLE); } } break; } case UART_IIR_INTID_RDA: case UART_IIR_INTID_CTI: handleReceiveInterrupt(); break; case UART_IIR_INTID_THRE: handleTransmitInterrupt(); break; default: break; } } } void openxc::interface::uart::read(UartDevice* device, openxc::util::bytebuffer::IncomingMessageCallback callback) { if(device != NULL) { if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) { processQueue(&device->receiveQueue, callback); if(!QUEUE_FULL(uint8_t, &device->receiveQueue)) { resumeReceive(); } } } } /* Auto flow control does work, but it turns the uart write functions into * blocking functions, which drags USB down. Instead we handle it manually so we * can make them asynchronous and let USB run at full speed. */ void configureFlowControl() { if (UART_FullModemGetStatus(LPC_UART1) & UART1_MODEM_STAT_CTS) { // Enable UART Transmit UART_TxCmd(UART1_DEVICE, ENABLE); } // Enable Modem status interrupt UART_IntConfig(UART1_DEVICE, UART1_INTCFG_MS, ENABLE); // Enable CTS1 signal transition interrupt UART_IntConfig(UART1_DEVICE, UART1_INTCFG_CTS, ENABLE); } void configureUartPins() { PINSEL_CFG_Type PinCfg; PinCfg.Funcnum = UART1_FUNCNUM; PinCfg.OpenDrain = 0; PinCfg.Pinmode = 0; PinCfg.Portnum = UART1_PORTNUM; PinCfg.Pinnum = UART1_TX_PINNUM; PINSEL_ConfigPin(&PinCfg); PinCfg.Pinnum = UART1_RX_PINNUM; PINSEL_ConfigPin(&PinCfg); PinCfg.Portnum = UART1_FLOW_PORTNUM; PinCfg.Funcnum = UART1_FLOW_FUNCNUM; PinCfg.Pinnum = UART1_CTS1_PINNUM; PINSEL_ConfigPin(&PinCfg); PinCfg.Pinnum = UART1_RTS1_PINNUM; PINSEL_ConfigPin(&PinCfg); } void configureFifo() { UART_FIFO_CFG_Type fifoConfig; UART_FIFOConfigStructInit(&fifoConfig); UART_FIFOConfig(UART1_DEVICE, &fifoConfig); } void configureInterrupts() { UART_IntConfig(UART1_DEVICE, UART_INTCFG_RBR, ENABLE); enableTransmitInterrupt(); /* preemption = 1, sub-priority = 1 */ NVIC_SetPriority(UART1_IRQn, ((0x01<<3)|0x01)); NVIC_EnableIRQ(UART1_IRQn); } void openxc::interface::uart::changeBaudRate(UartDevice* device, int baud) { UART_CFG_Type UARTConfigStruct; UART_ConfigStructInit(&UARTConfigStruct); UARTConfigStruct.Baud_rate = baud; UART_Init(UART1_DEVICE, &UARTConfigStruct); RTS_STATE = INACTIVE; TRANSMIT_INTERRUPT_STATUS = RESET; configureFifo(); configureInterrupts(); configureFlowControl(); resumeReceive(); } void openxc::interface::uart::writeByte(UartDevice* device, uint8_t byte) { UART_SendByte(UART1_DEVICE, byte); } int openxc::interface::uart::readByte(UartDevice* device) { if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) { return QUEUE_POP(uint8_t, &device->receiveQueue); } return -1; } void openxc::interface::uart::initialize(UartDevice* device) { if(device == NULL) { debug("Can't initialize a NULL UartDevice"); return; } initializeCommon(device); // Configure P0.18 as an input, pulldown LPC_PINCON->PINMODE1 |= (1 << 5); // Ensure BT reset line is held high. LPC_GPIO1->FIODIR |= (1 << 17); gpio::setDirection(UART_STATUS_PORT, UART_STATUS_PIN, GpioDirection::GPIO_DIRECTION_INPUT); configureUartPins(); changeBaudRate(device, device->baudRate); debug("Done."); } void openxc::interface::uart::processSendQueue(UartDevice* device) { if(!QUEUE_EMPTY(uint8_t, &device->sendQueue)) { if(TRANSMIT_INTERRUPT_STATUS == RESET) { handleTransmitInterrupt(); } else { enableTransmitInterrupt(); } } } bool openxc::interface::uart::connected(UartDevice* device) { return device != NULL && gpio::getValue(UART_STATUS_PORT, UART_STATUS_PIN) != GpioValue::GPIO_VALUE_LOW; }
#include <string.h> #include "lpc17xx_pinsel.h" #include "lpc17xx_uart.h" #include "interface/uart.h" #include "pipeline.h" #include "config.h" #include "util/bytebuffer.h" #include "util/log.h" #include "gpio.h" // Only UART1 supports hardware flow control, so this has to be UART1 #define UART1_DEVICE (LPC_UART_TypeDef*)LPC_UART1 #define UART_STATUS_PORT 0 #define UART_STATUS_PIN 18 #ifdef BLUEBOARD #define UART1_FUNCNUM 2 #define UART1_PORTNUM 2 #define UART1_TX_PINNUM 0 #define UART1_RX_PINNUM 1 #define UART1_FLOW_PORTNUM UART1_PORTNUM #define UART1_FLOW_FUNCNUM UART1_FUNCNUM #define UART1_CTS1_PINNUM 2 #define UART1_RTS1_PINNUM 7 #else // Ford OpenXC VI Prototype #define UART1_FUNCNUM 1 #define UART1_PORTNUM 0 #define UART1_TX_PINNUM 15 #define UART1_RX_PINNUM 16 #define UART1_FLOW_PORTNUM 2 #define UART1_FLOW_FUNCNUM 2 #define UART1_RTS1_PINNUM 2 #define UART1_CTS1_PINNUM 7 #endif namespace gpio = openxc::gpio; using openxc::config::getConfiguration; using openxc::util::log::debug; using openxc::pipeline::Pipeline; using openxc::util::bytebuffer::processQueue; using openxc::gpio::GpioValue; using openxc::gpio::GpioDirection; __IO int32_t RTS_STATE; __IO FlagStatus TRANSMIT_INTERRUPT_STATUS; /* Disable request to send through RTS line. We cannot handle any more data * right now. */ void pauseReceive() { if(RTS_STATE == ACTIVE) { // Disable request to send through RTS line UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, INACTIVE); RTS_STATE = INACTIVE; } } /* Enable request to send through RTS line. We can handle more data now. */ void resumeReceive() { if (RTS_STATE == INACTIVE) { // Enable request to send through RTS line UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, ACTIVE); RTS_STATE = ACTIVE; } } void disableTransmitInterrupt() { UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, DISABLE); } void enableTransmitInterrupt() { TRANSMIT_INTERRUPT_STATUS = SET; UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, ENABLE); } void handleReceiveInterrupt() { while(!QUEUE_FULL(uint8_t, &getConfiguration()->uart.receiveQueue)) { uint8_t byte; uint32_t received = UART_Receive(UART1_DEVICE, &byte, 1, NONE_BLOCKING); if(received > 0) { QUEUE_PUSH(uint8_t, &getConfiguration()->uart.receiveQueue, byte); if(QUEUE_FULL(uint8_t, &getConfiguration()->uart.receiveQueue)) { pauseReceive(); } } else { break; } } } void handleTransmitInterrupt() { disableTransmitInterrupt(); while(UART_CheckBusy(UART1_DEVICE) == SET); while(!QUEUE_EMPTY(uint8_t, &getConfiguration()->uart.sendQueue)) { uint8_t byte = QUEUE_PEEK(uint8_t, &getConfiguration()->uart.sendQueue); // We used to use non-blocking here, but then we got into a race // condition - if the transmit interrupt occurred while adding more data // to the queue, you could lose data. We should be able to switch back // to non-blocking if we disabled interrupts while modifying the queue // (good practice anyway) but for now switching this to block sends // seems to work OK without any significant impacts. if(UART_Send(UART1_DEVICE, &byte, 1, BLOCKING)) { QUEUE_POP(uint8_t, &getConfiguration()->uart.sendQueue); } else { break; } } if(QUEUE_EMPTY(uint8_t, &getConfiguration()->uart.sendQueue)) { disableTransmitInterrupt(); TRANSMIT_INTERRUPT_STATUS = RESET; } else { enableTransmitInterrupt(); } } extern "C" { void UART1_IRQHandler() { uint32_t interruptSource = UART_GetIntId(UART1_DEVICE) & UART_IIR_INTID_MASK; switch(interruptSource) { case UART1_IIR_INTID_MODEM: { // Check Modem status uint8_t modemStatus = UART_FullModemGetStatus(LPC_UART1); // Check CTS status change flag if (modemStatus & UART1_MODEM_STAT_DELTA_CTS) { // if CTS status is active, continue to send data if (modemStatus & UART1_MODEM_STAT_CTS) { UART_TxCmd(UART1_DEVICE, ENABLE); } else { // Otherwise, Stop current transmission immediately UART_TxCmd(UART1_DEVICE, DISABLE); } } break; } case UART_IIR_INTID_RDA: case UART_IIR_INTID_CTI: handleReceiveInterrupt(); break; case UART_IIR_INTID_THRE: handleTransmitInterrupt(); break; default: break; } } } void openxc::interface::uart::read(UartDevice* device, openxc::util::bytebuffer::IncomingMessageCallback callback) { if(device != NULL) { if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) { processQueue(&device->receiveQueue, callback); if(!QUEUE_FULL(uint8_t, &device->receiveQueue)) { resumeReceive(); } } } } /* Auto flow control does work, but it turns the uart write functions into * blocking functions, which drags USB down. Instead we handle it manually so we * can make them asynchronous and let USB run at full speed. */ void configureFlowControl() { if (UART_FullModemGetStatus(LPC_UART1) & UART1_MODEM_STAT_CTS) { // Enable UART Transmit UART_TxCmd(UART1_DEVICE, ENABLE); } // Enable Modem status interrupt UART_IntConfig(UART1_DEVICE, UART1_INTCFG_MS, ENABLE); // Enable CTS1 signal transition interrupt UART_IntConfig(UART1_DEVICE, UART1_INTCFG_CTS, ENABLE); } void configureUartPins() { PINSEL_CFG_Type PinCfg; PinCfg.Funcnum = UART1_FUNCNUM; PinCfg.OpenDrain = 0; PinCfg.Pinmode = 0; PinCfg.Portnum = UART1_PORTNUM; PinCfg.Pinnum = UART1_TX_PINNUM; PINSEL_ConfigPin(&PinCfg); PinCfg.Pinnum = UART1_RX_PINNUM; PINSEL_ConfigPin(&PinCfg); PinCfg.Portnum = UART1_FLOW_PORTNUM; PinCfg.Funcnum = UART1_FLOW_FUNCNUM; PinCfg.Pinnum = UART1_CTS1_PINNUM; PINSEL_ConfigPin(&PinCfg); PinCfg.Pinnum = UART1_RTS1_PINNUM; PINSEL_ConfigPin(&PinCfg); } void configureFifo() { UART_FIFO_CFG_Type fifoConfig; UART_FIFOConfigStructInit(&fifoConfig); UART_FIFOConfig(UART1_DEVICE, &fifoConfig); } void configureInterrupts() { UART_IntConfig(UART1_DEVICE, UART_INTCFG_RBR, ENABLE); enableTransmitInterrupt(); /* preemption = 1, sub-priority = 1 */ NVIC_SetPriority(UART1_IRQn, ((0x01<<3)|0x01)); NVIC_EnableIRQ(UART1_IRQn); } void openxc::interface::uart::changeBaudRate(UartDevice* device, int baud) { UART_CFG_Type UARTConfigStruct; UART_ConfigStructInit(&UARTConfigStruct); UARTConfigStruct.Baud_rate = baud; UART_Init(UART1_DEVICE, &UARTConfigStruct); RTS_STATE = INACTIVE; TRANSMIT_INTERRUPT_STATUS = RESET; configureFifo(); configureInterrupts(); configureFlowControl(); resumeReceive(); } void openxc::interface::uart::writeByte(UartDevice* device, uint8_t byte) { UART_SendByte(UART1_DEVICE, byte); } int openxc::interface::uart::readByte(UartDevice* device) { if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) { return QUEUE_POP(uint8_t, &device->receiveQueue); } return -1; } void openxc::interface::uart::initialize(UartDevice* device) { if(device == NULL) { debug("Can't initialize a NULL UartDevice"); return; } initializeCommon(device); // Configure P0.18 as an input, pulldown LPC_PINCON->PINMODE1 |= (1 << 5); // Ensure BT reset line is held high. LPC_GPIO1->FIODIR |= (1 << 17); gpio::setDirection(UART_STATUS_PORT, UART_STATUS_PIN, GpioDirection::GPIO_DIRECTION_INPUT); configureUartPins(); changeBaudRate(device, device->baudRate); debug("Done."); } void openxc::interface::uart::processSendQueue(UartDevice* device) { if(!QUEUE_EMPTY(uint8_t, &device->sendQueue)) { if(TRANSMIT_INTERRUPT_STATUS == RESET) { handleTransmitInterrupt(); } else { enableTransmitInterrupt(); } } } bool openxc::interface::uart::connected(UartDevice* device) { return device != NULL && gpio::getValue(UART_STATUS_PORT, UART_STATUS_PIN) != GpioValue::GPIO_VALUE_LOW; }
Use blocking writes to UART on LP17xx to work around race condition.
Use blocking writes to UART on LP17xx to work around race condition. Fixed #306.
C++
bsd-3-clause
openxc/vi-firmware,openxc/vi-firmware,mgiannikouris/vi-firmware,ene-ilies/vi-firmware,mgiannikouris/vi-firmware,ene-ilies/vi-firmware,openxc/vi-firmware,ene-ilies/vi-firmware,openxc/vi-firmware,ene-ilies/vi-firmware,mgiannikouris/vi-firmware,mgiannikouris/vi-firmware
446a3d717711962fa980a4c5a39920d77f85fe8d
src/LexAPDL.cxx
src/LexAPDL.cxx
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '/' || ch == '*'); } inline bool IsABlank(unsigned int ch) { return (ch == ' ') || (ch == 0x09) || (ch == 0x0b) ; } static void ColouriseAPDLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { //~ FILE *fp; //~ fp = fopen("myoutput.txt", "w"); WordList &commands = *keywordlists[0]; WordList &processors = *keywordlists[1]; WordList &functions = *keywordlists[2]; // backtrack to the beginning of the document, this may be slow for big documents. initStyle = SCE_APDL_DEFAULT; StyleContext sc(0, startPos+length, initStyle, styler); // backtrack to the nearest keyword //~ while ((startPos > 1) && (styler.StyleAt(startPos) != SCE_APDL_WORD)) { //~ startPos--; //~ } //~ startPos = styler.LineStart(styler.GetLine(startPos)); //~ initStyle = styler.StyleAt(startPos - 1); //~ StyleContext sc(startPos, endPos-startPos, initStyle, styler); bool firstInLine = true; bool atEOL; for (; sc.More(); sc.Forward()) { atEOL = (sc.ch == '\r' && sc.chNext == '\n') || (sc.ch == '\n'); //~ if (sc.ch == '\r') { //~ fprintf(fp,"CR\t%d\t%d", atEOL, firstInLine); //~ } else if (sc.ch == '\n') { //~ fprintf(fp,"LF\t%d\t%d", atEOL, firstInLine); //~ } else { //~ fprintf(fp,"%c\t%d\t%d", sc.ch, atEOL, firstInLine); //~ } // Determine if the current state should terminate. if (sc.state == SCE_APDL_COMMENT) { //~ fprintf(fp,"\tCOMMENT"); if (atEOL) { sc.SetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_COMMENTBLOCK) { //~ fprintf(fp,"\tCOMMENTBLOCK"); if (atEOL) { if (sc.ch == '\r') { sc.Forward(); } sc.ForwardSetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_NUMBER) { //~ fprintf(fp,"\tNUMBER"); if (isdigit(sc.ch)) { } else if ((sc.ch == 'e' || sc.ch == 'E') && (isdigit(sc.chNext) || sc.chNext == '+' || sc.chNext == '-')) { } else if (sc.ch == '.') { } else if ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')) { } else { sc.SetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_STRING) { //~ fprintf(fp,"\tSTRING"); if (sc.ch == '\"') { //~ sc.ForwardSetState(SCE_APDL_DEFAULT); sc.Forward(); atEOL = (sc.ch == '\r' && sc.chNext == '\n') || (sc.ch == '\n'); if (atEOL) { firstInLine = true; } sc.SetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_WORD) { //~ fprintf(fp,"\tWORD"); if (!IsAWordChar(sc.ch) || sc.ch == '%') { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (commands.InList(s) && firstInLine) { if (IsABlank(sc.ch) || sc.ch == ',' || atEOL) { sc.ChangeState(SCE_APDL_COMMAND); } if (sc.ch != '\n') { firstInLine = false; } } else if (processors.InList(s)) { if (IsABlank(sc.ch) || atEOL) { sc.ChangeState(SCE_APDL_PROCESSOR); while (sc.ch != '\n') { sc.Forward(); } sc.Forward(); } } else if (functions.InList(s)) { sc.ChangeState(SCE_APDL_FUNCTION); if (sc.ch != '\n') { firstInLine = false; } } else { if (sc.ch != '\n') { firstInLine = false; } } sc.SetState(SCE_APDL_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_APDL_DEFAULT) { if (sc.ch == '!' && sc.chNext != '!') { sc.SetState(SCE_APDL_COMMENT); } else if (sc.ch == '!' && sc.chNext == '!') { sc.SetState(SCE_APDL_COMMENTBLOCK); } else if (IsADigit(sc.ch) && !IsAWordChar(sc.chPrev)) { sc.SetState(SCE_APDL_NUMBER); } else if (sc.ch == '.' && (isoperator(static_cast<char>(sc.chPrev)) || IsABlank(sc.chPrev) || sc.chPrev == '\n' || sc.chPrev == '\r')) { sc.SetState(SCE_APDL_NUMBER); } else if (sc.ch == '\"') { sc.SetState(SCE_APDL_STRING); } else if (IsAWordStart(sc.ch) && (!IsADigit(sc.chPrev))) { sc.SetState(SCE_APDL_WORD); } } //~ fprintf(fp,"\n"); if (atEOL) { firstInLine = true; } } sc.Complete(); } static const char * const apdlWordListDesc[] = { "Commands", "Processors", "Functions", 0 }; LexerModule lmAPDL(SCLEX_APDL, ColouriseAPDLDoc, "apdl", 0, apdlWordListDesc);
// Scintilla source code edit control /** @file LexAPDL.cxx ** Lexer for APDL. Based on the lexer for Assembler by The Black Horus. ** By Hadar Raz. **/ // Copyright 1998-2003 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80 && (isalnum(ch) || ch == '_')); } static inline bool IsAnOperator(char ch) { // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '^' || ch == '[' || ch == ']' || ch == '<' || ch == '&' || ch == '>' || ch == ',' || ch == '|' || ch == '~' || ch == '$' || ch == ':' || ch == '%') return true; return false; } static void ColouriseAPDLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { int stringStart = ' '; WordList &processors = *keywordlists[0]; WordList &commands = *keywordlists[1]; WordList &slashcommands = *keywordlists[2]; WordList &starcommands = *keywordlists[3]; WordList &arguments = *keywordlists[4]; WordList &functions = *keywordlists[5]; // Do not leak onto next line initStyle = SCE_APDL_DEFAULT; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // Determine if the current state should terminate. if (sc.state == SCE_APDL_NUMBER) { if (!(IsADigit(sc.ch) || sc.ch == '.' || (sc.ch == 'e' || sc.ch == 'E') || ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')))) { sc.SetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_COMMENTBLOCK) { if (sc.atLineEnd) { if (sc.ch == '\r') { sc.Forward(); } sc.ForwardSetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_STRING) { if (sc.atLineEnd) { sc.SetState(SCE_APDL_DEFAULT); } else if ((sc.ch == '\'' && stringStart == '\'') || (sc.ch == '\"' && stringStart == '\"')) { sc.ForwardSetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_WORD) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (processors.InList(s)) { sc.ChangeState(SCE_APDL_PROCESSOR); } else if (slashcommands.InList(s)) { sc.ChangeState(SCE_APDL_SLASHCOMMAND); } else if (starcommands.InList(s)) { sc.ChangeState(SCE_APDL_STARCOMMAND); } else if (commands.InList(s)) { sc.ChangeState(SCE_APDL_COMMAND); } else if (arguments.InList(s)) { sc.ChangeState(SCE_APDL_ARGUMENT); } else if (functions.InList(s)) { sc.ChangeState(SCE_APDL_FUNCTION); } sc.SetState(SCE_APDL_DEFAULT); } } else if (sc.state == SCE_APDL_OPERATOR) { if (!IsAnOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_APDL_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_APDL_DEFAULT) { if (sc.ch == '!' && sc.chNext == '!') { sc.SetState(SCE_APDL_COMMENTBLOCK); } else if (sc.ch == '!') { sc.SetState(SCE_APDL_COMMENT); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_APDL_NUMBER); } else if (sc.ch == '\'' || sc.ch == '\"') { sc.SetState(SCE_APDL_STRING); stringStart = sc.ch; } else if (IsAWordChar(sc.ch) || ((sc.ch == '*' || sc.ch == '/') && !isgraph(sc.chPrev))) { sc.SetState(SCE_APDL_WORD); } else if (IsAnOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_APDL_OPERATOR); } } } sc.Complete(); } static const char * const apdlWordListDesc[] = { "processors", "commands", "slashommands", "starcommands", "arguments", "functions", 0 }; LexerModule lmAPDL(SCLEX_APDL, ColouriseAPDLDoc, "apdl", 0, apdlWordListDesc);
Update from Hadar Raz to add more lexical classes.
Update from Hadar Raz to add more lexical classes.
C++
isc
rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror
1b06789707ec4ba6300bb724389944a629619704
system_wrappers/source/thread_posix.cc
system_wrappers/source/thread_posix.cc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // The state of a thread is controlled by the two member variables // alive_ and dead_. // alive_ represents the state the thread has been ordered to achieve. // It is set to true by the thread at startup, and is set to false by // other threads, using SetNotAlive() and Stop(). // dead_ represents the state the thread has achieved. // It is written by the thread encapsulated by this class only // (except at init). It is read only by the Stop() method. // The Run() method fires event_ when it's started; this ensures that the // Start() method does not continue until after dead_ is false. // This protects against premature Stop() calls from the creator thread, but // not from other threads. // Their transitions and states: // alive_ dead_ Set by // false true Constructor // true false Run() method entry // false any Run() method run_function failure // any false Run() method exit (happens only with alive_ false) // false any SetNotAlive // false any Stop Stop waits for dead_ to become true. // // Summarized a different way: // Variable Writer Reader // alive_ Constructor(false) Run.loop // Run.start(true) // Run.fail(false) // SetNotAlive(false) // Stop(false) // // dead_ Constructor(true) Stop.loop // Run.start(false) // Run.exit(true) #include "webrtc/system_wrappers/source/thread_posix.h" #include <algorithm> #include <assert.h> #include <errno.h> #include <string.h> // strncpy #include <unistd.h> #ifdef WEBRTC_LINUX #include <linux/unistd.h> #include <sched.h> #include <sys/prctl.h> #include <sys/syscall.h> #include <sys/types.h> #endif #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/sleep.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { int ConvertToSystemPriority(ThreadPriority priority, int min_prio, int max_prio) { assert(max_prio - min_prio > 2); const int top_prio = max_prio - 1; const int low_prio = min_prio + 1; switch (priority) { case kLowPriority: return low_prio; case kNormalPriority: // The -1 ensures that the kHighPriority is always greater or equal to // kNormalPriority. return (low_prio + top_prio - 1) / 2; case kHighPriority: return std::max(top_prio - 2, low_prio); case kHighestPriority: return std::max(top_prio - 1, low_prio); case kRealtimePriority: return top_prio; } assert(false); return low_prio; } extern "C" { static void* StartThread(void* lp_parameter) { static_cast<ThreadPosix*>(lp_parameter)->Run(); return 0; } } ThreadWrapper* ThreadPosix::Create(ThreadRunFunction func, ThreadObj obj, ThreadPriority prio, const char* thread_name) { ThreadPosix* ptr = new ThreadPosix(func, obj, prio, thread_name); if (!ptr) { return NULL; } const int error = ptr->Construct(); if (error) { delete ptr; return NULL; } return ptr; } ThreadPosix::ThreadPosix(ThreadRunFunction func, ThreadObj obj, ThreadPriority prio, const char* thread_name) : run_function_(func), obj_(obj), crit_state_(CriticalSectionWrapper::CreateCriticalSection()), alive_(false), dead_(true), prio_(prio), event_(EventWrapper::Create()), name_(), set_thread_name_(false), #if (defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)) pid_(-1), #endif attr_(), thread_(0) { if (thread_name != NULL) { set_thread_name_ = true; strncpy(name_, thread_name, kThreadMaxNameLength); name_[kThreadMaxNameLength - 1] = '\0'; } } uint32_t ThreadWrapper::GetThreadId() { #if defined(WEBRTC_ANDROID) || defined(WEBRTC_LINUX) return static_cast<uint32_t>(syscall(__NR_gettid)); #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) return pthread_mach_thread_np(pthread_self()); #else return reinterpret_cast<uint32_t>(pthread_self()); #endif } int ThreadPosix::Construct() { int result = 0; #if !defined(WEBRTC_ANDROID) // Enable immediate cancellation if requested, see Shutdown(). result = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if (result != 0) { return -1; } result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); if (result != 0) { return -1; } #endif result = pthread_attr_init(&attr_); if (result != 0) { return -1; } return 0; } ThreadPosix::~ThreadPosix() { pthread_attr_destroy(&attr_); delete event_; delete crit_state_; } #define HAS_THREAD_ID !defined(WEBRTC_IOS) && !defined(WEBRTC_MAC) bool ThreadPosix::Start(unsigned int& thread_id) { int result = pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED); // Set the stack stack size to 1M. result |= pthread_attr_setstacksize(&attr_, 1024 * 1024); #ifdef WEBRTC_THREAD_RR const int policy = SCHED_RR; #else const int policy = SCHED_FIFO; #endif event_->Reset(); // If pthread_create was successful, a thread was created and is running. // Don't return false if it was successful since if there are any other // failures the state will be: thread was started but not configured as // asked for. However, the caller of this API will assume that a false // return value means that the thread never started. result |= pthread_create(&thread_, &attr_, &StartThread, this); if (result != 0) { return false; } { CriticalSectionScoped cs(crit_state_); dead_ = false; } // Wait up to 10 seconds for the OS to call the callback function. Prevents // race condition if Stop() is called too quickly after start. if (kEventSignaled != event_->Wait(WEBRTC_EVENT_10_SEC)) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "posix thread event never triggered"); // Timed out. Something went wrong. return true; } #if HAS_THREAD_ID thread_id = static_cast<unsigned int>(thread_); #endif sched_param param; const int min_prio = sched_get_priority_min(policy); const int max_prio = sched_get_priority_max(policy); if ((min_prio == EINVAL) || (max_prio == EINVAL)) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "unable to retreive min or max priority for threads"); return true; } if (max_prio - min_prio <= 2) { // There is no room for setting priorities with any granularity. return true; } param.sched_priority = ConvertToSystemPriority(prio_, min_prio, max_prio); result = pthread_setschedparam(thread_, policy, &param); if (result == EINVAL) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "unable to set thread priority"); } return true; } // CPU_ZERO and CPU_SET are not available in NDK r7, so disable // SetAffinity on Android for now. #if (defined(WEBRTC_LINUX) && (!defined(WEBRTC_ANDROID))) bool ThreadPosix::SetAffinity(const int* processor_numbers, const unsigned int amount_of_processors) { if (!processor_numbers || (amount_of_processors == 0)) { return false; } cpu_set_t mask; CPU_ZERO(&mask); for (unsigned int processor = 0; processor < amount_of_processors; ++processor) { CPU_SET(processor_numbers[processor], &mask); } #if defined(WEBRTC_ANDROID) // Android. const int result = syscall(__NR_sched_setaffinity, pid_, sizeof(mask), &mask); #else // "Normal" Linux. const int result = sched_setaffinity(pid_, sizeof(mask), &mask); #endif if (result != 0) { return false; } return true; } #else // NOTE: On Mac OS X, use the Thread affinity API in // /usr/include/mach/thread_policy.h: thread_policy_set and mach_thread_self() // instead of Linux gettid() syscall. bool ThreadPosix::SetAffinity(const int* , const unsigned int) { return false; } #endif void ThreadPosix::SetNotAlive() { CriticalSectionScoped cs(crit_state_); alive_ = false; } bool ThreadPosix::Stop() { bool dead = false; { CriticalSectionScoped cs(crit_state_); alive_ = false; dead = dead_; } // TODO(hellner) why not use an event here? // Wait up to 10 seconds for the thread to terminate for (int i = 0; i < 1000 && !dead; ++i) { SleepMs(10); { CriticalSectionScoped cs(crit_state_); dead = dead_; } } if (dead) { return true; } else { return false; } } void ThreadPosix::Run() { { CriticalSectionScoped cs(crit_state_); alive_ = true; } #if (defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)) pid_ = GetThreadId(); #endif // The event the Start() is waiting for. event_->Set(); if (set_thread_name_) { #ifdef WEBRTC_LINUX prctl(PR_SET_NAME, (unsigned long)name_, 0, 0, 0); #endif WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread with name:%s started ", name_); } else { WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread without name started"); } bool alive = true; bool run = true; while (alive) { run = run_function_(obj_); CriticalSectionScoped cs(crit_state_); if (!run) { alive_ = false; } alive = alive_; } if (set_thread_name_) { // Don't set the name for the trace thread because it may cause a // deadlock. TODO(hellner) there should be a better solution than // coupling the thread and the trace class like this. if (strcmp(name_, "Trace")) { WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread with name:%s stopped", name_); } } else { WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread without name stopped"); } { CriticalSectionScoped cs(crit_state_); dead_ = true; } } } // namespace webrtc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // The state of a thread is controlled by the two member variables // alive_ and dead_. // alive_ represents the state the thread has been ordered to achieve. // It is set to true by the thread at startup, and is set to false by // other threads, using SetNotAlive() and Stop(). // dead_ represents the state the thread has achieved. // It is written by the thread encapsulated by this class only // (except at init). It is read only by the Stop() method. // The Run() method fires event_ when it's started; this ensures that the // Start() method does not continue until after dead_ is false. // This protects against premature Stop() calls from the creator thread, but // not from other threads. // Their transitions and states: // alive_ dead_ Set by // false true Constructor // true false Run() method entry // false any Run() method run_function failure // any false Run() method exit (happens only with alive_ false) // false any SetNotAlive // false any Stop Stop waits for dead_ to become true. // // Summarized a different way: // Variable Writer Reader // alive_ Constructor(false) Run.loop // Run.start(true) // Run.fail(false) // SetNotAlive(false) // Stop(false) // // dead_ Constructor(true) Stop.loop // Run.start(false) // Run.exit(true) #include "webrtc/system_wrappers/source/thread_posix.h" #include <algorithm> #include <assert.h> #include <errno.h> #include <string.h> // strncpy #include <unistd.h> #ifdef WEBRTC_LINUX #include <linux/unistd.h> #include <sched.h> #include <sys/prctl.h> #include <sys/syscall.h> #include <sys/types.h> #endif #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/sleep.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { int ConvertToSystemPriority(ThreadPriority priority, int min_prio, int max_prio) { assert(max_prio - min_prio > 2); const int top_prio = max_prio - 1; const int low_prio = min_prio + 1; switch (priority) { case kLowPriority: return low_prio; case kNormalPriority: // The -1 ensures that the kHighPriority is always greater or equal to // kNormalPriority. return (low_prio + top_prio - 1) / 2; case kHighPriority: return std::max(top_prio - 2, low_prio); case kHighestPriority: return std::max(top_prio - 1, low_prio); case kRealtimePriority: return top_prio; } assert(false); return low_prio; } extern "C" { static void* StartThread(void* lp_parameter) { static_cast<ThreadPosix*>(lp_parameter)->Run(); return 0; } } ThreadWrapper* ThreadPosix::Create(ThreadRunFunction func, ThreadObj obj, ThreadPriority prio, const char* thread_name) { ThreadPosix* ptr = new ThreadPosix(func, obj, prio, thread_name); if (!ptr) { return NULL; } const int error = ptr->Construct(); if (error) { delete ptr; return NULL; } return ptr; } ThreadPosix::ThreadPosix(ThreadRunFunction func, ThreadObj obj, ThreadPriority prio, const char* thread_name) : run_function_(func), obj_(obj), crit_state_(CriticalSectionWrapper::CreateCriticalSection()), alive_(false), dead_(true), prio_(prio), event_(EventWrapper::Create()), name_(), set_thread_name_(false), #if (defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)) pid_(-1), #endif attr_(), thread_(0) { if (thread_name != NULL) { set_thread_name_ = true; strncpy(name_, thread_name, kThreadMaxNameLength); name_[kThreadMaxNameLength - 1] = '\0'; } } uint32_t ThreadWrapper::GetThreadId() { #if defined(WEBRTC_ANDROID) || defined(WEBRTC_LINUX) return static_cast<uint32_t>(syscall(__NR_gettid)); #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) return pthread_mach_thread_np(pthread_self()); #else return reinterpret_cast<uint32_t>(pthread_self()); #endif } int ThreadPosix::Construct() { int result = 0; #if !defined(WEBRTC_ANDROID) // Enable immediate cancellation if requested, see Shutdown(). result = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if (result != 0) { return -1; } result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); if (result != 0) { return -1; } #endif result = pthread_attr_init(&attr_); if (result != 0) { return -1; } return 0; } ThreadPosix::~ThreadPosix() { pthread_attr_destroy(&attr_); delete event_; delete crit_state_; } #define HAS_THREAD_ID !defined(WEBRTC_IOS) && !defined(WEBRTC_MAC) bool ThreadPosix::Start(unsigned int& thread_id) { int result = pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED); // Set the stack stack size to 1M. result |= pthread_attr_setstacksize(&attr_, 1024 * 1024); event_->Reset(); // If pthread_create was successful, a thread was created and is running. // Don't return false if it was successful since if there are any other // failures the state will be: thread was started but not configured as // asked for. However, the caller of this API will assume that a false // return value means that the thread never started. result |= pthread_create(&thread_, &attr_, &StartThread, this); if (result != 0) { return false; } { CriticalSectionScoped cs(crit_state_); dead_ = false; } // Wait up to 10 seconds for the OS to call the callback function. Prevents // race condition if Stop() is called too quickly after start. if (kEventSignaled != event_->Wait(WEBRTC_EVENT_10_SEC)) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "posix thread event never triggered"); // Timed out. Something went wrong. return true; } #if HAS_THREAD_ID thread_id = static_cast<unsigned int>(thread_); #endif return true; } // CPU_ZERO and CPU_SET are not available in NDK r7, so disable // SetAffinity on Android for now. #if (defined(WEBRTC_LINUX) && (!defined(WEBRTC_ANDROID))) bool ThreadPosix::SetAffinity(const int* processor_numbers, const unsigned int amount_of_processors) { if (!processor_numbers || (amount_of_processors == 0)) { return false; } cpu_set_t mask; CPU_ZERO(&mask); for (unsigned int processor = 0; processor < amount_of_processors; ++processor) { CPU_SET(processor_numbers[processor], &mask); } #if defined(WEBRTC_ANDROID) // Android. const int result = syscall(__NR_sched_setaffinity, pid_, sizeof(mask), &mask); #else // "Normal" Linux. const int result = sched_setaffinity(pid_, sizeof(mask), &mask); #endif if (result != 0) { return false; } return true; } #else // NOTE: On Mac OS X, use the Thread affinity API in // /usr/include/mach/thread_policy.h: thread_policy_set and mach_thread_self() // instead of Linux gettid() syscall. bool ThreadPosix::SetAffinity(const int* , const unsigned int) { return false; } #endif void ThreadPosix::SetNotAlive() { CriticalSectionScoped cs(crit_state_); alive_ = false; } bool ThreadPosix::Stop() { bool dead = false; { CriticalSectionScoped cs(crit_state_); alive_ = false; dead = dead_; } // TODO(hellner) why not use an event here? // Wait up to 10 seconds for the thread to terminate for (int i = 0; i < 1000 && !dead; ++i) { SleepMs(10); { CriticalSectionScoped cs(crit_state_); dead = dead_; } } if (dead) { return true; } else { return false; } } void ThreadPosix::Run() { { CriticalSectionScoped cs(crit_state_); alive_ = true; } #if (defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)) pid_ = GetThreadId(); #endif // The event the Start() is waiting for. event_->Set(); if (set_thread_name_) { #ifdef WEBRTC_LINUX prctl(PR_SET_NAME, (unsigned long)name_, 0, 0, 0); #endif WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread with name:%s started ", name_); } else { WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread without name started"); } #ifdef WEBRTC_THREAD_RR const int policy = SCHED_RR; #else const int policy = SCHED_FIFO; #endif const int min_prio = sched_get_priority_min(policy); const int max_prio = sched_get_priority_max(policy); if ((min_prio == -1) || (max_prio == -1)) { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "unable to retreive min or max priority for threads"); } if (max_prio - min_prio > 2) { sched_param param; param.sched_priority = ConvertToSystemPriority(prio_, min_prio, max_prio); if (pthread_setschedparam(pthread_self(), policy, &param) != 0) { WEBRTC_TRACE( kTraceError, kTraceUtility, -1, "unable to set thread priority"); } } bool alive = true; bool run = true; while (alive) { run = run_function_(obj_); CriticalSectionScoped cs(crit_state_); if (!run) { alive_ = false; } alive = alive_; } if (set_thread_name_) { // Don't set the name for the trace thread because it may cause a // deadlock. TODO(hellner) there should be a better solution than // coupling the thread and the trace class like this. if (strcmp(name_, "Trace")) { WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread with name:%s stopped", name_); } } else { WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Thread without name stopped"); } { CriticalSectionScoped cs(crit_state_); dead_ = true; } } } // namespace webrtc
Set thread scheduling parameters inside the new thread.
Set thread scheduling parameters inside the new thread. This makes it possible to restrict threads from modifying scheduling parameters of another thread in the Chrome Linux sandbox. BUG= [email protected] Review URL: https://webrtc-codereview.appspot.com/28539004 git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@7324 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758
bc4732e13a0dedd4374cbb5f96c8bb32d767bc34
Response.cpp
Response.cpp
/*******************************************************************************/ #include "ResponseRequest.h" #include "LogFile.h" /*******************************************************************************/ string ResponseRequest::Path_folder() { char szPath[MAX_PATH] = {}; GetModuleFileNameA(NULL, szPath, MAX_PATH); // Pointer to the last occurrence of "\" char *lstChr = strrchr(szPath, '\\'); // replaced by zero (truncate) *lstChr = '\0'; return szPath; } /*******************************************************************************/ string ResponseRequest::Read_symbolic_content(ifstream& inFin) { string response_body((istreambuf_iterator<char>(inFin)), istreambuf_iterator<char>()); return response_body; } /*******************************************************************************/ void ResponseRequest::Send_response(SOCKET client_socket, string &tmp_res, int &t_result) { t_result = send(client_socket, tmp_res.c_str(), static_cast<int>(tmp_res.size()), 0); if (t_result == SOCKET_ERROR) { throw exception("Error in send(): " + WSAGetLastError()); } } /*******************************************************************************/ void ResponseRequest::Response_js(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\js\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: application/javascript;\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_image(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\image\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: image/png;\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_css(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\css\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: text/css;\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_default_html(SOCKET client_socket) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\html\\index.html"; path_to_file = Path_folder() + folder; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 202 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: text/html;\n"; response += "Connection: keep-alive\n"; response += "X-Powered-By: c++\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_html(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\html\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 202 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: text/html;\n"; response += "Connection: keep-alive\n"; response += "X-Powered-By: c++\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); }
/*******************************************************************************/ #include "ResponseRequest.h" #include "LogFile.h" /*******************************************************************************/ string ResponseRequest::Path_folder() { char szPath[MAX_PATH] = {}; GetModuleFileNameA(NULL, szPath, MAX_PATH); // Pointer to the last occurrence of "\" char *lstChr = strrchr(szPath, '\\'); // replaced by zero (truncate) *lstChr = '\0'; return szPath; } /*******************************************************************************/ string ResponseRequest::Read_symbolic_content(ifstream& inFin) { string response_body((istreambuf_iterator<char>(inFin)), istreambuf_iterator<char>()); return response_body; } /*******************************************************************************/ void ResponseRequest::Send_response(SOCKET client_socket, string &tmp_res, int &t_result) { t_result = send(client_socket, tmp_res.c_str(), static_cast<int>(tmp_res.size()), 0); if (t_result == SOCKET_ERROR) { throw exception("Error in send(): " + WSAGetLastError()); } } /*******************************************************************************/ void ResponseRequest::Response_js(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\js\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: application/javascript;\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_image(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\image\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: image/png;\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_css(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\css\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: text/css;\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_default_html(SOCKET client_socket) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\html\\index.html"; path_to_file = Path_folder() + folder; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: text/html;\n"; response += "Connection: keep-alive\n"; response += "X-Powered-By: c++\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); } /*******************************************************************************/ void ResponseRequest::Response_html(SOCKET client_socket, string &file_name) { int result = int(); string response = string(); string path_to_file = string(); string folder = "\\html\\"; path_to_file = Path_folder() + folder + file_name; ifstream fin(path_to_file, ios::binary); if (!fin.is_open()) { throw exception( ("Missing " + path_to_file).c_str() ); } else { response += "HTTP/1.1 200 OK\n"; response += "Server: VaV/V2\n"; response += "Content-Type: text/html;\n"; response += "Connection: keep-alive\n"; response += "X-Powered-By: c++\r\n\r\n"; response += Read_symbolic_content(fin); } fin.close(); Send_response(client_socket, response, result); }
repair code response
repair code response
C++
mpl-2.0
Cempl/http-server-ws,Cempl/http-server-ws,Cempl/http-server-ws,Cempl/http-server-ws
51b42af047c40d45447b6cda6648982ea8b439fc
src/base/addr_range.hh
src/base/addr_range.hh
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt * Andreas Hansson */ #ifndef __BASE_ADDR_RANGE_HH__ #define __BASE_ADDR_RANGE_HH__ #include <vector> #include "base/bitfield.hh" #include "base/cprintf.hh" #include "base/misc.hh" #include "base/types.hh" class AddrRange { private: /// Private fields for the start and end of the range Addr _start; Addr _end; /// The high bit of the slice that is used for interleaving uint8_t intlvHighBit; /// The number of bits used for interleaving, set to 0 to disable uint8_t intlvBits; /// The value to compare the slice addr[high:(high - bits + 1)] /// with. uint8_t intlvMatch; public: AddrRange() : _start(1), _end(0), intlvHighBit(0), intlvBits(0), intlvMatch(0) {} AddrRange(Addr _start, Addr _end, uint8_t _intlv_high_bit, uint8_t _intlv_bits, uint8_t _intlv_match) : _start(_start), _end(_end), intlvHighBit(_intlv_high_bit), intlvBits(_intlv_bits), intlvMatch(_intlv_match) {} AddrRange(Addr _start, Addr _end) : _start(_start), _end(_end), intlvHighBit(0), intlvBits(0), intlvMatch(0) {} /** * Create an address range by merging a collection of interleaved * ranges. * * @param ranges Interleaved ranges to be merged */ AddrRange(const std::vector<AddrRange>& ranges) : _start(1), _end(0), intlvHighBit(0), intlvBits(0), intlvMatch(0) { if (!ranges.empty()) { // get the values from the first one and check the others _start = ranges.front()._start; _end = ranges.front()._end; intlvHighBit = ranges.front().intlvHighBit; intlvBits = ranges.front().intlvBits; if (ranges.size() != (ULL(1) << intlvBits)) fatal("Got %d ranges spanning %d interleaving bits\n", ranges.size(), intlvBits); uint8_t match = 0; for (std::vector<AddrRange>::const_iterator r = ranges.begin(); r != ranges.end(); ++r) { if (!mergesWith(*r)) fatal("Can only merge ranges with the same start, end " "and interleaving bits\n"); if (r->intlvMatch != match) fatal("Expected interleave match %d but got %d when " "merging\n", match, r->intlvMatch); ++match; } // our range is complete and we can turn this into a // non-interleaved range intlvHighBit = 0; intlvBits = 0; } } /** * Determine if the range is interleaved or not. * * @return true if interleaved */ bool interleaved() const { return intlvBits != 0; } /** * Determing the interleaving granularity of the range. * * @return The size of the regions created by the interleaving bits */ uint64_t granularity() const { return ULL(1) << intlvHighBit; } /** * Determine the number of interleaved address stripes this range * is part of. * * @return The number of stripes spanned by the interleaving bits */ uint32_t stripes() const { return ULL(1) << intlvBits; } /** * Get the size of the address range. For a case where * interleaving is used we make the simplifying assumption that * the size is a divisible by the size of the interleaving slice. */ Addr size() const { return (_end - _start + 1) >> intlvBits; } /** * Determine if the range is valid. */ bool valid() const { return _start < _end; } /** * Get the start address of the range. */ Addr start() const { return _start; } /** * Get a string representation of the range. This could * alternatively be implemented as a operator<<, but at the moment * that seems like overkill. */ std::string to_string() const { if (interleaved()) return csprintf("[%#llx : %#llx], [%d : %d] = %d", _start, _end, intlvHighBit, intlvHighBit - intlvBits + 1, intlvMatch); else return csprintf("[%#llx : %#llx]", _start, _end); } /** * Determine if another range merges with the current one, i.e. if * they are part of the same contigous range and have the same * interleaving bits. * * @param r Range to evaluate merging with * @return true if the two ranges would merge */ bool mergesWith(const AddrRange& r) const { return r._start == _start && r._end == _end && r.intlvHighBit == intlvHighBit && r.intlvBits == intlvBits; } /** * Determine if another range intersects this one, i.e. if there * is an address that is both in this range and the other * range. No check is made to ensure either range is valid. * * @param r Range to intersect with * @return true if the intersection of the two ranges is not empty */ bool intersects(const AddrRange& r) const { if (!interleaved()) { return _start <= r._end && _end >= r._start; } // the current range is interleaved, split the check up in // three cases if (r.size() == 1) // keep it simple and check if the address is within // this range return contains(r.start()); else if (!r.interleaved()) // be conservative and ignore the interleaving return _start <= r._end && _end >= r._start; else if (mergesWith(r)) // restrict the check to ranges that belong to the // same chunk return intlvMatch == r.intlvMatch; else panic("Cannot test intersection of interleaved range %s\n", to_string()); } /** * Determine if this range is a subset of another range, i.e. if * every address in this range is also in the other range. No * check is made to ensure either range is valid. * * @param r Range to compare with * @return true if the this range is a subset of the other one */ bool isSubset(const AddrRange& r) const { if (interleaved()) panic("Cannot test subset of interleaved range %s\n", to_string()); return _start >= r._start && _end <= r._end; } /** * Determine if the range contains an address. * * @param a Address to compare with * @return true if the address is in the range */ bool contains(const Addr& a) const { // check if the address is in the range and if there is either // no interleaving, or with interleaving also if the selected // bits from the address match the interleaving value return a >= _start && a <= _end && (interleaved() || (bits(a, intlvHighBit, intlvHighBit - intlvBits + 1) == intlvMatch)); } /** * Keep the operators away from SWIG. */ #ifndef SWIG /** * Less-than operator used to turn an STL map into a binary search * tree of non-overlapping address ranges. * * @param r Range to compare with * @return true if the start address is less than that of the other range */ bool operator<(const AddrRange& r) const { if (_start != r._start) return _start < r._start; else // for now assume that the end is also the same, and that // we are looking at the same interleaving bits return intlvMatch < r.intlvMatch; } #endif // SWIG }; inline AddrRange RangeEx(Addr start, Addr end) { return AddrRange(start, end - 1); } inline AddrRange RangeIn(Addr start, Addr end) { return AddrRange(start, end); } inline AddrRange RangeSize(Addr start, Addr size) { return AddrRange(start, start + size - 1); } #endif // __BASE_ADDR_RANGE_HH__
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt * Andreas Hansson */ #ifndef __BASE_ADDR_RANGE_HH__ #define __BASE_ADDR_RANGE_HH__ #include <vector> #include "base/bitfield.hh" #include "base/cprintf.hh" #include "base/misc.hh" #include "base/types.hh" class AddrRange { private: /// Private fields for the start and end of the range Addr _start; Addr _end; /// The high bit of the slice that is used for interleaving uint8_t intlvHighBit; /// The number of bits used for interleaving, set to 0 to disable uint8_t intlvBits; /// The value to compare the slice addr[high:(high - bits + 1)] /// with. uint8_t intlvMatch; public: AddrRange() : _start(1), _end(0), intlvHighBit(0), intlvBits(0), intlvMatch(0) {} AddrRange(Addr _start, Addr _end, uint8_t _intlv_high_bit, uint8_t _intlv_bits, uint8_t _intlv_match) : _start(_start), _end(_end), intlvHighBit(_intlv_high_bit), intlvBits(_intlv_bits), intlvMatch(_intlv_match) {} AddrRange(Addr _start, Addr _end) : _start(_start), _end(_end), intlvHighBit(0), intlvBits(0), intlvMatch(0) {} /** * Create an address range by merging a collection of interleaved * ranges. * * @param ranges Interleaved ranges to be merged */ AddrRange(const std::vector<AddrRange>& ranges) : _start(1), _end(0), intlvHighBit(0), intlvBits(0), intlvMatch(0) { if (!ranges.empty()) { // get the values from the first one and check the others _start = ranges.front()._start; _end = ranges.front()._end; intlvHighBit = ranges.front().intlvHighBit; intlvBits = ranges.front().intlvBits; if (ranges.size() != (ULL(1) << intlvBits)) fatal("Got %d ranges spanning %d interleaving bits\n", ranges.size(), intlvBits); uint8_t match = 0; for (std::vector<AddrRange>::const_iterator r = ranges.begin(); r != ranges.end(); ++r) { if (!mergesWith(*r)) fatal("Can only merge ranges with the same start, end " "and interleaving bits\n"); if (r->intlvMatch != match) fatal("Expected interleave match %d but got %d when " "merging\n", match, r->intlvMatch); ++match; } // our range is complete and we can turn this into a // non-interleaved range intlvHighBit = 0; intlvBits = 0; } } /** * Determine if the range is interleaved or not. * * @return true if interleaved */ bool interleaved() const { return intlvBits != 0; } /** * Determing the interleaving granularity of the range. * * @return The size of the regions created by the interleaving bits */ uint64_t granularity() const { return ULL(1) << intlvHighBit; } /** * Determine the number of interleaved address stripes this range * is part of. * * @return The number of stripes spanned by the interleaving bits */ uint32_t stripes() const { return ULL(1) << intlvBits; } /** * Get the size of the address range. For a case where * interleaving is used we make the simplifying assumption that * the size is a divisible by the size of the interleaving slice. */ Addr size() const { return (_end - _start + 1) >> intlvBits; } /** * Determine if the range is valid. */ bool valid() const { return _start < _end; } /** * Get the start address of the range. */ Addr start() const { return _start; } /** * Get a string representation of the range. This could * alternatively be implemented as a operator<<, but at the moment * that seems like overkill. */ std::string to_string() const { if (interleaved()) return csprintf("[%#llx : %#llx], [%d : %d] = %d", _start, _end, intlvHighBit, intlvHighBit - intlvBits + 1, intlvMatch); else return csprintf("[%#llx : %#llx]", _start, _end); } /** * Determine if another range merges with the current one, i.e. if * they are part of the same contigous range and have the same * interleaving bits. * * @param r Range to evaluate merging with * @return true if the two ranges would merge */ bool mergesWith(const AddrRange& r) const { return r._start == _start && r._end == _end && r.intlvHighBit == intlvHighBit && r.intlvBits == intlvBits; } /** * Determine if another range intersects this one, i.e. if there * is an address that is both in this range and the other * range. No check is made to ensure either range is valid. * * @param r Range to intersect with * @return true if the intersection of the two ranges is not empty */ bool intersects(const AddrRange& r) const { if (!interleaved()) { return _start <= r._end && _end >= r._start; } // the current range is interleaved, split the check up in // three cases if (r.size() == 1) // keep it simple and check if the address is within // this range return contains(r.start()); else if (!r.interleaved()) // be conservative and ignore the interleaving return _start <= r._end && _end >= r._start; else if (mergesWith(r)) // restrict the check to ranges that belong to the // same chunk return intlvMatch == r.intlvMatch; else panic("Cannot test intersection of interleaved range %s\n", to_string()); } /** * Determine if this range is a subset of another range, i.e. if * every address in this range is also in the other range. No * check is made to ensure either range is valid. * * @param r Range to compare with * @return true if the this range is a subset of the other one */ bool isSubset(const AddrRange& r) const { if (interleaved()) panic("Cannot test subset of interleaved range %s\n", to_string()); return _start >= r._start && _end <= r._end; } /** * Determine if the range contains an address. * * @param a Address to compare with * @return true if the address is in the range */ bool contains(const Addr& a) const { // check if the address is in the range and if there is either // no interleaving, or with interleaving also if the selected // bits from the address match the interleaving value return a >= _start && a <= _end && (!interleaved() || (bits(a, intlvHighBit, intlvHighBit - intlvBits + 1) == intlvMatch)); } /** * Keep the operators away from SWIG. */ #ifndef SWIG /** * Less-than operator used to turn an STL map into a binary search * tree of non-overlapping address ranges. * * @param r Range to compare with * @return true if the start address is less than that of the other range */ bool operator<(const AddrRange& r) const { if (_start != r._start) return _start < r._start; else // for now assume that the end is also the same, and that // we are looking at the same interleaving bits return intlvMatch < r.intlvMatch; } #endif // SWIG }; inline AddrRange RangeEx(Addr start, Addr end) { return AddrRange(start, end - 1); } inline AddrRange RangeIn(Addr start, Addr end) { return AddrRange(start, end); } inline AddrRange RangeSize(Addr start, Addr size) { return AddrRange(start, start + size - 1); } #endif // __BASE_ADDR_RANGE_HH__
Fix a bug in the address interleaving
base: Fix a bug in the address interleaving This patch fixes a minor (but important) typo in the matching of an address to an interleaved range.
C++
bsd-3-clause
andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin
0fb94d2fb11a7b95e5218f5a14562f139ec8af84
src/input_output/FGPropertyManager.cpp
src/input_output/FGPropertyManager.cpp
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Header: FGPropertyManager.cpp Author: Tony Peden Based on work originally by David Megginson Date: 2/2002 ------------- Copyright (C) 2002 ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGPropertyManager.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ using namespace std; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COMMENTS, REFERENCES, and NOTES [use "class documentation" below for API docs] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ namespace JSBSim { bool FGPropertyManager::suppress_warning = true; std::vector<SGPropertyNode_ptr> FGPropertyManager::tied_properties; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Unbind(void) { vector<SGPropertyNode_ptr>::iterator it; for (it = tied_properties.begin();it < tied_properties.end();it++) (*it)->untie(); tied_properties.clear(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::mkPropertyName(string name, bool lowercase) { /* do this two pass to avoid problems with characters getting skipped because the index changed */ unsigned i; for(i=0;i<name.length();i++) { if( lowercase && isupper(name[i]) ) name[i]=tolower(name[i]); else if( isspace(name[i]) ) name[i]='-'; } return name; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGPropertyManager* FGPropertyManager::GetNode (const string &path, bool create) { SGPropertyNode* node=this->getNode(path.c_str(), create); if (node == 0 && !suppress_warning) { cerr << "FGPropertyManager::GetNode() No node found for " << path << endl; } return (FGPropertyManager*)node; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGPropertyManager* FGPropertyManager::GetNode (const string &relpath, int index, bool create) { return (FGPropertyManager*)getNode(relpath.c_str(),index,create); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::HasNode (const string &path) { // Checking if a node exists shouldn't write a warning if it doesn't exist suppress_warning = true; bool has_node = (GetNode(path, false) != 0); suppress_warning = false; return has_node; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetName( void ) { return string( getName() ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetPrintableName( void ) { string temp_string(getName()); size_t initial_location=0; size_t found_location; found_location = temp_string.rfind("/"); if (found_location != string::npos) temp_string = temp_string.substr(found_location); found_location = temp_string.find('_',initial_location); while (found_location != string::npos) { temp_string.replace(found_location,1," "); initial_location = found_location+1; found_location = temp_string.find('_',initial_location); } return temp_string; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetFullyQualifiedName(void) { vector<string> stack; stack.push_back( getDisplayName(true) ); SGPropertyNode* tmpn=getParent(); bool atroot=false; while( !atroot ) { stack.push_back( tmpn->getDisplayName(true) ); if( !tmpn->getParent() ) atroot=true; else tmpn=tmpn->getParent(); } string fqname=""; for(unsigned i=stack.size()-1;i>0;i--) { fqname+= stack[i]; fqname+= "/"; } fqname+= stack[0]; return fqname; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetRelativeName( const string &path ) { string temp_string = GetFullyQualifiedName(); size_t len = path.length(); if ( (len > 0) && (temp_string.substr(0,len) == path) ) { temp_string = temp_string.erase(0,len); } return temp_string; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::GetBool (const string &name, bool defaultValue) { return getBoolValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGPropertyManager::GetInt (const string &name, int defaultValue ) { return getIntValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGPropertyManager::GetLong (const string &name, long defaultValue ) { return getLongValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% float FGPropertyManager::GetFloat (const string &name, float defaultValue ) { return getFloatValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGPropertyManager::GetDouble (const string &name, double defaultValue ) { return getDoubleValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetString (const string &name, string defaultValue ) { return string(getStringValue(name.c_str(), defaultValue.c_str())); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetBool (const string &name, bool val) { return setBoolValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetInt (const string &name, int val) { return setIntValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetLong (const string &name, long val) { return setLongValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetFloat (const string &name, float val) { return setFloatValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetDouble (const string &name, double val) { return setDoubleValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetString (const string &name, const string &val) { return setStringValue(name.c_str(), val.c_str()); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::SetArchivable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) cerr << "Attempt to set archive flag for non-existent property " << name << endl; else node->setAttribute(SGPropertyNode::ARCHIVE, state); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::SetReadable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) cerr << "Attempt to set read flag for non-existant property " << name << endl; else node->setAttribute(SGPropertyNode::READ, state); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::SetWritable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) cerr << "Attempt to set write flag for non-existant property " << name << endl; else node->setAttribute(SGPropertyNode::WRITE, state); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Untie (const string &name) { if (!untie(name.c_str())) cerr << "Failed to untie property " << name << endl; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, bool *pointer, bool useDefault) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<bool>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, int *pointer, bool useDefault ) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<int>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, long *pointer, bool useDefault ) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<long>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, float *pointer, bool useDefault ) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<float>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, double *pointer, bool useDefault) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<double>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } } // namespace JSBSim
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Header: FGPropertyManager.cpp Author: Tony Peden Based on work originally by David Megginson Date: 2/2002 ------------- Copyright (C) 2002 ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGPropertyManager.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ using namespace std; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COMMENTS, REFERENCES, and NOTES [use "class documentation" below for API docs] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ namespace JSBSim { bool FGPropertyManager::suppress_warning = true; std::vector<SGPropertyNode_ptr> FGPropertyManager::tied_properties; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Unbind(void) { vector<SGPropertyNode_ptr>::iterator it; for (it = tied_properties.begin();it < tied_properties.end();it++) (*it)->untie(); tied_properties.clear(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::mkPropertyName(string name, bool lowercase) { /* do this two pass to avoid problems with characters getting skipped because the index changed */ unsigned i; for(i=0;i<name.length();i++) { if( lowercase && isupper(name[i]) ) name[i]=tolower(name[i]); else if( isspace(name[i]) ) name[i]='-'; } return name; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGPropertyManager* FGPropertyManager::GetNode (const string &path, bool create) { SGPropertyNode* node=this->getNode(path.c_str(), create); if (node == 0 && !suppress_warning) { cerr << "FGPropertyManager::GetNode() No node found for " << path << endl; } return (FGPropertyManager*)node; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGPropertyManager* FGPropertyManager::GetNode (const string &relpath, int index, bool create) { return (FGPropertyManager*)getNode(relpath.c_str(),index,create); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::HasNode (const string &path) { // Checking if a node exists shouldn't write a warning if it doesn't exist suppress_warning = true; bool has_node = (GetNode(path, false) != 0); suppress_warning = false; return has_node; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetName( void ) { return string( getName() ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetPrintableName( void ) { string temp_string(getName()); size_t initial_location=0; size_t found_location; found_location = temp_string.rfind("/"); if (found_location != string::npos) temp_string = temp_string.substr(found_location); found_location = temp_string.find('_',initial_location); while (found_location != string::npos) { temp_string.replace(found_location,1," "); initial_location = found_location+1; found_location = temp_string.find('_',initial_location); } return temp_string; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetFullyQualifiedName(void) { vector<string> stack; stack.push_back( getDisplayName(true) ); SGPropertyNode* tmpn=getParent(); bool atroot=false; while( !atroot ) { stack.push_back( tmpn->getDisplayName(true) ); if( !tmpn->getParent() ) atroot=true; else tmpn=tmpn->getParent(); } string fqname=""; for(unsigned i=stack.size()-1;i>0;i--) { fqname+= stack[i]; fqname+= "/"; } fqname+= stack[0]; return fqname; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetRelativeName( const string &path ) { string temp_string = GetFullyQualifiedName(); size_t len = path.length(); if ( (len > 0) && (temp_string.substr(0,len) == path) ) { temp_string = temp_string.erase(0,len); } return temp_string; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::GetBool (const string &name, bool defaultValue) { return getBoolValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGPropertyManager::GetInt (const string &name, int defaultValue ) { return getIntValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGPropertyManager::GetLong (const string &name, long defaultValue ) { return getLongValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% float FGPropertyManager::GetFloat (const string &name, float defaultValue ) { return getFloatValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGPropertyManager::GetDouble (const string &name, double defaultValue ) { return getDoubleValue(name.c_str(), defaultValue); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGPropertyManager::GetString (const string &name, string defaultValue ) { return string(getStringValue(name.c_str(), defaultValue.c_str())); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetBool (const string &name, bool val) { return setBoolValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetInt (const string &name, int val) { return setIntValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetLong (const string &name, long val) { return setLongValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetFloat (const string &name, float val) { return setFloatValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetDouble (const string &name, double val) { return setDoubleValue(name.c_str(), val); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGPropertyManager::SetString (const string &name, const string &val) { return setStringValue(name.c_str(), val.c_str()); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::SetArchivable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) cerr << "Attempt to set archive flag for non-existent property " << name << endl; else node->setAttribute(SGPropertyNode::ARCHIVE, state); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::SetReadable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) cerr << "Attempt to set read flag for non-existant property " << name << endl; else node->setAttribute(SGPropertyNode::READ, state); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::SetWritable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) cerr << "Attempt to set write flag for non-existant property " << name << endl; else node->setAttribute(SGPropertyNode::WRITE, state); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Untie (const string &name) { SGPropertyNode* property = getNode(name.c_str()); if (!property) { cerr << "Attempt to untie a non-existant property." << name << endl; return; } vector <SGPropertyNode_ptr>::iterator it; for (it = tied_properties.begin(); it != tied_properties.end(); ++it) { if (*it == property) { property->untie(); tied_properties.erase(it); if (debug_lvl & 0x20) cout << "Untied " << name << endl; return; } } cerr << "Failed to untie property " << name << endl << "JSBSim is not the owner of this property." << endl; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, bool *pointer, bool useDefault) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<bool>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, int *pointer, bool useDefault ) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<int>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, long *pointer, bool useDefault ) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<long>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, float *pointer, bool useDefault ) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<float>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropertyManager::Tie (const string &name, double *pointer, bool useDefault) { SGPropertyNode* property = getNode(name.c_str(), true); if (!property) { cerr << "Could not get or create property " << name << endl; return; } if (!property->tie(SGRawValuePointer<double>(pointer), useDefault)) cerr << "Failed to tie property " << name << " to a pointer" << endl; else { tied_properties.push_back(property); if (debug_lvl & 0x20) cout << name << endl; } } } // namespace JSBSim
Make sanity checks before untying a property. Also make sure that, once untied, the property is no longer listed in the properties tied by JSBSim
Make sanity checks before untying a property. Also make sure that, once untied, the property is no longer listed in the properties tied by JSBSim
C++
lgpl-2.1
adrcad/jsbsim,AEgisTG/jsbsim,airware/jsbsim,hrabcak/jsbsim,airware/jsbsim,airware/jsbsim,cs8425/jsbsim,hrabcak/jsbsim,cs8425/jsbsim,AEgisTG/jsbsim,tridge/jsbsim,AEgisTG/jsbsim,tridge/jsbsim,pmatigakis/jsbsim,cs8425/jsbsim,Stonelinks/jsbsim,Stonelinks/jsbsim,DolanP/jsbsim-dll,tridge/jsbsim,adrcad/jsbsim,AEgisTG/jsbsim,DolanP/jsbsim-dll,adrcad/jsbsim,esden/jsbsim,airware/jsbsim,pmatigakis/jsbsim,adrcad/jsbsim,hrabcak/jsbsim,Stonelinks/jsbsim,esden/jsbsim,hrabcak/jsbsim,tridge/jsbsim,pmatigakis/jsbsim,AEgisTG/jsbsim,tridge/jsbsim,airware/jsbsim,pmatigakis/jsbsim,airware/jsbsim,DolanP/jsbsim-dll,hrabcak/jsbsim,pmatigakis/jsbsim,Stonelinks/jsbsim,Stonelinks/jsbsim,DolanP/jsbsim-dll,hrabcak/jsbsim,Stonelinks/jsbsim,tridge/jsbsim,adrcad/jsbsim,Stonelinks/jsbsim,DolanP/jsbsim-dll,esden/jsbsim,esden/jsbsim,pmatigakis/jsbsim,pmatigakis/jsbsim,adrcad/jsbsim,hrabcak/jsbsim,airware/jsbsim,cs8425/jsbsim,AEgisTG/jsbsim,esden/jsbsim,cs8425/jsbsim,cs8425/jsbsim,tridge/jsbsim,AEgisTG/jsbsim
9281d8ad4c17228a9e108b08701367400d82a315
loess.hpp
loess.hpp
#ifndef _LUTCALIB_LOESS_H #define _LUTCALIB_LOESS_H #include "ceres/ceres.h" #include "opencv2/core/core.hpp" template <int x_degree, int y_degree> struct Poly2dError { Poly2dError(double x, double y, double val, double w) : x_(x), y_(y), val_(val), w_(w) {} template <typename T> bool operator()(const T* const p, T* residuals) const { T xvars[x_degree]; T yvar = T(1.0); xvars[0] = T(1.0); for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*T(x_); T res = T(0.0); for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res += p[j*x_degree+i]*(yvar*xvars[i]); } yvar = yvar*T(y_); } residuals[0] = (T(val_) - res)*T(w_); return true; } // Factory to hide the construction of the CostFunction object from // the client code. static ceres::CostFunction* Create(double x, double y, double val, double w) { return (new ceres::AutoDiffCostFunction<Poly2dError, 1, x_degree*y_degree>( new Poly2dError(x, y, val, w))); } double x_,y_,val_, w_; }; template <int x_degree, int y_degree> struct PolyPers2dError { PolyPers2dError(double x, double y, double valx, double valy, double w) : x_(x), y_(y), val_x_(valx), val_y_(valy), w_(w) {} template <typename T> bool operator()(const T* const p, T* residuals) const { T warped[3]; warped[0] = T(x_)*p[0] + T(y_)*p[1] + p[2]; warped[1] = T(x_)*p[3] + T(y_)*p[4] + p[5]; warped[2] = T(x_)*p[6] + T(y_)*p[7] + p[8]; warped[0] /= warped[2]; warped[1] /= warped[2]; T xvars[x_degree]; T yvar = T(1.0); xvars[0] = T(1.0); for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*warped[0]; T res_x = warped[0]; T res_y = warped[1]; for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res_x += p[9+j*x_degree+i]*(yvar*xvars[i]); res_y += p[9+j*x_degree+i+x_degree*y_degree]*(yvar*xvars[i]); } yvar = yvar*warped[1]; } residuals[0] = sqrt(abs(T(val_x_) - res_x)*T(w_)+1e-18); residuals[1] = sqrt(abs(T(val_y_) - res_y)*T(w_)+1e-18); return true; } // Factory to hide the construction of the CostFunction object from // the client code. static ceres::CostFunction* Create(double x, double y, double valx, double valy, double w) { return (new ceres::AutoDiffCostFunction<PolyPers2dError, 2, 9+2*x_degree*y_degree>( new PolyPers2dError(x, y, valx, valy, w))); } double x_,y_,val_x_,val_y_, w_; }; //TODO ignore residuals after below a certine weight! //NOTE: z coordinate of wps is ignored (assumed to be constant - e.g. flat target) template<int x_degree, int y_degree> double fit_2d_poly_2d(std::vector<cv::Point2f> &ips, std::vector<cv::Point3f> &wps, cv::Point2f center, double *coeffs, double sigma, int *count = NULL) { ceres::Solver::Options options; options.max_num_iterations = 1000; options.num_threads = 1; //options.minimizer_progress_to_stdout = true; //options.trust_region_strategy_type = ceres::DOGLEG; options.linear_solver_type = ceres::DENSE_QR; options.logging_type = ceres::SILENT; double w_sum = 0.0; cv::Point2f wc(0, 0); coeffs[0] = wps[0].x; for(int i=1;i<x_degree*y_degree;i++) coeffs[i] = 0.0; coeffs[x_degree*y_degree] = wps[0].y; for(int i=1;i<x_degree*y_degree;i++) coeffs[i+x_degree*y_degree] = 0.0; ceres::Problem problem_x; ceres::Problem problem_y; if (count) (*count) = 0; for(int i=0;i<ips.size();i++) { cv::Point2f ip = ips[i]-center; double w = exp(-(ip.x*ip.x+ip.y*ip.y)/(2.0*sigma*sigma)); if (w <= 0.05) continue; if (count) (*count)++; w_sum += w; wc += w*ip; w = sqrt(w); //root to get w after squaring by ceres! ceres::CostFunction* cost_function = Poly2dError<x_degree,y_degree>::Create(ip.x, ip.y,wps[i].x, w); problem_x.AddResidualBlock(cost_function, NULL, coeffs); cost_function = Poly2dError<x_degree,y_degree>::Create(ip.x, ip.y,wps[i].y, w); problem_y.AddResidualBlock(cost_function, NULL, coeffs+x_degree*y_degree); } if (norm(wc*(1.0/w_sum)) >= 5.0) return std::numeric_limits<double>::quiet_NaN(); ceres::Solver::Summary summary_x; ceres::Solver::Summary summary_y; ceres::Solve(options, &problem_x, &summary_x); ceres::Solve(options, &problem_y, &summary_y); //std::cout << summary_x.FullReport() << "\n"; //std::cout << summary_y.FullReport() << "\n"; return sqrt((summary_x.final_cost+summary_y.final_cost)/w_sum); } //TODO ignore residuals after below a certine weight! //NOTE: z coordinate of wps is ignored (assumed to be constant - e.g. flat target) template<int x_degree, int y_degree> double fit_2d_pers_poly_2d(std::vector<cv::Point2f> &ips, std::vector<cv::Point3f> &wps, cv::Point2f center, double *coeffs, double sigma, int *count = NULL) { ceres::Solver::Options options; options.max_num_iterations = 1000; //options.num_threads = 8; //options.num_linear_solver_threads = 8; //options.minimizer_progress_to_stdout = true; //options.trust_region_strategy_type = ceres::DOGLEG; options.linear_solver_type = ceres::DENSE_QR; options.logging_type = ceres::SILENT; double w_sum = 0.0; cv::Point2f wc(0, 0); for(int i=0;i<9;i++) if (i % 4 == 0) coeffs[i] = 1.0; else coeffs[i] = 0.0; coeffs[2] = wps[0].x; coeffs[5] = wps[0].y; coeffs[9+0] = 1.0; for(int i=1;i<x_degree*y_degree;i++) coeffs[9+i] = 0.0; coeffs[9+x_degree*y_degree] = 1.0; for(int i=1;i<x_degree*y_degree;i++) coeffs[9+i+x_degree*y_degree] = 0.0; ceres::Problem problem; if (count) (*count) = 0; for(int i=0;i<ips.size();i++) { cv::Point2f ip = ips[i]-center; double w = exp(-(ip.x*ip.x+ip.y*ip.y)/(2.0*sigma*sigma)); if (w <= 0.05) continue; if (count) (*count)++; w_sum += w; wc += w*ip; ceres::CostFunction* cost_function = PolyPers2dError<x_degree,y_degree>::Create(ip.x, ip.y, wps[i].x, wps[i].y, w); problem.AddResidualBlock(cost_function, NULL, coeffs); } if (norm(wc*(1.0/w_sum)) >= 10.0) return std::numeric_limits<double>::quiet_NaN(); ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); //std::cout << summary.FullReport() << "\n"; return sqrt((summary.final_cost)/w_sum); } template<int x_degree, int y_degree> cv::Point2f eval_2d_poly_2d(cv::Point2f p, double *coeffs) { double xvars[x_degree]; double yvar = 1.0; xvars[0] = 1.0; for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*p.x; double res_x = 0.0; double res_y = 0.0; for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res_x += coeffs[j*x_degree+i]*(yvar*xvars[i]); res_y += coeffs[j*x_degree+i+x_degree*y_degree]*(yvar*xvars[i]); } yvar = yvar*p.y; } return cv::Point2f(res_x, res_y); } template<int x_degree, int y_degree> cv::Point2f eval_2d_pers_poly_2d(cv::Point2f p, double *coeffs) { double warped[3]; warped[0] = p.x*coeffs[0] + p.y*coeffs[1] + coeffs[2]; warped[1] = p.x*coeffs[3] + p.y*coeffs[4] + coeffs[5]; warped[2] = p.x*coeffs[6] + p.y*coeffs[7] + coeffs[8]; warped[0] /= warped[2]; warped[1] /= warped[2]; double xvars[x_degree]; double yvar = 1.0; xvars[0] = 1.0; for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*warped[0]; double res_x = warped[0]; double res_y = warped[1]; for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res_x += coeffs[9+j*x_degree+i]*(yvar*xvars[i]); res_y += coeffs[9+j*x_degree+i+x_degree*y_degree]*(yvar*xvars[i]); } yvar = yvar*warped[1]; } return cv::Point2f(res_x, res_y); } #endif
#ifndef _LUTCALIB_LOESS_H #define _LUTCALIB_LOESS_H #include "ceres/ceres.h" #include "opencv2/core/core.hpp" template <int x_degree, int y_degree> struct Poly2dError { Poly2dError(double x, double y, double val, double w) : x_(x), y_(y), val_(val), w_(w) {} template <typename T> bool operator()(const T* const p, T* residuals) const { T xvars[x_degree]; T yvar = T(1.0); xvars[0] = T(1.0); for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*T(x_); T res = T(0.0); for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res += p[j*x_degree+i]*(yvar*xvars[i]); } yvar = yvar*T(y_); } residuals[0] = (T(val_) - res)*T(w_); return true; } // Factory to hide the construction of the CostFunction object from // the client code. static ceres::CostFunction* Create(double x, double y, double val, double w) { return (new ceres::AutoDiffCostFunction<Poly2dError, 1, x_degree*y_degree>( new Poly2dError(x, y, val, w))); } double x_,y_,val_, w_; }; template <int x_degree, int y_degree> struct PolyPers2dError { PolyPers2dError(double x, double y, double valx, double valy, double w) : x_(x), y_(y), val_x_(valx), val_y_(valy), w_(w) {} template <typename T> bool operator()(const T* const p, T* residuals) const { T warped[3]; warped[0] = T(x_)*p[0] + T(y_)*p[1] + p[2]; warped[1] = T(x_)*p[3] + T(y_)*p[4] + p[5]; warped[2] = T(x_)*p[6] + T(y_)*p[7] + p[8]; warped[0] /= warped[2]; warped[1] /= warped[2]; T xvars[x_degree]; T yvar = T(1.0); xvars[0] = T(1.0); for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*warped[0]; T res_x = warped[0]; T res_y = warped[1]; for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res_x += p[9+j*x_degree+i]*(yvar*xvars[i]); res_y += p[9+j*x_degree+i+x_degree*y_degree]*(yvar*xvars[i]); } yvar = yvar*warped[1]; } residuals[0] = sqrt(abs(T(val_x_) - res_x)*T(w_)+1e-18); residuals[1] = sqrt(abs(T(val_y_) - res_y)*T(w_)+1e-18); return true; } // Factory to hide the construction of the CostFunction object from // the client code. static ceres::CostFunction* Create(double x, double y, double valx, double valy, double w) { return (new ceres::AutoDiffCostFunction<PolyPers2dError, 2, 9+2*x_degree*y_degree>( new PolyPers2dError(x, y, valx, valy, w))); } double x_,y_,val_x_,val_y_, w_; }; //TODO ignore residuals after below a certine weight! //NOTE: z coordinate of wps is ignored (assumed to be constant - e.g. flat target) template<int x_degree, int y_degree> double fit_2d_poly_2d(std::vector<cv::Point2f> &ips, std::vector<cv::Point3f> &wps, cv::Point2f center, double *coeffs, double sigma, int *count = NULL) { ceres::Solver::Options options; options.max_num_iterations = 1000; options.num_threads = 1; //options.minimizer_progress_to_stdout = true; //options.trust_region_strategy_type = ceres::DOGLEG; options.linear_solver_type = ceres::DENSE_QR; options.logging_type = ceres::SILENT; double w_sum = 0.0; cv::Point2f wc(0, 0); coeffs[0] = wps[0].x; for(int i=1;i<x_degree*y_degree;i++) coeffs[i] = 0.0; coeffs[x_degree*y_degree] = wps[0].y; for(int i=1;i<x_degree*y_degree;i++) coeffs[i+x_degree*y_degree] = 0.0; ceres::Problem problem_x; ceres::Problem problem_y; if (count) (*count) = 0; for(int i=0;i<ips.size();i++) { cv::Point2f ip = ips[i]-center; double w = exp(-(ip.x*ip.x+ip.y*ip.y)/(2.0*sigma*sigma)); if (w <= 0.05) continue; if (count) (*count)++; w_sum += w; wc += w*ip; w = sqrt(w); //root to get w after squaring by ceres! ceres::CostFunction* cost_function = Poly2dError<x_degree,y_degree>::Create(ip.x, ip.y,wps[i].x, w); problem_x.AddResidualBlock(cost_function, NULL, coeffs); cost_function = Poly2dError<x_degree,y_degree>::Create(ip.x, ip.y,wps[i].y, w); problem_y.AddResidualBlock(cost_function, NULL, coeffs+x_degree*y_degree); } if (norm(wc*(1.0/w_sum)) >= 5.0) return std::numeric_limits<double>::quiet_NaN(); ceres::Solver::Summary summary_x; ceres::Solver::Summary summary_y; ceres::Solve(options, &problem_x, &summary_x); ceres::Solve(options, &problem_y, &summary_y); //std::cout << summary_x.FullReport() << "\n"; //std::cout << summary_y.FullReport() << "\n"; return sqrt((summary_x.final_cost+summary_y.final_cost)/w_sum); } //TODO ignore residuals after below a certine weight! //NOTE: z coordinate of wps is ignored (assumed to be constant - e.g. flat target) template<int x_degree, int y_degree> double fit_2d_pers_poly_2d(std::vector<cv::Point2f> &ips, std::vector<cv::Point3f> &wps, cv::Point2f center, double *coeffs, double sigma, double scale, int *count = NULL) { ceres::Solver::Options options; options.max_num_iterations = 1000; //options.num_threads = 8; //options.num_linear_solver_threads = 8; //options.minimizer_progress_to_stdout = true; //options.trust_region_strategy_type = ceres::DOGLEG; options.linear_solver_type = ceres::DENSE_QR; options.logging_type = ceres::SILENT; double w_sum = 0.0; cv::Point2f wc(0, 0); for(int i=0;i<9;i++) if (i % 4 == 0) coeffs[i] = 1.0; else coeffs[i] = 0.0; coeffs[2] = wps[0].x; coeffs[5] = wps[0].y; coeffs[9+0] = 1.0; for(int i=1;i<x_degree*y_degree;i++) coeffs[9+i] = 0.0; coeffs[9+x_degree*y_degree] = 1.0; for(int i=1;i<x_degree*y_degree;i++) coeffs[9+i+x_degree*y_degree] = 0.0; ceres::Problem problem; if (count) (*count) = 0; for(int i=0;i<ips.size();i++) { cv::Point2f ip = (ips[i]-center); double w = exp(-(ip.x*ip.x+ip.y*ip.y)/(2.0*sigma*sigma)); if (w <= 0.05) continue; if (count) (*count)++; w_sum += w; wc += w*ip; ip *= scale; ceres::CostFunction* cost_function = PolyPers2dError<x_degree,y_degree>::Create(ip.x, ip.y, wps[i].x, wps[i].y, w); problem.AddResidualBlock(cost_function, NULL, coeffs); } if (norm(wc*(1.0/w_sum)) >= 10.0) return std::numeric_limits<double>::quiet_NaN(); ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); //std::cout << summary.FullReport() << "\n"; return sqrt((summary.final_cost)/w_sum); } template<int x_degree, int y_degree> cv::Point2f eval_2d_poly_2d(cv::Point2f p, double *coeffs) { double xvars[x_degree]; double yvar = 1.0; xvars[0] = 1.0; for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*p.x; double res_x = 0.0; double res_y = 0.0; for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res_x += coeffs[j*x_degree+i]*(yvar*xvars[i]); res_y += coeffs[j*x_degree+i+x_degree*y_degree]*(yvar*xvars[i]); } yvar = yvar*p.y; } return cv::Point2f(res_x, res_y); } template<int x_degree, int y_degree> cv::Point2f eval_2d_pers_poly_2d(cv::Point2f p, double *coeffs, double scale = 1.0) { double warped[3]; p *= scale; warped[0] = p.x*coeffs[0] + p.y*coeffs[1] + coeffs[2]; warped[1] = p.x*coeffs[3] + p.y*coeffs[4] + coeffs[5]; warped[2] = p.x*coeffs[6] + p.y*coeffs[7] + coeffs[8]; warped[0] /= warped[2]; warped[1] /= warped[2]; double xvars[x_degree]; double yvar = 1.0; xvars[0] = 1.0; for(int i=1;i<x_degree;i++) xvars[i] = xvars[i-1]*warped[0]; double res_x = warped[0]; double res_y = warped[1]; for(int j=0;j<y_degree;j++) { for(int i=0;i<x_degree;i++) { res_x += coeffs[9+j*x_degree+i]*(yvar*xvars[i]); res_y += coeffs[9+j*x_degree+i+x_degree*y_degree]*(yvar*xvars[i]); } yvar = yvar*warped[1]; } return cv::Point2f(res_x, res_y); } #endif
allow to scale x axis of proxy poly fit
allow to scale x axis of proxy poly fit
C++
mit
hendriksiedelmann/vigra_cmake,vigralibs/vigra_cmake
f4857cb7cf7663df97747dc39aec3e84531fa5a1
src/rdb_protocol/pb_server.cc
src/rdb_protocol/pb_server.cc
// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/pb_server.hpp" #include "concurrency/cross_thread_watchable.hpp" #include "concurrency/watchable.hpp" #include "rdb_protocol/counted_term.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/profile.hpp" #include "rdb_protocol/stream_cache.hpp" #include "rpc/semilattice/view/field.hpp" Response on_unparsable_query2(ql::protob_t<Query> q, std::string msg) { Response res; res.set_token((q.has() && q->has_token()) ? q->token() : -1); ql::fill_error(&res, Response::CLIENT_ERROR, msg); return res; } query2_server_t::query2_server_t(const std::set<ip_address_t> &local_addresses, int port, rdb_protocol_t::context_t *_ctx) : server(local_addresses, port, boost::bind(&query2_server_t::handle, this, _1, _2, _3), &on_unparsable_query2, _ctx->auth_metadata, INLINE), ctx(_ctx), parser_id(generate_uuid()), thread_counters(0) { } http_app_t *query2_server_t::get_http_app() { return &server; } int query2_server_t::get_port() const { return server.get_port(); } bool query2_server_t::handle(ql::protob_t<Query> q, Response *response_out, context_t *query2_context) { ql::stream_cache2_t *stream_cache2 = &query2_context->stream_cache2; signal_t *interruptor = query2_context->interruptor; guarantee(interruptor); response_out->set_token(q->token()); counted_t<const ql::datum_t> noreply = static_optarg("noreply", q); bool response_needed = !(noreply.has() && noreply->get_type() == ql::datum_t::type_t::R_BOOL && noreply->as_bool()); try { threadnum_t thread = get_thread_id(); guarantee(ctx->directory_read_manager); scoped_ptr_t<ql::env_t> env( new ql::env_t( ctx->extproc_pool, ctx->ns_repo, ctx->cross_thread_namespace_watchables[thread.threadnum]->get_watchable(), ctx->cross_thread_database_watchables[thread.threadnum]->get_watchable(), ctx->cluster_metadata, ctx->directory_read_manager, interruptor, ctx->machine_id, q)); // `ql::run` will set the status code ql::run(q, std::move(env), response_out, stream_cache2); } catch (const interrupted_exc_t &e) { ql::fill_error(response_out, Response::RUNTIME_ERROR, "Query interrupted. Did you shut down the server?"); } catch (const std::exception &e) { ql::fill_error(response_out, Response::RUNTIME_ERROR, strprintf("Unexpected exception: %s\n", e.what())); } catch (const ql::exc_t &e) { fill_error(response_out, Response::COMPILE_ERROR, e.what(), e.backtrace()); } catch (const ql::datum_exc_t &e) { fill_error(response_out, Response::COMPILE_ERROR, e.what(), ql::backtrace_t()); } return response_needed; } void make_empty_protob_bearer(ql::protob_t<Query> *request) { *request = ql::make_counted_query(); } Query *underlying_protob_value(ql::protob_t<Query> *request) { return request->get(); }
// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/pb_server.hpp" #include "concurrency/cross_thread_watchable.hpp" #include "concurrency/watchable.hpp" #include "rdb_protocol/counted_term.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/profile.hpp" #include "rdb_protocol/stream_cache.hpp" #include "rpc/semilattice/view/field.hpp" Response on_unparsable_query2(ql::protob_t<Query> q, std::string msg) { Response res; res.set_token((q.has() && q->has_token()) ? q->token() : -1); ql::fill_error(&res, Response::CLIENT_ERROR, msg); return res; } query2_server_t::query2_server_t(const std::set<ip_address_t> &local_addresses, int port, rdb_protocol_t::context_t *_ctx) : server(local_addresses, port, boost::bind(&query2_server_t::handle, this, _1, _2, _3), &on_unparsable_query2, _ctx->auth_metadata, INLINE), ctx(_ctx), parser_id(generate_uuid()), thread_counters(0) { } http_app_t *query2_server_t::get_http_app() { return &server; } int query2_server_t::get_port() const { return server.get_port(); } bool query2_server_t::handle(ql::protob_t<Query> q, Response *response_out, context_t *query2_context) { ql::stream_cache2_t *stream_cache2 = &query2_context->stream_cache2; signal_t *interruptor = query2_context->interruptor; guarantee(interruptor); response_out->set_token(q->token()); counted_t<const ql::datum_t> noreply = static_optarg("noreply", q); bool response_needed = !(noreply.has() && noreply->get_type() == ql::datum_t::type_t::R_BOOL && noreply->as_bool()); try { threadnum_t thread = get_thread_id(); guarantee(ctx->directory_read_manager); scoped_ptr_t<ql::env_t> env( new ql::env_t( ctx->extproc_pool, ctx->ns_repo, ctx->cross_thread_namespace_watchables[thread.threadnum]->get_watchable(), ctx->cross_thread_database_watchables[thread.threadnum]->get_watchable(), ctx->cluster_metadata, ctx->directory_read_manager, interruptor, ctx->machine_id, q)); // `ql::run` will set the status code ql::run(q, std::move(env), response_out, stream_cache2); } catch (const ql::exc_t &e) { fill_error(response_out, Response::COMPILE_ERROR, e.what(), e.backtrace()); } catch (const ql::datum_exc_t &e) { fill_error(response_out, Response::COMPILE_ERROR, e.what(), ql::backtrace_t()); } catch (const interrupted_exc_t &e) { ql::fill_error(response_out, Response::RUNTIME_ERROR, "Query interrupted. Did you shut down the server?"); } catch (const std::exception &e) { ql::fill_error(response_out, Response::RUNTIME_ERROR, strprintf("Unexpected exception: %s\n", e.what())); } return response_needed; } void make_empty_protob_bearer(ql::protob_t<Query> *request) { *request = ql::make_counted_query(); } Query *underlying_protob_value(ql::protob_t<Query> *request) { return request->get(); }
Fix a problem with catching generic exceptions.
Fix a problem with catching generic exceptions.
C++
apache-2.0
jmptrader/rethinkdb,4talesa/rethinkdb,jesseditson/rethinkdb,dparnell/rethinkdb,4talesa/rethinkdb,catroot/rethinkdb,robertjpayne/rethinkdb,elkingtonmcb/rethinkdb,spblightadv/rethinkdb,losywee/rethinkdb,matthaywardwebdesign/rethinkdb,bchavez/rethinkdb,urandu/rethinkdb,wujf/rethinkdb,mbroadst/rethinkdb,niieani/rethinkdb,ajose01/rethinkdb,KSanthanam/rethinkdb,grandquista/rethinkdb,4talesa/rethinkdb,jmptrader/rethinkdb,marshall007/rethinkdb,ayumilong/rethinkdb,RubenKelevra/rethinkdb,sbusso/rethinkdb,lenstr/rethinkdb,sebadiaz/rethinkdb,ajose01/rethinkdb,RubenKelevra/rethinkdb,losywee/rethinkdb,gavioto/rethinkdb,urandu/rethinkdb,wojons/rethinkdb,wojons/rethinkdb,wojons/rethinkdb,victorbriz/rethinkdb,rrampage/rethinkdb,mbroadst/rethinkdb,wojons/rethinkdb,sontek/rethinkdb,dparnell/rethinkdb,alash3al/rethinkdb,bchavez/rethinkdb,lenstr/rethinkdb,sebadiaz/rethinkdb,wujf/rethinkdb,KSanthanam/rethinkdb,scripni/rethinkdb,greyhwndz/rethinkdb,scripni/rethinkdb,mcanthony/rethinkdb,spblightadv/rethinkdb,eliangidoni/rethinkdb,scripni/rethinkdb,wkennington/rethinkdb,bpradipt/rethinkdb,victorbriz/rethinkdb,KSanthanam/rethinkdb,AntouanK/rethinkdb,losywee/rethinkdb,gavioto/rethinkdb,jesseditson/rethinkdb,sbusso/rethinkdb,sebadiaz/rethinkdb,captainpete/rethinkdb,wkennington/rethinkdb,niieani/rethinkdb,RubenKelevra/rethinkdb,tempbottle/rethinkdb,jmptrader/rethinkdb,spblightadv/rethinkdb,bchavez/rethinkdb,jmptrader/rethinkdb,dparnell/rethinkdb,sontek/rethinkdb,jesseditson/rethinkdb,rrampage/rethinkdb,victorbriz/rethinkdb,grandquista/rethinkdb,JackieXie168/rethinkdb,ayumilong/rethinkdb,AntouanK/rethinkdb,niieani/rethinkdb,4talesa/rethinkdb,urandu/rethinkdb,yakovenkodenis/rethinkdb,ajose01/rethinkdb,greyhwndz/rethinkdb,bchavez/rethinkdb,elkingtonmcb/rethinkdb,pap/rethinkdb,catroot/rethinkdb,urandu/rethinkdb,wkennington/rethinkdb,eliangidoni/rethinkdb,alash3al/rethinkdb,greyhwndz/rethinkdb,gdi2290/rethinkdb,sontek/rethinkdb,wojons/rethinkdb,sebadiaz/rethinkdb,mbroadst/rethinkdb,mquandalle/rethinkdb,scripni/rethinkdb,greyhwndz/rethinkdb,eliangidoni/rethinkdb,JackieXie168/rethinkdb,mbroadst/rethinkdb,matthaywardwebdesign/rethinkdb,captainpete/rethinkdb,mcanthony/rethinkdb,ajose01/rethinkdb,lenstr/rethinkdb,Wilbeibi/rethinkdb,tempbottle/rethinkdb,spblightadv/rethinkdb,gdi2290/rethinkdb,wojons/rethinkdb,jmptrader/rethinkdb,mbroadst/rethinkdb,sbusso/rethinkdb,matthaywardwebdesign/rethinkdb,bchavez/rethinkdb,tempbottle/rethinkdb,ajose01/rethinkdb,wkennington/rethinkdb,sbusso/rethinkdb,4talesa/rethinkdb,Wilbeibi/rethinkdb,sontek/rethinkdb,gdi2290/rethinkdb,sbusso/rethinkdb,alash3al/rethinkdb,Wilbeibi/rethinkdb,bpradipt/rethinkdb,grandquista/rethinkdb,AntouanK/rethinkdb,JackieXie168/rethinkdb,Qinusty/rethinkdb,matthaywardwebdesign/rethinkdb,mcanthony/rethinkdb,mquandalle/rethinkdb,rrampage/rethinkdb,RubenKelevra/rethinkdb,dparnell/rethinkdb,sebadiaz/rethinkdb,AntouanK/rethinkdb,eliangidoni/rethinkdb,yakovenkodenis/rethinkdb,victorbriz/rethinkdb,marshall007/rethinkdb,dparnell/rethinkdb,bchavez/rethinkdb,losywee/rethinkdb,JackieXie168/rethinkdb,eliangidoni/rethinkdb,matthaywardwebdesign/rethinkdb,tempbottle/rethinkdb,losywee/rethinkdb,mquandalle/rethinkdb,gdi2290/rethinkdb,wkennington/rethinkdb,captainpete/rethinkdb,spblightadv/rethinkdb,marshall007/rethinkdb,yaolinz/rethinkdb,tempbottle/rethinkdb,losywee/rethinkdb,scripni/rethinkdb,ajose01/rethinkdb,scripni/rethinkdb,greyhwndz/rethinkdb,mcanthony/rethinkdb,mbroadst/rethinkdb,sontek/rethinkdb,catroot/rethinkdb,bchavez/rethinkdb,yakovenkodenis/rethinkdb,yaolinz/rethinkdb,mbroadst/rethinkdb,pap/rethinkdb,mcanthony/rethinkdb,wujf/rethinkdb,robertjpayne/rethinkdb,bpradipt/rethinkdb,rrampage/rethinkdb,ayumilong/rethinkdb,grandquista/rethinkdb,wkennington/rethinkdb,losywee/rethinkdb,RubenKelevra/rethinkdb,wkennington/rethinkdb,captainpete/rethinkdb,greyhwndz/rethinkdb,jesseditson/rethinkdb,eliangidoni/rethinkdb,catroot/rethinkdb,matthaywardwebdesign/rethinkdb,ajose01/rethinkdb,niieani/rethinkdb,gavioto/rethinkdb,urandu/rethinkdb,ayumilong/rethinkdb,bpradipt/rethinkdb,rrampage/rethinkdb,4talesa/rethinkdb,mquandalle/rethinkdb,Wilbeibi/rethinkdb,robertjpayne/rethinkdb,dparnell/rethinkdb,robertjpayne/rethinkdb,4talesa/rethinkdb,grandquista/rethinkdb,mbroadst/rethinkdb,dparnell/rethinkdb,gavioto/rethinkdb,lenstr/rethinkdb,KSanthanam/rethinkdb,urandu/rethinkdb,JackieXie168/rethinkdb,KSanthanam/rethinkdb,catroot/rethinkdb,gdi2290/rethinkdb,mcanthony/rethinkdb,elkingtonmcb/rethinkdb,sontek/rethinkdb,Wilbeibi/rethinkdb,niieani/rethinkdb,matthaywardwebdesign/rethinkdb,RubenKelevra/rethinkdb,captainpete/rethinkdb,mquandalle/rethinkdb,tempbottle/rethinkdb,mcanthony/rethinkdb,victorbriz/rethinkdb,greyhwndz/rethinkdb,jesseditson/rethinkdb,yaolinz/rethinkdb,Qinusty/rethinkdb,sebadiaz/rethinkdb,jesseditson/rethinkdb,yaolinz/rethinkdb,jesseditson/rethinkdb,yaolinz/rethinkdb,ajose01/rethinkdb,eliangidoni/rethinkdb,gavioto/rethinkdb,elkingtonmcb/rethinkdb,yakovenkodenis/rethinkdb,robertjpayne/rethinkdb,wkennington/rethinkdb,gdi2290/rethinkdb,matthaywardwebdesign/rethinkdb,mbroadst/rethinkdb,sontek/rethinkdb,Qinusty/rethinkdb,sebadiaz/rethinkdb,marshall007/rethinkdb,urandu/rethinkdb,mquandalle/rethinkdb,RubenKelevra/rethinkdb,AntouanK/rethinkdb,yakovenkodenis/rethinkdb,pap/rethinkdb,sbusso/rethinkdb,ayumilong/rethinkdb,Qinusty/rethinkdb,gavioto/rethinkdb,yakovenkodenis/rethinkdb,ayumilong/rethinkdb,marshall007/rethinkdb,spblightadv/rethinkdb,KSanthanam/rethinkdb,spblightadv/rethinkdb,robertjpayne/rethinkdb,yakovenkodenis/rethinkdb,tempbottle/rethinkdb,lenstr/rethinkdb,yaolinz/rethinkdb,victorbriz/rethinkdb,sontek/rethinkdb,losywee/rethinkdb,lenstr/rethinkdb,eliangidoni/rethinkdb,eliangidoni/rethinkdb,Qinusty/rethinkdb,bpradipt/rethinkdb,wujf/rethinkdb,bchavez/rethinkdb,bpradipt/rethinkdb,victorbriz/rethinkdb,pap/rethinkdb,JackieXie168/rethinkdb,gdi2290/rethinkdb,catroot/rethinkdb,grandquista/rethinkdb,Qinusty/rethinkdb,KSanthanam/rethinkdb,niieani/rethinkdb,pap/rethinkdb,lenstr/rethinkdb,robertjpayne/rethinkdb,scripni/rethinkdb,marshall007/rethinkdb,alash3al/rethinkdb,mcanthony/rethinkdb,wojons/rethinkdb,grandquista/rethinkdb,bpradipt/rethinkdb,ayumilong/rethinkdb,robertjpayne/rethinkdb,captainpete/rethinkdb,rrampage/rethinkdb,pap/rethinkdb,urandu/rethinkdb,Wilbeibi/rethinkdb,RubenKelevra/rethinkdb,JackieXie168/rethinkdb,marshall007/rethinkdb,jmptrader/rethinkdb,ayumilong/rethinkdb,captainpete/rethinkdb,JackieXie168/rethinkdb,tempbottle/rethinkdb,marshall007/rethinkdb,Qinusty/rethinkdb,elkingtonmcb/rethinkdb,rrampage/rethinkdb,elkingtonmcb/rethinkdb,mquandalle/rethinkdb,captainpete/rethinkdb,jesseditson/rethinkdb,rrampage/rethinkdb,4talesa/rethinkdb,lenstr/rethinkdb,gavioto/rethinkdb,sbusso/rethinkdb,catroot/rethinkdb,alash3al/rethinkdb,pap/rethinkdb,niieani/rethinkdb,wujf/rethinkdb,elkingtonmcb/rethinkdb,Wilbeibi/rethinkdb,victorbriz/rethinkdb,niieani/rethinkdb,mquandalle/rethinkdb,Wilbeibi/rethinkdb,pap/rethinkdb,yakovenkodenis/rethinkdb,AntouanK/rethinkdb,spblightadv/rethinkdb,jmptrader/rethinkdb,wujf/rethinkdb,catroot/rethinkdb,wojons/rethinkdb,sbusso/rethinkdb,alash3al/rethinkdb,KSanthanam/rethinkdb,gavioto/rethinkdb,yaolinz/rethinkdb,alash3al/rethinkdb,yaolinz/rethinkdb,AntouanK/rethinkdb,jmptrader/rethinkdb,grandquista/rethinkdb,dparnell/rethinkdb,elkingtonmcb/rethinkdb,greyhwndz/rethinkdb,alash3al/rethinkdb,sebadiaz/rethinkdb,bpradipt/rethinkdb,dparnell/rethinkdb,wujf/rethinkdb,JackieXie168/rethinkdb,robertjpayne/rethinkdb,scripni/rethinkdb,bchavez/rethinkdb,bpradipt/rethinkdb,Qinusty/rethinkdb,Qinusty/rethinkdb,AntouanK/rethinkdb,grandquista/rethinkdb
d93176fde22272c83c80dd5593d2b19965a2c6f9
clangd/Threading.cpp
clangd/Threading.cpp
#include "Threading.h" #include "Trace.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/Threading.h" #include <atomic> #include <thread> #ifdef __USE_POSIX #include <pthread.h> #endif namespace clang { namespace clangd { void Notification::notify() { { std::lock_guard<std::mutex> Lock(Mu); Notified = true; } CV.notify_all(); } void Notification::wait() const { std::unique_lock<std::mutex> Lock(Mu); CV.wait(Lock, [this] { return Notified; }); } Semaphore::Semaphore(std::size_t MaxLocks) : FreeSlots(MaxLocks) {} bool Semaphore::try_lock() { std::unique_lock<std::mutex> Lock(Mutex); if (FreeSlots > 0) { --FreeSlots; return true; } return false; } void Semaphore::lock() { trace::Span Span("WaitForFreeSemaphoreSlot"); // trace::Span can also acquire locks in ctor and dtor, we make sure it // happens when Semaphore's own lock is not held. { std::unique_lock<std::mutex> Lock(Mutex); SlotsChanged.wait(Lock, [&]() { return FreeSlots > 0; }); --FreeSlots; } } void Semaphore::unlock() { std::unique_lock<std::mutex> Lock(Mutex); ++FreeSlots; Lock.unlock(); SlotsChanged.notify_one(); } AsyncTaskRunner::~AsyncTaskRunner() { wait(); } bool AsyncTaskRunner::wait(Deadline D) const { std::unique_lock<std::mutex> Lock(Mutex); return clangd::wait(Lock, TasksReachedZero, D, [&] { return InFlightTasks == 0; }); } void AsyncTaskRunner::runAsync(const llvm::Twine &Name, llvm::unique_function<void()> Action) { { std::lock_guard<std::mutex> Lock(Mutex); ++InFlightTasks; } auto CleanupTask = llvm::make_scope_exit([this]() { std::lock_guard<std::mutex> Lock(Mutex); int NewTasksCnt = --InFlightTasks; if (NewTasksCnt == 0) { // Note: we can't unlock here because we don't want the object to be // destroyed before we notify. TasksReachedZero.notify_one(); } }); std::thread( [](std::string Name, decltype(Action) Action, decltype(CleanupTask)) { llvm::set_thread_name(Name); Action(); // Make sure function stored by Action is destroyed before CleanupTask // is run. Action = nullptr; }, Name.str(), std::move(Action), std::move(CleanupTask)) .detach(); } Deadline timeoutSeconds(llvm::Optional<double> Seconds) { using namespace std::chrono; if (!Seconds) return Deadline::infinity(); return steady_clock::now() + duration_cast<steady_clock::duration>(duration<double>(*Seconds)); } void wait(std::unique_lock<std::mutex> &Lock, std::condition_variable &CV, Deadline D) { if (D == Deadline::zero()) return; if (D == Deadline::infinity()) return CV.wait(Lock); CV.wait_until(Lock, D.time()); } static std::atomic<bool> AvoidThreadStarvation = {false}; void setCurrentThreadPriority(ThreadPriority Priority) { // Some *really* old glibcs are missing SCHED_IDLE. #if defined(__linux__) && defined(SCHED_IDLE) sched_param priority; priority.sched_priority = 0; pthread_setschedparam( pthread_self(), Priority == ThreadPriority::Low && !AvoidThreadStarvation ? SCHED_IDLE : SCHED_OTHER, &priority); #endif } void preventThreadStarvationInTests() { AvoidThreadStarvation = true; } } // namespace clangd } // namespace clang
#include "Threading.h" #include "Trace.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/Threading.h" #include <atomic> #include <thread> #ifdef __USE_POSIX #include <pthread.h> #elif defined(__APPLE__) #include <sys/resource.h> #endif namespace clang { namespace clangd { void Notification::notify() { { std::lock_guard<std::mutex> Lock(Mu); Notified = true; } CV.notify_all(); } void Notification::wait() const { std::unique_lock<std::mutex> Lock(Mu); CV.wait(Lock, [this] { return Notified; }); } Semaphore::Semaphore(std::size_t MaxLocks) : FreeSlots(MaxLocks) {} bool Semaphore::try_lock() { std::unique_lock<std::mutex> Lock(Mutex); if (FreeSlots > 0) { --FreeSlots; return true; } return false; } void Semaphore::lock() { trace::Span Span("WaitForFreeSemaphoreSlot"); // trace::Span can also acquire locks in ctor and dtor, we make sure it // happens when Semaphore's own lock is not held. { std::unique_lock<std::mutex> Lock(Mutex); SlotsChanged.wait(Lock, [&]() { return FreeSlots > 0; }); --FreeSlots; } } void Semaphore::unlock() { std::unique_lock<std::mutex> Lock(Mutex); ++FreeSlots; Lock.unlock(); SlotsChanged.notify_one(); } AsyncTaskRunner::~AsyncTaskRunner() { wait(); } bool AsyncTaskRunner::wait(Deadline D) const { std::unique_lock<std::mutex> Lock(Mutex); return clangd::wait(Lock, TasksReachedZero, D, [&] { return InFlightTasks == 0; }); } void AsyncTaskRunner::runAsync(const llvm::Twine &Name, llvm::unique_function<void()> Action) { { std::lock_guard<std::mutex> Lock(Mutex); ++InFlightTasks; } auto CleanupTask = llvm::make_scope_exit([this]() { std::lock_guard<std::mutex> Lock(Mutex); int NewTasksCnt = --InFlightTasks; if (NewTasksCnt == 0) { // Note: we can't unlock here because we don't want the object to be // destroyed before we notify. TasksReachedZero.notify_one(); } }); std::thread( [](std::string Name, decltype(Action) Action, decltype(CleanupTask)) { llvm::set_thread_name(Name); Action(); // Make sure function stored by Action is destroyed before CleanupTask // is run. Action = nullptr; }, Name.str(), std::move(Action), std::move(CleanupTask)) .detach(); } Deadline timeoutSeconds(llvm::Optional<double> Seconds) { using namespace std::chrono; if (!Seconds) return Deadline::infinity(); return steady_clock::now() + duration_cast<steady_clock::duration>(duration<double>(*Seconds)); } void wait(std::unique_lock<std::mutex> &Lock, std::condition_variable &CV, Deadline D) { if (D == Deadline::zero()) return; if (D == Deadline::infinity()) return CV.wait(Lock); CV.wait_until(Lock, D.time()); } static std::atomic<bool> AvoidThreadStarvation = {false}; void setCurrentThreadPriority(ThreadPriority Priority) { // Some *really* old glibcs are missing SCHED_IDLE. #if defined(__linux__) && defined(SCHED_IDLE) sched_param priority; priority.sched_priority = 0; pthread_setschedparam( pthread_self(), Priority == ThreadPriority::Low && !AvoidThreadStarvation ? SCHED_IDLE : SCHED_OTHER, &priority); #elif defined(__APPLE__) // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html setpriority(PRIO_DARWIN_THREAD, 0, Priority == ThreadPriority::Low && !AvoidThreadStarvation ? PRIO_DARWIN_BG : 0); #endif } void preventThreadStarvationInTests() { AvoidThreadStarvation = true; } } // namespace clangd } // namespace clang
Add thread priority lowering for MacOS as well
[clangd] Add thread priority lowering for MacOS as well Reviewers: ilya-biryukov Subscribers: ioeric, MaskRay, jkorous, arphaman, cfe-commits Tags: #clang Differential Revision: https://reviews.llvm.org/D58492 git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@354765 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
e3d686ff15b04e74be3e919f748caab814730ed7
src/main/cpp/include/io/filesystem.hpp
src/main/cpp/include/io/filesystem.hpp
#pragma once /* MIT License Copyright (c) 2017 Blockchain-VCS 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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file #include <string> namespace BlockchainCpp::IO::Filesystem { #ifdef _WIN32 HANDLE createFile(LPCSTR fileName, DWORD desiredAccess, DWORD shareMode, LPSECURITY_ATTRIBUTES attributes, DWORD creationDisposition, DWORD flags, HANDLE templateFile); BOOL createDirectory(LPCSTR directoryName, LPSECURITY_ATTRIBUTES attributes); BOOL closeFile(HANDLE file); BOOL openFile(LPCSTR fileName, LPOFSTRUCT reOpenBuf, UINT style); BOOL deleteFile(LPCSTR filePath); #elif __linux__ || __unix__ || __APPLE__ int mkdir(std::string path, mode_t mode); int open(std::string pathname, int flags); int open(std::string pathname, int flags, mode_t mode); int creat(std::string pathname, mode_t mode); void remove(std::string file); #endif }
#pragma once /* MIT License Copyright (c) 2017 Blockchain-VCS 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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file #include <string> namespace BlockchainCpp::IO::Filesystem { #ifdef _WIN32 HANDLE createFile(LPCSTR fileName, DWORD desiredAccess, DWORD shareMode, LPSECURITY_ATTRIBUTES attributes, DWORD creationDisposition, DWORD flags, HANDLE templateFile); BOOL createDirectory(LPCSTR directoryName, LPSECURITY_ATTRIBUTES attributes); BOOL closeFile(HANDLE file); BOOL openFile(LPCSTR fileName, LPOFSTRUCT reOpenBuf, UINT style); BOOL deleteFile(LPCSTR filePath); #elif __linux__ || __unix__ || __APPLE__ int createDirectory(std::string path, mode_t mode); int openFile(std::string pathname, int flags); int openFile(std::string pathname, int flags, mode_t mode); int createFile(std::string pathname, mode_t mode); void deleteFile(std::string file); #endif }
Unify Function Names
Unify Function Names
C++
mit
ZetaChain/ZetaChain_Native,ZetaChain/ZetaChain_Native
dc6361ad9e0c8be583b749be2ef712aca0a6547c
src/NullHMD.cpp
src/NullHMD.cpp
#include "IHMD.hpp" #include <bx/fpumath.h> #include <SDL.h> #include "Registry.hpp" namespace xveearr { namespace { const unsigned int gViewportWidth = 1280 / 2; const unsigned int gViewportHeight = 720; const float gLeftEye[] = { -50.0f, 0.0f, 0.f }; const float gRightEye[] = { 50.0f, 0.0f, 0.f }; float gLookAt[] = { 0.f, 0.0f, -10.f }; } class NullHMD: public IHMD { public: NullHMD() { mRenderData[Eye::Left].mFrameBuffer = BGFX_INVALID_HANDLE; mRenderData[Eye::Right].mFrameBuffer = BGFX_INVALID_HANDLE; } bool init(const ApplicationContext&) { bx::mtxSRT(mHeadTransform, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 600.f); return true; } void shutdown() { } void initRenderer() { } void shutdownRenderer() { } void beginRender() { } void endRender() { } void prepareResources() { mRenderData[Eye::Left].mFrameBuffer = bgfx::createFrameBuffer( gViewportWidth, gViewportHeight, bgfx::TextureFormat::RGBA8 ); mRenderData[Eye::Right].mFrameBuffer = bgfx::createFrameBuffer( gViewportWidth, gViewportHeight, bgfx::TextureFormat::RGBA8 ); } void releaseResources() { if(bgfx::isValid(mRenderData[Eye::Left].mFrameBuffer)) { bgfx::destroyFrameBuffer(mRenderData[Eye::Left].mFrameBuffer); } if(bgfx::isValid(mRenderData[Eye::Right].mFrameBuffer)) { bgfx::destroyFrameBuffer(mRenderData[Eye::Right].mFrameBuffer); } } void getViewportSize(unsigned int& width, unsigned int& height) { width = gViewportWidth; height = gViewportHeight; } const char* getName() const { return "null"; } void update() { const Uint8* keyStates = SDL_GetKeyboardState(NULL); float translation[3] = {}; float rotation[3] = {}; if(keyStates[SDL_SCANCODE_A]) { translation[0] = -4.f; } if(keyStates[SDL_SCANCODE_D]) { translation[0] = 4.f; } if(keyStates[SDL_SCANCODE_W]) { translation[2] = -4.f; } if(keyStates[SDL_SCANCODE_S]) { translation[2] = 4.f; } if(keyStates[SDL_SCANCODE_Q]) { rotation[1] = -0.01f; } if(keyStates[SDL_SCANCODE_E]) { rotation[1] = 0.01f; } if(keyStates[SDL_SCANCODE_R]) { rotation[0] = -0.01f; } if(keyStates[SDL_SCANCODE_F]) { rotation[0] = 0.01f; } float move[16]; bx::mtxSRT(move, 1.f, 1.f, 1.f, rotation[0], rotation[1], rotation[2], translation[0], translation[1], translation[2] ); float tmp[16]; memcpy(tmp, mHeadTransform, sizeof(tmp)); bx::mtxMul(mHeadTransform, move, tmp); float leftEye[3]; float leftLookAt[3]; float leftRelLookat[3]; bx::vec3MulMtx(leftEye, gLeftEye, mHeadTransform); bx::vec3Add(leftRelLookat, gLeftEye, gLookAt); bx::vec3MulMtx(leftLookAt, leftRelLookat, mHeadTransform); bx::mtxLookAtRh( mRenderData[Eye::Left].mViewTransform, leftEye, leftLookAt ); bx::mtxProjRh(mRenderData[Eye::Left].mViewProjection, 50.0f, (float)gViewportWidth / (float)gViewportHeight, 1.f, 100000.f ); float rightEye[3]; float rightLookAt[3]; float rightRelLookat[3]; bx::vec3MulMtx(rightEye, gRightEye, mHeadTransform); bx::vec3Add(rightRelLookat, gRightEye, gLookAt); bx::vec3MulMtx(rightLookAt, rightRelLookat, mHeadTransform); bx::mtxLookAtRh( mRenderData[Eye::Right].mViewTransform, rightEye, rightLookAt ); bx::mtxProjRh(mRenderData[Eye::Right].mViewProjection, 50.0f, (float)gViewportWidth / (float)gViewportHeight, 1.f, 100000.f ); } const RenderData& getRenderData(Eye::Enum eye) { return mRenderData[eye]; } private: float mHeadTransform[16]; RenderData mRenderData[Eye::Count]; }; NullHMD gNullHMDInstance; Registry<IHMD>::Entry gFakeHMDEntry(&gNullHMDInstance); }
#include "IHMD.hpp" #include <bx/fpumath.h> #include <SDL.h> #include "Registry.hpp" namespace xveearr { namespace { const unsigned int gViewportWidth = 1280 / 2; const unsigned int gViewportHeight = 720; const float gLeftEye[] = { -50.0f, 0.0f, 0.f }; const float gRightEye[] = { 50.0f, 0.0f, 0.f }; float gLookAt[] = { 0.f, 0.0f, -10.f }; } class NullHMD: public IHMD { public: NullHMD() { mRenderData[Eye::Left].mFrameBuffer = BGFX_INVALID_HANDLE; mRenderData[Eye::Right].mFrameBuffer = BGFX_INVALID_HANDLE; } bool init(const ApplicationContext&) { bx::mtxSRT(mHeadTransform, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 600.f); return true; } void shutdown() { } void initRenderer() { } void shutdownRenderer() { } void beginRender() { } void endRender() { } void prepareResources() { mRenderData[Eye::Left].mFrameBuffer = createEyeFB(); mRenderData[Eye::Right].mFrameBuffer = createEyeFB(); } void releaseResources() { if(bgfx::isValid(mRenderData[Eye::Left].mFrameBuffer)) { bgfx::destroyFrameBuffer(mRenderData[Eye::Left].mFrameBuffer); } if(bgfx::isValid(mRenderData[Eye::Right].mFrameBuffer)) { bgfx::destroyFrameBuffer(mRenderData[Eye::Right].mFrameBuffer); } } void getViewportSize(unsigned int& width, unsigned int& height) { width = gViewportWidth; height = gViewportHeight; } const char* getName() const { return "null"; } void update() { const Uint8* keyStates = SDL_GetKeyboardState(NULL); float translation[3] = {}; float rotation[3] = {}; if(keyStates[SDL_SCANCODE_A]) { translation[0] = -4.f; } if(keyStates[SDL_SCANCODE_D]) { translation[0] = 4.f; } if(keyStates[SDL_SCANCODE_W]) { translation[2] = -4.f; } if(keyStates[SDL_SCANCODE_S]) { translation[2] = 4.f; } if(keyStates[SDL_SCANCODE_Q]) { rotation[1] = -0.01f; } if(keyStates[SDL_SCANCODE_E]) { rotation[1] = 0.01f; } if(keyStates[SDL_SCANCODE_R]) { rotation[0] = -0.01f; } if(keyStates[SDL_SCANCODE_F]) { rotation[0] = 0.01f; } float move[16]; bx::mtxSRT(move, 1.f, 1.f, 1.f, rotation[0], rotation[1], rotation[2], translation[0], translation[1], translation[2] ); float tmp[16]; memcpy(tmp, mHeadTransform, sizeof(tmp)); bx::mtxMul(mHeadTransform, move, tmp); float leftEye[3]; float leftLookAt[3]; float leftRelLookat[3]; bx::vec3MulMtx(leftEye, gLeftEye, mHeadTransform); bx::vec3Add(leftRelLookat, gLeftEye, gLookAt); bx::vec3MulMtx(leftLookAt, leftRelLookat, mHeadTransform); bx::mtxLookAtRh( mRenderData[Eye::Left].mViewTransform, leftEye, leftLookAt ); bx::mtxProjRh(mRenderData[Eye::Left].mViewProjection, 50.0f, (float)gViewportWidth / (float)gViewportHeight, 1.f, 100000.f ); float rightEye[3]; float rightLookAt[3]; float rightRelLookat[3]; bx::vec3MulMtx(rightEye, gRightEye, mHeadTransform); bx::vec3Add(rightRelLookat, gRightEye, gLookAt); bx::vec3MulMtx(rightLookAt, rightRelLookat, mHeadTransform); bx::mtxLookAtRh( mRenderData[Eye::Right].mViewTransform, rightEye, rightLookAt ); bx::mtxProjRh(mRenderData[Eye::Right].mViewProjection, 50.0f, (float)gViewportWidth / (float)gViewportHeight, 1.f, 100000.f ); } const RenderData& getRenderData(Eye::Enum eye) { return mRenderData[eye]; } private: bgfx::FrameBufferHandle createEyeFB() { bgfx::TextureHandle textures[] = { bgfx::createTexture2D( gViewportWidth, gViewportHeight, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT|BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP ), bgfx::createTexture2D( gViewportWidth, gViewportHeight, 1, bgfx::TextureFormat::D16, BGFX_TEXTURE_RT_WRITE_ONLY ) }; return bgfx::createFrameBuffer(BX_COUNTOF(textures), textures, true); } float mHeadTransform[16]; RenderData mRenderData[Eye::Count]; }; NullHMD gNullHMDInstance; Registry<IHMD>::Entry gFakeHMDEntry(&gNullHMDInstance); }
Add a depth target for each eye framebuffer
Add a depth target for each eye framebuffer
C++
bsd-2-clause
bullno1/xveearr,bullno1/xveearr,bullno1/xveearr
53cbf2d0d26e28e2845d622bae309e34818f0f58
src/PIDFile.cpp
src/PIDFile.cpp
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <string> #include <sstream> #include <sys/stat.h> #include <sys/file.h> #include <sys/types.h> #include <fcntl.h> #include <libclientserver.h> PIDFile::PIDFile(std::string Filename) { m_IsOwner = false; m_filename = Filename; } PIDFile::~PIDFile() { if (IsOwner()) { Remove(); } } bool PIDFile::Create() { int fd = open(m_filename.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP); FILE *file = NULL; int tpid = -1; int ret = 0; if (IsOwner()) abort(); //Error with caller attempting to create pidfile twice if (fd < 0) { switch(errno) { case EEXIST: //Lets see if we can fix fd file = fopen(m_filename.c_str(), "r"); if (!file) return false; ret = fscanf(file, "%d", &tpid); fclose(file); if (ret != 1) //Issue here is that we have an unparsable pid file. Should we remove it? return false; do { std::string self; std::string pidexe; if (GetOwnExePath(&self) == false) return false; if (GetPIDExePath(tpid, &pidexe) == true) { printf("Compare %s - %s\n", self.c_str(), pidexe.c_str()); if (self == pidexe) return false; //The pid in the file matchs us and is a valid process } if (unlink(m_filename.c_str()) < 0) //Not "us" just overwrite it abort(); fd = open(m_filename.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP); if (fd < 0) return false; } while(0); break; default: return false; } } FILE *fp = fdopen(fd, "w"); if (!fp) abort(); //Should never happen fprintf(fp, "%d\n", getpid()); fclose(fp); m_IsOwner = true; return true; } void PIDFile::Remove() { if (IsOwner() == false) abort(); //Your not the owner if (unlink(m_filename.c_str()) < 0) abort(); //We should be the owner of this file m_IsOwner = false; } bool PIDFile::IsOwner() { return m_IsOwner; } bool PIDFile::GetOwnExePath(std::string *name) { char buf[256]; if (readlink("/proc/self/exe", buf, sizeof(buf)) < 0) return false; *name = buf; return true; } bool PIDFile::GetPIDExePath(int pid, std::string *name) { char buf1[256]; char buf2[256]; sprintf(buf1, "/proc/%d/exe", pid); int ret = readlink(buf1, buf2, sizeof(buf2)); if (ret < 0) return false; buf2[ret] = 0; *name = buf2; return true; }
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <string> #include <sstream> #include <sys/stat.h> #include <sys/file.h> #include <sys/types.h> #include <fcntl.h> #include <libclientserver.h> PIDFile::PIDFile(std::string Filename) { m_IsOwner = false; m_filename = Filename; } PIDFile::~PIDFile() { if (IsOwner()) { Remove(); } } bool PIDFile::Create() { int fd = open(m_filename.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP); FILE *file = NULL; int tpid = -1; int ret = 0; if (IsOwner()) abort(); //Error with caller attempting to create pidfile twice if (fd < 0) { switch(errno) { case EEXIST: //Lets see if we can fix fd file = fopen(m_filename.c_str(), "r"); if (!file) return false; ret = fscanf(file, "%d", &tpid); fclose(file); if (ret != 1) //Issue here is that we have an unparsable pid file. Should we remove it? return false; do { std::string self; std::string pidexe; if (GetOwnExePath(&self) == false) return false; if (GetPIDExePath(tpid, &pidexe) == true) { if (self == pidexe) return false; //The pid in the file matchs us and is a valid process } if (unlink(m_filename.c_str()) < 0) //Not "us" just overwrite it abort(); fd = open(m_filename.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP); if (fd < 0) return false; } while(0); break; default: return false; } } FILE *fp = fdopen(fd, "w"); if (!fp) abort(); //Should never happen fprintf(fp, "%d\n", getpid()); fclose(fp); m_IsOwner = true; return true; } void PIDFile::Remove() { if (IsOwner() == false) abort(); //Your not the owner if (unlink(m_filename.c_str()) < 0) abort(); //We should be the owner of this file m_IsOwner = false; } bool PIDFile::IsOwner() { return m_IsOwner; } bool PIDFile::GetOwnExePath(std::string *name) { char buf[256]; if (readlink("/proc/self/exe", buf, sizeof(buf)) < 0) return false; *name = buf; return true; } bool PIDFile::GetPIDExePath(int pid, std::string *name) { char buf1[256]; char buf2[256]; sprintf(buf1, "/proc/%d/exe", pid); int ret = readlink(buf1, buf2, sizeof(buf2)); if (ret < 0) return false; buf2[ret] = 0; *name = buf2; return true; }
Remove debug printf
Remove debug printf
C++
mit
mistralol/libclientserver,mistralol/libclientserver
82e6097d336ee3071be7ef9194e1548c1a49f87b
views/touchui/touch_selection_controller_impl_unittest.cc
views/touchui/touch_selection_controller_impl_unittest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/utf_string_conversions.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/render_text.h" #include "views/controls/textfield/native_textfield_views.h" #include "views/controls/textfield/textfield.h" #include "views/test/views_test_base.h" #include "views/touchui/touch_selection_controller.h" #include "views/touchui/touch_selection_controller_impl.h" #include "views/widget/widget.h" namespace views { class TouchSelectionControllerImplTest : public ViewsTestBase { public: TouchSelectionControllerImplTest() : widget_(NULL), textfield_(NULL), textfield_view_(NULL) { } virtual void SetUp() { Widget::SetPureViews(true); } virtual void TearDown() { Widget::SetPureViews(false); if (widget_) widget_->Close(); ViewsTestBase::TearDown(); } void CreateTextfield() { textfield_ = new Textfield(); widget_ = new Widget; Widget::InitParams params(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 200, 200); widget_->Init(params); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(textfield_); textfield_view_ = static_cast<NativeTextfieldViews*>( textfield_->GetNativeWrapperForTesting()); textfield_view_->SetBoundsRect(params.bounds); textfield_->set_id(1); DCHECK(textfield_view_); textfield_->RequestFocus(); } protected: gfx::Point GetCursorPosition(int cursor_pos) { gfx::RenderText* render_text = textfield_view_->GetRenderText(); gfx::Rect cursor_bounds = render_text->GetCursorBounds( gfx::SelectionModel(cursor_pos), false); return gfx::Point(cursor_bounds.x(), cursor_bounds.bottom()); } TouchSelectionControllerImpl* GetSelectionController() { return static_cast<TouchSelectionControllerImpl*>( textfield_view_->touch_selection_controller_.get()); } void SimulateSelectionHandleDrag(gfx::Point p, int selection_handle) { TouchSelectionControllerImpl* controller = GetSelectionController(); // Do the work of OnMousePressed(). if (selection_handle == 1) controller->dragging_handle_ = controller->selection_handle_1_.get(); else controller->dragging_handle_ = controller->selection_handle_2_.get(); controller->SelectionHandleDragged(p); // Do the work of OnMouseReleased(). controller->dragging_handle_ = NULL; } // If textfield has selection, this method verifies that the selection handles // are visible and at the correct positions (at the end points of selection). // |cursor_at_selection_handle_1| is used to decide whether selection // handle 1's position is matched against the start of selection or the end. void VerifySelectionHandlePositions(bool cursor_at_selection_handle_1) { if (textfield_->HasSelection()) { EXPECT_TRUE(GetSelectionController()->IsSelectionHandle1Visible()); EXPECT_TRUE(GetSelectionController()->IsSelectionHandle2Visible()); ui::Range selected_range; textfield_view_->GetSelectedRange(&selected_range); gfx::Point selection_start = GetCursorPosition(selected_range.start()); gfx::Point selection_end = GetCursorPosition(selected_range.end()); gfx::Point sh1 = GetSelectionController()->GetSelectionHandle1Position(); gfx::Point sh2 = GetSelectionController()->GetSelectionHandle2Position(); sh1.Offset(10, 0); // offset by kSelectionHandleRadius. sh2.Offset(10, 0); if (cursor_at_selection_handle_1) { EXPECT_EQ(sh1, selection_end); EXPECT_EQ(sh2, selection_start); } else { EXPECT_EQ(sh1, selection_start); EXPECT_EQ(sh2, selection_end); } } else { EXPECT_FALSE(GetSelectionController()->IsSelectionHandle1Visible()); EXPECT_FALSE(GetSelectionController()->IsSelectionHandle2Visible()); } } Widget* widget_; Textfield* textfield_; NativeTextfieldViews* textfield_view_; private: DISALLOW_COPY_AND_ASSIGN(TouchSelectionControllerImplTest); }; // Tests that the selection handles are placed appropriately when selection in // a Textfield changes. TEST_F(TouchSelectionControllerImplTest, SelectionInTextfieldTest) { CreateTextfield(); textfield_->SetText(ASCIIToUTF16("some text")); // Test selecting a range. textfield_->SelectRange(ui::Range(3, 7)); VerifySelectionHandlePositions(false); // Test selecting everything. textfield_->SelectAll(); VerifySelectionHandlePositions(false); // Test with no selection. textfield_->ClearSelection(); VerifySelectionHandlePositions(false); // Test with lost focus. widget_->GetFocusManager()->ClearFocus(); VerifySelectionHandlePositions(false); // Test with focus re-gained. widget_->GetFocusManager()->SetFocusedView(textfield_); VerifySelectionHandlePositions(false); } // Tests if the SelectRect callback is called appropriately when selection // handles are moved. TEST_F(TouchSelectionControllerImplTest, SelectRectCallbackTest) { CreateTextfield(); textfield_->SetText(ASCIIToUTF16("textfield with selected text")); textfield_->SelectRange(ui::Range(3, 7)); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "tfie"); VerifySelectionHandlePositions(false); // Drag selection handle 2 to right by 3 chars. int x = textfield_->font().GetStringWidth(ASCIIToUTF16("ld ")); SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "tfield "); VerifySelectionHandlePositions(false); // Drag selection handle 1 to the left by a large amount (selection should // just stick to the beginning of the textfield). SimulateSelectionHandleDrag(gfx::Point(-50, 0), 1); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "textfield "); VerifySelectionHandlePositions(true); // Drag selection handle 1 across selection handle 2. x = textfield_->font().GetStringWidth(ASCIIToUTF16("textfield with ")); SimulateSelectionHandleDrag(gfx::Point(x, 0), 1); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "with "); VerifySelectionHandlePositions(true); // Drag selection handle 2 across selection handle 1. x = textfield_->font().GetStringWidth(ASCIIToUTF16("with selected ")); SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "selected "); VerifySelectionHandlePositions(false); } } // namespace views
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/utf_string_conversions.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/render_text.h" #include "views/controls/textfield/native_textfield_views.h" #include "views/controls/textfield/textfield.h" #include "views/test/views_test_base.h" #include "views/touchui/touch_selection_controller.h" #include "views/touchui/touch_selection_controller_impl.h" #include "views/widget/widget.h" namespace views { class TouchSelectionControllerImplTest : public ViewsTestBase { public: TouchSelectionControllerImplTest() : widget_(NULL), textfield_(NULL), textfield_view_(NULL) { } virtual void SetUp() { Widget::SetPureViews(true); } virtual void TearDown() { Widget::SetPureViews(false); if (widget_) widget_->Close(); ViewsTestBase::TearDown(); } void CreateTextfield() { textfield_ = new Textfield(); widget_ = new Widget; Widget::InitParams params(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 200, 200); widget_->Init(params); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(textfield_); textfield_view_ = static_cast<NativeTextfieldViews*>( textfield_->GetNativeWrapperForTesting()); textfield_view_->SetBoundsRect(params.bounds); textfield_->set_id(1); DCHECK(textfield_view_); textfield_->RequestFocus(); } protected: gfx::Point GetCursorPosition(int cursor_pos) { gfx::RenderText* render_text = textfield_view_->GetRenderText(); gfx::Rect cursor_bounds = render_text->GetCursorBounds( gfx::SelectionModel(cursor_pos), false); return gfx::Point(cursor_bounds.x(), cursor_bounds.bottom() - 1); } TouchSelectionControllerImpl* GetSelectionController() { return static_cast<TouchSelectionControllerImpl*>( textfield_view_->touch_selection_controller_.get()); } void SimulateSelectionHandleDrag(gfx::Point p, int selection_handle) { TouchSelectionControllerImpl* controller = GetSelectionController(); // Do the work of OnMousePressed(). if (selection_handle == 1) controller->dragging_handle_ = controller->selection_handle_1_.get(); else controller->dragging_handle_ = controller->selection_handle_2_.get(); controller->SelectionHandleDragged(p); // Do the work of OnMouseReleased(). controller->dragging_handle_ = NULL; } // If textfield has selection, this method verifies that the selection handles // are visible and at the correct positions (at the end points of selection). // |cursor_at_selection_handle_1| is used to decide whether selection // handle 1's position is matched against the start of selection or the end. void VerifySelectionHandlePositions(bool cursor_at_selection_handle_1) { if (textfield_->HasSelection()) { EXPECT_TRUE(GetSelectionController()->IsSelectionHandle1Visible()); EXPECT_TRUE(GetSelectionController()->IsSelectionHandle2Visible()); ui::Range selected_range; textfield_view_->GetSelectedRange(&selected_range); gfx::Point selection_start = GetCursorPosition(selected_range.start()); gfx::Point selection_end = GetCursorPosition(selected_range.end()); gfx::Point sh1 = GetSelectionController()->GetSelectionHandle1Position(); gfx::Point sh2 = GetSelectionController()->GetSelectionHandle2Position(); sh1.Offset(10, 0); // offset by kSelectionHandleRadius. sh2.Offset(10, 0); if (cursor_at_selection_handle_1) { EXPECT_EQ(sh1, selection_end); EXPECT_EQ(sh2, selection_start); } else { EXPECT_EQ(sh1, selection_start); EXPECT_EQ(sh2, selection_end); } } else { EXPECT_FALSE(GetSelectionController()->IsSelectionHandle1Visible()); EXPECT_FALSE(GetSelectionController()->IsSelectionHandle2Visible()); } } Widget* widget_; Textfield* textfield_; NativeTextfieldViews* textfield_view_; private: DISALLOW_COPY_AND_ASSIGN(TouchSelectionControllerImplTest); }; // Tests that the selection handles are placed appropriately when selection in // a Textfield changes. TEST_F(TouchSelectionControllerImplTest, SelectionInTextfieldTest) { CreateTextfield(); textfield_->SetText(ASCIIToUTF16("some text")); // Test selecting a range. textfield_->SelectRange(ui::Range(3, 7)); VerifySelectionHandlePositions(false); // Test selecting everything. textfield_->SelectAll(); VerifySelectionHandlePositions(false); // Test with no selection. textfield_->ClearSelection(); VerifySelectionHandlePositions(false); // Test with lost focus. widget_->GetFocusManager()->ClearFocus(); VerifySelectionHandlePositions(false); // Test with focus re-gained. widget_->GetFocusManager()->SetFocusedView(textfield_); VerifySelectionHandlePositions(false); } // Tests if the SelectRect callback is called appropriately when selection // handles are moved. TEST_F(TouchSelectionControllerImplTest, SelectRectCallbackTest) { CreateTextfield(); textfield_->SetText(ASCIIToUTF16("textfield with selected text")); textfield_->SelectRange(ui::Range(3, 7)); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "tfie"); VerifySelectionHandlePositions(false); // Drag selection handle 2 to right by 3 chars. int x = textfield_->font().GetStringWidth(ASCIIToUTF16("ld ")); SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "tfield "); VerifySelectionHandlePositions(false); // Drag selection handle 1 to the left by a large amount (selection should // just stick to the beginning of the textfield). SimulateSelectionHandleDrag(gfx::Point(-50, 0), 1); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "textfield "); VerifySelectionHandlePositions(true); // Drag selection handle 1 across selection handle 2. x = textfield_->font().GetStringWidth(ASCIIToUTF16("textfield with ")); SimulateSelectionHandleDrag(gfx::Point(x, 0), 1); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "with "); VerifySelectionHandlePositions(true); // Drag selection handle 2 across selection handle 1. x = textfield_->font().GetStringWidth(ASCIIToUTF16("with selected ")); SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "selected "); VerifySelectionHandlePositions(false); } } // namespace views
Fix test that started failing due to http://codereview.chromium.org/7696013/
Fix test that started failing due to http://codereview.chromium.org/7696013/ BUG=none TEST=none Review URL: http://codereview.chromium.org/7728002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@98114 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,ropik/chromium
fa395f49fcad58c2d13d1cbaad15c2b7e7cfca5e
src-qt5/PCDM/src/themeStruct.cpp
src-qt5/PCDM/src/themeStruct.cpp
/* PCDM Login Manager: * Written by Ken Moore ([email protected]) 2012/2013 * Copyright(c) 2013 by the PC-BSD Project * Available under the 3-clause BSD license */ #include "themeStruct.h" #include <QDir> void ThemeStruct::loadThemeFile(QString filePath){ qDebug() << "Loading PCDM Theme File:" << filePath; //Create the required Items: itemNames.clear(); itemNames << "background" << "header" << "user" << "password" << "login" << "anonlogin" << "desktop" << "system" << "locale" << "keyboard" << "vkeyboard" << "toolbar" << "nextde" << "previousde"; items.clear(); for(int i=0; i<itemNames.length(); i++){ ThemeItem it; items << it; } //Get the directory the current theme file is in int li = filePath.lastIndexOf("/"); QString currDir = filePath; if(li > 0){ currDir.truncate(li); } else{ currDir.clear(); } if(!currDir.endsWith("/")){ currDir.append("/"); } //Now initialize variables for the file search QString iconFileDir; int numspacers = 0; QFile file(filePath); if( !file.open(QIODevice::ReadOnly | QIODevice::Text)){ return; } QTextStream in(&file); while( !in.atEnd() ){ QString line = in.readLine().simplified(); if( line.isEmpty() || line.startsWith("#") ){}//ignore empty and comment lines else if(line.startsWith("APP_STYLESHEET_START")){ //save all the following lines as the stylesheet QStringList styleLines; while( !line.startsWith("APP_STYLESHEET_END") && !in.atEnd() ){ line = in.readLine().simplified(); styleLines << line; } //Now compress into a single string and save it applicationStyleSheet = styleLines.join(" "); }else{ //Read off individual values for each item //Remove comments at the end of lines line = line.section("#",0,0).simplified(); //Get the important bits from the line QString prop = line.section("=",0,0).simplified(); //property QString val = line.section("=",1,1).simplified(); //value QString itemName = prop.section("_",0,0).toLower(); //item name QString itemCat = prop.section("_",1,3).simplified(); //item category for value int index = itemNames.indexOf( itemName ); //index for this item //qDebug() << "File Item:" << prop << val << itemName << itemCat << index; //Now save this item as appropriate if(prop == "IMAGE_DIR" && !val.isEmpty()){ //default directory for icons if(!val.endsWith("/")){val.append("/");} iconFileDir = val; if(iconFileDir.startsWith("./")){ iconFileDir.replace(0,2,currDir); } }else if( prop == "ADDSPACER" ){ //create a spacer item itemNames << "spacer"+QString::number(numspacers); numspacers++; ThemeItem it; items << it; index = items.length() -1; //last item in the list //read whether it is vertical items[index].isVertical = (val.section("::",0,0).toLower() == "vertical"); //Now get the location val = val.section("::",1,1).remove("[").remove("]").simplified(); //qDebug() << "ADDSPACER:" << line << val; items[index].x1 = val.section(",",0,0).section("-",0,0).toInt(); items[index].x2 = -1; items[index].y1 = val.section(",",1,1).section("-",0,0).toInt(); items[index].y2 = -1; }else if( (index != -1) && !val.isEmpty() ){ //Save the value to the structure based upon the type of value it is if(itemCat == "IMAGE"){ if(val.startsWith("/")){ items[index].icon = val; } else{ items[index].icon = iconFileDir + val; } }else if(itemCat == "IMAGE_SIZE"){ items[index].iconSize = QSize( val.section("x",0,0).toInt(), val.section("x",1,1).toInt() ); }else if(prop == "TOOLBAR_LOCATION"){ //special instructions for this item location items[index].value = val; //should be [bottom | top | left | right] }else if(prop == "TOOLBAR_STYLE"){ //special instructions for this item items[index].icon = val; //should be [icononly | textonly | textbesideicon | textundericon ] }else if(itemCat == "LOCATION"){ val = val.remove("[").remove("]").simplified(); //remove the brackets QString x = val.section(",",0,0); QString y = val.section(",",1,1); if(x.indexOf("-") == -1){ items[index].x1 = x.toInt(); items[index].x2 = -1;} else{ items[index].x1 = x.section("-",0,0).toInt(); items[index].x2 = x.section("-",1,1).toInt(); } if(y.indexOf("-") == -1){ items[index].y1 = y.toInt(); items[index].y2 = -1;} else{ items[index].y1 = y.section("-",0,0).toInt(); items[index].y2 = y.section("-",1,1).toInt(); } }else if(itemCat == "ORIENTATION"){ items[index].isVertical = (val.toLower() == "vertical"); if(val.toLower()=="simple"){ items[index].value = "simple"; } }else if(itemCat == "DISABLE"){ items[index].enabled = (val.toLower() != "true"); } } } // end if line is not a comment or empty } // end reading lines from file file.close(); } ThemeItem ThemeStruct::exportItem(QString item){ int index = itemNames.indexOf(item); ThemeItem TI; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid export item:"<<item; }else{ //Now format the output TI = items[index]; } return TI; } void ThemeStruct::importItem(QString item, ThemeItem TI){ int index = itemNames.indexOf(item); if( index == -1 ){ qDebug() << "ThemeStruct: Invalid import item:"<<item; }else{ items[index] = TI; } } bool ThemeStruct::validItem(QString item){ int index = itemNames.indexOf(item); bool ret = false; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; }else{ bool chk = items[index].enabled && items[index].value.isEmpty() && items[index].icon.isEmpty() && ( (items[index].x1==-1) || (items[index].y1==-1) ); ret = !chk; //true if the checks do not catch an empty item } return ret; } QStringList ThemeStruct::invalidItems(){ //Scan all the current Items and make a list of all the invalid ones // This makes it easy to auto-populate these invalid items with defaults QStringList inv; for(int i=0; i<itemNames.length(); i++){ if( !validItem(itemNames[i]) ){ inv << itemNames[i]; } } return inv; } bool ThemeStruct::itemIsEnabled(QString item){ int index = itemNames.indexOf(item); bool ret = false; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; }else{ ret = items[index].enabled; } return ret; } bool ThemeStruct::itemIsVertical(QString item){ int index = itemNames.indexOf(item); bool ret = false; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; }else{ ret = items[index].isVertical; } return ret; } QString ThemeStruct::itemValue(QString item){ int index = itemNames.indexOf(item); QString ret; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; ret = ""; }else{ ret = items[index].value; } return ret; } QString ThemeStruct::itemIcon(QString item){ int index = itemNames.indexOf(item); QString ret; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; ret = ""; }else{ ret = items[index].icon; } //qDebug() << "Theme:" << item << "Icon:" << ret; if(!ret.isEmpty() && !QFile::exists(ret)){ //Try to turn this into a valid icon path QDir dir("/usr/local/share/pixmaps"); QStringList found = dir.entryList(QStringList() << ret+".*", QDir::Files, QDir::NoSort); if(found.isEmpty()){ found = dir.entryList(QStringList() << ret+"*", QDir::Files, QDir::NoSort); } if(found.isEmpty()){ found = dir.entryList(QStringList() << "*"+ret+"*", QDir::Files, QDir::NoSort); } if(!found.isEmpty()){ ret = dir.filePath(found.first()); } } return ret; } QSize ThemeStruct::itemIconSize(QString item){ int index = itemNames.indexOf(item); QSize ret; if( index == -1 ){ //qDebug() << "ThemeStruct: Invalid item:"<<item; //ret = QSize(32,32); }else{ ret = items[index].iconSize; } //qDebug() << "Theme:" << item << "Size:" << ret; return ret; } int ThemeStruct::itemLocation(QString item, QString variable){ int index = itemNames.indexOf(item); int ret = 0; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; return ret; }else{ variable = variable.toLower(); if(variable == "row"){ ret = items[index].x1; } else if(variable == "col"){ ret = items[index].y1; } else if(variable == "rowspan"){ int span = items[index].x2 - items[index].x1; if(span < 0){ span = 0; } //Make sure it is always positive ret = span +1; //add 1 for the end point }else if(variable == "colspan"){ int span = items[index].y2 - items[index].y1; if(span < 0){ span = 0; } //Make sure it is always positive ret = span +1; //add 1 for the end point } } //qDebug() << "Theme:" << item << variable << ret; return ret; //catch for errors; } QString ThemeStruct::styleSheet(){ return applicationStyleSheet; } QStringList ThemeStruct::getSpacers(){ QStringList spc; QString isvert; for(int i=0; i<itemNames.length(); i++){ if( itemNames[i].startsWith("spacer") ){ if(items[i].isVertical){ isvert="true"; } else{ isvert="false"; } spc << isvert + "::" + QString::number(items[i].x1) +"::"+ QString::number(items[i].y1); } } //qDebug() << "Spacers:" << spc; return spc; }
/* PCDM Login Manager: * Written by Ken Moore ([email protected]) 2012/2013 * Copyright(c) 2013 by the PC-BSD Project * Available under the 3-clause BSD license */ #include "themeStruct.h" #include <QDir> void ThemeStruct::loadThemeFile(QString filePath){ qDebug() << "Loading PCDM Theme File:" << filePath; //Create the required Items: itemNames.clear(); itemNames << "background" << "header" << "user" << "password" << "login" << "anonlogin" << "desktop" << "system" << "locale" << "keyboard" << "vkeyboard" << "toolbar" << "nextde" << "previousde"; items.clear(); for(int i=0; i<itemNames.length(); i++){ ThemeItem it; items << it; } //Get the directory the current theme file is in int li = filePath.lastIndexOf("/"); QString currDir = filePath; if(li > 0){ currDir.truncate(li); } else{ currDir.clear(); } if(!currDir.endsWith("/")){ currDir.append("/"); } //Now initialize variables for the file search QString iconFileDir; int numspacers = 0; QFile file(filePath); if( !file.open(QIODevice::ReadOnly | QIODevice::Text)){ return; } QTextStream in(&file); while( !in.atEnd() ){ QString line = in.readLine().simplified(); if( line.isEmpty() || line.startsWith("#") ){}//ignore empty and comment lines else if(line.startsWith("APP_STYLESHEET_START")){ //save all the following lines as the stylesheet QStringList styleLines; while( !line.startsWith("APP_STYLESHEET_STOP") && !in.atEnd() ){ line = in.readLine().simplified(); styleLines << line; } //Now compress into a single string and save it applicationStyleSheet = styleLines.join(" "); }else{ //Read off individual values for each item //Remove comments at the end of lines line = line.section("#",0,0).simplified(); //Get the important bits from the line QString prop = line.section("=",0,0).simplified(); //property QString val = line.section("=",1,1).simplified(); //value QString itemName = prop.section("_",0,0).toLower(); //item name QString itemCat = prop.section("_",1,3).simplified(); //item category for value int index = itemNames.indexOf( itemName ); //index for this item //qDebug() << "File Item:" << prop << val << itemName << itemCat << index; //Now save this item as appropriate if(prop == "IMAGE_DIR" && !val.isEmpty()){ //default directory for icons if(!val.endsWith("/")){val.append("/");} iconFileDir = val; if(iconFileDir.startsWith("./")){ iconFileDir.replace(0,2,currDir); } }else if( prop == "ADDSPACER" ){ //create a spacer item itemNames << "spacer"+QString::number(numspacers); numspacers++; ThemeItem it; items << it; index = items.length() -1; //last item in the list //read whether it is vertical items[index].isVertical = (val.section("::",0,0).toLower() == "vertical"); //Now get the location val = val.section("::",1,1).remove("[").remove("]").simplified(); //qDebug() << "ADDSPACER:" << line << val; items[index].x1 = val.section(",",0,0).section("-",0,0).toInt(); items[index].x2 = -1; items[index].y1 = val.section(",",1,1).section("-",0,0).toInt(); items[index].y2 = -1; }else if( (index != -1) && !val.isEmpty() ){ //Save the value to the structure based upon the type of value it is if(itemCat == "IMAGE"){ if(val.startsWith("/")){ items[index].icon = val; } else{ items[index].icon = iconFileDir + val; } }else if(itemCat == "IMAGE_SIZE"){ items[index].iconSize = QSize( val.section("x",0,0).toInt(), val.section("x",1,1).toInt() ); }else if(prop == "TOOLBAR_LOCATION"){ //special instructions for this item location items[index].value = val; //should be [bottom | top | left | right] }else if(prop == "TOOLBAR_STYLE"){ //special instructions for this item items[index].icon = val; //should be [icononly | textonly | textbesideicon | textundericon ] }else if(itemCat == "LOCATION"){ val = val.remove("[").remove("]").simplified(); //remove the brackets QString x = val.section(",",0,0); QString y = val.section(",",1,1); if(x.indexOf("-") == -1){ items[index].x1 = x.toInt(); items[index].x2 = -1;} else{ items[index].x1 = x.section("-",0,0).toInt(); items[index].x2 = x.section("-",1,1).toInt(); } if(y.indexOf("-") == -1){ items[index].y1 = y.toInt(); items[index].y2 = -1;} else{ items[index].y1 = y.section("-",0,0).toInt(); items[index].y2 = y.section("-",1,1).toInt(); } }else if(itemCat == "ORIENTATION"){ items[index].isVertical = (val.toLower() == "vertical"); if(val.toLower()=="simple"){ items[index].value = "simple"; } }else if(itemCat == "DISABLE"){ items[index].enabled = (val.toLower() != "true"); } } } // end if line is not a comment or empty } // end reading lines from file file.close(); } ThemeItem ThemeStruct::exportItem(QString item){ int index = itemNames.indexOf(item); ThemeItem TI; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid export item:"<<item; }else{ //Now format the output TI = items[index]; } return TI; } void ThemeStruct::importItem(QString item, ThemeItem TI){ int index = itemNames.indexOf(item); if( index == -1 ){ qDebug() << "ThemeStruct: Invalid import item:"<<item; }else{ items[index] = TI; } } bool ThemeStruct::validItem(QString item){ int index = itemNames.indexOf(item); bool ret = false; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; }else{ bool chk = items[index].enabled && items[index].value.isEmpty() && items[index].icon.isEmpty() && ( (items[index].x1==-1) || (items[index].y1==-1) ); ret = !chk; //true if the checks do not catch an empty item } return ret; } QStringList ThemeStruct::invalidItems(){ //Scan all the current Items and make a list of all the invalid ones // This makes it easy to auto-populate these invalid items with defaults QStringList inv; for(int i=0; i<itemNames.length(); i++){ if( !validItem(itemNames[i]) ){ inv << itemNames[i]; } } return inv; } bool ThemeStruct::itemIsEnabled(QString item){ int index = itemNames.indexOf(item); bool ret = false; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; }else{ ret = items[index].enabled; } return ret; } bool ThemeStruct::itemIsVertical(QString item){ int index = itemNames.indexOf(item); bool ret = false; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; }else{ ret = items[index].isVertical; } return ret; } QString ThemeStruct::itemValue(QString item){ int index = itemNames.indexOf(item); QString ret; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; ret = ""; }else{ ret = items[index].value; } return ret; } QString ThemeStruct::itemIcon(QString item){ int index = itemNames.indexOf(item); QString ret; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; ret = ""; }else{ ret = items[index].icon; } //qDebug() << "Theme:" << item << "Icon:" << ret; if(!ret.isEmpty() && !QFile::exists(ret)){ //Try to turn this into a valid icon path QDir dir("/usr/local/share/pixmaps"); QStringList found = dir.entryList(QStringList() << ret+".*", QDir::Files, QDir::NoSort); if(found.isEmpty()){ found = dir.entryList(QStringList() << ret+"*", QDir::Files, QDir::NoSort); } if(found.isEmpty()){ found = dir.entryList(QStringList() << "*"+ret+"*", QDir::Files, QDir::NoSort); } if(!found.isEmpty()){ ret = dir.filePath(found.first()); } } return ret; } QSize ThemeStruct::itemIconSize(QString item){ int index = itemNames.indexOf(item); QSize ret; if( index == -1 ){ //qDebug() << "ThemeStruct: Invalid item:"<<item; //ret = QSize(32,32); }else{ ret = items[index].iconSize; } //qDebug() << "Theme:" << item << "Size:" << ret; return ret; } int ThemeStruct::itemLocation(QString item, QString variable){ int index = itemNames.indexOf(item); int ret = 0; if( index == -1 ){ qDebug() << "ThemeStruct: Invalid item:"<<item; return ret; }else{ variable = variable.toLower(); if(variable == "row"){ ret = items[index].x1; } else if(variable == "col"){ ret = items[index].y1; } else if(variable == "rowspan"){ int span = items[index].x2 - items[index].x1; if(span < 0){ span = 0; } //Make sure it is always positive ret = span +1; //add 1 for the end point }else if(variable == "colspan"){ int span = items[index].y2 - items[index].y1; if(span < 0){ span = 0; } //Make sure it is always positive ret = span +1; //add 1 for the end point } } //qDebug() << "Theme:" << item << variable << ret; return ret; //catch for errors; } QString ThemeStruct::styleSheet(){ return applicationStyleSheet; } QStringList ThemeStruct::getSpacers(){ QStringList spc; QString isvert; for(int i=0; i<itemNames.length(); i++){ if( itemNames[i].startsWith("spacer") ){ if(items[i].isVertical){ isvert="true"; } else{ isvert="false"; } spc << isvert + "::" + QString::number(items[i].x1) +"::"+ QString::number(items[i].y1); } } //qDebug() << "Spacers:" << spc; return spc; }
Change APP_STYLESHEET_END to APP_STYLESHEET_STOP to match the theme files.
Change APP_STYLESHEET_END to APP_STYLESHEET_STOP to match the theme files. The code has been looking for APP_STYLESHEET_END, whereas the themes have been using APP_STYLESHEET_STOP. It works the way that it's been, because the code also checks for the end of the file, and APP_STYLESHEET_STOP is at the end of the file, but they really should match. I'm not sure that it really matters whether it's END or STOP, but I went with STOP, because that meant changing one line of code instead of changing all of the themes.
C++
bsd-3-clause
trueos/pcdm,trueos/pcdm,trueos/pcdm
5ad0351a86b7f0a7bab958b3fde8c608b0d4c8ae
src/Utility.cpp
src/Utility.cpp
#include "Utility.h" #include <vector> #include <random> #include <chrono> #include <fstream> #include <algorithm> #include <string> #include <cctype> #include <iostream> namespace String { namespace { const auto whitespace = " \t\n"; } } std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count) { std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = (delim.empty() ? s.find_first_of(" \t\n", start_index) : s.find(delim, start_index)); result.push_back(s.substr(start_index, end_index-start_index)); if(end_index == std::string::npos) { start_index = std::string::npos; } else { start_index = end_index + (delim.empty() ? 1 : delim.size()); } ++split_count; } if(start_index < s.size()) { result.push_back(s.substr(start_index)); } if(delim.empty()) { auto it = result.begin(); while(it != result.end()) { if((*it).empty()) { it = result.erase(it); } else { (*it) = String::trim_outer_whitespace(*it); ++it; } } } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) { if(beginning.size() > s.size()) { return false; } return std::equal(beginning.begin(), beginning.end(), s.begin()); } bool String::starts_with(const std::string& s, char beginning) { return s[0] == beginning; } std::string String::consolidate_inner_whitespace(const std::string& s) { size_t start = s.find_first_not_of(whitespace); auto initial_whitespace = s.substr(0, start); size_t last_non_whitespace = s.find_last_not_of(whitespace); std::string final_whitespace; if(last_non_whitespace != std::string::npos) { final_whitespace = s.substr(last_non_whitespace + 1); } std::string result; while(true) { auto end = s.find_first_of(whitespace, start); // [start, end) is all non-whitespace if( ! result.empty()) { result += " "; } result += s.substr(start, end - start); start = s.find_first_not_of(whitespace, end); if(start == std::string::npos) { start = end; // only whitespace left break; } } return initial_whitespace + result + final_whitespace; } std::string String::trim_outer_whitespace(const std::string& s) { auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return std::string{}; } auto text_end = s.find_last_not_of(whitespace); if(text_end == std::string::npos) { return s.substr(text_start); } return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) { return trim_outer_whitespace(consolidate_inner_whitespace(s)); } std::string String::strip_comments(const std::string& str, char comment) { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, char start, char end) { auto start_comment_index = str.find(start); auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { return consolidate_inner_whitespace(trim_outer_whitespace(str)); } auto first_part = str.substr(0, start_comment_index); auto last_part = str.substr(end_comment_index + 1); return strip_block_comment(first_part + " " + last_part, start, end); } std::string String::lowercase(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](char c) -> char { return std::tolower(c); }); return s; } int Random::random_integer(int min, int max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using uid = std::uniform_int_distribution<int>; thread_local static auto dist = uid{}; return dist(generator, uid::param_type{min, max}); } double Random::random_normal(double standard_deviation) { thread_local static std::mt19937_64 generator(std::random_device{}()); using nd = std::normal_distribution<double>; thread_local static auto dist = nd{}; return dist(generator, nd::param_type{0.0, standard_deviation}); } double Random::random_real(double min, double max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using urd = std::uniform_real_distribution<double>; thread_local static auto dist = urd{}; return dist(generator, urd::param_type{min, max}); } bool Random::coin_flip() { return success_probability(0.5); } bool Random::success_probability(double probability) { return random_real(0.0, 1.0) < probability; } // Mean moves left in game given that a number of moves have been made already. double Math::average_moves_left(double mean_moves, double width, size_t moves_so_far) { // Assumes the number of moves in a game has a log-normal distribution. // // A = Sum(x = moves_so_far + 1 to infinity) P(x)*x = average number of moves // given game has already progressed // moves_so_far // // B = Sum(x = moves_so_far + 1 to infinity) P(x) = renormalization of P(x) for a // truncated range auto M = std::log(mean_moves); auto S = width; auto S2 = std::pow(S, 2); auto Sr2 = S*std::sqrt(2); auto ln_x = std::log(moves_so_far); auto A = 0.5*std::exp(M + S2/2)*(1 + std::erf((M + S2 - ln_x)/Sr2)); auto B = 0.5*(1 + std::erf((M-ln_x)/Sr2)); auto expected_mean = A/B; return expected_mean - moves_so_far; } Configuration_File::Configuration_File(const std::string& file_name) { std::ifstream ifs(file_name); std::string line; while(std::getline(ifs, line)) { line = String::strip_comments(line, '#'); if(line.empty()) { continue; } if( ! String::contains(line, '=')) { throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line); } auto line_split = String::split(line, "=", 1); auto parameter = String::lowercase(String::remove_extra_whitespace(line_split[0])); parameters[parameter] = String::trim_outer_whitespace(line_split[1]); } } std::string Configuration_File::get_text(const std::string& parameter) const { try { return parameters.at(parameter); } catch(const std::out_of_range&) { for(const auto& key_value : parameters) { std::cerr << "\"" << key_value.first << "\" --> \"" << key_value.second << "\"" << std::endl; } throw std::runtime_error("Configuration parameter not found: " + parameter); } } double Configuration_File::get_number(const std::string& parameter) const { try { return std::stod(get_text(parameter)); } catch(const std::invalid_argument&) { throw std::runtime_error("Invalid number for \"" + parameter + "\" : " + get_text(parameter)); } } std::ofstream Scoped_Stopwatch::out_file; std::mutex Scoped_Stopwatch::write_lock; Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) : place_name(name), start_time(std::chrono::steady_clock::now()), stopped(false) { } Scoped_Stopwatch::~Scoped_Stopwatch() { stop(); } void Scoped_Stopwatch::stop() { auto end_time = std::chrono::steady_clock::now(); if(stopped) { return; } std::lock_guard<std::mutex> write_lock_guard(write_lock); if( ! out_file.is_open()) { out_file.open("timings.txt"); } out_file << place_name << "|" << std::chrono::duration_cast<std::chrono::duration<double>> (end_time - start_time).count() << '\n'; stopped = true; } void Scoped_Stopwatch::add_info(const std::string& info) { place_name += info; }
#include "Utility.h" #include <vector> #include <random> #include <chrono> #include <fstream> #include <algorithm> #include <string> #include <cctype> #include <iostream> namespace String { namespace { const auto whitespace = " \t\n"; } } std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count) { std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = (delim.empty() ? s.find_first_of(" \t\n", start_index) : s.find(delim, start_index)); result.push_back(s.substr(start_index, end_index-start_index)); if(end_index == std::string::npos) { start_index = std::string::npos; } else { start_index = end_index + (delim.empty() ? 1 : delim.size()); } ++split_count; } if(start_index < s.size()) { result.push_back(s.substr(start_index)); } if(delim.empty()) { auto it = result.begin(); while(it != result.end()) { if((*it).empty()) { it = result.erase(it); } else { (*it) = String::trim_outer_whitespace(*it); ++it; } } } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) { if(beginning.size() > s.size()) { return false; } return std::equal(beginning.begin(), beginning.end(), s.begin()); } bool String::starts_with(const std::string& s, char beginning) { return s[0] == beginning; } std::string String::consolidate_inner_whitespace(const std::string& s) { size_t start = s.find_first_not_of(whitespace); auto initial_whitespace = s.substr(0, start); size_t last_non_whitespace = s.find_last_not_of(whitespace); std::string final_whitespace; if(last_non_whitespace != std::string::npos) { final_whitespace = s.substr(last_non_whitespace + 1); } std::string result; while(true) { auto end = s.find_first_of(whitespace, start); // [start, end) is all non-whitespace if( ! result.empty()) { result += " "; } result += s.substr(start, end - start); start = s.find_first_not_of(whitespace, end); if(start == std::string::npos) { start = end; // only whitespace left break; } } return initial_whitespace + result + final_whitespace; } std::string String::trim_outer_whitespace(const std::string& s) { auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return std::string{}; } auto text_end = s.find_last_not_of(whitespace); if(text_end == std::string::npos) { return s.substr(text_start); } return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) { return trim_outer_whitespace(consolidate_inner_whitespace(s)); } std::string String::strip_comments(const std::string& str, char comment) { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, char start, char end) { auto start_comment_index = str.find(start); auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { return consolidate_inner_whitespace(trim_outer_whitespace(str)); } auto first_part = str.substr(0, start_comment_index); auto last_part = str.substr(end_comment_index + 1); return strip_block_comment(first_part + " " + last_part, start, end); } std::string String::lowercase(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](char c) -> char { return std::tolower(c); }); return s; } int Random::random_integer(int min, int max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using uid = std::uniform_int_distribution<int>; thread_local static auto dist = uid{}; return dist(generator, uid::param_type{min, max}); } double Random::random_normal(double standard_deviation) { thread_local static std::mt19937_64 generator(std::random_device{}()); using nd = std::normal_distribution<double>; thread_local static auto dist = nd{}; return dist(generator, nd::param_type{0.0, standard_deviation}); } double Random::random_real(double min, double max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using urd = std::uniform_real_distribution<double>; thread_local static auto dist = urd{}; return dist(generator, urd::param_type{min, max}); } bool Random::coin_flip() { return success_probability(0.5); } bool Random::success_probability(double probability) { return random_real(0.0, 1.0) < probability; } // Mean moves left in game given that a number of moves have been made already. double Math::average_moves_left(double mean_moves, double width, size_t moves_so_far) { // Assumes the number of moves in a game has a log-normal distribution. // // A = Sum(x = moves_so_far + 1 to infinity) P(x)*x = average number of moves // given game has already progressed // moves_so_far // // B = Sum(x = moves_so_far + 1 to infinity) P(x) = renormalization of P(x) for a // truncated range auto M = std::log(mean_moves); auto S = width; auto S2 = std::pow(S, 2); auto Sr2 = S*std::sqrt(2); auto ln_x = std::log(moves_so_far); auto A = std::exp(M + S2/2)*(1 + std::erf((M + S2 - ln_x)/Sr2)); auto B = 1 + std::erf((M-ln_x)/Sr2); auto expected_mean = A/B; return expected_mean - moves_so_far; } Configuration_File::Configuration_File(const std::string& file_name) { std::ifstream ifs(file_name); std::string line; while(std::getline(ifs, line)) { line = String::strip_comments(line, '#'); if(line.empty()) { continue; } if( ! String::contains(line, '=')) { throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line); } auto line_split = String::split(line, "=", 1); auto parameter = String::lowercase(String::remove_extra_whitespace(line_split[0])); parameters[parameter] = String::trim_outer_whitespace(line_split[1]); } } std::string Configuration_File::get_text(const std::string& parameter) const { try { return parameters.at(parameter); } catch(const std::out_of_range&) { for(const auto& key_value : parameters) { std::cerr << "\"" << key_value.first << "\" --> \"" << key_value.second << "\"" << std::endl; } throw std::runtime_error("Configuration parameter not found: " + parameter); } } double Configuration_File::get_number(const std::string& parameter) const { try { return std::stod(get_text(parameter)); } catch(const std::invalid_argument&) { throw std::runtime_error("Invalid number for \"" + parameter + "\" : " + get_text(parameter)); } } std::ofstream Scoped_Stopwatch::out_file; std::mutex Scoped_Stopwatch::write_lock; Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) : place_name(name), start_time(std::chrono::steady_clock::now()), stopped(false) { } Scoped_Stopwatch::~Scoped_Stopwatch() { stop(); } void Scoped_Stopwatch::stop() { auto end_time = std::chrono::steady_clock::now(); if(stopped) { return; } std::lock_guard<std::mutex> write_lock_guard(write_lock); if( ! out_file.is_open()) { out_file.open("timings.txt"); } out_file << place_name << "|" << std::chrono::duration_cast<std::chrono::duration<double>> (end_time - start_time).count() << '\n'; stopped = true; } void Scoped_Stopwatch::add_info(const std::string& info) { place_name += info; }
Delete unneeded factors in average_moves_left()
Delete unneeded factors in average_moves_left()
C++
mit
MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess
8f28548f05e5fdc0626b910e2d56a1a6c0b826dc
dune/gdt/operators/projections/lagrange.hh
dune/gdt/operators/projections/lagrange.hh
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_PROJECTIONS_LAGRANGE_HH #define DUNE_GDT_OPERATORS_PROJECTIONS_LAGRANGE_HH #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/la/container/vector-interface.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localoperator/lagrange-projection.hh> #include <dune/gdt/spaces/interface.hh> #include "../default.hh" #include "../interfaces.hh" namespace Dune { namespace GDT { /** * \todo Add a check if the range space provides Lagrange points (after implementing the appropriate interface/mixin * for those spaces). * \note Do we have to set all range DoFs to infinity here? */ template <class GridViewImp, class SourceImp, class RangeImp> class LagrangeProjectionLocalizableOperator : public LocalizableOperatorDefault<GridViewImp, SourceImp, RangeImp> { typedef LocalizableOperatorDefault<GridViewImp, SourceImp, RangeImp> BaseType; public: template <class... Args> explicit LagrangeProjectionLocalizableOperator(Args&&... args) : BaseType(std::forward<Args>(args)...) , local_operator_() { this->add(local_operator_); } private: const LocalLagrangeProjectionOperator local_operator_; }; // class LagrangeProjectionLocalizableOperator template <class GridViewType, class SourceType, class SpaceType, class VectorType> typename std:: enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, std::unique_ptr<LagrangeProjectionLocalizableOperator<GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>>::type make_lagrange_projection_localizable_operator(const GridViewType& grid_view, const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { return DSC::make_unique<LagrangeProjectionLocalizableOperator<GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>( grid_view, source, range); } template <class SourceType, class SpaceType, class VectorType> typename std:: enable_if<Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, std::unique_ptr<LagrangeProjectionLocalizableOperator<typename SpaceType::GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>>::type make_lagrange_projection_localizable_operator(const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { return DSC::make_unique<LagrangeProjectionLocalizableOperator<typename SpaceType::GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>( range.space().grid_view(), source, range); } // forward template <class GridViewImp, class FieldImp = double> class LagrangeProjectionOperator; namespace internal { template <class GridViewImp, class FieldImp> class LagrangeProjectionOperatorTraits { public: typedef LagrangeProjectionOperator<GridViewImp, FieldImp> derived_type; typedef FieldImp FieldType; }; } // namespace internal template <class GridViewImp, class FieldImp> class LagrangeProjectionOperator : public OperatorInterface<internal::LagrangeProjectionOperatorTraits<GridViewImp, FieldImp>> { typedef OperatorInterface<internal::LagrangeProjectionOperatorTraits<GridViewImp, FieldImp>> BaseType; public: typedef internal::LagrangeProjectionOperatorTraits<GridViewImp, FieldImp> Traits; typedef GridViewImp GridViewType; using typename BaseType::FieldType; private: typedef typename Stuff::Grid::Entity<GridViewType>::Type E; typedef typename GridViewType::ctype D; static const size_t d = GridViewType::dimension; public: LagrangeProjectionOperator(GridViewType grid_view) : grid_view_(grid_view) { } template <class R, size_t r, size_t rC, class S, class V> void apply(const Stuff::LocalizableFunctionInterface<E, D, d, R, r, rC>& source, DiscreteFunction<S, V>& range) const { make_lagrange_projection_localizable_operator(grid_view_, source, range)->apply(); } template <class RangeType, class SourceType> FieldType apply2(const RangeType& /*range*/, const SourceType& /*source*/) const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } template <class RangeType, class SourceType> void apply_inverse(const RangeType& /*range*/, SourceType& /*source*/, const Stuff::Common::Configuration& /*opts*/) const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } std::vector<std::string> invert_options() const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } Stuff::Common::Configuration invert_options(const std::string& /*type*/) const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } private: GridViewType grid_view_; }; // class LagrangeProjectionOperator template <class GridViewType> typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value, std::unique_ptr<LagrangeProjectionOperator<GridViewType>>>::type make_lagrange_projection_operator(const GridViewType& grid_view) { return DSC::make_unique<LagrangeProjectionOperator<GridViewType>>(grid_view); } template <class GridViewType, class SourceType, class SpaceType, class VectorType> typename std:: enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, std::unique_ptr<LagrangeProjectionLocalizableOperator<GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>>::type project_lagrange(const GridViewType& grid_view, const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { make_lagrange_projection_operator(grid_view)->apply(source, range); } template <class SourceType, class SpaceType, class VectorType> typename std:: enable_if<Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, std::unique_ptr<LagrangeProjectionLocalizableOperator<typename SpaceType::GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>>::type project_lagrange(const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { make_lagrange_projection_operator(range.space().grid_view())->apply(source, range); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_PROJECTIONS_LAGRANGE_HH
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_PROJECTIONS_LAGRANGE_HH #define DUNE_GDT_OPERATORS_PROJECTIONS_LAGRANGE_HH #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/la/container/vector-interface.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localoperator/lagrange-projection.hh> #include <dune/gdt/spaces/interface.hh> #include "../default.hh" #include "../interfaces.hh" namespace Dune { namespace GDT { /** * \todo Add a check if the range space provides Lagrange points (after implementing the appropriate interface/mixin * for those spaces). * \note Do we have to set all range DoFs to infinity here? */ template <class GridViewImp, class SourceImp, class RangeImp> class LagrangeProjectionLocalizableOperator : public LocalizableOperatorDefault<GridViewImp, SourceImp, RangeImp> { typedef LocalizableOperatorDefault<GridViewImp, SourceImp, RangeImp> BaseType; public: template <class... Args> explicit LagrangeProjectionLocalizableOperator(Args&&... args) : BaseType(std::forward<Args>(args)...) , local_operator_() { this->add(local_operator_); } private: const LocalLagrangeProjectionOperator local_operator_; }; // class LagrangeProjectionLocalizableOperator template <class GridViewType, class SourceType, class SpaceType, class VectorType> typename std:: enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, std::unique_ptr<LagrangeProjectionLocalizableOperator<GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>>::type make_lagrange_projection_localizable_operator(const GridViewType& grid_view, const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { return DSC::make_unique<LagrangeProjectionLocalizableOperator<GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>( grid_view, source, range); } template <class SourceType, class SpaceType, class VectorType> typename std:: enable_if<Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, std::unique_ptr<LagrangeProjectionLocalizableOperator<typename SpaceType::GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>>::type make_lagrange_projection_localizable_operator(const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { return DSC::make_unique<LagrangeProjectionLocalizableOperator<typename SpaceType::GridViewType, SourceType, DiscreteFunction<SpaceType, VectorType>>>( range.space().grid_view(), source, range); } // forward template <class GridViewImp, class FieldImp = double> class LagrangeProjectionOperator; namespace internal { template <class GridViewImp, class FieldImp> class LagrangeProjectionOperatorTraits { public: typedef LagrangeProjectionOperator<GridViewImp, FieldImp> derived_type; typedef FieldImp FieldType; }; } // namespace internal template <class GridViewImp, class FieldImp> class LagrangeProjectionOperator : public OperatorInterface<internal::LagrangeProjectionOperatorTraits<GridViewImp, FieldImp>> { typedef OperatorInterface<internal::LagrangeProjectionOperatorTraits<GridViewImp, FieldImp>> BaseType; public: typedef internal::LagrangeProjectionOperatorTraits<GridViewImp, FieldImp> Traits; typedef GridViewImp GridViewType; using typename BaseType::FieldType; private: typedef typename Stuff::Grid::Entity<GridViewType>::Type E; typedef typename GridViewType::ctype D; static const size_t d = GridViewType::dimension; public: LagrangeProjectionOperator(GridViewType grid_view) : grid_view_(grid_view) { } template <class R, size_t r, size_t rC, class S, class V> void apply(const Stuff::LocalizableFunctionInterface<E, D, d, R, r, rC>& source, DiscreteFunction<S, V>& range) const { make_lagrange_projection_localizable_operator(grid_view_, source, range)->apply(); } template <class RangeType, class SourceType> FieldType apply2(const RangeType& /*range*/, const SourceType& /*source*/) const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } template <class RangeType, class SourceType> void apply_inverse(const RangeType& /*range*/, SourceType& /*source*/, const Stuff::Common::Configuration& /*opts*/) const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } std::vector<std::string> invert_options() const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } Stuff::Common::Configuration invert_options(const std::string& /*type*/) const { DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!"); } private: GridViewType grid_view_; }; // class LagrangeProjectionOperator template <class GridViewType> typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value, std::unique_ptr<LagrangeProjectionOperator<GridViewType>>>::type make_lagrange_projection_operator(const GridViewType& grid_view) { return DSC::make_unique<LagrangeProjectionOperator<GridViewType>>(grid_view); } template <class GridViewType, class SourceType, class SpaceType, class VectorType> typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, void>::type project_lagrange(const GridViewType& grid_view, const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { make_lagrange_projection_operator(grid_view)->apply(source, range); } template <class SourceType, class SpaceType, class VectorType> typename std::enable_if<Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value, void>::type project_lagrange(const SourceType& source, DiscreteFunction<SpaceType, VectorType>& range) { make_lagrange_projection_operator(range.space().grid_view())->apply(source, range); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_PROJECTIONS_LAGRANGE_HH
fix `project_lagrange`
[operators.projections.lagrange] fix `project_lagrange`
C++
bsd-2-clause
pymor/dune-gdt
21fa354c2272d2b15e7f2ab8f9c3fc8b19f12e17
src/backend.cpp
src/backend.cpp
/* Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]> Copyright (C) 2008 Lukas Durfina <[email protected]> Copyright (C) 2009 Fathi Boudra <[email protected]> Copyright (C) 2009-2011 vlc-phonon AUTHORS <[email protected]> Copyright (C) 2011-2013 Harald Sitter <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include <QtCore/QCoreApplication> #include <QtCore/QLatin1Literal> #include <QtCore/QtPlugin> #include <QtCore/QVariant> #include <QMessageBox> #include <phonon/GlobalDescriptionContainer> #include <phonon/pulsesupport.h> #include <vlc/libvlc_version.h> #include "audio/audiooutput.h" #include "audio/audiodataoutput.h" #include "audio/volumefadereffect.h" #include "devicemanager.h" #include "effect.h" #include "effectmanager.h" #include "equalizereffect.h" #include "mediaobject.h" #include "sinknode.h" #include "utils/debug.h" #include "utils/libvlc.h" #include "utils/mime.h" #ifdef PHONON_EXPERIMENTAL #include "video/videodataoutput.h" #endif #ifndef PHONON_NO_GRAPHICSVIEW #include "video/videographicsobject.h" #endif #include "video/videowidget.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend) #endif namespace Phonon { namespace VLC { Backend *Backend::self; Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) , m_deviceManager(0) , m_effectManager(0) { self = this; // Backend information properties setProperty("identifier", QLatin1String("phonon_vlc")); setProperty("backendName", QLatin1String("VLC")); setProperty("backendComment", QLatin1String("VLC backend for Phonon")); setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION)); setProperty("backendIcon", QLatin1String("vlc")); setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc")); // Check if we should enable debug output int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt(); if (debugLevel > 3) // 3 is maximum debugLevel = 3; Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel)); // Actual libVLC initialisation if (LibVLC::init()) { debug() << "Using VLC version" << libvlc_get_version(); if (!qApp->applicationName().isEmpty()) { QString userAgent = QString("%0/%1 (Phonon/%2; Phonon-VLC/%3)").arg( qApp->applicationName(), qApp->applicationVersion(), PHONON_VERSION_STR, PHONON_VLC_VERSION); libvlc_set_user_agent(libvlc, qApp->applicationName().toUtf8().constData(), userAgent.toUtf8().constData()); } else { qWarning("WARNING: Setting the user agent for streaming and" " PulseAudio requires you to set QCoreApplication::applicationName()"); } #ifdef __GNUC__ #warning application name ought to be configurable by the consumer ... new api #endif #if (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 1, 0, 0)) if (!qApp->applicationName().isEmpty() && !qApp->applicationVersion().isEmpty()) { const QString id = QString("org.kde.phonon.%1").arg(qApp->applicationName()); const QString version = qApp->applicationVersion(); const QString icon = qApp->applicationName(); libvlc_set_app_id(libvlc, id.toUtf8().constData(), version.toUtf8().constData(), icon.toUtf8().constData()); } else if (PulseSupport::getInstance()->isActive()) { qWarning("WARNING: Setting PulseAudio context information requires you" " to set QCoreApplication::applicationName() and" " QCoreApplication::applicationVersion()"); } #endif } else { #ifdef __GNUC__ #warning TODO - this error message is about as useful as a cooling unit in the arctic #endif QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setWindowTitle(tr("LibVLC Failed to Initialize")); msg.setText(tr("Phonon's VLC backend failed to start." "\n\n" "This usually means a problem with your VLC installation," " please report a bug with your distributor.")); msg.setDetailedText(LibVLC::errorMessage()); msg.exec(); fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC"; } // Initialise PulseAudio support PulseSupport *pulse = PulseSupport::getInstance(); pulse->enable(); connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType))); m_deviceManager = new DeviceManager(this); m_effectManager = new EffectManager(this); } Backend::~Backend() { if (LibVLC::self) delete LibVLC::self; if (GlobalAudioChannels::self) delete GlobalAudioChannels::self; if (GlobalSubtitles::self) delete GlobalSubtitles::self; PulseSupport::shutdown(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { if (!LibVLC::self || !libvlc) return 0; switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(parent); #ifdef __GNUC__ #warning using sout in VLC2 breaks libvlcs vout functions, see vlc bug 6992 // https://trac.videolan.org/vlc/ticket/6992 #endif #if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0)) // FWIW: the case is inside the if because that gives clear indication which // frontend objects are not supported! case AudioDataOutputClass: return new AudioDataOutput(parent); #endif #ifdef PHONON_EXPERIMENTAL case VideoDataOutputClass: return new VideoDataOutput(parent); #endif #ifndef PHONON_NO_GRAPHICSVIEW case VideoGraphicsObjectClass: return new VideoGraphicsObject(parent); #endif case EffectClass: return effectManager()->createEffect(args[0].toInt(), parent); case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); // case VolumeFaderEffectClass: #ifdef __GNUC__ #warning VFE crashes and has volume bugs ... deactivated // return new VolumeFaderEffect(parent); #endif } warning() << "Backend class" << c << "is not supported by Phonon VLC :("; return 0; } QStringList Backend::availableMimeTypes() const { if (m_supportedMimeTypes.isEmpty()) const_cast<Backend *>(this)->m_supportedMimeTypes = mimeTypeList(); return m_supportedMimeTypes; } QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const { QList<int> list; switch (type) { case Phonon::AudioChannelType: { list << GlobalAudioChannels::instance()->globalIndexes(); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { return deviceManager()->deviceIds(type); } break; case Phonon::EffectType: { QList<EffectInfo> effectList = effectManager()->effects(); for (int eff = 0; eff < effectList.size(); ++eff) { list.append(eff); } } break; case Phonon::SubtitleType: { list << GlobalSubtitles::instance()->globalIndexes(); } break; } return list; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioChannelType: { const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { // Index should be unique, even for different categories return deviceManager()->deviceProperties(index); } break; case Phonon::EffectType: { const QList<EffectInfo> effectList = effectManager()->effects(); if (index >= 0 && index <= effectList.size()) { const EffectInfo &effect = effectList.at(index); ret.insert("name", effect.name()); ret.insert("description", effect.description()); ret.insert("author", effect.author()); } else { Q_ASSERT(1); // Since we use list position as ID, this should not happen } } break; case Phonon::SubtitleType: { const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); ret.insert("type", description.property("type")); } break; } return ret; } bool Backend::startConnectionChange(QSet<QObject *> objects) { //FIXME foreach(QObject * object, objects) { debug() << "Object:" << object->metaObject()->className(); } // There is nothing we can do but hope the connection changes will not take too long // so that buffers would underrun // But we should be pretty safe the way xine works by not doing anything here. return true; } bool Backend::connectNodes(QObject *source, QObject *sink) { debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className(); SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Connect the SinkNode to a MediaObject sinkNode->connectToMediaObject(mediaObject); return true; } VolumeFaderEffect *effect = qobject_cast<VolumeFaderEffect *>(source); if (effect) { sinkNode->connectToMediaObject(effect->mediaObject()); return true; } } warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed"; return false; } bool Backend::disconnectNodes(QObject *source, QObject *sink) { SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *const mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Disconnect the SinkNode from a MediaObject sinkNode->disconnectFromMediaObject(mediaObject); return true; } VolumeFaderEffect *const effect = qobject_cast<VolumeFaderEffect *>(source); if (effect) { sinkNode->disconnectFromMediaObject(effect->mediaObject()); return true; } } return false; } bool Backend::endConnectionChange(QSet<QObject *> objects) { foreach(QObject *object, objects) { debug() << "Object:" << object->metaObject()->className(); } return true; } DeviceManager *Backend::deviceManager() const { return m_deviceManager; } EffectManager *Backend::effectManager() const { return m_effectManager; } } // namespace VLC } // namespace Phonon
/* Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]> Copyright (C) 2008 Lukas Durfina <[email protected]> Copyright (C) 2009 Fathi Boudra <[email protected]> Copyright (C) 2009-2011 vlc-phonon AUTHORS <[email protected]> Copyright (C) 2011-2013 Harald Sitter <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include <QtCore/QCoreApplication> #include <QtCore/QLatin1Literal> #include <QtCore/QtPlugin> #include <QtCore/QVariant> #include <QMessageBox> #include <phonon/GlobalDescriptionContainer> #include <phonon/pulsesupport.h> #include <vlc/libvlc_version.h> #include "audio/audiooutput.h" #include "audio/audiodataoutput.h" #include "audio/volumefadereffect.h" #include "devicemanager.h" #include "effect.h" #include "effectmanager.h" #include "mediaobject.h" #include "sinknode.h" #include "utils/debug.h" #include "utils/libvlc.h" #include "utils/mime.h" #ifdef PHONON_EXPERIMENTAL #include "video/videodataoutput.h" #endif #ifndef PHONON_NO_GRAPHICSVIEW #include "video/videographicsobject.h" #endif #include "video/videowidget.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend) #endif namespace Phonon { namespace VLC { Backend *Backend::self; Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) , m_deviceManager(0) , m_effectManager(0) { self = this; // Backend information properties setProperty("identifier", QLatin1String("phonon_vlc")); setProperty("backendName", QLatin1String("VLC")); setProperty("backendComment", QLatin1String("VLC backend for Phonon")); setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION)); setProperty("backendIcon", QLatin1String("vlc")); setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc")); // Check if we should enable debug output int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt(); if (debugLevel > 3) // 3 is maximum debugLevel = 3; Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel)); // Actual libVLC initialisation if (LibVLC::init()) { debug() << "Using VLC version" << libvlc_get_version(); if (!qApp->applicationName().isEmpty()) { QString userAgent = QString("%0/%1 (Phonon/%2; Phonon-VLC/%3)").arg( qApp->applicationName(), qApp->applicationVersion(), PHONON_VERSION_STR, PHONON_VLC_VERSION); libvlc_set_user_agent(libvlc, qApp->applicationName().toUtf8().constData(), userAgent.toUtf8().constData()); } else { qWarning("WARNING: Setting the user agent for streaming and" " PulseAudio requires you to set QCoreApplication::applicationName()"); } #ifdef __GNUC__ #warning application name ought to be configurable by the consumer ... new api #endif #if (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 1, 0, 0)) if (!qApp->applicationName().isEmpty() && !qApp->applicationVersion().isEmpty()) { const QString id = QString("org.kde.phonon.%1").arg(qApp->applicationName()); const QString version = qApp->applicationVersion(); const QString icon = qApp->applicationName(); libvlc_set_app_id(libvlc, id.toUtf8().constData(), version.toUtf8().constData(), icon.toUtf8().constData()); } else if (PulseSupport::getInstance()->isActive()) { qWarning("WARNING: Setting PulseAudio context information requires you" " to set QCoreApplication::applicationName() and" " QCoreApplication::applicationVersion()"); } #endif } else { #ifdef __GNUC__ #warning TODO - this error message is about as useful as a cooling unit in the arctic #endif QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setWindowTitle(tr("LibVLC Failed to Initialize")); msg.setText(tr("Phonon's VLC backend failed to start." "\n\n" "This usually means a problem with your VLC installation," " please report a bug with your distributor.")); msg.setDetailedText(LibVLC::errorMessage()); msg.exec(); fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC"; } // Initialise PulseAudio support PulseSupport *pulse = PulseSupport::getInstance(); pulse->enable(); connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType))); m_deviceManager = new DeviceManager(this); m_effectManager = new EffectManager(this); } Backend::~Backend() { if (LibVLC::self) delete LibVLC::self; if (GlobalAudioChannels::self) delete GlobalAudioChannels::self; if (GlobalSubtitles::self) delete GlobalSubtitles::self; PulseSupport::shutdown(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { if (!LibVLC::self || !libvlc) return 0; switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(parent); #ifdef __GNUC__ #warning using sout in VLC2 breaks libvlcs vout functions, see vlc bug 6992 // https://trac.videolan.org/vlc/ticket/6992 #endif #if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0)) // FWIW: the case is inside the if because that gives clear indication which // frontend objects are not supported! case AudioDataOutputClass: return new AudioDataOutput(parent); #endif #ifdef PHONON_EXPERIMENTAL case VideoDataOutputClass: return new VideoDataOutput(parent); #endif #ifndef PHONON_NO_GRAPHICSVIEW case VideoGraphicsObjectClass: return new VideoGraphicsObject(parent); #endif case EffectClass: return effectManager()->createEffect(args[0].toInt(), parent); case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); // case VolumeFaderEffectClass: #ifdef __GNUC__ #warning VFE crashes and has volume bugs ... deactivated // return new VolumeFaderEffect(parent); #endif } warning() << "Backend class" << c << "is not supported by Phonon VLC :("; return 0; } QStringList Backend::availableMimeTypes() const { if (m_supportedMimeTypes.isEmpty()) const_cast<Backend *>(this)->m_supportedMimeTypes = mimeTypeList(); return m_supportedMimeTypes; } QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const { QList<int> list; switch (type) { case Phonon::AudioChannelType: { list << GlobalAudioChannels::instance()->globalIndexes(); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { return deviceManager()->deviceIds(type); } break; case Phonon::EffectType: { QList<EffectInfo> effectList = effectManager()->effects(); for (int eff = 0; eff < effectList.size(); ++eff) { list.append(eff); } } break; case Phonon::SubtitleType: { list << GlobalSubtitles::instance()->globalIndexes(); } break; } return list; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioChannelType: { const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { // Index should be unique, even for different categories return deviceManager()->deviceProperties(index); } break; case Phonon::EffectType: { const QList<EffectInfo> effectList = effectManager()->effects(); if (index >= 0 && index <= effectList.size()) { const EffectInfo &effect = effectList.at(index); ret.insert("name", effect.name()); ret.insert("description", effect.description()); ret.insert("author", effect.author()); } else { Q_ASSERT(1); // Since we use list position as ID, this should not happen } } break; case Phonon::SubtitleType: { const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); ret.insert("type", description.property("type")); } break; } return ret; } bool Backend::startConnectionChange(QSet<QObject *> objects) { //FIXME foreach(QObject * object, objects) { debug() << "Object:" << object->metaObject()->className(); } // There is nothing we can do but hope the connection changes will not take too long // so that buffers would underrun // But we should be pretty safe the way xine works by not doing anything here. return true; } bool Backend::connectNodes(QObject *source, QObject *sink) { debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className(); SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Connect the SinkNode to a MediaObject sinkNode->connectToMediaObject(mediaObject); return true; } VolumeFaderEffect *effect = qobject_cast<VolumeFaderEffect *>(source); if (effect) { sinkNode->connectToMediaObject(effect->mediaObject()); return true; } } warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed"; return false; } bool Backend::disconnectNodes(QObject *source, QObject *sink) { SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *const mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Disconnect the SinkNode from a MediaObject sinkNode->disconnectFromMediaObject(mediaObject); return true; } VolumeFaderEffect *const effect = qobject_cast<VolumeFaderEffect *>(source); if (effect) { sinkNode->disconnectFromMediaObject(effect->mediaObject()); return true; } } return false; } bool Backend::endConnectionChange(QSet<QObject *> objects) { foreach(QObject *object, objects) { debug() << "Object:" << object->metaObject()->className(); } return true; } DeviceManager *Backend::deviceManager() const { return m_deviceManager; } EffectManager *Backend::effectManager() const { return m_effectManager; } } // namespace VLC } // namespace Phonon
drop useless eqeffect include in backend (should fix build)
drop useless eqeffect include in backend (should fix build)
C++
lgpl-2.1
KDE/phonon-vlc,KDE/phonon-vlc,BinChengfei/phonon-vlc,KDE/phonon-vlc,BinChengfei/phonon-vlc,BinChengfei/phonon-vlc
bb785a948b28b4967f4be24397647dc60ca8097b
src/core/encodings.cpp
src/core/encodings.cpp
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 "flusspferd/binary.hpp" #include "flusspferd/encodings.hpp" #include "flusspferd/create.hpp" #include <iconv.h> #include <errno.h> #include <sstream> #include <boost/algorithm/string.hpp> using namespace boost; using namespace flusspferd; void flusspferd::load_encodings_module(object container) { object exports = container.get_property_object("exports"); // Load the binary module container.call("require", "binary"); create_native_function( exports, "convertToString", &encodings::convert_to_string); create_native_function( exports, "convertFromString", &encodings::convert_from_string); create_native_function( exports, "convert", &encodings::convert); load_class<encodings::transcoder>(exports); } // the UTF-16 bom is codepoint U+feff static char16_t const bom_le = *(char16_t*)"\xff\xfe"; static char16_t const bom_native = 0xfeff; static char const * const native_charset = bom_le == bom_native ? "utf-16le" : "utf-16be"; // JAVASCRIPT METHODS flusspferd::string encodings::convert_to_string(std::string const &enc_, binary &source_binary) { transcoder &trans = create_native_object<transcoder>(object(), enc_, native_charset); root_object root_obj(trans); trans.push_accumulate(source_binary); binary &out = trans.close(boost::none); return flusspferd::string( reinterpret_cast<char16_t const *>(&out.get_data()[0]), out.get_length() / sizeof(char16_t)); } object encodings::convert_from_string(std::string const &enc, string const &str) { transcoder &trans = create_native_object<transcoder>(object(), native_charset, enc); root_object root_obj(trans); binary &source_binary = create_native_object<byte_string>( object(), reinterpret_cast<binary::element_type const *>(str.data()), str.size() * sizeof(char16_t)); root_object root_obj2(source_binary); trans.push_accumulate(source_binary); return trans.close(boost::none); } object encodings::convert( std::string const &from_, std::string const &to_, binary &source_binary) { transcoder &trans = create_native_object<transcoder>(object(), from_, to_); root_object root_obj(trans); trans.push_accumulate(source_binary); return trans.close(boost::none); } // TRANSCODER class encodings::transcoder::impl { public: impl() : conv(iconv_t(-1)) {} ~impl() { if (conv != iconv_t(-1)) iconv_close(conv); } binary::vector_type accumulator; binary::vector_type multibyte_part; iconv_t conv; }; void encodings::transcoder::trace(tracer &) { } encodings::transcoder::transcoder(object const &obj, call_context &x) : base_type(obj) { init(x.arg[0].to_std_string(), x.arg[1].to_std_string()); } encodings::transcoder::transcoder( object const &obj, std::string const &from, std::string const &to) : base_type(obj) { init(from, to); } encodings::transcoder::~transcoder() { } void encodings::transcoder::init(std::string const &from, std::string const &to) { boost::scoped_ptr<impl> p(new impl); define_property( "sourceCharset", flusspferd::value(from), property_attributes(read_only_property | permanent_property)); define_property( "destinationCharset", flusspferd::value(to), property_attributes(read_only_property | permanent_property)); p->conv = iconv_open(to.c_str(), from.c_str()); if (p->conv == iconv_t(-1)) throw exception("Could not create Transcoder with iconv"); this->p.swap(p); } binary &encodings::transcoder::push( binary &input, boost::optional<byte_array&> const &output_) { binary &output = get_output_binary(output_); root_object root_obj(output); append_accumulator(output); do_push(input, output.get_data()); return output; } void encodings::transcoder::push_accumulate(binary &input) { do_push(input, p->accumulator); } binary &encodings::transcoder::close( boost::optional<byte_array&> const &output_) { if (!p->multibyte_part.empty()) throw exception("Invalid multibyte sequence at the end of input"); binary &output = get_output_binary(output_); root_object root_obj(output); append_accumulator(output); if (p->conv != iconv_t(-1)) { binary::vector_type &out_v = output.get_data(); std::size_t start = out_v.size(); // 32 bytes should suffice for the initial state shift std::size_t outlen = 32; out_v.resize(out_v.size() + outlen); char *outbuf = reinterpret_cast<char*>(&out_v[start]); if (iconv(p->conv, 0, 0, &outbuf, &outlen) == std::size_t(-1)) throw exception("Adding closing character sequence failed"); out_v.resize(out_v.size() - outlen); if (iconv_close(p->conv) == -1) throw exception("Closing character set conversion descriptor failed"); p->conv = iconv_t(-1); } return output; } binary &encodings::transcoder::get_output_binary( boost::optional<byte_array&> const &output_) { return output_ ? static_cast<binary&>(output_.get()) : static_cast<binary&>( create_native_object<byte_string>( object(), (byte_string::element_type*)0, 0)); } void encodings::transcoder::do_push(binary &input, binary::vector_type &out_v) { binary::vector_type &in_v = p->multibyte_part.empty() ? input.get_data() : p->multibyte_part; if (!p->multibyte_part.empty()) in_v.insert(in_v.end(), input.get_data().begin(), input.get_data().end()); // A rough guess how much space might be needed for the new characters. std::size_t out_estimate = in_v.size() + in_v.size()/16 + 32; std::size_t out_start = out_v.size(); for (;;) { out_v.resize(out_v.size() + out_estimate); #ifdef ICONV_ACCEPTS_NONCONST_INPUT char *inbuf; #else char const *inbuf; #endif inbuf = reinterpret_cast<char *>(&in_v[0]); char *outbuf = reinterpret_cast<char*>(&out_v[out_start]); std::size_t inbytesleft = in_v.size(); std::size_t outbytesleft = out_estimate; std::size_t n_chars = iconv( p->conv, &inbuf, &inbytesleft, &outbuf, &outbytesleft); if (n_chars == std::size_t(-1)) { switch (errno) { case EILSEQ: throw exception("Invalid multi-byte sequence in input"); case E2BIG: out_v.resize(out_v.size() - out_estimate); out_estimate *= 2; break; case EINVAL: p->multibyte_part.assign(outbuf, outbuf + outbytesleft); out_v.resize(out_v.size() - outbytesleft); return; default: throw exception("Unknown error in character conversion"); } } else { out_v.resize(out_v.size() - outbytesleft); return; } } } void encodings::transcoder::append_accumulator(binary &output) { binary::vector_type &out_v = output.get_data(); if (!p->accumulator.empty()) { if (!out_v.empty()) { out_v.insert(out_v.end(), p->accumulator.begin(), p->accumulator.end()); binary::vector_type().swap(p->accumulator); } else { out_v.swap(p->accumulator); } } }
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 "flusspferd/binary.hpp" #include "flusspferd/encodings.hpp" #include "flusspferd/create.hpp" #include <iconv.h> #include <errno.h> #include <sstream> #include <boost/algorithm/string.hpp> using namespace boost; using namespace flusspferd; void flusspferd::load_encodings_module(object container) { object exports = container.get_property_object("exports"); // Load the binary module container.call("require", "binary"); create_native_function( exports, "convertToString", &encodings::convert_to_string); create_native_function( exports, "convertFromString", &encodings::convert_from_string); create_native_function( exports, "convert", &encodings::convert); load_class<encodings::transcoder>(exports); } // the UTF-16 bom is codepoint U+feff static char16_t const bom_le = *(char16_t*)"\xff\xfe"; static char16_t const bom_native = 0xfeff; static char const * const native_charset = bom_le == bom_native ? "utf-16le" : "utf-16be"; // JAVASCRIPT METHODS flusspferd::string encodings::convert_to_string(std::string const &enc_, binary &source_binary) { transcoder &trans = create_native_object<transcoder>(object(), enc_, native_charset); root_object root_obj(trans); trans.push_accumulate(source_binary); binary &out = trans.close(boost::none); return flusspferd::string( reinterpret_cast<char16_t const *>(&out.get_data()[0]), out.get_length() / sizeof(char16_t)); } object encodings::convert_from_string(std::string const &enc, string const &str) { transcoder &trans = create_native_object<transcoder>(object(), native_charset, enc); root_object root_obj(trans); binary &source_binary = create_native_object<byte_string>( object(), reinterpret_cast<binary::element_type const *>(str.data()), str.size() * sizeof(char16_t)); root_object root_obj2(source_binary); trans.push_accumulate(source_binary); return trans.close(boost::none); } object encodings::convert( std::string const &from_, std::string const &to_, binary &source_binary) { transcoder &trans = create_native_object<transcoder>(object(), from_, to_); root_object root_obj(trans); trans.push_accumulate(source_binary); return trans.close(boost::none); } // TRANSCODER class encodings::transcoder::impl { public: impl() : conv(iconv_t(-1)) {} ~impl() { if (conv != iconv_t(-1)) iconv_close(conv); } binary::vector_type accumulator; binary::vector_type multibyte_part; iconv_t conv; }; void encodings::transcoder::trace(tracer &) { } encodings::transcoder::transcoder(object const &obj, call_context &x) : base_type(obj) { init(x.arg[0].to_std_string(), x.arg[1].to_std_string()); } encodings::transcoder::transcoder( object const &obj, std::string const &from, std::string const &to) : base_type(obj) { init(from, to); } encodings::transcoder::~transcoder() { } void encodings::transcoder::init(std::string const &from, std::string const &to) { boost::scoped_ptr<impl> p(new impl); define_property( "sourceCharset", flusspferd::value(from), property_attributes(read_only_property | permanent_property)); define_property( "destinationCharset", flusspferd::value(to), property_attributes(read_only_property | permanent_property)); p->conv = iconv_open(to.c_str(), from.c_str()); if (p->conv == iconv_t(-1)) { std::ostringstream message; message << "Could not create Transcoder (iconv) " << "from charset \"" << from << "\" " << "to charset \"" << to << "\""; throw exception(message.str()); } this->p.swap(p); } binary &encodings::transcoder::push( binary &input, boost::optional<byte_array&> const &output_) { binary &output = get_output_binary(output_); root_object root_obj(output); append_accumulator(output); do_push(input, output.get_data()); return output; } void encodings::transcoder::push_accumulate(binary &input) { do_push(input, p->accumulator); } binary &encodings::transcoder::close( boost::optional<byte_array&> const &output_) { if (!p->multibyte_part.empty()) throw exception("Invalid multibyte sequence at the end of input"); binary &output = get_output_binary(output_); root_object root_obj(output); append_accumulator(output); if (p->conv != iconv_t(-1)) { binary::vector_type &out_v = output.get_data(); std::size_t start = out_v.size(); // 32 bytes should suffice for the initial state shift std::size_t outlen = 32; out_v.resize(out_v.size() + outlen); char *outbuf = reinterpret_cast<char*>(&out_v[start]); if (iconv(p->conv, 0, 0, &outbuf, &outlen) == std::size_t(-1)) throw exception("Adding closing character sequence failed"); out_v.resize(out_v.size() - outlen); if (iconv_close(p->conv) == -1) throw exception("Closing character set conversion descriptor failed"); p->conv = iconv_t(-1); } return output; } binary &encodings::transcoder::get_output_binary( boost::optional<byte_array&> const &output_) { return output_ ? static_cast<binary&>(output_.get()) : static_cast<binary&>( create_native_object<byte_string>( object(), (byte_string::element_type*)0, 0)); } void encodings::transcoder::do_push(binary &input, binary::vector_type &out_v) { binary::vector_type &in_v = p->multibyte_part.empty() ? input.get_data() : p->multibyte_part; if (!p->multibyte_part.empty()) in_v.insert(in_v.end(), input.get_data().begin(), input.get_data().end()); // A rough guess how much space might be needed for the new characters. std::size_t out_estimate = in_v.size() + in_v.size()/16 + 32; std::size_t out_start = out_v.size(); for (;;) { out_v.resize(out_v.size() + out_estimate); #ifdef ICONV_ACCEPTS_NONCONST_INPUT char *inbuf; #else char const *inbuf; #endif inbuf = reinterpret_cast<char *>(&in_v[0]); char *outbuf = reinterpret_cast<char*>(&out_v[out_start]); std::size_t inbytesleft = in_v.size(); std::size_t outbytesleft = out_estimate; std::size_t n_chars = iconv( p->conv, &inbuf, &inbytesleft, &outbuf, &outbytesleft); if (n_chars == std::size_t(-1)) { switch (errno) { case EILSEQ: throw exception("Invalid multi-byte sequence in input"); case E2BIG: out_v.resize(out_v.size() - out_estimate); out_estimate *= 2; break; case EINVAL: p->multibyte_part.assign(outbuf, outbuf + outbytesleft); out_v.resize(out_v.size() - outbytesleft); return; default: throw exception("Unknown error in character conversion"); } } else { out_v.resize(out_v.size() - outbytesleft); return; } } } void encodings::transcoder::append_accumulator(binary &output) { binary::vector_type &out_v = output.get_data(); if (!p->accumulator.empty()) { if (!out_v.empty()) { out_v.insert(out_v.end(), p->accumulator.begin(), p->accumulator.end()); binary::vector_type().swap(p->accumulator); } else { out_v.swap(p->accumulator); } } }
make error messages more understandables (fixes #137)
core/encodings: make error messages more understandables (fixes #137)
C++
mit
Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd
5d019f4d76d04976c7c7c3d07a95289d9f75dd77
src/core/utils/log.cpp
src/core/utils/log.cpp
#include "log.h" #include <algorithm> #include <array> #include <chrono> #include <exception> #include <iomanip> #include <iostream> #include <ostream> #include <string> using namespace allpix; // NOTE: we have to check for exceptions before we do the actual logging (which may also throw exceptions) DefaultLogger::DefaultLogger() : os(), exception_count_(get_uncaught_exceptions(true)), indent_count_(0) {} DefaultLogger::~DefaultLogger() { // check if it is potentially safe to throw if(exception_count_ != get_uncaught_exceptions(false)) { return; } // get output string std::string out(os.str()); // replace every newline by indented code if necessary auto start_pos = out.find('\n'); if(start_pos != std::string::npos) { std::string spcs(indent_count_ + 1, ' '); spcs[0] = '\n'; do { out.replace(start_pos, 1, spcs); start_pos += spcs.length(); } while((start_pos = out.find('\n', start_pos)) != std::string::npos); } // add final newline out += '\n'; // print output to streams for(auto stream : get_streams()) { (*stream) << out; } } std::ostringstream& DefaultLogger::getStream(LogLevel level, const std::string& file, const std::string& function, uint32_t line) { // add date in all except short format if(get_format() != LogFormat::SHORT) { os << "|" << get_current_date() << "| "; } // add log level (shortly in the short format) if(get_format() != LogFormat::SHORT) { std::string level_str = "("; level_str += getStringFromLevel(level); level_str += ")"; os << std::setw(9) << level_str << " "; } else { os << "(" << getStringFromLevel(level).substr(0, 1) << ") "; } // add section if available if(!get_section().empty()) { os << "[" << get_section() << "] "; } // print function name and line number information in debug format if(get_format() == LogFormat::DEBUG) { os << "<" << file << "/" << function << ":L" << line << "> "; } // save the indent count to fix with newlines indent_count_ = static_cast<unsigned int>(os.str().size()); return os; } // reporting level LogLevel& DefaultLogger::get_reporting_level() { static LogLevel reporting_level = LogLevel::INFO; return reporting_level; } void DefaultLogger::setReportingLevel(LogLevel level) { get_reporting_level() = level; } LogLevel DefaultLogger::getReportingLevel() { return get_reporting_level(); } // convert string to log level and vice versa std::string DefaultLogger::getStringFromLevel(LogLevel level) { static const std::array<std::string, 6> type = {{"QUIET", "FATAL", "ERROR", "WARNING", "INFO", "DEBUG"}}; return type.at(static_cast<decltype(type)::size_type>(level)); } LogLevel DefaultLogger::getLevelFromString(const std::string& level) { if(level == "DEBUG") { return LogLevel::DEBUG; } if(level == "INFO") { return LogLevel::INFO; } if(level == "WARNING") { return LogLevel::WARNING; } if(level == "ERROR") { return LogLevel::ERROR; } if(level == "FATAL") { return LogLevel::FATAL; } if(level == "QUIET") { return LogLevel::QUIET; } throw std::invalid_argument("unknown log level"); } // log format LogFormat& DefaultLogger::get_format() { static LogFormat reporting_level = LogFormat::DEFAULT; return reporting_level; } void DefaultLogger::setFormat(LogFormat level) { get_format() = level; } LogFormat DefaultLogger::getFormat() { return get_format(); } // convert string to log level and vice versa std::string DefaultLogger::getStringFromFormat(LogFormat format) { static const std::array<std::string, 3> type = {{"SHORT", "DEFAULT", "DEBUG"}}; return type.at(static_cast<decltype(type)::size_type>(format)); } LogFormat DefaultLogger::getFormatFromString(const std::string& format) { if(format == "SHORT") { return LogFormat::SHORT; } if(format == "DEFAULT") { return LogFormat::DEFAULT; } if(format == "DEBUG") { return LogFormat::DEBUG; } throw std::invalid_argument("unknown log format"); } // change streams std::vector<std::ostream*>& DefaultLogger::get_streams() { static std::vector<std::ostream*> streams = {&std::cerr}; return streams; } const std::vector<std::ostream*>& DefaultLogger::getStreams() { return get_streams(); } void DefaultLogger::clearStreams() { get_streams().clear(); } void DefaultLogger::addStream(std::ostream& stream) { get_streams().push_back(&stream); } // section names std::string& DefaultLogger::get_section() { static std::string section; return section; } void DefaultLogger::setSection(std::string section) { get_section() = std::move(section); } std::string DefaultLogger::getSection() { return get_section(); } std::string DefaultLogger::get_current_date() { // FIXME: revise this to get microseconds in a better way auto now = std::chrono::system_clock::now(); auto in_time_t = std::chrono::system_clock::to_time_t(now); std::stringstream ss; ss << std::put_time(std::localtime(&in_time_t), "%X"); auto seconds_from_epoch = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch() - seconds_from_epoch).count(); ss << "."; ss << std::setfill('0') << std::setw(3); ss << millis; return ss.str(); } int DefaultLogger::get_uncaught_exceptions(bool cons = false) { #if __cplusplus > 201402L // we can only do this fully correctly in C++17 return std::uncaught_exceptions(); #else if(cons) { return 0; } return static_cast<int>(std::uncaught_exception()); #endif }
#include "log.h" #include <algorithm> #include <array> #include <chrono> #include <exception> #include <iomanip> #include <iostream> #include <ostream> #include <string> using namespace allpix; // NOTE: we have to check for exceptions before we do the actual logging (which may also throw exceptions) DefaultLogger::DefaultLogger() : os(), exception_count_(get_uncaught_exceptions(true)), indent_count_(0) {} DefaultLogger::~DefaultLogger() { // check if it is potentially safe to throw if(exception_count_ != get_uncaught_exceptions(false)) { return; } // get output string std::string out(os.str()); // replace every newline by indented code if necessary auto start_pos = out.find('\n'); if(start_pos != std::string::npos) { std::string spcs(indent_count_ + 1, ' '); spcs[0] = '\n'; do { out.replace(start_pos, 1, spcs); start_pos += spcs.length(); } while((start_pos = out.find('\n', start_pos)) != std::string::npos); } // add final newline out += '\n'; // print output to streams for(auto stream : get_streams()) { (*stream) << out; } } std::ostringstream& DefaultLogger::getStream(LogLevel level, const std::string& file, const std::string& function, uint32_t line) { // add date in all except short format if(get_format() != LogFormat::SHORT) { os << "|" << get_current_date() << "| "; } // add log level (shortly in the short format) if(get_format() != LogFormat::SHORT) { std::string level_str = "("; level_str += getStringFromLevel(level); level_str += ")"; os << std::setw(9) << level_str << " "; } else { os << "(" << getStringFromLevel(level).substr(0, 1) << ") "; } // add section if available if(!get_section().empty()) { os << "[" << get_section() << "] "; } // print function name and line number information in debug format if(get_format() == LogFormat::DEBUG) { os << "<" << file << "/" << function << ":L" << line << "> "; } // save the indent count to fix with newlines indent_count_ = static_cast<unsigned int>(os.str().size()); return os; } // reporting level LogLevel& DefaultLogger::get_reporting_level() { static LogLevel reporting_level = LogLevel::INFO; return reporting_level; } void DefaultLogger::setReportingLevel(LogLevel level) { get_reporting_level() = level; } LogLevel DefaultLogger::getReportingLevel() { return get_reporting_level(); } // convert string to log level and vice versa std::string DefaultLogger::getStringFromLevel(LogLevel level) { static const std::array<std::string, 6> type = {{"QUIET", "FATAL", "ERROR", "WARNING", "INFO", "DEBUG"}}; return type.at(static_cast<decltype(type)::size_type>(level)); } LogLevel DefaultLogger::getLevelFromString(const std::string& level) { if(level == "DEBUG") { return LogLevel::DEBUG; } if(level == "INFO") { return LogLevel::INFO; } if(level == "WARNING") { return LogLevel::WARNING; } if(level == "ERROR") { return LogLevel::ERROR; } if(level == "FATAL") { return LogLevel::FATAL; } if(level == "QUIET") { return LogLevel::QUIET; } throw std::invalid_argument("unknown log level"); } // log format LogFormat& DefaultLogger::get_format() { static LogFormat reporting_level = LogFormat::DEFAULT; return reporting_level; } void DefaultLogger::setFormat(LogFormat level) { get_format() = level; } LogFormat DefaultLogger::getFormat() { return get_format(); } // convert string to log level and vice versa std::string DefaultLogger::getStringFromFormat(LogFormat format) { static const std::array<std::string, 3> type = {{"SHORT", "DEFAULT", "DEBUG"}}; return type.at(static_cast<decltype(type)::size_type>(format)); } LogFormat DefaultLogger::getFormatFromString(const std::string& format) { if(format == "SHORT") { return LogFormat::SHORT; } if(format == "DEFAULT") { return LogFormat::DEFAULT; } if(format == "DEBUG") { return LogFormat::DEBUG; } throw std::invalid_argument("unknown log format"); } // change streams std::vector<std::ostream*>& DefaultLogger::get_streams() { static std::vector<std::ostream*> streams = {&std::cout}; return streams; } const std::vector<std::ostream*>& DefaultLogger::getStreams() { return get_streams(); } void DefaultLogger::clearStreams() { get_streams().clear(); } void DefaultLogger::addStream(std::ostream& stream) { get_streams().push_back(&stream); } // section names std::string& DefaultLogger::get_section() { static std::string section; return section; } void DefaultLogger::setSection(std::string section) { get_section() = std::move(section); } std::string DefaultLogger::getSection() { return get_section(); } std::string DefaultLogger::get_current_date() { // FIXME: revise this to get microseconds in a better way auto now = std::chrono::system_clock::now(); auto in_time_t = std::chrono::system_clock::to_time_t(now); std::stringstream ss; ss << std::put_time(std::localtime(&in_time_t), "%X"); auto seconds_from_epoch = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch() - seconds_from_epoch).count(); ss << "."; ss << std::setfill('0') << std::setw(3); ss << millis; return ss.str(); } int DefaultLogger::get_uncaught_exceptions(bool cons = false) { #if __cplusplus > 201402L // we can only do this fully correctly in C++17 return std::uncaught_exceptions(); #else if(cons) { return 0; } return static_cast<int>(std::uncaught_exception()); #endif }
change default stream from stderr to stdout
change default stream from stderr to stdout
C++
mit
Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared
b09011b2efe6c6f709b668fc9aa7f7def6563f6b
src/coverage_market.cc
src/coverage_market.cc
/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "coverage_market.hh" #include "model.hh" #include "helper.hh" #include <regex.h> Coverage_Market::Coverage_Market(Log& l, std::string& _params) : Coverage(l) { params = _params; } void Coverage_Market::history(int action, std::vector<int>& props, Verdict::Verdict verdict) { if (action) { execute(action); } else { // verdict // Ok. We'll need to init the system. } } bool Coverage_Market::execute(int action) { /* Dummy */ for(size_t i=0;i<Units.size();i++) { Units[i]->execute(action); } return true; } float Coverage_Market::getCoverage() { val v,tmp; v.first=0; v.second=0; for(size_t i=0;i<Units.size();i++) { Units[i]->update(); tmp=Units[i]->get_value(); v.first+=tmp.first; v.second+=tmp.second; } if (v.second) { return ((float)v.first)/((float)v.second); } return 0; } int Coverage_Market::fitness(int* action,int n,float* fitness) { float m=-1; int pos=-1; for(int i=0;i<n;i++) { val b(0,0); val e(0,0); val tmp; log.debug("%s:%i\n",__func__,i); for(size_t j=0;j<Units.size();j++) { log.debug("%s:%i,%i (%i)\n",__func__,i,j,action[i]); Units[j]->update(); tmp=Units[j]->get_value(); b.first+=tmp.first; b.second+=tmp.second; Units[j]->push(); Units[j]->execute(action[i]); Units[j]->update(); tmp=Units[j]->get_value(); e.first+=tmp.first; e.second+=tmp.second; Units[j]->pop(); Units[j]->update(); } log.debug("(%i:%i) (%i:%i)\n",b.first,b.second, e.first,e.second); if (b.second) { fitness[i]=((float)(e.first-b.first))/((float)(b.second)); } else { fitness[i]=0.0; } if (m<fitness[i]) { pos=i; m=fitness[i]; } } return pos; } #include "dparse.h" extern "C" { extern D_ParserTables parser_tables_covlang; } extern Coverage_Market* cobj; void Coverage_Market::add_requirement(std::string& req) { cobj=this; D_Parser *p = new_D_Parser(&parser_tables_covlang, 32); D_ParseNode* ret=dparse(p,(char*)req.c_str(),req.length()); status=p->syntax_errors==0; if (ret) { free_D_ParseNode(p, ret); } free_D_Parser(p); } Coverage_Market::unit* Coverage_Market::req_rx_action(const char m,const std::string &action) { /* m(ode) == a|e a(ll): cover all matching actions e(xists): cover any of matching actions */ if (!status) { return NULL; } Coverage_Market::unit* u=NULL; if (m) { std::vector<int> actions; regexpmatch(action, model->getActionNames(), actions, false); if (actions.empty()) { errormsg = "No actions matching \"" + action + "\""; status = false; return NULL; } for(unsigned int i=0; i < actions.size(); i++) { if (u) { if (m=='e') { u=new Coverage_Market::unit_or(u,new Coverage_Market::unit_leaf(actions[i])); } else { u=new Coverage_Market::unit_and(u,new Coverage_Market::unit_leaf(actions[i])); } } else { u=new Coverage_Market::unit_leaf(actions[i]); } } } else { int an = model->action_number(action.c_str()); if (an<=0) { errormsg="No such action \"" + action + "\""; status=false; } u = new Coverage_Market::unit_leaf(an); } if (u==NULL) { errormsg=std::string("parse error"); status=false; } return u; } FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Market, "usecase")
/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "coverage_market.hh" #include "model.hh" #include "helper.hh" #include <regex.h> Coverage_Market::Coverage_Market(Log& l, std::string& _params) : Coverage(l) { params = _params; } void Coverage_Market::history(int action, std::vector<int>& props, Verdict::Verdict verdict) { if (action) { execute(action); } else { // verdict // Ok. We'll need to init the system. } } bool Coverage_Market::execute(int action) { /* Dummy */ for(size_t i=0;i<Units.size();i++) { Units[i]->execute(action); } return true; } float Coverage_Market::getCoverage() { val v,tmp; v.first=0; v.second=0; for(size_t i=0;i<Units.size();i++) { Units[i]->update(); tmp=Units[i]->get_value(); v.first+=tmp.first; v.second+=tmp.second; } if (v.second) { return ((float)v.first)/((float)v.second); } return 0; } int Coverage_Market::fitness(int* action,int n,float* fitness) { float m=-1; int pos=-1; for(int i=0;i<n;i++) { val b(0,0); val e(0,0); val tmp; log.debug("%s:%i\n",__func__,i); for(size_t j=0;j<Units.size();j++) { log.debug("%s:%i,%i (%i)\n",__func__,i,j,action[i]); Units[j]->update(); tmp=Units[j]->get_value(); b.first+=tmp.first; b.second+=tmp.second; Units[j]->push(); Units[j]->execute(action[i]); Units[j]->update(); tmp=Units[j]->get_value(); e.first+=tmp.first; e.second+=tmp.second; Units[j]->pop(); Units[j]->update(); } log.debug("(%i:%i) (%i:%i)\n",b.first,b.second, e.first,e.second); if (b.second) { fitness[i]=((float)(e.first-b.first))/((float)(b.second)); } else { fitness[i]=0.0; } if (m<fitness[i]) { pos=i; m=fitness[i]; } } return pos; } #include "dparse.h" extern "C" { extern D_ParserTables parser_tables_covlang; } extern Coverage_Market* cobj; void Coverage_Market::add_requirement(std::string& req) { cobj=this; D_Parser *p = new_D_Parser(&parser_tables_covlang, 32); D_ParseNode* ret=dparse(p,(char*)req.c_str(),req.length()); status&=p->syntax_errors==0; if (ret) { free_D_ParseNode(p, ret); } free_D_Parser(p); } Coverage_Market::unit* Coverage_Market::req_rx_action(const char m,const std::string &action) { /* m(ode) == a|e a(ll): cover all matching actions e(xists): cover any of matching actions */ if (!status) { return NULL; } Coverage_Market::unit* u=NULL; if (m) { std::vector<int> actions; regexpmatch(action, model->getActionNames(), actions, false); if (actions.empty()) { errormsg = "No actions matching \"" + action + "\""; status = false; return NULL; } for(unsigned int i=0; i < actions.size(); i++) { if (u) { if (m=='e') { u=new Coverage_Market::unit_or(u,new Coverage_Market::unit_leaf(actions[i])); } else { u=new Coverage_Market::unit_and(u,new Coverage_Market::unit_leaf(actions[i])); } } else { u=new Coverage_Market::unit_leaf(actions[i]); } } } else { int an = model->action_number(action.c_str()); if (an<=0) { errormsg="No such action \"" + action + "\""; status=false; u = new Coverage_Market::unit_leaf(0); } else { u = new Coverage_Market::unit_leaf(an); } } if (u==NULL) { errormsg=std::string("parse error"); status=false; } return u; } FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Market, "usecase")
Fix usecase coverage bug when no matching action
Fix usecase coverage bug when no matching action
C++
lgpl-2.1
OMKR/fMBT,yoonkiss/fMBT,CosminNiculae/fMBT,rseymour/fMBT,violep01/fMBT,giantpinkwalrus/fMBT,acozzette/fMBT,01org/fMBT,rseymour/fMBT,mixu-/fMBT,violep01/fMBT,pombreda/fMBT,yoonkiss/fMBT,rseymour/fMBT,heivi/fMBT,pombreda/fMBT,01org/fMBT,OMKR/fMBT,rseymour/fMBT,OMKR/fMBT,acozzette/fMBT,mlq/fMBT,pyykkis/fMBT,pyykkis/fMBT,yoonkiss/fMBT,mixu-/fMBT,yoonkiss/fMBT,violep01/fMBT,mlq/fMBT,heivi/fMBT,pablovirolainen/fMBT,CosminNiculae/fMBT,pombreda/fMBT,giantpinkwalrus/fMBT,CosminNiculae/fMBT,violep01/fMBT,giantpinkwalrus/fMBT,OMKR/fMBT,pablovirolainen/fMBT,pombreda/fMBT,01org/fMBT,acozzette/fMBT,pyykkis/fMBT,01org/fMBT,heivi/fMBT,CosminNiculae/fMBT,heivi/fMBT,acozzette/fMBT,mixu-/fMBT,01org/fMBT,CosminNiculae/fMBT,yoonkiss/fMBT,mixu-/fMBT,pyykkis/fMBT,pombreda/fMBT,pyykkis/fMBT,heivi/fMBT,rseymour/fMBT,mlq/fMBT,heivi/fMBT,mlq/fMBT,pyykkis/fMBT,giantpinkwalrus/fMBT,heivi/fMBT,mlq/fMBT,giantpinkwalrus/fMBT,pablovirolainen/fMBT,pombreda/fMBT,mlq/fMBT,OMKR/fMBT,pablovirolainen/fMBT,pablovirolainen/fMBT,rseymour/fMBT,acozzette/fMBT,CosminNiculae/fMBT,mixu-/fMBT,pombreda/fMBT,OMKR/fMBT,CosminNiculae/fMBT,violep01/fMBT,mlq/fMBT,pablovirolainen/fMBT,rseymour/fMBT
5120b895f6a5ab26cc559724e96727af042e0bdd
src/bindings.cc
src/bindings.cc
// Copyright 2010, Camilo Aguilar. Cloudescape, LLC. #include "bindings.h" /* size of the event structure, not counting name */ #define EVENT_SIZE (sizeof (struct inotify_event)) /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) namespace NodeInotify { static Persistent<String> path_sym; static Persistent<String> watch_for_sym; static Persistent<String> callback_sym; static Persistent<String> persistent_sym; static Persistent<String> watch_sym; static Persistent<String> mask_sym; static Persistent<String> cookie_sym; static Persistent<String> name_sym; void Inotify::Initialize(Handle<Object> target) { Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New); t->Inherit(EventEmitter::constructor_template); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "addWatch", Inotify::AddWatch); NODE_SET_PROTOTYPE_METHOD(t, "removeWatch", Inotify::RemoveWatch); NODE_SET_PROTOTYPE_METHOD(t, "close", Inotify::Close); //Constants initialization NODE_DEFINE_CONSTANT(t, IN_ACCESS); //File was accessed (read) NODE_DEFINE_CONSTANT(t, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps, //extended attributes, link count (since Linux 2.6.25), //UID, GID, etc. NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); //File opened for writing was closed NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); //File not opened for writing was closed NODE_DEFINE_CONSTANT(t, IN_CREATE); //File/directory created in watched directory NODE_DEFINE_CONSTANT(t, IN_DELETE); //File/directory deleted from watched directory NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); //Watched file/directory was itself deleted NODE_DEFINE_CONSTANT(t, IN_MODIFY); //File was modified NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); //Watched file/directory was itself moved NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); //File moved out of watched directory NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); //File moved into watched directory NODE_DEFINE_CONSTANT(t, IN_OPEN); //File was opened NODE_DEFINE_CONSTANT(t, IN_IGNORED); // Watch was removed explicitly (inotify.watch.rm) or //automatically (file was deleted, or file system was //unmounted) NODE_DEFINE_CONSTANT(t, IN_ISDIR); //Subject of this event is a directory NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event) NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); //File system containing watched object was unmounted NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS); NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); // Only watch the path if it is a directory. NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); // Do not follow a sym link NODE_DEFINE_CONSTANT(t, IN_ONESHOT); // Only send event once NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it //already exists (instead of replacing mask). NODE_DEFINE_CONSTANT(t, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close NODE_DEFINE_CONSTANT(t, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves path_sym = NODE_PSYMBOL("path"); watch_for_sym = NODE_PSYMBOL("watch_for"); callback_sym = NODE_PSYMBOL("callback"); persistent_sym = NODE_PSYMBOL("persistent"); watch_sym = NODE_PSYMBOL("watch"); mask_sym = NODE_PSYMBOL("mask"); cookie_sym = NODE_PSYMBOL("cookie"); name_sym = NODE_PSYMBOL("name"); Local<ObjectTemplate> object_tmpl = t->InstanceTemplate(); object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent); t->SetClassName(String::NewSymbol("Inotify")); target->Set(String::NewSymbol("Inotify"), t->GetFunction()); } Inotify::Inotify() : EventEmitter() { ev_init(&read_watcher, Inotify::Callback); read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback persistent = true; } Inotify::Inotify(bool nonpersistent) : EventEmitter() { ev_init(&read_watcher, Inotify::Callback); read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback persistent = nonpersistent; } Inotify::~Inotify() { if(!persistent) { ev_ref(EV_DEFAULT_UC); } ev_io_stop(EV_DEFAULT_UC_ &read_watcher); assert(!ev_is_active(&read_watcher)); assert(!ev_is_pending(&read_watcher)); } Handle<Value> Inotify::New(const Arguments& args) { HandleScope scope; Inotify *inotify = NULL; if(args.Length() == 1 && args[0]->IsBoolean()) { inotify = new Inotify(args[0]->IsTrue()); } else { inotify = new Inotify(); } inotify->fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); //nonblock //inotify->fd = inotify_init1(IN_CLOEXEC); //block if(inotify->fd == -1) { ThrowException(String::New(strerror(errno))); return Null(); } ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ); ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher); Local<Object> obj = args.This(); inotify->Wrap(obj); if(!inotify->persistent) { ev_unref(EV_DEFAULT_UC); } /*Increment object references to avoid be GCed while I'm waiting for inotify events in th ev_pool. Also, the object is not weak anymore */ inotify->Ref(); return scope.Close(obj); } Handle<Value> Inotify::AddWatch(const Arguments& args) { HandleScope scope; uint32_t mask = 0; int watch_descriptor = 0; if(args.Length() < 1 || !args[0]->IsObject()) { return ThrowException(Exception::TypeError( String::New("You must specify an object as first argument"))); } Local<Object> args_ = args[0]->ToObject(); if(!args_->Has(path_sym)) { return ThrowException(Exception::TypeError( String::New("You must specify a path to watch for events"))); } if(!args_->Has(callback_sym) || !args_->Get(callback_sym)->IsFunction()) { return ThrowException(Exception::TypeError( String::New("You must specify a callback function"))); } if(!args_->Has(watch_for_sym)) { mask |= IN_ALL_EVENTS; } else { if(!args_->Get(watch_for_sym)->IsInt32()) { return ThrowException(Exception::TypeError( String::New("You must specify OR'ed set of events"))); } mask |= args_->Get(watch_for_sym)->Int32Value(); if(mask == 0) { return ThrowException(Exception::TypeError( String::New("You must specify OR'ed set of events"))); } } String::Utf8Value path(args_->Get(path_sym)); Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This()); /* add watch */ watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask); Local<Integer> descriptor = Integer::New(watch_descriptor); //Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym)); inotify->handle_->Set(descriptor, args_->Get(callback_sym)); return scope.Close(descriptor); } Handle<Value> Inotify::RemoveWatch(const Arguments& args) { HandleScope scope; uint32_t watch = 0; int ret = -1; if(args.Length() == 0 || !args[0]->IsInt32()) { return ThrowException(Exception::TypeError( String::New("You must specify a valid watcher descriptor as argument"))); } watch = args[0]->Int32Value(); Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This()); ret = inotify_rm_watch(inotify->fd, watch); if(ret == -1) { ThrowException(String::New(strerror(errno))); return False(); } //inotify->handle_->Delete(args[0]->ToString()); return True(); } Handle<Value> Inotify::Close(const Arguments& args) { HandleScope scope; int ret = -1; Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This()); ret = close(inotify->fd); if(ret == -1) { ThrowException(String::New(strerror(errno))); return False(); } if(!inotify->persistent) { ev_ref(EV_DEFAULT_UC); } ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher); /*Eliminating reference created inside of Inotify::New. The object is also weak again. Now v8 can do its stuff and GC the object. */ inotify->Unref(); return True(); } void Inotify::Callback(EV_P_ ev_io *watcher, int revents) { HandleScope scope; Inotify *inotify = static_cast<Inotify*>(watcher->data); assert(watcher == &inotify->read_watcher); char buffer[BUF_LEN]; int length = read(inotify->fd, buffer, BUF_LEN); Local<Value> argv[1]; TryCatch try_catch; int i = 0; while (i < length) { struct inotify_event *event; event = (struct inotify_event *) &buffer[i]; Local<Object> obj = Object::New(); obj->Set(watch_sym, Integer::New(event->wd)); obj->Set(mask_sym, Integer::New(event->mask)); obj->Set(cookie_sym, Integer::New(event->cookie)); if(event->len) { obj->Set(name_sym, String::New(event->name)); } argv[0] = obj; inotify->Ref(); Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd)); Local<Function> callback = Local<Function>::Cast(callback_); callback->Call(inotify->handle_, 1, argv); inotify->Unref(); if (try_catch.HasCaught()) { FatalException(try_catch); } i += EVENT_SIZE + event->len; } } Handle<Value> Inotify::GetPersistent(Local<String> property, const AccessorInfo& info) { Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This()); return inotify->persistent ? True() : False(); } }//namespace NodeInotify
// Copyright 2010, Camilo Aguilar. Cloudescape, LLC. #include "bindings.h" /* size of the event structure, not counting name */ #define EVENT_SIZE (sizeof (struct inotify_event)) /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) namespace NodeInotify { static Persistent<String> path_sym; static Persistent<String> watch_for_sym; static Persistent<String> callback_sym; static Persistent<String> persistent_sym; static Persistent<String> watch_sym; static Persistent<String> mask_sym; static Persistent<String> cookie_sym; static Persistent<String> name_sym; void Inotify::Initialize(Handle<Object> target) { Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New); t->Inherit(EventEmitter::constructor_template); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "addWatch", Inotify::AddWatch); NODE_SET_PROTOTYPE_METHOD(t, "removeWatch", Inotify::RemoveWatch); NODE_SET_PROTOTYPE_METHOD(t, "close", Inotify::Close); //Constants initialization NODE_DEFINE_CONSTANT(t, IN_ACCESS); //File was accessed (read) NODE_DEFINE_CONSTANT(t, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps, //extended attributes, link count (since Linux 2.6.25), //UID, GID, etc. NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); //File opened for writing was closed NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); //File not opened for writing was closed NODE_DEFINE_CONSTANT(t, IN_CREATE); //File/directory created in watched directory NODE_DEFINE_CONSTANT(t, IN_DELETE); //File/directory deleted from watched directory NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); //Watched file/directory was itself deleted NODE_DEFINE_CONSTANT(t, IN_MODIFY); //File was modified NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); //Watched file/directory was itself moved NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); //File moved out of watched directory NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); //File moved into watched directory NODE_DEFINE_CONSTANT(t, IN_OPEN); //File was opened NODE_DEFINE_CONSTANT(t, IN_IGNORED); // Watch was removed explicitly (inotify.watch.rm) or //automatically (file was deleted, or file system was //unmounted) NODE_DEFINE_CONSTANT(t, IN_ISDIR); //Subject of this event is a directory NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event) NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); //File system containing watched object was unmounted NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS); NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); // Only watch the path if it is a directory. NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); // Do not follow a sym link NODE_DEFINE_CONSTANT(t, IN_ONESHOT); // Only send event once NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it //already exists (instead of replacing mask). NODE_DEFINE_CONSTANT(t, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close NODE_DEFINE_CONSTANT(t, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves path_sym = NODE_PSYMBOL("path"); watch_for_sym = NODE_PSYMBOL("watch_for"); callback_sym = NODE_PSYMBOL("callback"); persistent_sym = NODE_PSYMBOL("persistent"); watch_sym = NODE_PSYMBOL("watch"); mask_sym = NODE_PSYMBOL("mask"); cookie_sym = NODE_PSYMBOL("cookie"); name_sym = NODE_PSYMBOL("name"); Local<ObjectTemplate> object_tmpl = t->InstanceTemplate(); object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent); t->SetClassName(String::NewSymbol("Inotify")); target->Set(String::NewSymbol("Inotify"), t->GetFunction()); } Inotify::Inotify() : EventEmitter() { ev_init(&read_watcher, Inotify::Callback); read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback persistent = true; } Inotify::Inotify(bool nonpersistent) : EventEmitter() { ev_init(&read_watcher, Inotify::Callback); read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback persistent = nonpersistent; } Inotify::~Inotify() { if(!persistent) { ev_ref(EV_DEFAULT_UC); } ev_io_stop(EV_DEFAULT_UC_ &read_watcher); assert(!ev_is_active(&read_watcher)); assert(!ev_is_pending(&read_watcher)); } Handle<Value> Inotify::New(const Arguments& args) { HandleScope scope; Inotify *inotify = NULL; if(args.Length() == 1 && args[0]->IsBoolean()) { inotify = new Inotify(args[0]->IsTrue()); } else { inotify = new Inotify(); } inotify->fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); //nonblock //inotify->fd = inotify_init1(IN_CLOEXEC); //block if(inotify->fd == -1) { ThrowException(String::New(strerror(errno))); return Null(); } ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ); ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher); Local<Object> obj = args.This(); inotify->Wrap(obj); if(!inotify->persistent) { ev_unref(EV_DEFAULT_UC); } /*Increment object references to avoid be GCed while I'm waiting for inotify events in th ev_pool. Also, the object is not weak anymore */ inotify->Ref(); return scope.Close(obj); } Handle<Value> Inotify::AddWatch(const Arguments& args) { HandleScope scope; uint32_t mask = 0; int watch_descriptor = 0; if(args.Length() < 1 || !args[0]->IsObject()) { return ThrowException(Exception::TypeError( String::New("You must specify an object as first argument"))); } Local<Object> args_ = args[0]->ToObject(); if(!args_->Has(path_sym)) { return ThrowException(Exception::TypeError( String::New("You must specify a path to watch for events"))); } if(!args_->Has(callback_sym) || !args_->Get(callback_sym)->IsFunction()) { return ThrowException(Exception::TypeError( String::New("You must specify a callback function"))); } if(!args_->Has(watch_for_sym)) { mask |= IN_ALL_EVENTS; } else { if(!args_->Get(watch_for_sym)->IsInt32()) { return ThrowException(Exception::TypeError( String::New("You must specify OR'ed set of events"))); } mask |= args_->Get(watch_for_sym)->Int32Value(); if(mask == 0) { return ThrowException(Exception::TypeError( String::New("You must specify OR'ed set of events"))); } } String::Utf8Value path(args_->Get(path_sym)); Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This()); /* add watch */ watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask); Local<Integer> descriptor = Integer::New(watch_descriptor); //Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym)); inotify->handle_->Set(descriptor, args_->Get(callback_sym)); return scope.Close(descriptor); } Handle<Value> Inotify::RemoveWatch(const Arguments& args) { HandleScope scope; uint32_t watch = 0; int ret = -1; if(args.Length() == 0 || !args[0]->IsInt32()) { return ThrowException(Exception::TypeError( String::New("You must specify a valid watcher descriptor as argument"))); } watch = args[0]->Int32Value(); Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This()); ret = inotify_rm_watch(inotify->fd, watch); if(ret == -1) { ThrowException(String::New(strerror(errno))); return False(); } return True(); } Handle<Value> Inotify::Close(const Arguments& args) { HandleScope scope; int ret = -1; Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This()); ret = close(inotify->fd); if(ret == -1) { ThrowException(String::New(strerror(errno))); return False(); } if(!inotify->persistent) { ev_ref(EV_DEFAULT_UC); } ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher); /*Eliminating reference created inside of Inotify::New. The object is also weak again. Now v8 can do its stuff and GC the object. */ inotify->Unref(); return True(); } void Inotify::Callback(EV_P_ ev_io *watcher, int revents) { HandleScope scope; Inotify *inotify = static_cast<Inotify*>(watcher->data); assert(watcher == &inotify->read_watcher); char buffer[BUF_LEN]; int length = read(inotify->fd, buffer, BUF_LEN); Local<Value> argv[1]; TryCatch try_catch; int i = 0; while (i < length) { struct inotify_event *event; event = (struct inotify_event *) &buffer[i]; Local<Object> obj = Object::New(); obj->Set(watch_sym, Integer::New(event->wd)); obj->Set(mask_sym, Integer::New(event->mask)); obj->Set(cookie_sym, Integer::New(event->cookie)); if(event->len) { obj->Set(name_sym, String::New(event->name)); } argv[0] = obj; inotify->Ref(); Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd)); Local<Function> callback = Local<Function>::Cast(callback_); callback->Call(inotify->handle_, 1, argv); inotify->Unref(); if(event->mask & IN_IGNORED) { //deleting callback because the watch was removed printf("entrooo"); Local<Value> wd = Integer::New(event->wd); inotify->handle_->Delete(wd->ToString()); } if (try_catch.HasCaught()) { FatalException(try_catch); } i += EVENT_SIZE + event->len; } } Handle<Value> Inotify::GetPersistent(Local<String> property, const AccessorInfo& info) { Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This()); return inotify->persistent ? True() : False(); } }//namespace NodeInotify
delete javascript callback when the watch is removed
delete javascript callback when the watch is removed
C++
mit
c4milo/node-inotify,c4milo/node-inotify,edsadr/node-inotify,edsadr/node-inotify,edsadr/node-inotify,c4milo/node-inotify
209311d6431fce09f46d5a4c5f351adaf097f3f1
src/delegate/Stock.cxx
src/delegate/Stock.cxx
/* * Delegate helper pooling. * * author: Max Kellermann <[email protected]> */ #include "Stock.hxx" #include "stock/MapStock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "async.hxx" #include "failure.hxx" #include "system/fd_util.h" #include "event/Event.hxx" #include "event/Callback.hxx" #include "spawn/Spawn.hxx" #include "spawn/Prepared.hxx" #include "spawn/ChildOptions.hxx" #include "gerrno.h" #include "pool.hxx" #include <daemon/log.h> #include <assert.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> struct DelegateArgs { const char *executable_path; const ChildOptions *options; }; struct DelegateProcess final : HeapStockItem { const char *const uri; const pid_t pid; const int fd; Event event; explicit DelegateProcess(CreateStockItem c, const char *_uri, pid_t _pid, int _fd) :HeapStockItem(c), uri(_uri), pid(_pid), fd(_fd) { event.Set(fd, EV_READ|EV_TIMEOUT, MakeEventCallback(DelegateProcess, EventCallback), this); } ~DelegateProcess() override { if (fd >= 0) { event.Delete(); close(fd); } } void EventCallback(int fd, short event); /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { static constexpr struct timeval tv = { .tv_sec = 60, .tv_usec = 0, }; event.Add(tv); return true; } }; /* * libevent callback * */ inline void DelegateProcess::EventCallback(gcc_unused int _fd, short events) { assert(_fd == fd); if ((events & EV_TIMEOUT) == 0) { assert((events & EV_READ) != 0); char buffer; ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle delegate process: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data from idle delegate process\n"); } InvokeIdleDisconnect(); pool_commit(); } /* * stock class * */ static void delegate_stock_create(gcc_unused void *ctx, gcc_unused struct pool &parent_pool, CreateStockItem c, const char *uri, void *_info, gcc_unused struct pool &caller_pool, gcc_unused struct async_operation_ref &async_ref) { auto &info = *(DelegateArgs *)_info; PreparedChildProcess p; p.Append(info.executable_path); GError *error = nullptr; if (!info.options->CopyTo(p, true, nullptr, &error)) { c.InvokeCreateError(error); return; } int fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) { error = new_error_errno_msg("socketpair() failed: %s"); c.InvokeCreateError(error); return; } p.stdin_fd = fds[1]; pid_t pid = SpawnChildProcess(std::move(p)); if (pid < 0) { error = new_error_errno_msg2(-pid, "clone() failed"); close(fds[0]); c.InvokeCreateError(error); return; } auto *process = new DelegateProcess(c, uri, pid, fds[0]); process->InvokeCreateSuccess(); } static constexpr StockClass delegate_stock_class = { .create = delegate_stock_create, }; /* * interface * */ StockMap * delegate_stock_new(struct pool *pool) { return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16); } StockItem * delegate_stock_get(StockMap *delegate_stock, struct pool *pool, const char *helper, const ChildOptions &options, GError **error_r) { const char *uri = helper; char options_buffer[4096]; *options.MakeId(options_buffer) = 0; if (*options_buffer != 0) uri = p_strcat(pool, helper, "|", options_buffer, nullptr); DelegateArgs args; args.executable_path = helper; args.options = &options; return hstock_get_now(*delegate_stock, *pool, uri, &args, error_r); } void delegate_stock_put(StockMap *delegate_stock, StockItem &item, bool destroy) { auto *process = (DelegateProcess *)&item; hstock_put(*delegate_stock, process->uri, item, destroy); } int delegate_stock_item_get(StockItem &item) { auto *process = (DelegateProcess *)&item; return process->fd; }
/* * Delegate helper pooling. * * author: Max Kellermann <[email protected]> */ #include "Stock.hxx" #include "stock/MapStock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "async.hxx" #include "failure.hxx" #include "system/fd_util.h" #include "event/Event.hxx" #include "event/Callback.hxx" #include "spawn/Spawn.hxx" #include "spawn/Prepared.hxx" #include "spawn/ChildOptions.hxx" #include "gerrno.h" #include "pool.hxx" #include <daemon/log.h> #include <assert.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> struct DelegateArgs { const char *executable_path; const ChildOptions *options; DelegateArgs(const char *_executable_path, const ChildOptions &_options) :executable_path(_executable_path), options(&_options) {} }; struct DelegateProcess final : HeapStockItem { const char *const uri; const pid_t pid; const int fd; Event event; explicit DelegateProcess(CreateStockItem c, const char *_uri, pid_t _pid, int _fd) :HeapStockItem(c), uri(_uri), pid(_pid), fd(_fd) { event.Set(fd, EV_READ|EV_TIMEOUT, MakeEventCallback(DelegateProcess, EventCallback), this); } ~DelegateProcess() override { if (fd >= 0) { event.Delete(); close(fd); } } void EventCallback(int fd, short event); /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { static constexpr struct timeval tv = { .tv_sec = 60, .tv_usec = 0, }; event.Add(tv); return true; } }; /* * libevent callback * */ inline void DelegateProcess::EventCallback(gcc_unused int _fd, short events) { assert(_fd == fd); if ((events & EV_TIMEOUT) == 0) { assert((events & EV_READ) != 0); char buffer; ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle delegate process: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data from idle delegate process\n"); } InvokeIdleDisconnect(); pool_commit(); } /* * stock class * */ static void delegate_stock_create(gcc_unused void *ctx, gcc_unused struct pool &parent_pool, CreateStockItem c, const char *uri, void *_info, gcc_unused struct pool &caller_pool, gcc_unused struct async_operation_ref &async_ref) { auto &info = *(DelegateArgs *)_info; PreparedChildProcess p; p.Append(info.executable_path); GError *error = nullptr; if (!info.options->CopyTo(p, true, nullptr, &error)) { c.InvokeCreateError(error); return; } int fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) { error = new_error_errno_msg("socketpair() failed: %s"); c.InvokeCreateError(error); return; } p.stdin_fd = fds[1]; pid_t pid = SpawnChildProcess(std::move(p)); if (pid < 0) { error = new_error_errno_msg2(-pid, "clone() failed"); close(fds[0]); c.InvokeCreateError(error); return; } auto *process = new DelegateProcess(c, uri, pid, fds[0]); process->InvokeCreateSuccess(); } static constexpr StockClass delegate_stock_class = { .create = delegate_stock_create, }; /* * interface * */ StockMap * delegate_stock_new(struct pool *pool) { return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16); } StockItem * delegate_stock_get(StockMap *delegate_stock, struct pool *pool, const char *helper, const ChildOptions &options, GError **error_r) { const char *uri = helper; char options_buffer[4096]; *options.MakeId(options_buffer) = 0; if (*options_buffer != 0) uri = p_strcat(pool, helper, "|", options_buffer, nullptr); DelegateArgs args(helper, options); return hstock_get_now(*delegate_stock, *pool, uri, &args, error_r); } void delegate_stock_put(StockMap *delegate_stock, StockItem &item, bool destroy) { auto *process = (DelegateProcess *)&item; hstock_put(*delegate_stock, process->uri, item, destroy); } int delegate_stock_item_get(StockItem &item) { auto *process = (DelegateProcess *)&item; return process->fd; }
add DelegateArgs constructor
delegate/Stock: add DelegateArgs constructor
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
0b2cbb764effd880230f4134d9872a5db201d807
src/dev/arm/rv_ctrl.cc
src/dev/arm/rv_ctrl.cc
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi */ #include "base/trace.hh" #include "dev/arm/rv_ctrl.hh" #include "mem/packet.hh" #include "mem/packet_access.hh" RealViewCtrl::RealViewCtrl(Params *p) : BasicPioDevice(p) { pioSize = 0xD4; } Tick RealViewCtrl::read(PacketPtr pkt) { assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize); assert(pkt->getSize() == 4); Addr daddr = pkt->getAddr() - pioAddr; pkt->allocate(); switch(daddr) { case ProcId: pkt->set(params()->proc_id); break; case Clock24: Tick clk; clk = (Tick)(curTick() / (24 * SimClock::Float::MHz)); pkt->set((uint32_t)(clk)); break; case Flash: pkt->set<uint32_t>(0); break; case Clcd: pkt->set<uint32_t>(0x00001F00); break; case Osc0: pkt->set<uint32_t>(0x00012C5C); break; case Osc1: pkt->set<uint32_t>(0x00002CC0); break; case Osc2: pkt->set<uint32_t>(0x00002C75); break; case Osc3: pkt->set<uint32_t>(0x00020211); break; case Osc4: pkt->set<uint32_t>(0x00002C75); break; case Lock: pkt->set<uint32_t>(sysLock); break; default: panic("Tried to read RealView I/O at offset %#x that doesn't exist\n", daddr); break; } pkt->makeAtomicResponse(); return pioDelay; } Tick RealViewCtrl::write(PacketPtr pkt) { assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize); Addr daddr = pkt->getAddr() - pioAddr; switch (daddr) { case Flash: case Clcd: case Osc0: case Osc1: case Osc2: case Osc3: case Osc4: break; case Lock: sysLock.lockVal = pkt->get<uint16_t>(); break; default: panic("Tried to write RVIO at offset %#x that doesn't exist\n", daddr); break; } pkt->makeAtomicResponse(); return pioDelay; } void RealViewCtrl::serialize(std::ostream &os) { } void RealViewCtrl::unserialize(Checkpoint *cp, const std::string &section) { } RealViewCtrl * RealViewCtrlParams::create() { return new RealViewCtrl(this); }
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi */ #include "base/trace.hh" #include "dev/arm/rv_ctrl.hh" #include "mem/packet.hh" #include "mem/packet_access.hh" RealViewCtrl::RealViewCtrl(Params *p) : BasicPioDevice(p) { pioSize = 0xD4; } Tick RealViewCtrl::read(PacketPtr pkt) { assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize); assert(pkt->getSize() == 4); Addr daddr = pkt->getAddr() - pioAddr; pkt->allocate(); switch(daddr) { case ProcId: pkt->set(params()->proc_id); break; case Clock24: Tick clk; clk = (Tick)(curTick() / (24 * SimClock::Float::MHz)); pkt->set((uint32_t)(clk)); break; case Clock100: Tick clk100; clk100 = (Tick)(curTick() / (100 * SimClock::Float::MHz)); pkt->set((uint32_t)(clk100)); break; case Flash: pkt->set<uint32_t>(0); break; case Clcd: pkt->set<uint32_t>(0x00001F00); break; case Osc0: pkt->set<uint32_t>(0x00012C5C); break; case Osc1: pkt->set<uint32_t>(0x00002CC0); break; case Osc2: pkt->set<uint32_t>(0x00002C75); break; case Osc3: pkt->set<uint32_t>(0x00020211); break; case Osc4: pkt->set<uint32_t>(0x00002C75); break; case Lock: pkt->set<uint32_t>(sysLock); break; default: panic("Tried to read RealView I/O at offset %#x that doesn't exist\n", daddr); break; } pkt->makeAtomicResponse(); return pioDelay; } Tick RealViewCtrl::write(PacketPtr pkt) { assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize); Addr daddr = pkt->getAddr() - pioAddr; switch (daddr) { case Flash: case Clcd: case Osc0: case Osc1: case Osc2: case Osc3: case Osc4: break; case Lock: sysLock.lockVal = pkt->get<uint16_t>(); break; default: panic("Tried to write RVIO at offset %#x that doesn't exist\n", daddr); break; } pkt->makeAtomicResponse(); return pioDelay; } void RealViewCtrl::serialize(std::ostream &os) { } void RealViewCtrl::unserialize(Checkpoint *cp, const std::string &section) { } RealViewCtrl * RealViewCtrlParams::create() { return new RealViewCtrl(this); }
Add support for read of 100MHz clock in system controller.
ARM: Add support for read of 100MHz clock in system controller.
C++
bsd-3-clause
haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5
22474c1a961da2ed348d271c8d4fec4bdbea0958
test/UnitTests/src/App/ProjectTest.cpp
test/UnitTests/src/App/ProjectTest.cpp
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015-2019 OSRE ( Open Source Render Engine ) by Kim Kulling 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 <gtest/gtest.h> #include <osre/App/Project.h> #include <osre/IO/Directory.h> namespace OSRE { namespace UnitTest { using namespace ::OSRE::App; using namespace ::OSRE::IO; class ProjectTest : public ::testing::Test { // empty }; TEST_F(ProjectTest, createTest) { bool ok(true); try { Project myProject; } catch (...) { ok = false; } EXPECT_TRUE(ok); } TEST_F(ProjectTest, loadsaveTest) { Project myProject; bool res(true); // Not created must return false String oldPath, newPath; oldPath = Directory::getCurrentDirectory(); res = myProject.save("test", 0); EXPECT_FALSE(res); //// Save test //// // Created must return true res = myProject.create("test", 0, 1); EXPECT_TRUE(res); res = myProject.save("test", 0); EXPECT_TRUE(res); newPath = Directory::getCurrentDirectory(); EXPECT_EQ(oldPath, newPath); //// Load test //// Project myProject1; i32 major(-1), minor(-1); oldPath = Directory::getCurrentDirectory(); res = myProject1.load("test", major, minor, 0); EXPECT_TRUE(res); newPath = Directory::getCurrentDirectory(); EXPECT_EQ(oldPath, newPath); EXPECT_EQ(0, myProject1.getMajorVersion()); EXPECT_EQ(1, myProject1.getMinorVersion()); } } }
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015-2019 OSRE ( Open Source Render Engine ) by Kim Kulling 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 <gtest/gtest.h> #include <osre/App/Project.h> #include <osre/Common/osre_common.h> #include <osre/IO/Directory.h> namespace OSRE { namespace UnitTest { using namespace ::OSRE::App; using namespace ::OSRE::IO; class ProjectTest : public ::testing::Test { // empty }; TEST_F(ProjectTest, createTest) { bool ok(true); try { Project myProject; } catch (...) { ok = false; } EXPECT_TRUE(ok); } TEST_F(ProjectTest, loadsaveTest) { Project myProject; bool res(true); // Not created must return false String oldPath, newPath; oldPath = Directory::getCurrentDirectory(); res = myProject.save("test", 0); EXPECT_FALSE(res); //// Save test //// // Created must return true res = myProject.create("test", 0, 1); EXPECT_TRUE(res); res = myProject.save("test", 0); EXPECT_TRUE(res); newPath = Directory::getCurrentDirectory(); EXPECT_EQ(oldPath, newPath); //// Load test //// Project myProject1; i32 majorVersion(-1), minorVersion(-1); oldPath = Directory::getCurrentDirectory(); res = myProject1.load("test", majorVersion, minorVersion, 0); EXPECT_TRUE(res); newPath = Directory::getCurrentDirectory(); EXPECT_EQ(oldPath, newPath); EXPECT_EQ(0, myProject1.getMajorVersion()); EXPECT_EQ(1, myProject1.getMinorVersion()); } } }
Replace predefine gnu-variables.
Replace predefine gnu-variables.
C++
mit
kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre,kimkulling/osre
4a0ef89e1086362558d0aba04d55fc8ccf16c59e
test/cpp/asyncprogressworkersignal.cpp
test/cpp/asyncprogressworkersignal.cpp
/********************************************************************* * NAN - Native Abstractions for Node.js * * Copyright (c) 2016 NAN contributors * * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> ********************************************************************/ #ifndef _WIN32 #include <unistd.h> #define Sleep(x) usleep((x)*1000) #endif #include <nan.h> using namespace Nan; // NOLINT(build/namespaces) class ProgressWorker : public AsyncProgressWorker { public: ProgressWorker( Callback *callback , Callback *progress , int milliseconds , int iters) : AsyncProgressWorker(callback), progress(progress) , milliseconds(milliseconds), iters(iters) {} ~ProgressWorker() {} void Execute (const AsyncProgressWorker::ExecutionProgress& progress) { for (int i = 0; i < iters; ++i) { progress.Signal(); Sleep(milliseconds); } } void HandleProgressCallback(const char *data, size_t size) { HandleScope scope; v8::Local<v8::Value> arg = New<v8::Boolean>(data == NULL && size == 0); progress->Call(1, &arg); } private: Callback *progress; int milliseconds; int iters; }; NAN_METHOD(DoProgress) { Callback *progress = new Callback(info[2].As<v8::Function>()); Callback *callback = new Callback(info[3].As<v8::Function>()); AsyncQueueWorker(new ProgressWorker( callback , progress , To<uint32_t>(info[0]).FromJust() , To<uint32_t>(info[1]).FromJust())); } NAN_MODULE_INIT(Init) { Set(target , New<v8::String>("a").ToLocalChecked() , New<v8::FunctionTemplate>(DoProgress)->GetFunction()); } NODE_MODULE(asyncprogressworker, Init)
/********************************************************************* * NAN - Native Abstractions for Node.js * * Copyright (c) 2016 NAN contributors * * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> ********************************************************************/ #ifndef _WIN32 #include <unistd.h> #define Sleep(x) usleep((x)*1000) #endif #include <nan.h> using namespace Nan; // NOLINT(build/namespaces) class ProgressWorker : public AsyncProgressWorker { public: ProgressWorker( Callback *callback , Callback *progress , int milliseconds , int iters) : AsyncProgressWorker(callback), progress(progress) , milliseconds(milliseconds), iters(iters) {} ~ProgressWorker() {} void Execute (const AsyncProgressWorker::ExecutionProgress& progress) { for (int i = 0; i < iters; ++i) { progress.Signal(); Sleep(milliseconds); } } void HandleProgressCallback(const char *data, size_t size) { HandleScope scope; v8::Local<v8::Value> arg = New<v8::Boolean>(data == NULL && size == 0); progress->Call(1, &arg); } private: Callback *progress; int milliseconds; int iters; }; NAN_METHOD(DoProgress) { Callback *progress = new Callback(info[2].As<v8::Function>()); Callback *callback = new Callback(info[3].As<v8::Function>()); AsyncQueueWorker(new ProgressWorker( callback , progress , To<uint32_t>(info[0]).FromJust() , To<uint32_t>(info[1]).FromJust())); } NAN_MODULE_INIT(Init) { Set(target , New<v8::String>("a").ToLocalChecked() , New<v8::FunctionTemplate>(DoProgress)->GetFunction()); } NODE_MODULE(asyncprogressworkersignal, Init)
Fix broken test
Fix broken test
C++
mit
gagern/nan,nodejs/nan,eljefedelrodeodeljefe/nan,nodejs/nan,nodejs/nan,eljefedelrodeodeljefe/nan,gagern/nan,nodejs/nan,gagern/nan,eljefedelrodeodeljefe/nan,eljefedelrodeodeljefe/nan
5f20fd8b3355243f110840001b2505cdaf71d5c8
test/test_signature/test_signature.cpp
test/test_signature/test_signature.cpp
/* ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2010 Aldebaran Robotics */ #include <gtest/gtest.h> #include <alcommon-ng/functor/functionsignature.hpp> #include <alcommon-ng/functor/typesignature.hpp> //#include <alcommon-ng/tools/dataperftimer.hpp> #include <vector> #include <map> static const int gLoopCount = 1000000; static int gGlobalResult = 0; void vfun0() { gGlobalResult = 0; } void vfun1(const int &p0) { gGlobalResult = p0; } void vfun2(const int &p0,const int &p1) { gGlobalResult = p0 + p1; } void vfun3(const int &p0,const int &p1,const int &p2) { gGlobalResult = p0 + p1 + p2; } void vfun4(const int &p0,const int &p1,const int &p2,const int &p3) { gGlobalResult = p0 + p1 + p2 + p3; } void vfun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { gGlobalResult = p0 + p1 + p2 + p3 + p4; } void vfun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { gGlobalResult = p0 + p1 + p2 + p3 + p4 + p5; } int fun0() { return 0; } int fun1(const int &p0) { return p0; } int fun2(const int &p0,const int &p1) { return p0 + p1; } int fun3(const int &p0,const int &p1,const int &p2) { return p0 + p1 + p2; } int fun4(const int &p0,const int &p1,const int &p2,const int &p3) { return p0 + p1 + p2 + p3; } int fun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { return p0 + p1 + p2 + p3 + p4; } int fun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { return p0 + p1 + p2 + p3 + p4 + p5; } struct Foo { void voidCall() { return; } int intStringCall(const std::string &plouf) { return plouf.size(); } int fun0() { return 0; } int fun1(const int &p0) { return p0; } int fun2(const int &p0,const int &p1) { return p0 + p1; } int fun3(const int &p0,const int &p1,const int &p2) { return p0 + p1 + p2; } int fun4(const int &p0,const int &p1,const int &p2,const int &p3) { return p0 + p1 + p2 + p3; } int fun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { return p0 + p1 + p2 + p3 + p4; } int fun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { return p0 + p1 + p2 + p3 + p4 + p5; } void vfun0() { gGlobalResult = 0; } void vfun1(const int &p0) { gGlobalResult = p0; } void vfun2(const int &p0,const int &p1) { gGlobalResult = p0 + p1; } void vfun3(const int &p0,const int &p1,const int &p2) { gGlobalResult = p0 + p1 + p2; } void vfun4(const int &p0,const int &p1,const int &p2,const int &p3) { gGlobalResult = p0 + p1 + p2 + p3; } void vfun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { gGlobalResult = p0 + p1 + p2 + p3 + p4; } void vfun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { gGlobalResult = p0 + p1 + p2 + p3 + p4 + p5; } }; TEST(TestSignature, BasicTypeSignature) { EXPECT_EQ("b", AL::typeSignatureWithCopy<bool>::value()); EXPECT_EQ("i", AL::typeSignatureWithCopy<int>::value()); EXPECT_EQ("f", AL::typeSignatureWithCopy<float>::value()); EXPECT_EQ("d", AL::typeSignatureWithCopy<double>::value()); EXPECT_EQ("s", AL::typeSignatureWithCopy<std::string>::value()); EXPECT_EQ("[i]", AL::typeSignatureWithCopy< std::vector<int> >::value()); typedef std::map<int,int> MapInt; EXPECT_EQ("{ii}", AL::typeSignatureWithCopy< MapInt >::value() ); EXPECT_EQ("b#", AL::typeSignatureWithCopy<const bool>::value()); EXPECT_EQ("i#", AL::typeSignatureWithCopy<const int>::value()); EXPECT_EQ("f#", AL::typeSignatureWithCopy<const float>::value()); EXPECT_EQ("d#", AL::typeSignatureWithCopy<const double>::value()); EXPECT_EQ("s#", AL::typeSignatureWithCopy<const std::string>::value()); EXPECT_EQ("[i]#", AL::typeSignatureWithCopy<const std::vector< int > >::value()); EXPECT_EQ("{ii}#", AL::typeSignatureWithCopy<const MapInt >::value()); EXPECT_EQ("b#*", AL::typeSignatureWithCopy<const bool*>::value()); EXPECT_EQ("i#*", AL::typeSignatureWithCopy<const int*>::value()); EXPECT_EQ("f#*", AL::typeSignatureWithCopy<const float*>::value()); EXPECT_EQ("d#*", AL::typeSignatureWithCopy<const double*>::value()); EXPECT_EQ("s#*", AL::typeSignatureWithCopy<const std::string*>::value()); EXPECT_EQ("[i]#*", AL::typeSignatureWithCopy<const std::vector< int >* >::value()); EXPECT_EQ("{ii}#*",AL::typeSignatureWithCopy<const MapInt* >::value()); EXPECT_EQ("b#&", AL::typeSignatureWithCopy<const bool&>::value()); EXPECT_EQ("i#&", AL::typeSignatureWithCopy<const int&>::value()); EXPECT_EQ("f#&", AL::typeSignatureWithCopy<const float&>::value()); EXPECT_EQ("d#&", AL::typeSignatureWithCopy<const double&>::value()); EXPECT_EQ("s#&", AL::typeSignatureWithCopy<const std::string&>::value()); EXPECT_EQ("[i]#&", AL::typeSignatureWithCopy<const std::vector< int >& >::value()); EXPECT_EQ("{ii}#&", AL::typeSignatureWithCopy<const MapInt& >::value()); //ERROR EXPECT_EQ("UNKNOWN", AL::typeSignatureWithCopy<short>::value()); } TEST(TestSignature, ComplexTypeSignature) { typedef std::map<int,int> MapInt; //{ii} typedef std::map<MapInt,MapInt> MapInt2; //{{ii}{ii}} typedef std::map<std::vector<MapInt2>, std::vector<const std::vector<MapInt2&> > > FuckinMap; //{[{{ii}{ii}}][[{{ii}{ii}}&]#]} //and obama said: Yes We Can! EXPECT_EQ("{[{{ii}{ii}}][[{{ii}{ii}}&]#]}" , AL::typeSignatureWithCopy<FuckinMap>::value()); } TEST(TestSignature, BasicVoidFunctionSignature) { EXPECT_EQ("v:" , AL::functionSignature(&vfun0)); EXPECT_EQ("v:i" , AL::functionSignature(&vfun1)); EXPECT_EQ("v:ii" , AL::functionSignature(&vfun2)); EXPECT_EQ("v:iii" , AL::functionSignature(&vfun3)); EXPECT_EQ("v:iiii" , AL::functionSignature(&vfun4)); EXPECT_EQ("v:iiiii" , AL::functionSignature(&vfun5)); EXPECT_EQ("v:iiiiii", AL::functionSignature(&vfun6)); } TEST(TestSignature, BasicFunctionSignature) { EXPECT_EQ("i:" , AL::functionSignature(&fun0)); EXPECT_EQ("i:i" , AL::functionSignature(&fun1)); EXPECT_EQ("i:ii" , AL::functionSignature(&fun2)); EXPECT_EQ("i:iii" , AL::functionSignature(&fun3)); EXPECT_EQ("i:iiii" , AL::functionSignature(&fun4)); EXPECT_EQ("i:iiiii" , AL::functionSignature(&fun5)); EXPECT_EQ("i:iiiiii", AL::functionSignature(&fun6)); } TEST(TestSignature, BasicVoidMemberSignature) { EXPECT_EQ("v:" , AL::functionSignature(&Foo::vfun0)); EXPECT_EQ("v:i" , AL::functionSignature(&Foo::vfun1)); EXPECT_EQ("v:ii" , AL::functionSignature(&Foo::vfun2)); EXPECT_EQ("v:iii" , AL::functionSignature(&Foo::vfun3)); EXPECT_EQ("v:iiii" , AL::functionSignature(&Foo::vfun4)); EXPECT_EQ("v:iiiii" , AL::functionSignature(&Foo::vfun5)); EXPECT_EQ("v:iiiiii", AL::functionSignature(&Foo::vfun6)); } TEST(TestSignature, BasicMemberSignature) { EXPECT_EQ("i:" , AL::functionSignature(&Foo::fun0)); EXPECT_EQ("i:i" , AL::functionSignature(&Foo::fun1)); EXPECT_EQ("i:ii" , AL::functionSignature(&Foo::fun2)); EXPECT_EQ("i:iii" , AL::functionSignature(&Foo::fun3)); EXPECT_EQ("i:iiii" , AL::functionSignature(&Foo::fun4)); EXPECT_EQ("i:iiiii" , AL::functionSignature(&Foo::fun5)); EXPECT_EQ("i:iiiiii", AL::functionSignature(&Foo::fun6)); }
/* ** Author(s): ** - Cedric GESTES <[email protected]> ** ** Copyright (C) 2010 Aldebaran Robotics */ #include <gtest/gtest.h> #include <alcommon-ng/functor/functionsignature.hpp> #include <alcommon-ng/functor/typesignature.hpp> //#include <alcommon-ng/tools/dataperftimer.hpp> #include <vector> #include <map> static const int gLoopCount = 1000000; static int gGlobalResult = 0; void vfun0() { gGlobalResult = 0; } void vfun1(const int &p0) { gGlobalResult = p0; } void vfun2(const int &p0,const int &p1) { gGlobalResult = p0 + p1; } void vfun3(const int &p0,const int &p1,const int &p2) { gGlobalResult = p0 + p1 + p2; } void vfun4(const int &p0,const int &p1,const int &p2,const int &p3) { gGlobalResult = p0 + p1 + p2 + p3; } void vfun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { gGlobalResult = p0 + p1 + p2 + p3 + p4; } void vfun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { gGlobalResult = p0 + p1 + p2 + p3 + p4 + p5; } int fun0() { return 0; } int fun1(const int &p0) { return p0; } int fun2(const int &p0,const int &p1) { return p0 + p1; } int fun3(const int &p0,const int &p1,const int &p2) { return p0 + p1 + p2; } int fun4(const int &p0,const int &p1,const int &p2,const int &p3) { return p0 + p1 + p2 + p3; } int fun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { return p0 + p1 + p2 + p3 + p4; } int fun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { return p0 + p1 + p2 + p3 + p4 + p5; } struct Foo { void voidCall() { return; } int intStringCall(const std::string &plouf) { return plouf.size(); } int fun0() { return 0; } int fun1(const int &p0) { return p0; } int fun2(const int &p0,const int &p1) { return p0 + p1; } int fun3(const int &p0,const int &p1,const int &p2) { return p0 + p1 + p2; } int fun4(const int &p0,const int &p1,const int &p2,const int &p3) { return p0 + p1 + p2 + p3; } int fun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { return p0 + p1 + p2 + p3 + p4; } int fun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { return p0 + p1 + p2 + p3 + p4 + p5; } void vfun0() { gGlobalResult = 0; } void vfun1(const int &p0) { gGlobalResult = p0; } void vfun2(const int &p0,const int &p1) { gGlobalResult = p0 + p1; } void vfun3(const int &p0,const int &p1,const int &p2) { gGlobalResult = p0 + p1 + p2; } void vfun4(const int &p0,const int &p1,const int &p2,const int &p3) { gGlobalResult = p0 + p1 + p2 + p3; } void vfun5(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4) { gGlobalResult = p0 + p1 + p2 + p3 + p4; } void vfun6(const int &p0,const int &p1,const int &p2,const int &p3,const int &p4,const int &p5) { gGlobalResult = p0 + p1 + p2 + p3 + p4 + p5; } }; TEST(TestSignature, BasicTypeSignature) { EXPECT_EQ("b", AL::typeSignatureWithCopy<bool>::value()); EXPECT_EQ("i", AL::typeSignatureWithCopy<int>::value()); EXPECT_EQ("f", AL::typeSignatureWithCopy<float>::value()); EXPECT_EQ("d", AL::typeSignatureWithCopy<double>::value()); EXPECT_EQ("s", AL::typeSignatureWithCopy<std::string>::value()); EXPECT_EQ("[i]", AL::typeSignatureWithCopy< std::vector<int> >::value()); typedef std::map<int,int> MapInt; EXPECT_EQ("{ii}", AL::typeSignatureWithCopy< MapInt >::value() ); EXPECT_EQ("b#", AL::typeSignatureWithCopy<const bool>::value()); EXPECT_EQ("i#", AL::typeSignatureWithCopy<const int>::value()); EXPECT_EQ("f#", AL::typeSignatureWithCopy<const float>::value()); EXPECT_EQ("d#", AL::typeSignatureWithCopy<const double>::value()); EXPECT_EQ("s#", AL::typeSignatureWithCopy<const std::string>::value()); EXPECT_EQ("[i]#", AL::typeSignatureWithCopy<const std::vector< int > >::value()); EXPECT_EQ("{ii}#", AL::typeSignatureWithCopy<const MapInt >::value()); EXPECT_EQ("b#*", AL::typeSignatureWithCopy<const bool*>::value()); EXPECT_EQ("i#*", AL::typeSignatureWithCopy<const int*>::value()); EXPECT_EQ("f#*", AL::typeSignatureWithCopy<const float*>::value()); EXPECT_EQ("d#*", AL::typeSignatureWithCopy<const double*>::value()); EXPECT_EQ("s#*", AL::typeSignatureWithCopy<const std::string*>::value()); EXPECT_EQ("[i]#*", AL::typeSignatureWithCopy<const std::vector< int >* >::value()); EXPECT_EQ("{ii}#*",AL::typeSignatureWithCopy<const MapInt* >::value()); EXPECT_EQ("b#&", AL::typeSignatureWithCopy<const bool&>::value()); EXPECT_EQ("i#&", AL::typeSignatureWithCopy<const int&>::value()); EXPECT_EQ("f#&", AL::typeSignatureWithCopy<const float&>::value()); EXPECT_EQ("d#&", AL::typeSignatureWithCopy<const double&>::value()); EXPECT_EQ("s#&", AL::typeSignatureWithCopy<const std::string&>::value()); EXPECT_EQ("[i]#&", AL::typeSignatureWithCopy<const std::vector< int >& >::value()); EXPECT_EQ("{ii}#&", AL::typeSignatureWithCopy<const MapInt& >::value()); //ERROR EXPECT_EQ("UNKNOWN", AL::typeSignatureWithCopy<short>::value()); } TEST(TestSignature, ComplexTypeSignature) { typedef std::map<int,int> MapInt; //{ii} typedef std::map<MapInt,MapInt> MapInt2; //{{ii}{ii}} typedef std::map<std::vector<MapInt2>, std::vector<const std::vector<MapInt2&> > > FuckinMap; //{[{{ii}{ii}}][[{{ii}{ii}}&]#]} //and obama said: Yes We Can! EXPECT_EQ("{[{{ii}{ii}}][[{{ii}{ii}}&]#]}" , AL::typeSignatureWithCopy<FuckinMap>::value()); } #include <boost/function_types/result_type.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/function_arity.hpp> #include <boost/fusion/algorithm/iteration/for_each.hpp> #include <boost/fusion/include/for_each.hpp> #include <boost/mpl/string.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/int.hpp> //#include <boost/type_traits/is_float.hpp> #include <boost/fusion/include/value_of.hpp> #include <boost/utility.hpp> template <typename T> struct newTypeSignature { typedef boost::mpl::string<'UN', 'KN', 'OW', 'N'> value; }; template <> struct newTypeSignature<void> { typedef boost::mpl::string<'v'> value; }; template <> struct newTypeSignature<bool> { typedef boost::mpl::string<'b'> value; }; template <> struct newTypeSignature<char> { typedef boost::mpl::string<'c'> value; }; template <> struct newTypeSignature<int> { typedef boost::mpl::string<'i'> value; }; //TYPE QUALIFIER template <typename T> struct newTypeSignature<T*> { typedef typename boost::mpl::copy<boost::mpl::string<'*'>::type, boost::mpl::back_inserter< typename newTypeSignature<T>::value > >::type value; }; template <typename T> struct newTypeSignature<T&> { typedef typename boost::mpl::copy<boost::mpl::string<'&'>::type, boost::mpl::back_inserter< typename newTypeSignature<T>::value > >::type value; }; template <typename T> struct newTypeSignature<const T> { typedef typename boost::mpl::copy<boost::mpl::string<'#'>::type, boost::mpl::back_inserter< typename newTypeSignature<T>::value > >::type value; }; template <typename F> struct newFunctionSignature { typedef typename newTypeSignature< typename boost::function_types::result_type<F>::type >::value returnValue; typedef typename boost::mpl::copy<boost::mpl::string<':'>::type, boost::mpl::back_inserter< returnValue > >::type returnValueColon; typedef typename boost::function_types::parameter_types<F>::type ArgsType; //const int val = boost::function_types::function_arity<F>::value arity; // typedef typename boost::mpl::fold<ArgsType, // typename boost::mpl::string<>, // typename boost::mpl::copy<newTypeSignature< boost::mpl::_2 >::value, // boost::mpl::back_inserter< boost::mpl::_1 > // > // >::type argsValue; typedef typename boost::mpl::iter_fold<ArgsType, typename boost::mpl::string<>, typename boost::mpl::copy<newTypeSignature< typename boost::mpl::deref<boost::mpl::_2 > >::value, boost::mpl::back_inserter< boost::mpl::_1 > > >::type argsValue; // typedef if_< boost::mpl::bigger_than<arity, 0> , // returnValueColon, // typename boost::mpl::copy< newTypeSignature< boost::mpl::at<ArgsType, boost::mpl::int_<1> >::type >::value, // boost::mpl::back_inserter< returnValueColon > // >::type value; typedef typename boost::mpl::copy<argsValue, boost::mpl::back_inserter< returnValueColon > >::type value; // typedef iter_fold< // s // , state // , apply_wrap2< lambda<op>::type, _1, deref<_2> > // >::type t; // typedef begin<s>::type i1; // typedef apply<op,state,i1>::type state1; // typedef next<i1>::type i2; // typedef apply<op,state1,i2>::type state2; // ... // typedef apply<op,staten-1,in>::type staten; // typedef next<in>::type last; // typedef staten t; }; TEST(TestSignature, TOTO) { //boost::function_types<F>:: //boost::remove_pointer<T>::type; std::string sign; typedef newTypeSignature<bool>::value va; std::cout << "new type:" << boost::mpl::c_str<va>::value << std::endl; typedef newFunctionSignature<void (int, bool)>::value funva; std::cout << "new func:" << boost::mpl::c_str<funva>::value << std::endl; typedef boost::mpl::string<'t1'>::type t1; typedef boost::mpl::string<'t2'>::type t2; typedef boost::mpl::push_back<t1, boost::mpl::char_<'3'> >::type t3; typedef boost::mpl::insert_range<t1, boost::mpl::end<t1>::type, t2>::type t4; typedef boost::mpl::string<>::type t5; typedef boost::mpl::copy< t2, boost::mpl::back_inserter< t1 > >::type t6; std::cout << "t1:" << boost::mpl::c_str<t1>::value << std::endl; std::cout << "t2:" << boost::mpl::c_str<t2>::value << std::endl; std::cout << "t :" << boost::mpl::c_str<t3>::value << std::endl; std::cout << "t :" << boost::mpl::c_str<t4>::value << std::endl; std::cout << "t :" << boost::mpl::c_str<t5>::value << std::endl; std::cout << "t6:" << boost::mpl::c_str<t6>::value << std::endl; typedef boost::mpl::vector<long,float,short,double,float,long,long double> types; typedef boost::mpl::fold< types , boost::mpl::int_<0> , boost::mpl::if_< boost::is_float< boost::mpl::_2>, boost::mpl::next< boost::mpl::_1>, boost::mpl::_1 > >::type number_of_floats; BOOST_MPL_ASSERT_RELATION( number_of_floats::value, ==, 4 ); typedef boost::mpl::vector<bool, int, bool> paf; //result_of::value_of< typedef boost::mpl::at<paf, boost::mpl::int_<1> >::type toto; //typedef if_<true_,char,long>::type t1; typedef newTypeSignature< toto >::value res; std::cout << "t1:" << boost::mpl::c_str<res>::value << std::endl; // typedef boost::mpl::fold<types, // boost::mpl::string<>, // boost::mpl::insert_range< boost::mpl::_1, // boost::mpl::end<boost::mpl::_1>::type, // boost::mpl::string<'ca'>::type > // >::type argsValue; typedef boost::mpl::fold<types, typename boost::mpl::string<>, typename boost::mpl::copy< boost::mpl::_2, boost::mpl::back_inserter< boost::mpl::_1 > > >::type argsValue; // typedef begin<s>::type i1; // typedef apply<op,state,i1>::type state1; // typedef next<i1>::type i2; // typedef apply<op,state1,i2>::type state2; // ... // typedef apply<op,staten-1,in>::type staten; // typedef next<in>::type last; // typedef staten t; // typedef list_c<int,5,-1,0,-7,-2,0,-5,4> numbers; // typedef list_c<int,-1,-7,-2,-5> negatives; // typedef reverse_fold< // numbers // , list_c<int> // , if_< less< _2,int_<0> >, push_front<_1,_2,>, _1 > // >::type result; // BOOST_MPL_ASSERT(( equal< negatives,result > )); // using namespace boost::mpl; // typedef vector_c<int,5,-1,0,7,2,0,-5,4> numbers; // typedef iter_fold< // numbers // , begin<numbers>::type // , if_< less< deref<boost::mpl::_1>, deref<boost::mpl::_2> >,boost::mpl::_2,_1 > // >::type max_element_iter; // BOOST_MPL_ASSERT_RELATION( deref<max_element_iter>::type::value, ==, 7 ); } TEST(TestSignature, BasicVoidFunctionSignature) { EXPECT_EQ("v:" , AL::functionSignature(&vfun0)); EXPECT_EQ("v:i" , AL::functionSignature(&vfun1)); EXPECT_EQ("v:ii" , AL::functionSignature(&vfun2)); EXPECT_EQ("v:iii" , AL::functionSignature(&vfun3)); EXPECT_EQ("v:iiii" , AL::functionSignature(&vfun4)); EXPECT_EQ("v:iiiii" , AL::functionSignature(&vfun5)); EXPECT_EQ("v:iiiiii", AL::functionSignature(&vfun6)); } TEST(TestSignature, BasicFunctionSignature) { EXPECT_EQ("i:" , AL::functionSignature(&fun0)); EXPECT_EQ("i:i" , AL::functionSignature(&fun1)); EXPECT_EQ("i:ii" , AL::functionSignature(&fun2)); EXPECT_EQ("i:iii" , AL::functionSignature(&fun3)); EXPECT_EQ("i:iiii" , AL::functionSignature(&fun4)); EXPECT_EQ("i:iiiii" , AL::functionSignature(&fun5)); EXPECT_EQ("i:iiiiii", AL::functionSignature(&fun6)); } TEST(TestSignature, BasicVoidMemberSignature) { EXPECT_EQ("v:" , AL::functionSignature(&Foo::vfun0)); EXPECT_EQ("v:i" , AL::functionSignature(&Foo::vfun1)); EXPECT_EQ("v:ii" , AL::functionSignature(&Foo::vfun2)); EXPECT_EQ("v:iii" , AL::functionSignature(&Foo::vfun3)); EXPECT_EQ("v:iiii" , AL::functionSignature(&Foo::vfun4)); EXPECT_EQ("v:iiiii" , AL::functionSignature(&Foo::vfun5)); EXPECT_EQ("v:iiiiii", AL::functionSignature(&Foo::vfun6)); } TEST(TestSignature, BasicMemberSignature) { EXPECT_EQ("i:" , AL::functionSignature(&Foo::fun0)); EXPECT_EQ("i:i" , AL::functionSignature(&Foo::fun1)); EXPECT_EQ("i:ii" , AL::functionSignature(&Foo::fun2)); EXPECT_EQ("i:iii" , AL::functionSignature(&Foo::fun3)); EXPECT_EQ("i:iiii" , AL::functionSignature(&Foo::fun4)); EXPECT_EQ("i:iiiii" , AL::functionSignature(&Foo::fun5)); EXPECT_EQ("i:iiiiii", AL::functionSignature(&Foo::fun6)); }
test boost::mpl
test boost::mpl
C++
bsd-3-clause
aldebaran/libqi,aldebaran/libqi-java,aldebaran/libqi-java,bsautron/libqi,aldebaran/libqi,aldebaran/libqi,aldebaran/libqi-java,vbarbaresi/libqi
c1fe4422bd1c1250982f46ce8482cdce65a32fb8
sum_integrated_quantities.cpp
sum_integrated_quantities.cpp
#include <iomanip> #include <Castro.H> #include <Castro_F.H> #include <Geometry.H> void Castro::sum_integrated_quantities () { int finest_level = parent->finestLevel(); Real time = state[State_Type].curTime(); Real mass = 0.0; Real momentum[3] = { 0.0 }; Real rho_E = 0.0; Real rho_e = 0.0; Real rho_phi = 0.0; Real gravitational_energy = 0.0; Real kinetic_energy = 0.0; Real internal_energy = 0.0; Real total_energy = 0.0; Real angular_momentum[3] = { 0.0 }; Real moment_of_inertia[3][3] = { 0.0 }; Real m_r_squared[3] = { 0.0 }; #ifdef ROTATION Real omega[3] = { 0.0, 0.0, 2.0*3.14159265358979*rotational_period }; #endif Real L_grid[3] = { 0.0 }; Real mass_left = 0.0; Real mass_right = 0.0; Real com[3] = { 0.0 }; Real com_l[3] = { 0.0 }; Real com_r[3] = { 0.0 }; Real delta_com[3] = { 0.0 }; Real com_vel[3] = { 0.0 }; Real com_vel_l[3] = { 0.0 }; Real com_vel_r[3] = { 0.0 }; std::string name1; std::string name2; int index1; int index2; int datawidth = 14; int dataprecision = 6; for (int lev = 0; lev <= finest_level; lev++) { // Get the current level from Castro Castro& ca_lev = getLevel(lev); // Calculate center of mass quantities. mass_left += ca_lev.volWgtSumOneSide("density", time, 0, 0); mass_right += ca_lev.volWgtSumOneSide("density", time, 1, 0); for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) { switch ( i ) { case 0 : name1 = "xmom"; break; case 1 : name1 = "ymom"; break; case 2 : name1 = "zmom"; break; } delta_com[i] = ca_lev.locWgtSum("density", time, i); com[i] += delta_com[i]; com_l[i] += ca_lev.locWgtSumOneSide("density", time, i, 0, 0); com_r[i] += ca_lev.locWgtSumOneSide("density", time, i, 1, 0); com_vel_l[i] += ca_lev.volWgtSumOneSide(name1, time, 0, 0); com_vel_r[i] += ca_lev.volWgtSumOneSide(name1, time, 1, 0); } // Calculate total mass, momentum and energy of system. mass += ca_lev.volWgtSum("density", time); momentum[0] += ca_lev.volWgtSum("xmom", time); momentum[1] += ca_lev.volWgtSum("ymom", time); #if (BL_SPACEDIM == 3) momentum[2] += ca_lev.volWgtSum("zmom", time); #endif rho_E += ca_lev.volWgtSum("rho_E", time); rho_e += ca_lev.volWgtSum("rho_e", time); #ifdef GRAVITY if ( do_grav ) { rho_phi += ca_lev.volProductSum("density", "phi", time); } #endif // Calculate total angular momentum on the grid using L = r x p #if (BL_SPACEDIM == 3) for ( int i = 0; i <= 2; i++ ) { index1 = (i+1) % 3; index2 = (i+2) % 3; switch (i) { case 0 : name1 = "ymom"; name2 = "zmom"; break; case 1 : name1 = "zmom"; name2 = "xmom"; break; case 2 : name1 = "xmom"; name2 = "ymom"; break; } L_grid[i] = ca_lev.locWgtSum(name2, time, index1) - ca_lev.locWgtSum(name1, time, index2); angular_momentum[i] += L_grid[i]; } #elif (BL_SPACEDIM == 2) L_grid[2] = ca_lev.locWgtSum("ymom", time, 0) - ca_lev.locWgtSum("xmom", time, 1); #endif // Add rotation source terms #ifdef ROTATION if ( do_rotation ) { // Construct (symmetric) moment of inertia tensor for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) { m_r_squared[i] = ca_lev.locWgtSum2D("density", time, i, i); } for ( int i = 0; i <= 2; i++ ) { for ( int j = 0; j <= 2; j++ ) { if ( i <= j ) { if ( i != j ) { if ( ( i < BL_SPACEDIM ) && ( j < BL_SPACEDIM ) ) // Protect against computing z direction sum in 2D moment_of_inertia[i][j] = -ca_lev.locWgtSum2D("density", time, i, j); } else moment_of_inertia[i][j] = m_r_squared[(i+1)%3] + m_r_squared[(i+2)%3]; } else moment_of_inertia[i][j] = moment_of_inertia[j][i]; } } for ( int i = 0; i <= 2; i++ ) { // Momentum source from motion IN rotating frame == omega x (rho * r) momentum[i] += omega[(i+1)%3]*delta_com[(i+2)%3] - omega[(i+2)%3]*delta_com[(i+1)%3]; // Rotational energy from motion IN rotating frame == omega dot L_grid kinetic_energy += omega[i] * L_grid[i]; // Now add quantities due to motion OF rotating frame for ( int j = 0; j <=2; j++ ) { angular_momentum[i] += moment_of_inertia[i][j] * omega[j]; kinetic_energy += (1.0/2.0) * omega[i] * moment_of_inertia[i][j] * omega[j]; } } } #endif } // Complete calculations for COM quantities Real center = 0.0; for ( int i = 0; i <= 2; i++ ) { center = 0.5*(Geometry::ProbLo(i) + Geometry::ProbHi(i)); com[i] = com[i] / mass + center; com_l[i] = com_l[i] / mass_left + center; com_r[i] = com_r[i] / mass_right + center; com_vel_l[i] = com_vel_l[i] / mass_left; com_vel_r[i] = com_vel_r[i] / mass_right; com_vel[i] = momentum[i] / mass; } const Real* ml = &mass_left; const Real* mr = &mass_right; const Real* cxl = &com_l[0]; const Real* cxr = &com_r[0]; const Real* cyl = &com_l[1]; const Real* cyr = &com_r[1]; const Real* czl = &com_l[2]; const Real* czr = &com_r[2]; BL_FORT_PROC_CALL(COM_SAVE,com_save) (ml, mr, cxl, cxr, cyl, cyr, czl, czr); // Complete calculations for energy gravitational_energy = (-1.0/2.0) * rho_phi; // avoids double counting; CASTRO uses positive phi internal_energy = rho_e; kinetic_energy += rho_E - rho_e; total_energy = gravitational_energy + internal_energy + kinetic_energy; // Write data out to the log. if ( ParallelDescriptor::IOProcessor() ) { // The data log is only defined on the IO processor // for parallel runs, so the stream should only be opened inside. std::ostream& data_log1 = parent->DataLog(0); if ( data_log1.good() ) { // Write header row if (time == 0.0) { data_log1 << std::setw(datawidth) << "# TIME "; data_log1 << std::setw(datawidth) << " MASS "; data_log1 << std::setw(datawidth) << " XMOM "; data_log1 << std::setw(datawidth) << " YMOM "; data_log1 << std::setw(datawidth) << " ZMOM "; data_log1 << std::setw(datawidth) << " KIN. ENERGY "; data_log1 << std::setw(datawidth) << " GRAV. ENERGY"; data_log1 << std::setw(datawidth) << " INT. ENERGY "; data_log1 << std::setw(datawidth) << " TOTAL ENERGY"; data_log1 << std::setw(datawidth) << " ANG. MOM. X "; data_log1 << std::setw(datawidth) << " ANG. MOM. Y "; data_log1 << std::setw(datawidth) << " ANG. MOM. Z "; data_log1 << std::setw(datawidth) << " X COM "; data_log1 << std::setw(datawidth) << " Y COM "; data_log1 << std::setw(datawidth) << " Z COM "; data_log1 << std::setw(datawidth) << " LEFT MASS "; data_log1 << std::setw(datawidth) << " RIGHT MASS "; data_log1 << std::setw(datawidth) << " LEFT X COM "; data_log1 << std::setw(datawidth) << " RIGHT X COM "; data_log1 << std::setw(datawidth) << " LEFT Y COM "; data_log1 << std::setw(datawidth) << " RIGHT Y COM "; data_log1 << std::setw(datawidth) << " LEFT Z COM "; data_log1 << std::setw(datawidth) << " RIGHT Z COM "; data_log1 << std::setw(datawidth) << " X VEL "; data_log1 << std::setw(datawidth) << " Y VEL "; data_log1 << std::setw(datawidth) << " Z VEL "; data_log1 << std::setw(datawidth) << " LEFT X VEL "; data_log1 << std::setw(datawidth) << " RIGHT X VEL "; data_log1 << std::setw(datawidth) << " LEFT Y VEL "; data_log1 << std::setw(datawidth) << " RIGHT Y VEL "; data_log1 << std::setw(datawidth) << " LEFT Z VEL "; data_log1 << std::setw(datawidth) << " RIGHT Z VEL "; data_log1 << std::endl; } // Write data for the present time data_log1 << std::fixed; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << time; data_log1 << std::scientific; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << kinetic_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << gravitational_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << internal_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << total_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_left; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_right; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[2]; data_log1 << std::endl; } } }
#include <iomanip> #include <Castro.H> #include <Castro_F.H> #include <Geometry.H> void Castro::sum_integrated_quantities () { int finest_level = parent->finestLevel(); Real time = state[State_Type].curTime(); Real mass = 0.0; Real momentum[3] = { 0.0 }; Real rho_E = 0.0; Real rho_e = 0.0; Real rho_phi = 0.0; Real gravitational_energy = 0.0; Real kinetic_energy = 0.0; Real internal_energy = 0.0; Real total_energy = 0.0; Real angular_momentum[3] = { 0.0 }; Real moment_of_inertia[3][3] = { 0.0 }; Real m_r_squared[3] = { 0.0 }; #ifdef ROTATION Real omega[3] = { 0.0, 0.0, 2.0*3.14159265358979/rotational_period }; #endif Real L_grid[3] = { 0.0 }; Real mass_left = 0.0; Real mass_right = 0.0; Real com[3] = { 0.0 }; Real com_l[3] = { 0.0 }; Real com_r[3] = { 0.0 }; Real delta_com[3] = { 0.0 }; Real com_vel[3] = { 0.0 }; Real com_vel_l[3] = { 0.0 }; Real com_vel_r[3] = { 0.0 }; std::string name1; std::string name2; int index1; int index2; int datawidth = 14; int dataprecision = 6; for (int lev = 0; lev <= finest_level; lev++) { // Get the current level from Castro Castro& ca_lev = getLevel(lev); // Calculate center of mass quantities. mass_left += ca_lev.volWgtSumOneSide("density", time, 0, 0); mass_right += ca_lev.volWgtSumOneSide("density", time, 1, 0); for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) { switch ( i ) { case 0 : name1 = "xmom"; break; case 1 : name1 = "ymom"; break; case 2 : name1 = "zmom"; break; } delta_com[i] = ca_lev.locWgtSum("density", time, i); com[i] += delta_com[i]; com_l[i] += ca_lev.locWgtSumOneSide("density", time, i, 0, 0); com_r[i] += ca_lev.locWgtSumOneSide("density", time, i, 1, 0); com_vel_l[i] += ca_lev.volWgtSumOneSide(name1, time, 0, 0); com_vel_r[i] += ca_lev.volWgtSumOneSide(name1, time, 1, 0); } // Calculate total mass, momentum and energy of system. mass += ca_lev.volWgtSum("density", time); momentum[0] += ca_lev.volWgtSum("xmom", time); momentum[1] += ca_lev.volWgtSum("ymom", time); #if (BL_SPACEDIM == 3) momentum[2] += ca_lev.volWgtSum("zmom", time); #endif rho_E += ca_lev.volWgtSum("rho_E", time); rho_e += ca_lev.volWgtSum("rho_e", time); #ifdef GRAVITY if ( do_grav ) { rho_phi += ca_lev.volProductSum("density", "phi", time); } #endif // Calculate total angular momentum on the grid using L = r x p #if (BL_SPACEDIM == 3) for ( int i = 0; i <= 2; i++ ) { index1 = (i+1) % 3; index2 = (i+2) % 3; switch (i) { case 0 : name1 = "ymom"; name2 = "zmom"; break; case 1 : name1 = "zmom"; name2 = "xmom"; break; case 2 : name1 = "xmom"; name2 = "ymom"; break; } L_grid[i] = ca_lev.locWgtSum(name2, time, index1) - ca_lev.locWgtSum(name1, time, index2); angular_momentum[i] += L_grid[i]; } #elif (BL_SPACEDIM == 2) L_grid[2] = ca_lev.locWgtSum("ymom", time, 0) - ca_lev.locWgtSum("xmom", time, 1); #endif // Add rotation source terms #ifdef ROTATION if ( do_rotation ) { // Construct (symmetric) moment of inertia tensor for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) { m_r_squared[i] = ca_lev.locWgtSum2D("density", time, i, i); } for ( int i = 0; i <= 2; i++ ) { for ( int j = 0; j <= 2; j++ ) { if ( i <= j ) { if ( i != j ) { if ( ( i < BL_SPACEDIM ) && ( j < BL_SPACEDIM ) ) // Protect against computing z direction sum in 2D moment_of_inertia[i][j] = -ca_lev.locWgtSum2D("density", time, i, j); } else moment_of_inertia[i][j] = m_r_squared[(i+1)%3] + m_r_squared[(i+2)%3]; } else moment_of_inertia[i][j] = moment_of_inertia[j][i]; } } for ( int i = 0; i <= 2; i++ ) { // Momentum source from motion IN rotating frame == omega x (rho * r) momentum[i] += omega[(i+1)%3]*delta_com[(i+2)%3] - omega[(i+2)%3]*delta_com[(i+1)%3]; // Rotational energy from motion IN rotating frame == omega dot L_grid kinetic_energy += omega[i] * L_grid[i]; // Now add quantities due to motion OF rotating frame for ( int j = 0; j <=2; j++ ) { angular_momentum[i] += moment_of_inertia[i][j] * omega[j]; kinetic_energy += (1.0/2.0) * omega[i] * moment_of_inertia[i][j] * omega[j]; } } } #endif } // Complete calculations for COM quantities Real center = 0.0; for ( int i = 0; i <= 2; i++ ) { center = 0.5*(Geometry::ProbLo(i) + Geometry::ProbHi(i)); com[i] = com[i] / mass + center; com_l[i] = com_l[i] / mass_left + center; com_r[i] = com_r[i] / mass_right + center; com_vel_l[i] = com_vel_l[i] / mass_left; com_vel_r[i] = com_vel_r[i] / mass_right; com_vel[i] = momentum[i] / mass; } const Real* ml = &mass_left; const Real* mr = &mass_right; const Real* cxl = &com_l[0]; const Real* cxr = &com_r[0]; const Real* cyl = &com_l[1]; const Real* cyr = &com_r[1]; const Real* czl = &com_l[2]; const Real* czr = &com_r[2]; BL_FORT_PROC_CALL(COM_SAVE,com_save) (ml, mr, cxl, cxr, cyl, cyr, czl, czr); // Complete calculations for energy gravitational_energy = (-1.0/2.0) * rho_phi; // avoids double counting; CASTRO uses positive phi internal_energy = rho_e; kinetic_energy += rho_E - rho_e; total_energy = gravitational_energy + internal_energy + kinetic_energy; // Write data out to the log. if ( ParallelDescriptor::IOProcessor() ) { // The data log is only defined on the IO processor // for parallel runs, so the stream should only be opened inside. std::ostream& data_log1 = parent->DataLog(0); if ( data_log1.good() ) { // Write header row if (time == 0.0) { data_log1 << std::setw(datawidth) << "# TIME "; data_log1 << std::setw(datawidth) << " MASS "; data_log1 << std::setw(datawidth) << " XMOM "; data_log1 << std::setw(datawidth) << " YMOM "; data_log1 << std::setw(datawidth) << " ZMOM "; data_log1 << std::setw(datawidth) << " KIN. ENERGY "; data_log1 << std::setw(datawidth) << " GRAV. ENERGY"; data_log1 << std::setw(datawidth) << " INT. ENERGY "; data_log1 << std::setw(datawidth) << " TOTAL ENERGY"; data_log1 << std::setw(datawidth) << " ANG. MOM. X "; data_log1 << std::setw(datawidth) << " ANG. MOM. Y "; data_log1 << std::setw(datawidth) << " ANG. MOM. Z "; data_log1 << std::setw(datawidth) << " X COM "; data_log1 << std::setw(datawidth) << " Y COM "; data_log1 << std::setw(datawidth) << " Z COM "; data_log1 << std::setw(datawidth) << " LEFT MASS "; data_log1 << std::setw(datawidth) << " RIGHT MASS "; data_log1 << std::setw(datawidth) << " LEFT X COM "; data_log1 << std::setw(datawidth) << " RIGHT X COM "; data_log1 << std::setw(datawidth) << " LEFT Y COM "; data_log1 << std::setw(datawidth) << " RIGHT Y COM "; data_log1 << std::setw(datawidth) << " LEFT Z COM "; data_log1 << std::setw(datawidth) << " RIGHT Z COM "; data_log1 << std::setw(datawidth) << " X VEL "; data_log1 << std::setw(datawidth) << " Y VEL "; data_log1 << std::setw(datawidth) << " Z VEL "; data_log1 << std::setw(datawidth) << " LEFT X VEL "; data_log1 << std::setw(datawidth) << " RIGHT X VEL "; data_log1 << std::setw(datawidth) << " LEFT Y VEL "; data_log1 << std::setw(datawidth) << " RIGHT Y VEL "; data_log1 << std::setw(datawidth) << " LEFT Z VEL "; data_log1 << std::setw(datawidth) << " RIGHT Z VEL "; data_log1 << std::endl; } // Write data for the present time data_log1 << std::fixed; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << time; data_log1 << std::scientific; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << kinetic_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << gravitational_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << internal_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << total_energy; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_left; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_right; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[0]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[1]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[2]; data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[2]; data_log1 << std::endl; } } }
Fix bug in integral diagnostics: omega = 2 * pi / period, not 2 * pi * period.
Fix bug in integral diagnostics: omega = 2 * pi / period, not 2 * pi * period.
C++
mit
BoxLib-Codes/wdmerger,BoxLib-Codes/wdmerger,BoxLib-Codes/wdmerger,BoxLib-Codes/wdmerger
d4b83952c62b41ef1ad61dbec27639f409b9a6b8
src/ConnectionGraphicsObject.cpp
src/ConnectionGraphicsObject.cpp
#include "ConnectionGraphicsObject.hpp" #include <QtWidgets/QGraphicsSceneMouseEvent> #include <QtWidgets/QGraphicsDropShadowEffect> #include <QtWidgets/QGraphicsBlurEffect> #include <QtWidgets/QStyleOptionGraphicsItem> #include <QtWidgets/QGraphicsView> #include "FlowScene.hpp" #include "Connection.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionPainter.hpp" #include "ConnectionState.hpp" #include "ConnectionBlurEffect.hpp" #include "NodeGraphicsObject.hpp" #include "NodeConnectionInteraction.hpp" #include "Node.hpp" using QtNodes::ConnectionGraphicsObject; using QtNodes::Connection; using QtNodes::FlowScene; ConnectionGraphicsObject:: ConnectionGraphicsObject(FlowScene &scene, Connection &connection) : _scene(scene) , _connection(connection) { _scene.addItem(this); setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); setAcceptHoverEvents(true); // addGraphicsEffect(); setZValue(-1.0); } ConnectionGraphicsObject:: ~ConnectionGraphicsObject() { _scene.removeItem(this); } QtNodes::Connection& ConnectionGraphicsObject:: connection() { return _connection; } QRectF ConnectionGraphicsObject:: boundingRect() const { return _connection.connectionGeometry().boundingRect(); } QPainterPath ConnectionGraphicsObject:: shape() const { #ifdef DEBUG_DRAWING //QPainterPath path; //path.addRect(boundingRect()); //return path; #else auto const &geom = _connection.connectionGeometry(); return ConnectionPainter::getPainterStroke(geom); #endif } void ConnectionGraphicsObject:: setGeometryChanged() { prepareGeometryChange(); } void ConnectionGraphicsObject:: move() { for(PortType portType: { PortType::In, PortType::Out } ) { if (auto node = _connection.getNode(portType)) { auto const &nodeGraphics = node->nodeGraphicsObject(); auto const &nodeGeom = node->nodeGeometry(); QPointF scenePos = nodeGeom.portScenePosition(_connection.getPortIndex(portType), portType, nodeGraphics.sceneTransform()); QTransform sceneTransform = this->sceneTransform(); QPointF connectionPos = sceneTransform.inverted().map(scenePos); _connection.connectionGeometry().setEndPoint(portType, connectionPos); _connection.getConnectionGraphicsObject().setGeometryChanged(); _connection.getConnectionGraphicsObject().update(); } } } void ConnectionGraphicsObject::lock(bool locked) { setFlag(QGraphicsItem::ItemIsMovable, !locked); setFlag(QGraphicsItem::ItemIsFocusable, !locked); setFlag(QGraphicsItem::ItemIsSelectable, !locked); } void ConnectionGraphicsObject:: paint(QPainter* painter, QStyleOptionGraphicsItem const* option, QWidget*) { painter->setClipRect(option->exposedRect); ConnectionPainter::paint(painter, _connection); } void ConnectionGraphicsObject:: mousePressEvent(QGraphicsSceneMouseEvent* event) { QGraphicsItem::mousePressEvent(event); //event->ignore(); } void ConnectionGraphicsObject:: mouseMoveEvent(QGraphicsSceneMouseEvent* event) { prepareGeometryChange(); auto view = static_cast<QGraphicsView*>(event->widget()); auto node = locateNodeAt(event->scenePos(), _scene, view->transform()); auto &state = _connection.connectionState(); state.interactWithNode(node); if (node) { node->reactToPossibleConnection(state.requiredPort(), _connection.dataType(oppositePort(state.requiredPort())), event->scenePos()); } //------------------- QPointF offset = event->pos() - event->lastPos(); auto requiredPort = _connection.requiredPort(); if (requiredPort != PortType::None) { _connection.connectionGeometry().moveEndPoint(requiredPort, offset); } //------------------- update(); event->accept(); } void ConnectionGraphicsObject:: mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { ungrabMouse(); event->accept(); auto node = locateNodeAt(event->scenePos(), _scene, _scene.views()[0]->transform()); NodeConnectionInteraction interaction(*node, _connection, _scene); if (node && interaction.tryConnect()) { node->resetReactionToConnection(); } else if (_connection.connectionState().requiresPort()) { _scene.deleteConnection(_connection); } } void ConnectionGraphicsObject:: hoverEnterEvent(QGraphicsSceneHoverEvent* event) { _connection.connectionGeometry().setHovered(true); update(); _scene.connectionHovered(connection(), event->screenPos()); event->accept(); } void ConnectionGraphicsObject:: hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { _connection.connectionGeometry().setHovered(false); update(); _scene.connectionHoverLeft(connection()); event->accept(); } void ConnectionGraphicsObject:: addGraphicsEffect() { auto effect = new QGraphicsBlurEffect; effect->setBlurRadius(5); setGraphicsEffect(effect); //auto effect = new QGraphicsDropShadowEffect; //auto effect = new ConnectionBlurEffect(this); //effect->setOffset(4, 4); //effect->setColor(QColor(Qt::gray).darker(800)); }
#include "ConnectionGraphicsObject.hpp" #include <QtWidgets/QGraphicsSceneMouseEvent> #include <QtWidgets/QGraphicsDropShadowEffect> #include <QtWidgets/QGraphicsBlurEffect> #include <QtWidgets/QStyleOptionGraphicsItem> #include <QtWidgets/QGraphicsView> #include "FlowScene.hpp" #include "Connection.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionPainter.hpp" #include "ConnectionState.hpp" #include "ConnectionBlurEffect.hpp" #include "NodeGraphicsObject.hpp" #include "NodeConnectionInteraction.hpp" #include "Node.hpp" using QtNodes::ConnectionGraphicsObject; using QtNodes::Connection; using QtNodes::FlowScene; ConnectionGraphicsObject:: ConnectionGraphicsObject(FlowScene &scene, Connection &connection) : _scene(scene) , _connection(connection) { _scene.addItem(this); setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); setAcceptHoverEvents(true); // addGraphicsEffect(); setZValue(-1.0); } ConnectionGraphicsObject:: ~ConnectionGraphicsObject() { _scene.removeItem(this); } QtNodes::Connection& ConnectionGraphicsObject:: connection() { return _connection; } QRectF ConnectionGraphicsObject:: boundingRect() const { return _connection.connectionGeometry().boundingRect(); } QPainterPath ConnectionGraphicsObject:: shape() const { #ifdef DEBUG_DRAWING //QPainterPath path; //path.addRect(boundingRect()); //return path; #else auto const &geom = _connection.connectionGeometry(); return ConnectionPainter::getPainterStroke(geom); #endif } void ConnectionGraphicsObject:: setGeometryChanged() { prepareGeometryChange(); } void ConnectionGraphicsObject:: move() { for(PortType portType: { PortType::In, PortType::Out } ) { if (auto node = _connection.getNode(portType)) { auto const &nodeGraphics = node->nodeGraphicsObject(); auto const &nodeGeom = node->nodeGeometry(); QPointF scenePos = nodeGeom.portScenePosition(_connection.getPortIndex(portType), portType, nodeGraphics.sceneTransform()); QTransform sceneTransform = this->sceneTransform(); QPointF connectionPos = sceneTransform.inverted().map(scenePos); _connection.connectionGeometry().setEndPoint(portType, connectionPos); _connection.getConnectionGraphicsObject().setGeometryChanged(); _connection.getConnectionGraphicsObject().update(); } } } void ConnectionGraphicsObject::lock(bool locked) { setFlag(QGraphicsItem::ItemIsMovable, !locked); setFlag(QGraphicsItem::ItemIsFocusable, !locked); setFlag(QGraphicsItem::ItemIsSelectable, !locked); } void ConnectionGraphicsObject:: paint(QPainter* painter, QStyleOptionGraphicsItem const* option, QWidget*) { painter->setClipRect(option->exposedRect); ConnectionPainter::paint(painter, _connection); } void ConnectionGraphicsObject:: mousePressEvent(QGraphicsSceneMouseEvent* event) { QGraphicsItem::mousePressEvent(event); //event->ignore(); } void ConnectionGraphicsObject:: mouseMoveEvent(QGraphicsSceneMouseEvent* event) { prepareGeometryChange(); auto view = static_cast<QGraphicsView*>(event->widget()); auto node = locateNodeAt(event->scenePos(), _scene, view->transform()); auto &state = _connection.connectionState(); state.interactWithNode(node); if (node) { node->reactToPossibleConnection(state.requiredPort(), _connection.dataType(oppositePort(state.requiredPort())), event->scenePos()); } //------------------- QPointF offset = event->pos() - event->lastPos(); auto requiredPort = _connection.requiredPort(); if (requiredPort != PortType::None) { _connection.connectionGeometry().moveEndPoint(requiredPort, offset); } //------------------- update(); event->accept(); } void ConnectionGraphicsObject:: mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { ungrabMouse(); event->accept(); auto node = locateNodeAt(event->scenePos(), _scene, _scene.views()[0]->transform()); if (node) { NodeConnectionInteraction interaction(*node, _connection, _scene); if (interaction.tryConnect()) { node->resetReactionToConnection(); return; } } if (_connection.connectionState().requiresPort()) { _scene.deleteConnection(_connection); } } void ConnectionGraphicsObject:: hoverEnterEvent(QGraphicsSceneHoverEvent* event) { _connection.connectionGeometry().setHovered(true); update(); _scene.connectionHovered(connection(), event->screenPos()); event->accept(); } void ConnectionGraphicsObject:: hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { _connection.connectionGeometry().setHovered(false); update(); _scene.connectionHoverLeft(connection()); event->accept(); } void ConnectionGraphicsObject:: addGraphicsEffect() { auto effect = new QGraphicsBlurEffect; effect->setBlurRadius(5); setGraphicsEffect(effect); //auto effect = new QGraphicsDropShadowEffect; //auto effect = new ConnectionBlurEffect(this); //effect->setOffset(4, 4); //effect->setColor(QColor(Qt::gray).darker(800)); }
Fix dereferencing nullptr (#194)
Fix dereferencing nullptr (#194) Dereferencing nullptr node causes crash on osx’s clang.
C++
bsd-3-clause
paceholder/nodeeditor
c244a601273c7fb332654913c88303aecf9f7374
tests/posit/arithmetic_reciprocate.cpp
tests/posit/arithmetic_reciprocate.cpp
// arithmetic_reciprocate.cpp: functional tests for arithmetic reciprocation // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include "common.hpp" // Configure the posit template environment // first: enable fast specialized posit configurations //#define POSIT_FAST_SPECIALIZATION // second: enable/disable posit arithmetic exceptions #define POSIT_THROW_ARITHMETIC_EXCEPTION 0 // third: enable tracing // when you define POSIT_VERBOSE_OUTPUT executing an reciprocate the code will print intermediate results //#define POSIT_VERBOSE_OUTPUT #define POSIT_TRACE_RECIPROCATE #define POSIT_TRACE_CONVERSION // minimum set of include files to reflect source code dependencies #include "../../posit/posit.hpp" #include "../../posit/numeric_limits.hpp" #ifdef POSIT_FAST_SPECIALIZATION #include "../../posit/specialized/posit_2_0.hpp" #include "../../posit/specialized/posit_3_0.hpp" #include "../../posit/specialized/posit_3_1.hpp" #include "../../posit/specialized/posit_4_0.hpp" #include "../../posit/specialized/posit_8_0.hpp" #endif // posit type manipulators such as pretty printers #include "../../posit/posit_manipulators.hpp" // test helpers #include "../test_helpers.hpp" #include "../posit_test_helpers.hpp" // generate specific test case that you can trace with the trace conditions in posit.hpp // Most bugs are traceable with _trace_conversion and _trace_add template<size_t nbits, size_t es, typename Ty> void GenerateTestCase(Ty a) { Ty reference; sw::unum::posit<nbits, es> pa, pref, preciprocal; pa = a; reference = (Ty)1.0 / a; pref = reference; preciprocal = pa.reciprocate(); std::cout << "input " << a << " reference 1/fa " << reference << " pref " << double(pref) << '(' << pref << ") result " << double(preciprocal) << '(' << preciprocal << ')' << std::endl; } #define MANUAL_TESTING 1 #define STRESS_TESTING 1 int main(int argc, char** argv) try { using namespace std; using namespace sw::unum; bool bReportIndividualTestCases = false; int nrOfFailedTestCases = 0; cout << "Posit reciprocate validation" << endl; std::string tag = "Reciprocation failed: "; #if MANUAL_TESTING // generate individual testcases to hand trace/debug posit<5, 0> p1(0.75); posit<5, 0> p1_reciprocal; posit<5, 0> p2(0.75), p2_reciprocal; p2_reciprocal = p2.reciprocate(); p1_reciprocal = p1.reciprocate(); cout << "posit : " << to_string(p1_reciprocal) << endl; cout << "reference: " << double(p2_reciprocal) << endl; GenerateTestCase<4, 0, double>(0.75); GenerateTestCase<5, 0, double>(0.75); GenerateTestCase<6, 0, double>(0.75); GenerateTestCase<16, 0, double>(0.75); posit<16, 0> p(1 / 0.75); cout << p.get() << " " << pretty_print(p, 17) << endl; tag = "Manual Testing: "; nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<3, 0>(tag, true), "posit<3,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<4, 0>(tag, true), "posit<4,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 0>(tag, true), "posit<5,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 0>(tag, true), "posit<6,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 1>(tag, true), "posit<5,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 1>(tag, true), "posit<6,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 1>(tag, true), "posit<7,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 2>(tag, true), "posit<8,2>", "reciprocation"); #else tag = "Reciprocation failed: "; nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<4, 0>(tag, bReportIndividualTestCases), "posit<4,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 0>(tag, bReportIndividualTestCases), "posit<5,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 1>(tag, bReportIndividualTestCases), "posit<5,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 0>(tag, bReportIndividualTestCases), "posit<6,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 1>(tag, bReportIndividualTestCases), "posit<6,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 2>(tag, bReportIndividualTestCases), "posit<6,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 0>(tag, bReportIndividualTestCases), "posit<7,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 1>(tag, bReportIndividualTestCases), "posit<7,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 2>(tag, bReportIndividualTestCases), "posit<7,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 3>(tag, bReportIndividualTestCases), "posit<7,3>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<10, 1>(tag, bReportIndividualTestCases), "posit<10,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<12, 1>(tag, bReportIndividualTestCases), "posit<12,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<14, 1>(tag, bReportIndividualTestCases), "posit<14,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<16, 1>(tag, bReportIndividualTestCases), "posit<16,1>", "reciprocation"); #if STRESS_TESTING nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<18, 1>(tag, bReportIndividualTestCases), "posit<18,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<20, 1>(tag, bReportIndividualTestCases), "posit<20,1>", "reciprocation"); #endif // STRESS_TESTING #endif // MANUAL_TESTING return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (const posit_arithmetic_exception& err) { std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const quire_exception& err) { std::cerr << "Uncaught quire exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const posit_internal_exception& err) { std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; }
// arithmetic_reciprocate.cpp: functional tests for arithmetic reciprocation // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include "common.hpp" // Configure the posit template environment // first: enable fast specialized posit configurations //#define POSIT_FAST_SPECIALIZATION // second: enable/disable posit arithmetic exceptions #define POSIT_THROW_ARITHMETIC_EXCEPTION 0 // third: enable tracing // when you define POSIT_VERBOSE_OUTPUT executing an reciprocate the code will print intermediate results //#define POSIT_VERBOSE_OUTPUT #define POSIT_TRACE_RECIPROCATE #define POSIT_TRACE_CONVERSION // minimum set of include files to reflect source code dependencies #include "../../posit/posit.hpp" #include "../../posit/numeric_limits.hpp" #ifdef POSIT_FAST_SPECIALIZATION #include "../../posit/specialized/posit_2_0.hpp" #include "../../posit/specialized/posit_3_0.hpp" #include "../../posit/specialized/posit_3_1.hpp" #include "../../posit/specialized/posit_4_0.hpp" #include "../../posit/specialized/posit_8_0.hpp" #endif // posit type manipulators such as pretty printers #include "../../posit/posit_manipulators.hpp" // test helpers #include "../test_helpers.hpp" #include "../posit_test_helpers.hpp" // generate specific test case that you can trace with the trace conditions in posit.hpp // Most bugs are traceable with _trace_conversion and _trace_add template<size_t nbits, size_t es, typename Ty> void GenerateTestCase(Ty a) { Ty reference; sw::unum::posit<nbits, es> pa, pref, preciprocal; pa = a; reference = (Ty)1.0 / a; pref = reference; preciprocal = pa.reciprocate(); std::cout << "input " << a << " reference 1/fa " << reference << " pref " << double(pref) << '(' << pref << ") result " << double(preciprocal) << '(' << preciprocal << ')' << std::endl; } #define MANUAL_TESTING 0 #define STRESS_TESTING 1 int main(int argc, char** argv) try { using namespace std; using namespace sw::unum; bool bReportIndividualTestCases = false; int nrOfFailedTestCases = 0; cout << "Posit reciprocate validation" << endl; std::string tag = "Reciprocation failed: "; #if MANUAL_TESTING // generate individual testcases to hand trace/debug posit<5, 0> p1(0.75); posit<5, 0> p1_reciprocal; posit<5, 0> p2(0.75), p2_reciprocal; p2_reciprocal = p2.reciprocate(); p1_reciprocal = p1.reciprocate(); cout << "posit : " << to_string(p1_reciprocal) << endl; cout << "reference: " << double(p2_reciprocal) << endl; GenerateTestCase<4, 0, double>(0.75); GenerateTestCase<5, 0, double>(0.75); GenerateTestCase<6, 0, double>(0.75); GenerateTestCase<16, 0, double>(0.75); posit<16, 0> p(1 / 0.75); cout << p.get() << " " << pretty_print(p, 17) << endl; tag = "Manual Testing: "; nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<3, 0>(tag, true), "posit<3,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<4, 0>(tag, true), "posit<4,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 0>(tag, true), "posit<5,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 0>(tag, true), "posit<6,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 1>(tag, true), "posit<5,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 1>(tag, true), "posit<6,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 1>(tag, true), "posit<7,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 2>(tag, true), "posit<8,2>", "reciprocation"); #else tag = "Reciprocation failed: "; nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<4, 0>(tag, bReportIndividualTestCases), "posit<4,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 0>(tag, bReportIndividualTestCases), "posit<5,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 1>(tag, bReportIndividualTestCases), "posit<5,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 0>(tag, bReportIndividualTestCases), "posit<6,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 1>(tag, bReportIndividualTestCases), "posit<6,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 2>(tag, bReportIndividualTestCases), "posit<6,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 0>(tag, bReportIndividualTestCases), "posit<7,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 1>(tag, bReportIndividualTestCases), "posit<7,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 2>(tag, bReportIndividualTestCases), "posit<7,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 3>(tag, bReportIndividualTestCases), "posit<7,3>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<10, 1>(tag, bReportIndividualTestCases), "posit<10,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<12, 1>(tag, bReportIndividualTestCases), "posit<12,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<14, 1>(tag, bReportIndividualTestCases), "posit<14,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<16, 1>(tag, bReportIndividualTestCases), "posit<16,1>", "reciprocation"); #if STRESS_TESTING nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<18, 1>(tag, bReportIndividualTestCases), "posit<18,1>", "reciprocation"); nrOfFailedTestCases += ReportTestResult(ValidateReciprocation<20, 1>(tag, bReportIndividualTestCases), "posit<20,1>", "reciprocation"); #endif // STRESS_TESTING #endif // MANUAL_TESTING return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (const posit_arithmetic_exception& err) { std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const quire_exception& err) { std::cerr << "Uncaught quire exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const posit_internal_exception& err) { std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; }
disable manual testing
disable manual testing
C++
mit
stillwater-sc/universal,stillwater-sc/universal,stillwater-sc/universal,stillwater-sc/universal
9fdde175d66ed7d33e4e7a7f64ca7e519e0903d9
tests/src/integration/sankaku-test.cpp
tests/src/integration/sankaku-test.cpp
#include <QtTest> #include <QStringList> #include "sankaku-test.h" #include "functions.h" void SankakuTest::testHtml() { QList<Image*> images = getImages("Sankaku", "idol.sankakucomplex.com", "regex", "rating:safe", "results.html"); // Check results QCOMPARE(images.count(), 20); qDebug() << images; QCOMPARE(images[0]->md5(), QString("7af162c8a2e5299d737de002fce087cf")); QCOMPARE(images[1]->md5(), QString("8dd5c24458feb851c4dfbb302ebf5c06")); QCOMPARE(images[2]->md5(), QString("33347fcbeb76b6d7d2c31a5d491d53ee")); } void SankakuTest::testJson() { QList<Image*> images = getImages("Sankaku", "idol.sankakucomplex.com", "json", "rating:safe", "results.json"); // Check results QCOMPARE(images.count(), 20); QCOMPARE(images[0]->md5(), QString("26d8d649afde8fab74f1cf09607daebb")); QCOMPARE(images[0]->createdAt(), QDateTime::fromMSecsSinceEpoch(1484391423000)); QCOMPARE(images[1]->md5(), QString("c68c77540ab3813c9bc7c5059f3a0ac2")); QCOMPARE(images[1]->createdAt(), QDateTime::fromMSecsSinceEpoch(1484391415000)); QCOMPARE(images[2]->md5(), QString("6b154030d5b017b75917d160fc22203a")); QCOMPARE(images[2]->createdAt(), QDateTime::fromMSecsSinceEpoch(1484391403000)); } void SankakuTest::testAnimatedUrls() { QList<Image*> images = getImages("Sankaku", "idol.sankakucomplex.com", "regex", "animated rating:safe", "results-animated.html"); // Check results QCOMPARE(images.count(), 20); QCOMPARE(images[0]->md5(), QString("6e7901eea2a5a2d2b96244593ed190df")); QCOMPARE(images[0]->url(), QString("https://is.sankakucomplex.com/data/6e/79/6e7901eea2a5a2d2b96244593ed190df.gif")); QCOMPARE(images[1]->md5(), QString("97b3355a7af0bfabc67f2678a4a837fd")); QCOMPARE(images[1]->url(), QString("https://is.sankakucomplex.com/data/97/b3/97b3355a7af0bfabc67f2678a4a837fd.gif")); QCOMPARE(images[2]->md5(), QString("d9f7f5089da4a677846d77da2c146088")); QCOMPARE(images[2]->url(), QString("https://is.sankakucomplex.com/data/d9/f7/d9f7f5089da4a677846d77da2c146088.webm")); } static SankakuTest instance;
#include <QtTest> #include <QStringList> #include "sankaku-test.h" #include "functions.h" void SankakuTest::testHtml() { QList<Image*> images = getImages("Sankaku", "idol.sankakucomplex.com", "regex", "rating:safe", "results.html"); // Check results QCOMPARE(images.count(), 20); QCOMPARE(images[0]->md5(), QString("7af162c8a2e5299d737de002fce087cf")); QCOMPARE(images[1]->md5(), QString("8dd5c24458feb851c4dfbb302ebf5c06")); QCOMPARE(images[2]->md5(), QString("33347fcbeb76b6d7d2c31a5d491d53ee")); } void SankakuTest::testJson() { QList<Image*> images = getImages("Sankaku", "idol.sankakucomplex.com", "json", "rating:safe", "results.json"); // Check results QCOMPARE(images.count(), 20); QCOMPARE(images[0]->md5(), QString("26d8d649afde8fab74f1cf09607daebb")); QCOMPARE(images[0]->createdAt(), QDateTime::fromMSecsSinceEpoch(1484391423000)); QCOMPARE(images[1]->md5(), QString("c68c77540ab3813c9bc7c5059f3a0ac2")); QCOMPARE(images[1]->createdAt(), QDateTime::fromMSecsSinceEpoch(1484391415000)); QCOMPARE(images[2]->md5(), QString("6b154030d5b017b75917d160fc22203a")); QCOMPARE(images[2]->createdAt(), QDateTime::fromMSecsSinceEpoch(1484391403000)); } void SankakuTest::testAnimatedUrls() { QList<Image*> images = getImages("Sankaku", "idol.sankakucomplex.com", "regex", "animated rating:safe", "results-animated.html"); // Check results QCOMPARE(images.count(), 20); QCOMPARE(images[0]->md5(), QString("6e7901eea2a5a2d2b96244593ed190df")); QCOMPARE(images[0]->url(), QString("https://is.sankakucomplex.com/data/6e/79/6e7901eea2a5a2d2b96244593ed190df.gif")); QCOMPARE(images[1]->md5(), QString("97b3355a7af0bfabc67f2678a4a837fd")); QCOMPARE(images[1]->url(), QString("https://is.sankakucomplex.com/data/97/b3/97b3355a7af0bfabc67f2678a4a837fd.gif")); QCOMPARE(images[2]->md5(), QString("d9f7f5089da4a677846d77da2c146088")); QCOMPARE(images[2]->url(), QString("https://is.sankakucomplex.com/data/d9/f7/d9f7f5089da4a677846d77da2c146088.webm")); } static SankakuTest instance;
Remove useless debug
Remove useless debug
C++
apache-2.0
Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber
04cf668a830356b2de94e31c14482898b1ecadb6
tests/unit/fem/test_linearform_ext.cpp
tests/unit/fem/test_linearform_ext.cpp
// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "unit_tests.hpp" #include <functional> #include <ctime> using namespace mfem; struct LinearFormExtTest { enum { DomainLF, DomainLFGrad, VectorDomainLF, VectorDomainLFGrad }; using vector_fct_t = void(const Vector&, Vector&); const double abs_tol = 1e-14, rel_tol = 1e-14; const char *mesh_filename; Mesh mesh; const int dim, vdim, ordering, gll, problem, p, q, SEED = 0x100001b3; H1_FECollection fec; FiniteElementSpace vfes, mfes; const Geometry::Type geom_type; IntegrationRules IntRulesGLL; const IntegrationRule *irGLL, *ir; Array<int> elem_marker; Vector one_vec, dim_vec, vdim_vec, vdim_dim_vec; ConstantCoefficient cst_coeff; VectorConstantCoefficient dim_cst_coeff, vdim_cst_coeff, vdim_dim_cst_coeff; std::function<vector_fct_t> vdim_vec_function = [&](const Vector&, Vector &y) { y.SetSize(vdim); y.Randomize(static_cast<int>(std::time(NULL))); }; std::function<vector_fct_t> vector_fct; VectorFunctionCoefficient vdim_fct_coeff; LinearForm lf_dev, lf_std; LinearFormIntegrator *lfi_dev, *lfi_std; LinearFormExtTest(const char *mesh_filename, int vdim, int ordering, bool gll, int problem, int p): mesh_filename(mesh_filename), mesh(Mesh::LoadFromFile(mesh_filename)), dim(mesh.Dimension()), vdim(vdim), ordering(ordering), gll(gll), problem(problem), p(p), q(2*p + (gll?-1:3)), fec(p, dim), vfes(&mesh, &fec, vdim, ordering), mfes(&mesh, &fec, dim), geom_type(vfes.GetFE(0)->GetGeomType()), IntRulesGLL(0, Quadrature1D::GaussLobatto), irGLL(&IntRulesGLL.Get(geom_type, q)), ir(&IntRules.Get(geom_type, q)), elem_marker(), one_vec(1), dim_vec(dim), vdim_vec(vdim), vdim_dim_vec(vdim*dim), cst_coeff(M_PI), dim_cst_coeff((dim_vec.Randomize(SEED), dim_vec)), vdim_cst_coeff((vdim_vec.Randomize(SEED), vdim_vec)), vdim_dim_cst_coeff((vdim_dim_vec.Randomize(SEED), vdim_dim_vec)), vector_fct(vdim_vec_function), vdim_fct_coeff(vdim, vector_fct), lf_dev(&vfes), lf_std(&vfes), lfi_dev(nullptr), lfi_std(nullptr) { for (int e = 0; e < mesh.GetNE(); e++) { mesh.SetAttribute(e, e%2?1:2); } mesh.SetAttributes(); MFEM_VERIFY(mesh.attributes.Size() == 2, "mesh attributes size error!"); elem_marker.SetSize(2); elem_marker[0] = 0; elem_marker[1] = 1; if (problem == DomainLF) { lfi_dev = new DomainLFIntegrator(cst_coeff); lfi_std = new DomainLFIntegrator(cst_coeff); } else if (problem == DomainLFGrad) { lfi_dev = new DomainLFGradIntegrator(dim_cst_coeff); lfi_std = new DomainLFGradIntegrator(dim_cst_coeff); } else if (problem == VectorDomainLF) { lfi_dev = new VectorDomainLFIntegrator(vdim_fct_coeff); lfi_std = new VectorDomainLFIntegrator(vdim_fct_coeff); } else if (problem == VectorDomainLFGrad) { lfi_dev = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); lfi_std = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); } else { REQUIRE(false); } lfi_dev->SetIntRule(gll ? irGLL : ir); lfi_std->SetIntRule(gll ? irGLL : ir); lf_dev.AddDomainIntegrator(lfi_dev, elem_marker); lf_std.AddDomainIntegrator(lfi_std, elem_marker); } void Run() { const bool scalar = problem == LinearFormExtTest::DomainLF || problem == LinearFormExtTest::DomainLFGrad; REQUIRE((!scalar || vdim == 1)); const bool grad = problem == LinearFormExtTest::DomainLFGrad || problem == LinearFormExtTest::VectorDomainLFGrad; CAPTURE(dim, p, q, ordering, vdim, scalar, grad); const bool use_device = true; lf_dev.Assemble(use_device); const bool dont_use_device = false; lf_std.Assemble(dont_use_device); lf_std -= lf_dev; REQUIRE(0.0 == MFEM_Approx(lf_std*lf_std, abs_tol, rel_tol)); } }; TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]") { const bool all = launch_all_non_regression_tests; const auto mesh = all ? GENERATE("../../data/star.mesh", "../../data/star-q3.mesh", "../../data/fichera.mesh", "../../data/fichera-q3.mesh") : GENERATE("../../data/star-q3.mesh", "../../data/fichera-q3.mesh"); const auto p = all ? GENERATE(1,2,3,4,5,6) : GENERATE(1,3); const auto gll = GENERATE(false, true); SECTION("Scalar") { const auto problem = GENERATE(LinearFormExtTest::DomainLF, LinearFormExtTest::DomainLFGrad); LinearFormExtTest(mesh, 1, Ordering::byNODES, gll, problem, p).Run(); } SECTION("Vector") { const auto vdim = all ? GENERATE(1,5,7) : GENERATE(1,5); const auto ordering = GENERATE(Ordering::byVDIM, Ordering::byNODES); const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF, LinearFormExtTest::VectorDomainLFGrad); LinearFormExtTest(mesh, vdim, ordering, gll, problem, p).Run(); } }
// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "unit_tests.hpp" #include <functional> #include <ctime> using namespace mfem; struct LinearFormExtTest { enum { DLFEval, QLFEval, DLFGrad, VDLFEval, VQLFEval, VDLFGrad }; using vector_fct_t = void(const Vector&, Vector&); const double abs_tol = 1e-14, rel_tol = 1e-14; const char *mesh_filename; Mesh mesh; const int dim, vdim, ordering, gll, problem, p, q, SEED = 0x100001b3; H1_FECollection fec; FiniteElementSpace vfes, mfes; const Geometry::Type geom_type; IntegrationRules IntRulesGLL; const IntegrationRule *irGLL, *ir; Array<int> elem_marker; Vector one_vec, dim_vec, vdim_vec, vdim_dim_vec; ConstantCoefficient cst_coeff; VectorConstantCoefficient dim_cst_coeff, vdim_cst_coeff, vdim_dim_cst_coeff; std::function<vector_fct_t> vdim_vec_function = [&](const Vector&, Vector &y) { y.SetSize(vdim); y.Randomize(SEED);}; std::function<vector_fct_t> vector_fct; VectorFunctionCoefficient vdim_fct_coeff; QuadratureSpace qspace; QuadratureFunction q_function, q_vdim_function; QuadratureFunctionCoefficient qfc; VectorQuadratureFunctionCoefficient qfvc; LinearForm lf_dev, lf_std; LinearFormIntegrator *lfi_dev, *lfi_std; LinearFormExtTest(const char *mesh_filename, int vdim, int ordering, bool gll, int problem, int p): mesh_filename(mesh_filename), mesh(Mesh::LoadFromFile(mesh_filename)), dim(mesh.Dimension()), vdim(vdim), ordering(ordering), gll(gll), problem(problem), p(p), q(2*p + (gll?-1:3)), fec(p, dim), vfes(&mesh, &fec, vdim, ordering), mfes(&mesh, &fec, dim), geom_type(vfes.GetFE(0)->GetGeomType()), IntRulesGLL(0, Quadrature1D::GaussLobatto), irGLL(&IntRulesGLL.Get(geom_type, q)), ir(&IntRules.Get(geom_type, q)), elem_marker(), one_vec(1), dim_vec(dim), vdim_vec(vdim), vdim_dim_vec(vdim*dim), cst_coeff(M_PI), dim_cst_coeff((dim_vec.Randomize(SEED), dim_vec)), vdim_cst_coeff((vdim_vec.Randomize(SEED), vdim_vec)), vdim_dim_cst_coeff((vdim_dim_vec.Randomize(SEED), vdim_dim_vec)), vector_fct(vdim_vec_function), vdim_fct_coeff(vdim, vector_fct), qspace(&mesh, q), q_function(&qspace, 1), q_vdim_function(&qspace, vdim), qfc((q_function.Randomize(SEED), q_function)), qfvc((q_vdim_function.Randomize(SEED), q_vdim_function)), lf_dev(&vfes), lf_std(&vfes), lfi_dev(nullptr), lfi_std(nullptr) { for (int e = 0; e < mesh.GetNE(); e++) { mesh.SetAttribute(e, e%2?1:2); } mesh.SetAttributes(); MFEM_VERIFY(mesh.attributes.Size() == 2, "mesh attributes size error!"); elem_marker.SetSize(2); elem_marker[0] = 0; elem_marker[1] = 1; if (problem == DLFEval) { lfi_dev = new DomainLFIntegrator(cst_coeff); lfi_std = new DomainLFIntegrator(cst_coeff); } else if (problem == QLFEval) { lfi_dev = new QuadratureLFIntegrator(qfc,NULL); lfi_std = new QuadratureLFIntegrator(qfc,NULL); } else if (problem == DLFGrad) { lfi_dev = new DomainLFGradIntegrator(dim_cst_coeff); lfi_std = new DomainLFGradIntegrator(dim_cst_coeff); } else if (problem == VDLFEval) { lfi_dev = new VectorDomainLFIntegrator(vdim_fct_coeff); lfi_std = new VectorDomainLFIntegrator(vdim_fct_coeff); } else if (problem == VQLFEval) { lfi_dev = new VectorQuadratureLFIntegrator(qfvc,NULL); lfi_std = new VectorQuadratureLFIntegrator(qfvc,NULL); } else if (problem == VDLFGrad) { lfi_dev = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); lfi_std = new VectorDomainLFGradIntegrator(vdim_dim_cst_coeff); } else { REQUIRE(false); } if (problem != QLFEval && problem != VQLFEval) { lfi_dev->SetIntRule(gll ? irGLL : ir); lfi_std->SetIntRule(gll ? irGLL : ir); } lf_dev.AddDomainIntegrator(lfi_dev, elem_marker); lf_std.AddDomainIntegrator(lfi_std, elem_marker); } void Run() { const bool scalar = problem == LinearFormExtTest::DLFEval || problem == LinearFormExtTest::QLFEval || problem == LinearFormExtTest::DLFGrad; REQUIRE((!scalar || vdim == 1)); const bool grad = problem == LinearFormExtTest::DLFGrad || problem == LinearFormExtTest::VDLFGrad; CAPTURE(dim, p, q, ordering, vdim, scalar, grad); const bool use_device = true; lf_dev.Assemble(use_device); const bool dont_use_device = false; lf_std.Assemble(dont_use_device); lf_std -= lf_dev; REQUIRE(0.0 == MFEM_Approx(lf_std*lf_std, abs_tol, rel_tol)); } }; TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]") { const bool all = launch_all_non_regression_tests; const auto mesh = all ? GENERATE("../../data/star.mesh", "../../data/star-q3.mesh", "../../data/fichera.mesh", "../../data/fichera-q3.mesh") : GENERATE("../../data/star-q3.mesh", "../../data/fichera-q3.mesh"); const auto p = all ? GENERATE(1,2,3,4,5,6) : GENERATE(1,3); const auto gll = GENERATE(false, true); SECTION("Scalar") { const auto problem = GENERATE(LinearFormExtTest::DLFEval, LinearFormExtTest::QLFEval, LinearFormExtTest::DLFGrad); LinearFormExtTest(mesh, 1, Ordering::byNODES, gll, problem, p).Run(); } SECTION("Vector") { const auto vdim = all ? GENERATE(1,5,7) : GENERATE(1,5); const auto ordering = GENERATE(Ordering::byVDIM, Ordering::byNODES); const auto problem = GENERATE(LinearFormExtTest::VDLFEval, LinearFormExtTest::VQLFEval, LinearFormExtTest::VDLFGrad); LinearFormExtTest(mesh, vdim, ordering, gll, problem, p).Run(); } }
Add tests/unit/fem/test_linearform_ext QuadratureLFIntegrator and VectorQuadratureLFIntegrator tests
Add tests/unit/fem/test_linearform_ext QuadratureLFIntegrator and VectorQuadratureLFIntegrator tests
C++
bsd-3-clause
mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem
4157ce946dc13e2d0c577740844eb77c4c3c532e
third_party/tcmalloc/allocator_shim.cc
third_party/tcmalloc/allocator_shim.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <config.h> // When defined, different heap allocators can be used via an environment // variable set before running the program. This may reduce the amount // of inlining that we get with malloc/free/etc. Disabling makes it // so that only tcmalloc can be used. #define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING // TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth // from the "user code" so that debugging tools (HeapChecker) can work. // __THROW is defined in glibc systems. It means, counter-intuitively, // "This function will never throw an exception." It's an optional // optimization tool, but we may need to use it to match glibc prototypes. #ifndef __THROW // I guess we're not on a glibc system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif // new_mode behaves similarly to MSVC's _set_new_mode. // If flag is 0 (default), calls to malloc will behave normally. // If flag is 1, calls to malloc will behave like calls to new, // and the std_new_handler will be invoked on failure. // Can be set by calling _set_new_mode(). static int new_mode = 0; typedef enum { TCMALLOC, // TCMalloc is the default allocator. JEMALLOC, // JEMalloc WINDEFAULT, // Windows Heap WINLFH, // Windows LFH Heap } Allocator; // This is the default allocator. static Allocator allocator = TCMALLOC; // We include tcmalloc and the win_allocator to get as much inlining as // possible. #include "tcmalloc.cc" #include "win_allocator.cc" // Forward declarations from jemalloc. extern "C" { void* je_malloc(size_t s); void* je_realloc(void* p, size_t s); void je_free(void* s); size_t je_msize(void* p); bool je_malloc_init_hard(); } extern "C" { // Call the new handler, if one has been set. // Returns true on successfully calling the handler, false otherwise. inline bool call_new_handler(bool nothrow) { // Get the current new handler. NB: this function is not // thread-safe. We make a feeble stab at making it so here, but // this lock only protects against tcmalloc interfering with // itself, not with other libraries calling set_new_handler. std::new_handler nh; { SpinLockHolder h(&set_new_handler_lock); nh = std::set_new_handler(0); (void) std::set_new_handler(nh); } #if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) if (!nh) return false; // Since exceptions are disabled, we don't really know if new_handler // failed. Assume it will abort if it fails. (*nh)(); return true; #else // If no new_handler is established, the allocation failed. if (!nh) { if (nothrow) return 0; throw std::bad_alloc(); } // Otherwise, try the new_handler. If it returns, retry the // allocation. If it throws std::bad_alloc, fail the allocation. // if it throws something else, don't interfere. try { (*nh)(); } catch (const std::bad_alloc&) { if (!nothrow) throw; return p; } #endif // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) } void* malloc(size_t size) __THROW { void* ptr; for (;;) { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: ptr = je_malloc(size); break; case WINDEFAULT: case WINLFH: ptr = win_heap_malloc(size); break; case TCMALLOC: default: ptr = do_malloc(size); break; } #else // TCMalloc case. ptr = do_malloc(size); #endif if (ptr) return ptr; if (!new_mode || !call_new_handler(true)) break; } return ptr; } void free(void* p) __THROW { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: je_free(p); return; case WINDEFAULT: case WINLFH: win_heap_free(p); return; } #endif // TCMalloc case. do_free(p); } void* realloc(void* ptr, size_t size) __THROW { void* new_ptr; for (;;) { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: new_ptr = je_realloc(ptr, size); break; case WINDEFAULT: case WINLFH: new_ptr = win_heap_realloc(ptr, size); break; case TCMALLOC: default: new_ptr = do_realloc(ptr, size); break; } #else // TCMalloc case. new_ptr = do_realloc(ptr, size); #endif if (new_ptr) return new_ptr; if (!new_mode || !call_new_handler(true)) break; } return new_ptr; } // TODO(mbelshe): Implement this for other allocators. void malloc_stats(void) __THROW { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: // No stats. return; case WINDEFAULT: case WINLFH: // No stats. return; } #endif tc_malloc_stats(); } #ifdef WIN32 extern "C" size_t _msize(void* p) { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: return je_msize(p); case WINDEFAULT: case WINLFH: return win_heap_msize(p); } #endif return MallocExtension::instance()->GetAllocatedSize(p); } // This is included to resolve references from libcmt. extern "C" intptr_t _get_heap_handle() { return 0; } // The CRT heap initialization stub. extern "C" int _heap_init() { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING const char* override = GetenvBeforeMain("CHROME_ALLOCATOR"); if (override) { if (!stricmp(override, "jemalloc")) allocator = JEMALLOC; else if (!stricmp(override, "winheap")) allocator = WINDEFAULT; else if (!stricmp(override, "winlfh")) allocator = WINLFH; else if (!stricmp(override, "tcmalloc")) allocator = TCMALLOC; } switch (allocator) { case JEMALLOC: return je_malloc_init_hard() ? 0 : 1; case WINDEFAULT: return win_heap_init(false) ? 1 : 0; case WINLFH: return win_heap_init(true) ? 1 : 0; case TCMALLOC: default: // fall through break; } #endif // Initializing tcmalloc. // We intentionally leak this object. It lasts for the process // lifetime. Trying to teardown at _heap_term() is so late that // you can't do anything useful anyway. new TCMallocGuard(); return 1; } // The CRT heap cleanup stub. extern "C" void _heap_term() {} // We set this to 1 because part of the CRT uses a check of _crtheap != 0 // to test whether the CRT has been initialized. Once we've ripped out // the allocators from libcmt, we need to provide this definition so that // the rest of the CRT is still usable. extern "C" void* _crtheap = reinterpret_cast<void*>(1); #endif // WIN32 #include "generic_allocators.cc" } // extern C
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <config.h> // When defined, different heap allocators can be used via an environment // variable set before running the program. This may reduce the amount // of inlining that we get with malloc/free/etc. Disabling makes it // so that only tcmalloc can be used. #define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING // TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth // from the "user code" so that debugging tools (HeapChecker) can work. // __THROW is defined in glibc systems. It means, counter-intuitively, // "This function will never throw an exception." It's an optional // optimization tool, but we may need to use it to match glibc prototypes. #ifndef __THROW // I guess we're not on a glibc system # define __THROW // __THROW is just an optimization, so ok to make it "" #endif // new_mode behaves similarly to MSVC's _set_new_mode. // If flag is 0 (default), calls to malloc will behave normally. // If flag is 1, calls to malloc will behave like calls to new, // and the std_new_handler will be invoked on failure. // Can be set by calling _set_new_mode(). static int new_mode = 0; typedef enum { TCMALLOC, // TCMalloc is the default allocator. JEMALLOC, // JEMalloc WINDEFAULT, // Windows Heap WINLFH, // Windows LFH Heap } Allocator; // This is the default allocator. static Allocator allocator = TCMALLOC; // We include tcmalloc and the win_allocator to get as much inlining as // possible. #include "tcmalloc.cc" #include "win_allocator.cc" // Forward declarations from jemalloc. extern "C" { void* je_malloc(size_t s); void* je_realloc(void* p, size_t s); void je_free(void* s); size_t je_msize(void* p); bool je_malloc_init_hard(); } extern "C" { // Call the new handler, if one has been set. // Returns true on successfully calling the handler, false otherwise. inline bool call_new_handler(bool nothrow) { // Get the current new handler. NB: this function is not // thread-safe. We make a feeble stab at making it so here, but // this lock only protects against tcmalloc interfering with // itself, not with other libraries calling set_new_handler. std::new_handler nh; { SpinLockHolder h(&set_new_handler_lock); nh = std::set_new_handler(0); (void) std::set_new_handler(nh); } #if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) if (!nh) return false; // Since exceptions are disabled, we don't really know if new_handler // failed. Assume it will abort if it fails. (*nh)(); return true; #else // If no new_handler is established, the allocation failed. if (!nh) { if (nothrow) return 0; throw std::bad_alloc(); } // Otherwise, try the new_handler. If it returns, retry the // allocation. If it throws std::bad_alloc, fail the allocation. // if it throws something else, don't interfere. try { (*nh)(); } catch (const std::bad_alloc&) { if (!nothrow) throw; return p; } #endif // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS) } void* malloc(size_t size) __THROW { void* ptr; for (;;) { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: ptr = je_malloc(size); break; case WINDEFAULT: case WINLFH: ptr = win_heap_malloc(size); break; case TCMALLOC: default: ptr = do_malloc(size); break; } #else // TCMalloc case. ptr = do_malloc(size); #endif if (ptr) return ptr; if (!new_mode || !call_new_handler(true)) break; } return ptr; } void free(void* p) __THROW { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: je_free(p); return; case WINDEFAULT: case WINLFH: win_heap_free(p); return; } #endif // TCMalloc case. do_free(p); } void* realloc(void* ptr, size_t size) __THROW { void* new_ptr; for (;;) { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: new_ptr = je_realloc(ptr, size); break; case WINDEFAULT: case WINLFH: new_ptr = win_heap_realloc(ptr, size); break; case TCMALLOC: default: new_ptr = do_realloc(ptr, size); break; } #else // TCMalloc case. new_ptr = do_realloc(ptr, size); #endif // Subtle warning: NULL return does not alwas indicate out-of-memory. If // the requested new size is zero, realloc should free the ptr and return // NULL. if (new_ptr || !size) return new_ptr; if (!new_mode || !call_new_handler(true)) break; } return new_ptr; } // TODO(mbelshe): Implement this for other allocators. void malloc_stats(void) __THROW { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: // No stats. return; case WINDEFAULT: case WINLFH: // No stats. return; } #endif tc_malloc_stats(); } #ifdef WIN32 extern "C" size_t _msize(void* p) { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING switch (allocator) { case JEMALLOC: return je_msize(p); case WINDEFAULT: case WINLFH: return win_heap_msize(p); } #endif return MallocExtension::instance()->GetAllocatedSize(p); } // This is included to resolve references from libcmt. extern "C" intptr_t _get_heap_handle() { return 0; } // The CRT heap initialization stub. extern "C" int _heap_init() { #ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING const char* override = GetenvBeforeMain("CHROME_ALLOCATOR"); if (override) { if (!stricmp(override, "jemalloc")) allocator = JEMALLOC; else if (!stricmp(override, "winheap")) allocator = WINDEFAULT; else if (!stricmp(override, "winlfh")) allocator = WINLFH; else if (!stricmp(override, "tcmalloc")) allocator = TCMALLOC; } switch (allocator) { case JEMALLOC: return je_malloc_init_hard() ? 0 : 1; case WINDEFAULT: return win_heap_init(false) ? 1 : 0; case WINLFH: return win_heap_init(true) ? 1 : 0; case TCMALLOC: default: // fall through break; } #endif // Initializing tcmalloc. // We intentionally leak this object. It lasts for the process // lifetime. Trying to teardown at _heap_term() is so late that // you can't do anything useful anyway. new TCMallocGuard(); return 1; } // The CRT heap cleanup stub. extern "C" void _heap_term() {} // We set this to 1 because part of the CRT uses a check of _crtheap != 0 // to test whether the CRT has been initialized. Once we've ripped out // the allocators from libcmt, we need to provide this definition so that // the rest of the CRT is still usable. extern "C" void* _crtheap = reinterpret_cast<void*>(1); #endif // WIN32 #include "generic_allocators.cc" } // extern C
Fix realloc to not call the new_handler (which is for failures) when the request was for realloc(ptr, 0). Calling realloc(ptr, 0) is valid, and we should delete ptr and return NULL.
Fix realloc to not call the new_handler (which is for failures) when the request was for realloc(ptr, 0). Calling realloc(ptr, 0) is valid, and we should delete ptr and return NULL. BUG=none TEST=none Review URL: http://codereview.chromium.org/194040 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@25700 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium
dc84d0bfbe63b5256b508c2520a52fde4eecf17a
src/control.cpp
src/control.cpp
/* */ #include "control.h" #include "lineFollowing/lineFollowing.h" #include "objectFollowing/objectFollowing.h" #include "manual/manual.h" /* */ Control::Control() { //Initializing Message printf("Connecting to the drone\n"); printf("If there is no version number response in the next 10 seconds, please restart the drone and code.\n"); fflush(stdout); flight_log = fopen(flightLog.c_str(), "w"); green = CV_RGB(0,255,0); //Connect to drone if (!ardrone.open()) { throw "Failed to initialize."; } //Set drone trim on flat surface ardrone.setFlatTrim(); //initialize flying mode code manualFlying = new ManualFlying(this); objectFollowing = new ObjectFollowing(this); lineFollowing = new LineFollowing(this); //Print default command information printf("To disconnect, press the ESC key\n\n"); printf("Currently the drone is in manual mode.\n"); printf("Use the b key for manual mode, the n key for object following, and the m key for line following. The number keys can be used to set a speed. Use spacebar to take off and land, which is required before any control can be executed.\n\n"); } void Control::fly() { //Execute flying instruction code switch (flyingMode) { case Manual: manualFlying->fly(); break; case ObjectFollow: objectFollowing->fly(); break; case LineFollow: lineFollowing->fly(); break; } return; } /* Detect ESC key press and */ bool Control::getKey(int wait) { key = cv::waitKey(wait); if (key == 0x1b) { return false; } //Escape key return true; } /* */ void Control::changeSpeed() { if ((key >= '0') && (key <= '9')) { //number keys speed = (key-'0')*0.1; } //Alternate controls for wii remote if (key == '+') { speed = speed + 0.1; } if (key == '-') { speed = speed - 0.1; } } /* */ void Control::getImage() { //Get an image image = ardrone.getImage(); } /* Switch between flying modes */ void Control::detectFlyingMode() { if (key == 'b') { flyingMode = Manual; } else if (key == 'n') { flyingMode = ObjectFollow; } else if (key == 'm') { flyingMode = LineFollow; } if (key == 'v') { if (flyingMode == Manual) { flyingMode = ObjectFollow; } else if (flyingMode == ObjectFollow) { flyingMode = LineFollow; } else if (flyingMode == LineFollow) { flyingMode = Manual; } } if (flyingMode == Manual) { ardrone.setCamera(0); printf("Manual flying mode is enabled\n"); printf("Press n for object following and m for line following\n"); printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n"); } else if (flyingMode == ObjectFollow) { ardrone.setCamera(0); printf("Object Following flying mode is enabled\n"); printf("Press b for manual and m for line following\n"); printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n"); } else if (flyingMode == LineFollow) { ardrone.setCamera(1); printf("Line Following flying mode is enabled\n"); printf("Press b for manual and n for object following\n"); printf("No control for line following yet exists\n\n"); } } /* Take off / Landing */ void Control::detectTakeoff() { if (key == ' ') { //spacebar if (ardrone.onGround()) { ardrone.takeoff(); fprintf(flight_log, "TAKEOFF\n"); takeoff_time = time(0); } else { ardrone.landing(); fprintf(flight_log, "LAND\n"); } } } /* */ void Control::overlayControl() { char modeDisplay[80]; //print buffer for flying mode char speedDisplay[80]; //print buffer for speed char flyingDisplay[80]; //print buffer for if flying char batteryDisplay[80]; //print buffer for battery char altitudeDisplay[80]; //print buffer for altitude char vxDisplay[80]; //print buffer for x (forward/reverse) velocity char vyDisplay[80]; //print buffer for y (sideways) velocity char vzDisplay[80]; //print buffer for z (up/down) velocity char vrDisplay[80]; //print buffer for r rotational velocity if (flyingMode == Manual) { sprintf(modeDisplay, "Manual Mode"); sprintf(vxDisplay, "vx = %3.2f", velocities.vx); sprintf(vyDisplay, "vy = %3.2f", velocities.vy); sprintf(vzDisplay, "vz = %3.2f", velocities.vz); sprintf(vrDisplay, "vr = %3.2f", velocities.vr); putText(image, vxDisplay, cvPoint(30,120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); putText(image, vyDisplay, cvPoint(30,140), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); putText(image, vzDisplay, cvPoint(30,160), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); putText(image, vrDisplay, cvPoint(30,180), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); } else if (ObjectFollow) { sprintf(modeDisplay, "Object Following Mode"); } else if (LineFollow) { sprintf(modeDisplay, "Line Following Mode"); } if (ardrone.onGround()) { sprintf(flyingDisplay, "Landed"); } else { sprintf(flyingDisplay, "Flying"); } altitude = ardrone.getAltitude(); sprintf(speedDisplay, "Speed = %3.2f", speed); sprintf(batteryDisplay, "Battery = %d", ardrone.getBatteryPercentage()); sprintf(altitudeDisplay, "Altitude = %f", ardrone.getAltitude()); //add flying mode to overlay putText(image, modeDisplay, cvPoint(30,20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add grounded or flying to overlay putText(image, flyingDisplay, cvPoint(30,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add battery percentage to overlay putText(image, batteryDisplay, cvPoint(30,60), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add altitude to overlay putText(image, altitudeDisplay, cvPoint(30,80), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add speed to overlay putText(image, speedDisplay, cvPoint(30,100), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); cv::namedWindow("camera", CV_WINDOW_NORMAL); cv::resizeWindow("camera", 700, 400); cv::imshow("camera", image); //Display the camera feed } /* */ void Control::move() { ardrone.move3D(velocities.vx * speed, velocities.vy * speed, velocities.vz, velocities.vr); return; } /* Close connection to drone */ void Control::close() { //Close flying modes manualFlying->close(); objectFollowing->close(); lineFollowing->close(); //close connections with drone ardrone.close(); return; }
/* */ #include "control.h" #include "lineFollowing/lineFollowing.h" #include "objectFollowing/objectFollowing.h" #include "manual/manual.h" /* */ Control::Control() { //Initializing Message printf("Connecting to the drone\n"); printf("If there is no version number response in the next 10 seconds, please restart the drone and code.\n"); fflush(stdout); flight_log = fopen(flightLog.c_str(), "w"); green = CV_RGB(0,255,0); //Connect to drone if (!ardrone.open()) { throw "Failed to initialize."; } //Set drone trim on flat surface ardrone.setFlatTrim(); //initialize flying mode code manualFlying = new ManualFlying(this); objectFollowing = new ObjectFollowing(this); lineFollowing = new LineFollowing(this); //Print default command information printf("To disconnect, press the ESC key\n\n"); printf("Currently the drone is in manual mode.\n"); printf("Use the b key for manual mode, the n key for object following, and the m key for line following. The number keys can be used to set a speed. Use spacebar to take off and land, which is required before any control can be executed.\n\n"); } void Control::fly() { //Execute flying instruction code switch (flyingMode) { case Manual: manualFlying->fly(); break; case ObjectFollow: objectFollowing->fly(); break; case LineFollow: lineFollowing->fly(); break; } return; } /* Detect ESC key press and */ bool Control::getKey(int wait) { key = cv::waitKey(wait); if (key == 0x1b) { return false; } //Escape key return true; } /* */ void Control::changeSpeed() { if ((key >= '0') && (key <= '9')) { //number keys speed = (key-'0')*0.1; } //Alternate controls for wii remote if (key == '+') { speed = speed + 0.1; } if (key == '-') { speed = speed - 0.1; } } /* */ void Control::getImage() { //Get an image image = ardrone.getImage(); } /* Switch between flying modes */ void Control::detectFlyingMode() { if (key == 'b') { flyingMode = Manual; ardrone.setCamera(0); printf("Manual flying mode is enabled\n"); printf("Press n for object following and m for line following\n"); printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n"); } else if (key == 'n') { flyingMode = ObjectFollow; ardrone.setCamera(0); printf("Object Following flying mode is enabled\n"); printf("Press b for manual and m for line following\n"); printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n"); } else if (key == 'm') { flyingMode = LineFollow; ardrone.setCamera(1); printf("Line Following flying mode is enabled\n"); printf("Press b for manual and n for object following\n"); printf("No control for line following yet exists\n\n"); } if (key == 'v') { if (flyingMode == Manual) { flyingMode = ObjectFollow; ardrone.setCamera(0); printf("Object Following flying mode is enabled\n"); printf("Press b for manual and m for line following\n"); printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n"); } else if (flyingMode == ObjectFollow) { flyingMode = LineFollow; ardrone.setCamera(1); printf("Line Following flying mode is enabled\n"); printf("Press b for manual and n for object following\n"); printf("No control for line following yet exists\n\n"); } else if (flyingMode == LineFollow) { flyingMode = Manual; ardrone.setCamera(0); printf("Manual flying mode is enabled\n"); printf("Press n for object following and m for line following\n"); printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n"); } } } /* Take off / Landing */ void Control::detectTakeoff() { if (key == ' ') { //spacebar if (ardrone.onGround()) { ardrone.takeoff(); fprintf(flight_log, "TAKEOFF\n"); takeoff_time = time(0); } else { ardrone.landing(); fprintf(flight_log, "LAND\n"); } } } /* */ void Control::overlayControl() { char modeDisplay[80]; //print buffer for flying mode char speedDisplay[80]; //print buffer for speed char flyingDisplay[80]; //print buffer for if flying char batteryDisplay[80]; //print buffer for battery char altitudeDisplay[80]; //print buffer for altitude char vxDisplay[80]; //print buffer for x (forward/reverse) velocity char vyDisplay[80]; //print buffer for y (sideways) velocity char vzDisplay[80]; //print buffer for z (up/down) velocity char vrDisplay[80]; //print buffer for r rotational velocity if (flyingMode == Manual) { sprintf(modeDisplay, "Manual Mode"); sprintf(vxDisplay, "vx = %3.2f", velocities.vx); sprintf(vyDisplay, "vy = %3.2f", velocities.vy); sprintf(vzDisplay, "vz = %3.2f", velocities.vz); sprintf(vrDisplay, "vr = %3.2f", velocities.vr); putText(image, vxDisplay, cvPoint(30,120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); putText(image, vyDisplay, cvPoint(30,140), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); putText(image, vzDisplay, cvPoint(30,160), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); putText(image, vrDisplay, cvPoint(30,180), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); } else if (flyingMode == ObjectFollow) { sprintf(modeDisplay, "Object Following Mode"); } else if (flyingMode == LineFollow) { sprintf(modeDisplay, "Line Following Mode"); } if (ardrone.onGround()) { sprintf(flyingDisplay, "Landed"); } else { sprintf(flyingDisplay, "Flying"); } altitude = ardrone.getAltitude(); sprintf(speedDisplay, "Speed = %3.2f", speed); sprintf(batteryDisplay, "Battery = %d", ardrone.getBatteryPercentage()); sprintf(altitudeDisplay, "Altitude = %f", ardrone.getAltitude()); //add flying mode to overlay putText(image, modeDisplay, cvPoint(30,20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add grounded or flying to overlay putText(image, flyingDisplay, cvPoint(30,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add battery percentage to overlay putText(image, batteryDisplay, cvPoint(30,60), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add altitude to overlay putText(image, altitudeDisplay, cvPoint(30,80), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); //add speed to overlay putText(image, speedDisplay, cvPoint(30,100), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); cv::namedWindow("camera", CV_WINDOW_NORMAL); cv::resizeWindow("camera", 700, 400); cv::imshow("camera", image); //Display the camera feed } /* */ void Control::move() { ardrone.move3D(velocities.vx * speed, velocities.vy * speed, velocities.vz, velocities.vr); return; } /* Close connection to drone */ void Control::close() { //Close flying modes manualFlying->close(); objectFollowing->close(); lineFollowing->close(); //close connections with drone ardrone.close(); return; }
Fix user display issues.
Fix user display issues.
C++
bsd-3-clause
tourdrone/cvdrone,tourdrone/cvdrone
4e287db2faefe0005fcfefa4a077b907af8417ea
src/cpu/base.hh
src/cpu/base.hh
/* * Copyright (c) 2011-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2011 Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Nathan Binkert * Rick Strong */ #ifndef __CPU_BASE_HH__ #define __CPU_BASE_HH__ #include <vector> #include "arch/interrupts.hh" #include "arch/isa_traits.hh" #include "arch/microcode_rom.hh" #include "base/statistics.hh" #include "config/the_isa.hh" #include "mem/mem_object.hh" #include "sim/eventq.hh" #include "sim/full_system.hh" #include "sim/insttracer.hh" #include "sim/system.hh" struct BaseCPUParams; class BranchPred; class CheckerCPU; class ThreadContext; class CPUProgressEvent : public Event { protected: Tick _interval; Counter lastNumInst; BaseCPU *cpu; bool _repeatEvent; public: CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0); void process(); void interval(Tick ival) { _interval = ival; } Tick interval() { return _interval; } void repeatEvent(bool repeat) { _repeatEvent = repeat; } virtual const char *description() const; }; class BaseCPU : public MemObject { protected: // @todo remove me after debugging with legion done Tick instCnt; // every cpu has an id, put it in the base cpu // Set at initialization, only time a cpuId might change is during a // takeover (which should be done from within the BaseCPU anyway, // therefore no setCpuId() method is provided int _cpuId; /** instruction side request id that must be placed in all requests */ MasterID _instMasterId; /** data side request id that must be placed in all requests */ MasterID _dataMasterId; /** An intrenal representation of a task identifier within gem5. This is * used so the CPU can add which taskId (which is an internal representation * of the OS process ID) to each request so components in the memory system * can track which process IDs are ultimately interacting with them */ uint32_t _taskId; /** The current OS process ID that is executing on this processor. This is * used to generate a taskId */ uint32_t _pid; /** Is the CPU switched out or active? */ bool _switchedOut; /** Cache the cache line size that we get from the system */ const unsigned int _cacheLineSize; public: /** * Purely virtual method that returns a reference to the data * port. All subclasses must implement this method. * * @return a reference to the data port */ virtual MasterPort &getDataPort() = 0; /** * Purely virtual method that returns a reference to the instruction * port. All subclasses must implement this method. * * @return a reference to the instruction port */ virtual MasterPort &getInstPort() = 0; /** Reads this CPU's ID. */ int cpuId() { return _cpuId; } /** Reads this CPU's unique data requestor ID */ MasterID dataMasterId() { return _dataMasterId; } /** Reads this CPU's unique instruction requestor ID */ MasterID instMasterId() { return _instMasterId; } /** * Get a master port on this CPU. All CPUs have a data and * instruction port, and this method uses getDataPort and * getInstPort of the subclasses to resolve the two ports. * * @param if_name the port name * @param idx ignored index * * @return a reference to the port with the given name */ BaseMasterPort &getMasterPort(const std::string &if_name, PortID idx = InvalidPortID); /** Get cpu task id */ uint32_t taskId() const { return _taskId; } /** Set cpu task id */ void taskId(uint32_t id) { _taskId = id; } uint32_t getPid() const { return _pid; } void setPid(uint32_t pid) { _pid = pid; } inline void workItemBegin() { numWorkItemsStarted++; } inline void workItemEnd() { numWorkItemsCompleted++; } // @todo remove me after debugging with legion done Tick instCount() { return instCnt; } TheISA::MicrocodeRom microcodeRom; protected: TheISA::Interrupts *interrupts; public: TheISA::Interrupts * getInterruptController() { return interrupts; } virtual void wakeup() = 0; void postInterrupt(int int_num, int index) { interrupts->post(int_num, index); if (FullSystem) wakeup(); } void clearInterrupt(int int_num, int index) { interrupts->clear(int_num, index); } void clearInterrupts() { interrupts->clearAll(); } bool checkInterrupts(ThreadContext *tc) const { return FullSystem && interrupts->checkInterrupts(tc); } class ProfileEvent : public Event { private: BaseCPU *cpu; Tick interval; public: ProfileEvent(BaseCPU *cpu, Tick interval); void process(); }; ProfileEvent *profileEvent; protected: std::vector<ThreadContext *> threadContexts; Trace::InstTracer * tracer; public: // Mask to align PCs to MachInst sized boundaries static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1); /// Provide access to the tracer pointer Trace::InstTracer * getTracer() { return tracer; } /// Notify the CPU that the indicated context is now active. The /// delay parameter indicates the number of ticks to wait before /// executing (typically 0 or 1). virtual void activateContext(ThreadID thread_num, Cycles delay) {} /// Notify the CPU that the indicated context is now suspended. virtual void suspendContext(ThreadID thread_num) {} /// Notify the CPU that the indicated context is now deallocated. virtual void deallocateContext(ThreadID thread_num) {} /// Notify the CPU that the indicated context is now halted. virtual void haltContext(ThreadID thread_num) {} /// Given a Thread Context pointer return the thread num int findContext(ThreadContext *tc); /// Given a thread num get tho thread context for it virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; } public: typedef BaseCPUParams Params; const Params *params() const { return reinterpret_cast<const Params *>(_params); } BaseCPU(Params *params, bool is_checker = false); virtual ~BaseCPU(); virtual void init(); virtual void startup(); virtual void regStats(); virtual void activateWhenReady(ThreadID tid) {}; void registerThreadContexts(); /** * Prepare for another CPU to take over execution. * * When this method exits, all internal state should have been * flushed. After the method returns, the simulator calls * takeOverFrom() on the new CPU with this CPU as its parameter. */ virtual void switchOut(); /** * Load the state of a CPU from the previous CPU object, invoked * on all new CPUs that are about to be switched in. * * A CPU model implementing this method is expected to initialize * its state from the old CPU and connect its memory (unless they * are already connected) to the memories connected to the old * CPU. * * @param cpu CPU to initialize read state from. */ virtual void takeOverFrom(BaseCPU *cpu); /** * Flush all TLBs in the CPU. * * This method is mainly used to flush stale translations when * switching CPUs. It is also exported to the Python world to * allow it to request a TLB flush after draining the CPU to make * it easier to compare traces when debugging * handover/checkpointing. */ void flushTLBs(); /** * Determine if the CPU is switched out. * * @return True if the CPU is switched out, false otherwise. */ bool switchedOut() const { return _switchedOut; } /** * Verify that the system is in a memory mode supported by the * CPU. * * Implementations are expected to query the system for the * current memory mode and ensure that it is what the CPU model * expects. If the check fails, the implementation should * terminate the simulation using fatal(). */ virtual void verifyMemoryMode() const { }; /** * Number of threads we're actually simulating (<= SMT_MAX_THREADS). * This is a constant for the duration of the simulation. */ ThreadID numThreads; /** * Vector of per-thread instruction-based event queues. Used for * scheduling events based on number of instructions committed by * a particular thread. */ EventQueue **comInstEventQueue; /** * Vector of per-thread load-based event queues. Used for * scheduling events based on number of loads committed by *a particular thread. */ EventQueue **comLoadEventQueue; System *system; /** * Get the cache line size of the system. */ inline unsigned int cacheLineSize() const { return _cacheLineSize; } /** * Serialize this object to the given output stream. * * @note CPU models should normally overload the serializeThread() * method instead of the serialize() method as this provides a * uniform data format for all CPU models and promotes better code * reuse. * * @param os The stream to serialize to. */ virtual void serialize(std::ostream &os); /** * Reconstruct the state of this object from a checkpoint. * * @note CPU models should normally overload the * unserializeThread() method instead of the unserialize() method * as this provides a uniform data format for all CPU models and * promotes better code reuse. * @param cp The checkpoint use. * @param section The section name of this object. */ virtual void unserialize(Checkpoint *cp, const std::string &section); /** * Serialize a single thread. * * @param os The stream to serialize to. * @param tid ID of the current thread. */ virtual void serializeThread(std::ostream &os, ThreadID tid) {}; /** * Unserialize one thread. * * @param cp The checkpoint use. * @param section The section name of this thread. * @param tid ID of the current thread. */ virtual void unserializeThread(Checkpoint *cp, const std::string &section, ThreadID tid) {}; /** * Return pointer to CPU's branch predictor (NULL if none). * @return Branch predictor pointer. */ virtual BranchPred *getBranchPred() { return NULL; }; virtual Counter totalInsts() const = 0; virtual Counter totalOps() const = 0; /** * Schedule an event that exits the simulation loops after a * predefined number of instructions. * * This method is usually called from the configuration script to * get an exit event some time in the future. It is typically used * when the script wants to simulate for a specific number of * instructions rather than ticks. * * @param tid Thread monitor. * @param insts Number of instructions into the future. * @param cause Cause to signal in the exit event. */ void scheduleInstStop(ThreadID tid, Counter insts, const char *cause); /** * Schedule an event that exits the simulation loops after a * predefined number of load operations. * * This method is usually called from the configuration script to * get an exit event some time in the future. It is typically used * when the script wants to simulate for a specific number of * loads rather than ticks. * * @param tid Thread monitor. * @param loads Number of load instructions into the future. * @param cause Cause to signal in the exit event. */ void scheduleLoadStop(ThreadID tid, Counter loads, const char *cause); // Function tracing private: bool functionTracingEnabled; std::ostream *functionTraceStream; Addr currentFunctionStart; Addr currentFunctionEnd; Tick functionEntryTick; void enableFunctionTrace(); void traceFunctionsInternal(Addr pc); private: static std::vector<BaseCPU *> cpuList; //!< Static global cpu list public: void traceFunctions(Addr pc) { if (functionTracingEnabled) traceFunctionsInternal(pc); } static int numSimulatedCPUs() { return cpuList.size(); } static Counter numSimulatedInsts() { Counter total = 0; int size = cpuList.size(); for (int i = 0; i < size; ++i) total += cpuList[i]->totalInsts(); return total; } static Counter numSimulatedOps() { Counter total = 0; int size = cpuList.size(); for (int i = 0; i < size; ++i) total += cpuList[i]->totalOps(); return total; } public: // Number of CPU cycles simulated Stats::Scalar numCycles; Stats::Scalar numWorkItemsStarted; Stats::Scalar numWorkItemsCompleted; }; #endif // __CPU_BASE_HH__
/* * Copyright (c) 2011-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2011 Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Nathan Binkert * Rick Strong */ #ifndef __CPU_BASE_HH__ #define __CPU_BASE_HH__ #include <vector> #include "arch/interrupts.hh" #include "arch/isa_traits.hh" #include "arch/microcode_rom.hh" #include "base/statistics.hh" #include "config/the_isa.hh" #include "mem/mem_object.hh" #include "sim/eventq.hh" #include "sim/full_system.hh" #include "sim/insttracer.hh" #include "sim/system.hh" struct BaseCPUParams; class CheckerCPU; class ThreadContext; class CPUProgressEvent : public Event { protected: Tick _interval; Counter lastNumInst; BaseCPU *cpu; bool _repeatEvent; public: CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0); void process(); void interval(Tick ival) { _interval = ival; } Tick interval() { return _interval; } void repeatEvent(bool repeat) { _repeatEvent = repeat; } virtual const char *description() const; }; class BaseCPU : public MemObject { protected: // @todo remove me after debugging with legion done Tick instCnt; // every cpu has an id, put it in the base cpu // Set at initialization, only time a cpuId might change is during a // takeover (which should be done from within the BaseCPU anyway, // therefore no setCpuId() method is provided int _cpuId; /** instruction side request id that must be placed in all requests */ MasterID _instMasterId; /** data side request id that must be placed in all requests */ MasterID _dataMasterId; /** An intrenal representation of a task identifier within gem5. This is * used so the CPU can add which taskId (which is an internal representation * of the OS process ID) to each request so components in the memory system * can track which process IDs are ultimately interacting with them */ uint32_t _taskId; /** The current OS process ID that is executing on this processor. This is * used to generate a taskId */ uint32_t _pid; /** Is the CPU switched out or active? */ bool _switchedOut; /** Cache the cache line size that we get from the system */ const unsigned int _cacheLineSize; public: /** * Purely virtual method that returns a reference to the data * port. All subclasses must implement this method. * * @return a reference to the data port */ virtual MasterPort &getDataPort() = 0; /** * Purely virtual method that returns a reference to the instruction * port. All subclasses must implement this method. * * @return a reference to the instruction port */ virtual MasterPort &getInstPort() = 0; /** Reads this CPU's ID. */ int cpuId() { return _cpuId; } /** Reads this CPU's unique data requestor ID */ MasterID dataMasterId() { return _dataMasterId; } /** Reads this CPU's unique instruction requestor ID */ MasterID instMasterId() { return _instMasterId; } /** * Get a master port on this CPU. All CPUs have a data and * instruction port, and this method uses getDataPort and * getInstPort of the subclasses to resolve the two ports. * * @param if_name the port name * @param idx ignored index * * @return a reference to the port with the given name */ BaseMasterPort &getMasterPort(const std::string &if_name, PortID idx = InvalidPortID); /** Get cpu task id */ uint32_t taskId() const { return _taskId; } /** Set cpu task id */ void taskId(uint32_t id) { _taskId = id; } uint32_t getPid() const { return _pid; } void setPid(uint32_t pid) { _pid = pid; } inline void workItemBegin() { numWorkItemsStarted++; } inline void workItemEnd() { numWorkItemsCompleted++; } // @todo remove me after debugging with legion done Tick instCount() { return instCnt; } TheISA::MicrocodeRom microcodeRom; protected: TheISA::Interrupts *interrupts; public: TheISA::Interrupts * getInterruptController() { return interrupts; } virtual void wakeup() = 0; void postInterrupt(int int_num, int index) { interrupts->post(int_num, index); if (FullSystem) wakeup(); } void clearInterrupt(int int_num, int index) { interrupts->clear(int_num, index); } void clearInterrupts() { interrupts->clearAll(); } bool checkInterrupts(ThreadContext *tc) const { return FullSystem && interrupts->checkInterrupts(tc); } class ProfileEvent : public Event { private: BaseCPU *cpu; Tick interval; public: ProfileEvent(BaseCPU *cpu, Tick interval); void process(); }; ProfileEvent *profileEvent; protected: std::vector<ThreadContext *> threadContexts; Trace::InstTracer * tracer; public: // Mask to align PCs to MachInst sized boundaries static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1); /// Provide access to the tracer pointer Trace::InstTracer * getTracer() { return tracer; } /// Notify the CPU that the indicated context is now active. The /// delay parameter indicates the number of ticks to wait before /// executing (typically 0 or 1). virtual void activateContext(ThreadID thread_num, Cycles delay) {} /// Notify the CPU that the indicated context is now suspended. virtual void suspendContext(ThreadID thread_num) {} /// Notify the CPU that the indicated context is now deallocated. virtual void deallocateContext(ThreadID thread_num) {} /// Notify the CPU that the indicated context is now halted. virtual void haltContext(ThreadID thread_num) {} /// Given a Thread Context pointer return the thread num int findContext(ThreadContext *tc); /// Given a thread num get tho thread context for it virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; } public: typedef BaseCPUParams Params; const Params *params() const { return reinterpret_cast<const Params *>(_params); } BaseCPU(Params *params, bool is_checker = false); virtual ~BaseCPU(); virtual void init(); virtual void startup(); virtual void regStats(); virtual void activateWhenReady(ThreadID tid) {}; void registerThreadContexts(); /** * Prepare for another CPU to take over execution. * * When this method exits, all internal state should have been * flushed. After the method returns, the simulator calls * takeOverFrom() on the new CPU with this CPU as its parameter. */ virtual void switchOut(); /** * Load the state of a CPU from the previous CPU object, invoked * on all new CPUs that are about to be switched in. * * A CPU model implementing this method is expected to initialize * its state from the old CPU and connect its memory (unless they * are already connected) to the memories connected to the old * CPU. * * @param cpu CPU to initialize read state from. */ virtual void takeOverFrom(BaseCPU *cpu); /** * Flush all TLBs in the CPU. * * This method is mainly used to flush stale translations when * switching CPUs. It is also exported to the Python world to * allow it to request a TLB flush after draining the CPU to make * it easier to compare traces when debugging * handover/checkpointing. */ void flushTLBs(); /** * Determine if the CPU is switched out. * * @return True if the CPU is switched out, false otherwise. */ bool switchedOut() const { return _switchedOut; } /** * Verify that the system is in a memory mode supported by the * CPU. * * Implementations are expected to query the system for the * current memory mode and ensure that it is what the CPU model * expects. If the check fails, the implementation should * terminate the simulation using fatal(). */ virtual void verifyMemoryMode() const { }; /** * Number of threads we're actually simulating (<= SMT_MAX_THREADS). * This is a constant for the duration of the simulation. */ ThreadID numThreads; /** * Vector of per-thread instruction-based event queues. Used for * scheduling events based on number of instructions committed by * a particular thread. */ EventQueue **comInstEventQueue; /** * Vector of per-thread load-based event queues. Used for * scheduling events based on number of loads committed by *a particular thread. */ EventQueue **comLoadEventQueue; System *system; /** * Get the cache line size of the system. */ inline unsigned int cacheLineSize() const { return _cacheLineSize; } /** * Serialize this object to the given output stream. * * @note CPU models should normally overload the serializeThread() * method instead of the serialize() method as this provides a * uniform data format for all CPU models and promotes better code * reuse. * * @param os The stream to serialize to. */ virtual void serialize(std::ostream &os); /** * Reconstruct the state of this object from a checkpoint. * * @note CPU models should normally overload the * unserializeThread() method instead of the unserialize() method * as this provides a uniform data format for all CPU models and * promotes better code reuse. * @param cp The checkpoint use. * @param section The section name of this object. */ virtual void unserialize(Checkpoint *cp, const std::string &section); /** * Serialize a single thread. * * @param os The stream to serialize to. * @param tid ID of the current thread. */ virtual void serializeThread(std::ostream &os, ThreadID tid) {}; /** * Unserialize one thread. * * @param cp The checkpoint use. * @param section The section name of this thread. * @param tid ID of the current thread. */ virtual void unserializeThread(Checkpoint *cp, const std::string &section, ThreadID tid) {}; virtual Counter totalInsts() const = 0; virtual Counter totalOps() const = 0; /** * Schedule an event that exits the simulation loops after a * predefined number of instructions. * * This method is usually called from the configuration script to * get an exit event some time in the future. It is typically used * when the script wants to simulate for a specific number of * instructions rather than ticks. * * @param tid Thread monitor. * @param insts Number of instructions into the future. * @param cause Cause to signal in the exit event. */ void scheduleInstStop(ThreadID tid, Counter insts, const char *cause); /** * Schedule an event that exits the simulation loops after a * predefined number of load operations. * * This method is usually called from the configuration script to * get an exit event some time in the future. It is typically used * when the script wants to simulate for a specific number of * loads rather than ticks. * * @param tid Thread monitor. * @param loads Number of load instructions into the future. * @param cause Cause to signal in the exit event. */ void scheduleLoadStop(ThreadID tid, Counter loads, const char *cause); // Function tracing private: bool functionTracingEnabled; std::ostream *functionTraceStream; Addr currentFunctionStart; Addr currentFunctionEnd; Tick functionEntryTick; void enableFunctionTrace(); void traceFunctionsInternal(Addr pc); private: static std::vector<BaseCPU *> cpuList; //!< Static global cpu list public: void traceFunctions(Addr pc) { if (functionTracingEnabled) traceFunctionsInternal(pc); } static int numSimulatedCPUs() { return cpuList.size(); } static Counter numSimulatedInsts() { Counter total = 0; int size = cpuList.size(); for (int i = 0; i < size; ++i) total += cpuList[i]->totalInsts(); return total; } static Counter numSimulatedOps() { Counter total = 0; int size = cpuList.size(); for (int i = 0; i < size; ++i) total += cpuList[i]->totalOps(); return total; } public: // Number of CPU cycles simulated Stats::Scalar numCycles; Stats::Scalar numWorkItemsStarted; Stats::Scalar numWorkItemsCompleted; }; #endif // __CPU_BASE_HH__
Remove unused getBranchPred() method from BaseCPU
cpu: Remove unused getBranchPred() method from BaseCPU Remove unused virtual getBranchPred() method from BaseCPU as it is not implemented by any of the CPU models. It used to always return NULL.
C++
bsd-3-clause
LingxiaoJIA/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5
13bad8d61c1a1d25328ae99daf50ac71294b8bb1
src/deps_log.cc
src/deps_log.cc
// Copyright 2012 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. #include "deps_log.h" #include <assert.h> #include <stdio.h> #include <errno.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #endif #include "graph.h" #include "metrics.h" #include "state.h" #include "util.h" // The version is stored as 4 bytes after the signature and also serves as a // byte order mark. Signature and version combined are 16 bytes long. const char kFileSignature[] = "# ninjadeps\n"; const int kCurrentVersion = 1; DepsLog::~DepsLog() { Close(); } bool DepsLog::OpenForWrite(const string& path, string* err) { if (needs_recompaction_) { Close(); if (!Recompact(path, err)) return false; } file_ = fopen(path.c_str(), "ab"); if (!file_) { *err = strerror(errno); return false; } SetCloseOnExec(fileno(file_)); // Opening a file in append mode doesn't set the file pointer to the file's // end on Windows. Do that explicitly. fseek(file_, 0, SEEK_END); if (ftell(file_) == 0) { if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) { *err = strerror(errno); return false; } if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) { *err = strerror(errno); return false; } } return true; } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, const vector<Node*>& nodes) { return RecordDeps(node, mtime, nodes.size(), nodes.empty() ? NULL : (Node**)&nodes.front()); } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, int node_count, Node** nodes) { // Track whether there's any new data to be recorded. bool made_change = false; // Assign ids to all nodes that are missing one. if (node->id() < 0) { RecordId(node); made_change = true; } for (int i = 0; i < node_count; ++i) { if (nodes[i]->id() < 0) { RecordId(nodes[i]); made_change = true; } } // See if the new data is different than the existing data, if any. if (!made_change) { Deps* deps = GetDeps(node); if (!deps || deps->mtime != mtime || deps->node_count != node_count) { made_change = true; } else { for (int i = 0; i < node_count; ++i) { if (deps->nodes[i] != nodes[i]) { made_change = true; break; } } } } // Don't write anything if there's no new info. if (!made_change) return true; // Update on-disk representation. uint16_t size = 4 * (1 + 1 + (uint16_t)node_count); size |= 0x8000; // Deps record: set high bit. fwrite(&size, 2, 1, file_); int id = node->id(); fwrite(&id, 4, 1, file_); int timestamp = mtime; fwrite(&timestamp, 4, 1, file_); for (int i = 0; i < node_count; ++i) { id = nodes[i]->id(); fwrite(&id, 4, 1, file_); } // Update in-memory representation. Deps* deps = new Deps(mtime, node_count); for (int i = 0; i < node_count; ++i) deps->nodes[i] = nodes[i]; UpdateDeps(node->id(), deps); return true; } void DepsLog::Close() { if (file_) fclose(file_); file_ = NULL; } bool DepsLog::Load(const string& path, State* state, string* err) { METRIC_RECORD(".ninja_deps load"); char buf[32 << 10]; FILE* f = fopen(path.c_str(), "rb"); if (!f) { if (errno == ENOENT) return true; *err = strerror(errno); return false; } bool valid_header = true; int version = 0; if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1) valid_header = false; if (!valid_header || strcmp(buf, kFileSignature) != 0 || version != kCurrentVersion) { *err = "bad deps log signature or version; starting over"; fclose(f); unlink(path.c_str()); // Don't report this as a failure. An empty deps log will cause // us to rebuild the outputs anyway. return true; } long offset; bool read_failed = false; int unique_dep_record_count = 0; int total_dep_record_count = 0; for (;;) { offset = ftell(f); uint16_t size; if (fread(&size, 2, 1, f) < 1) { if (!feof(f)) read_failed = true; break; } bool is_deps = (size >> 15) != 0; size = size & 0x7FFF; if (fread(buf, size, 1, f) < 1) { read_failed = true; break; } if (is_deps) { assert(size % 4 == 0); int* deps_data = reinterpret_cast<int*>(buf); int out_id = deps_data[0]; int mtime = deps_data[1]; deps_data += 2; int deps_count = (size / 4) - 2; Deps* deps = new Deps(mtime, deps_count); for (int i = 0; i < deps_count; ++i) { assert(deps_data[i] < (int)nodes_.size()); assert(nodes_[deps_data[i]]); deps->nodes[i] = nodes_[deps_data[i]]; } total_dep_record_count++; if (!UpdateDeps(out_id, deps)) ++unique_dep_record_count; } else { StringPiece path(buf, size); Node* node = state->GetNode(path); assert(node->id() < 0); node->set_id(nodes_.size()); nodes_.push_back(node); } } if (read_failed) { // An error occurred while loading; try to recover by truncating the // file to the last fully-read record. if (ferror(f)) { *err = strerror(ferror(f)); } else { *err = "premature end of file"; } fclose(f); if (!Truncate(path.c_str(), offset, err)) return false; // The truncate succeeded; we'll just report the load error as a // warning because the build can proceed. *err += "; recovering"; return true; } fclose(f); // Rebuild the log if there are too many dead records. int kMinCompactionEntryCount = 1000; int kCompactionRatio = 3; if (total_dep_record_count > kMinCompactionEntryCount && total_dep_record_count > unique_dep_record_count * kCompactionRatio) { needs_recompaction_ = true; } return true; } DepsLog::Deps* DepsLog::GetDeps(Node* node) { // Abort if the node has no id (never referenced in the deps) or if // there's no deps recorded for the node. if (node->id() < 0 || node->id() >= (int)deps_.size()) return NULL; return deps_[node->id()]; } bool DepsLog::Recompact(const string& path, string* err) { METRIC_RECORD(".ninja_deps recompact"); printf("Recompacting deps...\n"); string temp_path = path + ".recompact"; // OpenForWrite() opens for append. Make sure it's not appending to a // left-over file from a previous recompaction attempt that crashed somehow. unlink(temp_path.c_str()); DepsLog new_log; if (!new_log.OpenForWrite(temp_path, err)) return false; // Clear all known ids so that new ones can be reassigned. The new indices // will refer to the ordering in new_log, not in the current log. for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i) (*i)->set_id(-1); // Write out all deps again. for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) { Deps* deps = deps_[old_id]; if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps. if (!new_log.RecordDeps(nodes_[old_id], deps->mtime, deps->node_count, deps->nodes)) { new_log.Close(); return false; } } new_log.Close(); // All nodes now have ids that refer to new_log, so steal its data. deps_.swap(new_log.deps_); nodes_.swap(new_log.nodes_); if (unlink(path.c_str()) < 0) { *err = strerror(errno); return false; } if (rename(temp_path.c_str(), path.c_str()) < 0) { *err = strerror(errno); return false; } return true; } bool DepsLog::UpdateDeps(int out_id, Deps* deps) { if (out_id >= (int)deps_.size()) deps_.resize(out_id + 1); bool delete_old = deps_[out_id] != NULL; if (delete_old) delete deps_[out_id]; deps_[out_id] = deps; return delete_old; } bool DepsLog::RecordId(Node* node) { uint16_t size = (uint16_t)node->path().size(); fwrite(&size, 2, 1, file_); fwrite(node->path().data(), node->path().size(), 1, file_); node->set_id(nodes_.size()); nodes_.push_back(node); return true; }
// Copyright 2012 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. #include "deps_log.h" #include <assert.h> #include <stdio.h> #include <errno.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #endif #include "graph.h" #include "metrics.h" #include "state.h" #include "util.h" // The version is stored as 4 bytes after the signature and also serves as a // byte order mark. Signature and version combined are 16 bytes long. const char kFileSignature[] = "# ninjadeps\n"; const int kCurrentVersion = 1; // Since the size field is 2 bytes and the top bit marks deps entries, a single // record can be at most 32 kB. Set the buffer size to this and flush the file // buffer after every record to make sure records aren't written partially. const int kMaxBufferSize = 1 << 15; DepsLog::~DepsLog() { Close(); } bool DepsLog::OpenForWrite(const string& path, string* err) { if (needs_recompaction_) { Close(); if (!Recompact(path, err)) return false; } file_ = fopen(path.c_str(), "ab"); if (!file_) { *err = strerror(errno); return false; } setvbuf(file_, NULL, _IOFBF, kMaxBufferSize); SetCloseOnExec(fileno(file_)); // Opening a file in append mode doesn't set the file pointer to the file's // end on Windows. Do that explicitly. fseek(file_, 0, SEEK_END); if (ftell(file_) == 0) { if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) { *err = strerror(errno); return false; } if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) { *err = strerror(errno); return false; } } fflush(file_); return true; } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, const vector<Node*>& nodes) { return RecordDeps(node, mtime, nodes.size(), nodes.empty() ? NULL : (Node**)&nodes.front()); } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, int node_count, Node** nodes) { // Track whether there's any new data to be recorded. bool made_change = false; // Assign ids to all nodes that are missing one. if (node->id() < 0) { RecordId(node); made_change = true; } for (int i = 0; i < node_count; ++i) { if (nodes[i]->id() < 0) { RecordId(nodes[i]); made_change = true; } } // See if the new data is different than the existing data, if any. if (!made_change) { Deps* deps = GetDeps(node); if (!deps || deps->mtime != mtime || deps->node_count != node_count) { made_change = true; } else { for (int i = 0; i < node_count; ++i) { if (deps->nodes[i] != nodes[i]) { made_change = true; break; } } } } // Don't write anything if there's no new info. if (!made_change) return true; // Update on-disk representation. uint16_t size = 4 * (1 + 1 + (uint16_t)node_count); size |= 0x8000; // Deps record: set high bit. fwrite(&size, 2, 1, file_); int id = node->id(); fwrite(&id, 4, 1, file_); int timestamp = mtime; fwrite(&timestamp, 4, 1, file_); for (int i = 0; i < node_count; ++i) { id = nodes[i]->id(); fwrite(&id, 4, 1, file_); } fflush(file_); // Update in-memory representation. Deps* deps = new Deps(mtime, node_count); for (int i = 0; i < node_count; ++i) deps->nodes[i] = nodes[i]; UpdateDeps(node->id(), deps); return true; } void DepsLog::Close() { if (file_) fclose(file_); file_ = NULL; } bool DepsLog::Load(const string& path, State* state, string* err) { METRIC_RECORD(".ninja_deps load"); char buf[32 << 10]; FILE* f = fopen(path.c_str(), "rb"); if (!f) { if (errno == ENOENT) return true; *err = strerror(errno); return false; } bool valid_header = true; int version = 0; if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1) valid_header = false; if (!valid_header || strcmp(buf, kFileSignature) != 0 || version != kCurrentVersion) { *err = "bad deps log signature or version; starting over"; fclose(f); unlink(path.c_str()); // Don't report this as a failure. An empty deps log will cause // us to rebuild the outputs anyway. return true; } long offset; bool read_failed = false; int unique_dep_record_count = 0; int total_dep_record_count = 0; for (;;) { offset = ftell(f); uint16_t size; if (fread(&size, 2, 1, f) < 1) { if (!feof(f)) read_failed = true; break; } bool is_deps = (size >> 15) != 0; size = size & 0x7FFF; if (fread(buf, size, 1, f) < 1) { read_failed = true; break; } if (is_deps) { assert(size % 4 == 0); int* deps_data = reinterpret_cast<int*>(buf); int out_id = deps_data[0]; int mtime = deps_data[1]; deps_data += 2; int deps_count = (size / 4) - 2; Deps* deps = new Deps(mtime, deps_count); for (int i = 0; i < deps_count; ++i) { assert(deps_data[i] < (int)nodes_.size()); assert(nodes_[deps_data[i]]); deps->nodes[i] = nodes_[deps_data[i]]; } total_dep_record_count++; if (!UpdateDeps(out_id, deps)) ++unique_dep_record_count; } else { StringPiece path(buf, size); Node* node = state->GetNode(path); assert(node->id() < 0); node->set_id(nodes_.size()); nodes_.push_back(node); } } if (read_failed) { // An error occurred while loading; try to recover by truncating the // file to the last fully-read record. if (ferror(f)) { *err = strerror(ferror(f)); } else { *err = "premature end of file"; } fclose(f); if (!Truncate(path.c_str(), offset, err)) return false; // The truncate succeeded; we'll just report the load error as a // warning because the build can proceed. *err += "; recovering"; return true; } fclose(f); // Rebuild the log if there are too many dead records. int kMinCompactionEntryCount = 1000; int kCompactionRatio = 3; if (total_dep_record_count > kMinCompactionEntryCount && total_dep_record_count > unique_dep_record_count * kCompactionRatio) { needs_recompaction_ = true; } return true; } DepsLog::Deps* DepsLog::GetDeps(Node* node) { // Abort if the node has no id (never referenced in the deps) or if // there's no deps recorded for the node. if (node->id() < 0 || node->id() >= (int)deps_.size()) return NULL; return deps_[node->id()]; } bool DepsLog::Recompact(const string& path, string* err) { METRIC_RECORD(".ninja_deps recompact"); printf("Recompacting deps...\n"); string temp_path = path + ".recompact"; // OpenForWrite() opens for append. Make sure it's not appending to a // left-over file from a previous recompaction attempt that crashed somehow. unlink(temp_path.c_str()); DepsLog new_log; if (!new_log.OpenForWrite(temp_path, err)) return false; // Clear all known ids so that new ones can be reassigned. The new indices // will refer to the ordering in new_log, not in the current log. for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i) (*i)->set_id(-1); // Write out all deps again. for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) { Deps* deps = deps_[old_id]; if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps. if (!new_log.RecordDeps(nodes_[old_id], deps->mtime, deps->node_count, deps->nodes)) { new_log.Close(); return false; } } new_log.Close(); // All nodes now have ids that refer to new_log, so steal its data. deps_.swap(new_log.deps_); nodes_.swap(new_log.nodes_); if (unlink(path.c_str()) < 0) { *err = strerror(errno); return false; } if (rename(temp_path.c_str(), path.c_str()) < 0) { *err = strerror(errno); return false; } return true; } bool DepsLog::UpdateDeps(int out_id, Deps* deps) { if (out_id >= (int)deps_.size()) deps_.resize(out_id + 1); bool delete_old = deps_[out_id] != NULL; if (delete_old) delete deps_[out_id]; deps_[out_id] = deps; return delete_old; } bool DepsLog::RecordId(Node* node) { uint16_t size = (uint16_t)node->path().size(); fwrite(&size, 2, 1, file_); fwrite(node->path().data(), node->path().size(), 1, file_); fflush(file_); node->set_id(nodes_.size()); nodes_.push_back(node); return true; }
Make sure to not write partial deps entries.
Make sure to not write partial deps entries. When two ninja instances run in parallel in the same build directory, one instance could write a deps entry header and a few ids, and then the other instance could write a file name in the middle of the deps header. When ninja reads this deps log on the next run, it will deserialize the file name as indices, which will cause an out-of-bounds read. (This can happen if a user runs a "compile this file" that uses ninja to compile the current buffer in an editor, and also does a full build in a terminal at the same time for example.) While running two ninja instances in parallel in the same build directory isn't a good idea, it happens to mostly work in non-deps mode: There's redundant edge execution, but nothing crashes. This is partially because the command log is line-buffered and a single log entry only consists of a single line. This change makes sure that deps entries are always written in one go, like command log entries currently are. Running two ninja binaries in parallel on the same build directory still isn't a great idea, but it's less likely to lead to crashes. See issue #595.
C++
apache-2.0
liukd/ninja,purcell/ninja,synaptek/ninja,fuchsia-mirror/third_party-ninja,dpwright/ninja,Maratyszcza/ninja-pypi,nafest/ninja,iwadon/ninja,rjogrady/ninja,jendrikillner/ninja,nico/ninja,ctiller/ninja,sxlin/dist_ninja,tfarina/ninja,nicolasdespres/ninja,colincross/ninja,dpwright/ninja,ignatenkobrain/ninja,kissthink/ninja,atetubou/ninja,mgaunard/ninja,ThiagoGarciaAlves/ninja,bmeurer/ninja,kimgr/ninja,colincross/ninja,rjogrady/ninja,fifoforlifo/ninja,synaptek/ninja,bradking/ninja,dpwright/ninja,mohamed/ninja,guiquanz/ninja,sgraham/ninja,martine/ninja,kimgr/ninja,sgraham/ninja,rjogrady/ninja,metti/ninja,maruel/ninja,jhanssen/ninja,yannicklm/ninja,ninja-build/ninja,bradking/ninja,drbo/ninja,nocnokneo/ninja,juntalis/ninja,yannicklm/ninja,synaptek/ninja,martine/ninja,syntheticpp/ninja,glensc/ninja,AoD314/ninja,fifoforlifo/ninja,dendy/ninja,iwadon/ninja,mydongistiny/ninja,ndsol/subninja,rnk/ninja,ndsol/subninja,yannicklm/ninja,nafest/ninja,mohamed/ninja,juntalis/ninja,Ju2ender/ninja,rjogrady/ninja,tfarina/ninja,nico/ninja,sorbits/ninja,liukd/ninja,glensc/ninja,nocnokneo/ninja,ThiagoGarciaAlves/ninja,sorbits/ninja,dorgonman/ninja,ilor/ninja,mgaunard/ninja,syntheticpp/ninja,moroten/ninja,bmeurer/ninja,fuchsia-mirror/third_party-ninja,vvvrrooomm/ninja,moroten/ninja,ninja-build/ninja,moroten/ninja,nocnokneo/ninja,rnk/ninja,ignatenkobrain/ninja,AoD314/ninja,fuchsia-mirror/third_party-ninja,drbo/ninja,hnney/ninja,glensc/ninja,jendrikillner/ninja,dorgonman/ninja,yannicklm/ninja,tfarina/ninja,automeka/ninja,AoD314/ninja,sxlin/dist_ninja,syntheticpp/ninja,sxlin/dist_ninja,iwadon/ninja,sorbits/ninja,metti/ninja,liukd/ninja,nicolasdespres/ninja,Ju2ender/ninja,Ju2ender/ninja,nafest/ninja,ilor/ninja,juntalis/ninja,nickhutchinson/ninja,guiquanz/ninja,syntheticpp/ninja,dendy/ninja,bmeurer/ninja,automeka/ninja,atetubou/ninja,hnney/ninja,jhanssen/ninja,automeka/ninja,Qix-/ninja,ninja-build/ninja,nickhutchinson/ninja,tfarina/ninja,ndsol/subninja,dendy/ninja,sxlin/dist_ninja,nico/ninja,moroten/ninja,colincross/ninja,ninja-build/ninja,kissthink/ninja,guiquanz/ninja,dorgonman/ninja,mohamed/ninja,martine/ninja,sorbits/ninja,fifoforlifo/ninja,mgaunard/ninja,nafest/ninja,autopulated/ninja,lizh06/ninja,ilor/ninja,purcell/ninja,lizh06/ninja,nickhutchinson/ninja,dpwright/ninja,nicolasdespres/ninja,ThiagoGarciaAlves/ninja,fifoforlifo/ninja,AoD314/ninja,sxlin/dist_ninja,Qix-/ninja,bradking/ninja,drbo/ninja,iwadon/ninja,jimon/ninja,bradking/ninja,nico/ninja,autopulated/ninja,ctiller/ninja,kimgr/ninja,metti/ninja,Qix-/ninja,jhanssen/ninja,Maratyszcza/ninja-pypi,ilor/ninja,nickhutchinson/ninja,sxlin/dist_ninja,Ju2ender/ninja,ThiagoGarciaAlves/ninja,dendy/ninja,guiquanz/ninja,martine/ninja,metti/ninja,jimon/ninja,colincross/ninja,maruel/ninja,purcell/ninja,jendrikillner/ninja,purcell/ninja,mydongistiny/ninja,kissthink/ninja,juntalis/ninja,atetubou/ninja,jhanssen/ninja,drbo/ninja,ctiller/ninja,Maratyszcza/ninja-pypi,autopulated/ninja,nocnokneo/ninja,liukd/ninja,jendrikillner/ninja,rnk/ninja,glensc/ninja,maruel/ninja,sxlin/dist_ninja,lizh06/ninja,sgraham/ninja,mgaunard/ninja,sgraham/ninja,vvvrrooomm/ninja,vvvrrooomm/ninja,fuchsia-mirror/third_party-ninja,Maratyszcza/ninja-pypi,ignatenkobrain/ninja,automeka/ninja,jimon/ninja,mohamed/ninja,atetubou/ninja,lizh06/ninja,rnk/ninja,dorgonman/ninja,mydongistiny/ninja,maruel/ninja,bmeurer/ninja,vvvrrooomm/ninja,Qix-/ninja,kimgr/ninja,synaptek/ninja,hnney/ninja,ignatenkobrain/ninja,autopulated/ninja,hnney/ninja,nicolasdespres/ninja,kissthink/ninja,ctiller/ninja,ndsol/subninja,jimon/ninja,mydongistiny/ninja
ce2bd472ff4df4627a2806b91e42929466e79e41
src/fb_pool.cxx
src/fb_pool.cxx
/* * An allocator for fifo_buffer objects that can return unused memory * back to the kernel. * * author: Max Kellermann <[email protected]> */ #include "fb_pool.hxx" #include "SlicePool.hxx" #include "event/CleanupTimer.hxx" #include <assert.h> static constexpr size_t FB_SIZE = 8192; static SlicePool *fb_pool; static CleanupTimer fb_cleanup_timer; static bool fb_pool_cleanup(gcc_unused void *ctx) { fb_pool_compress(); return true; } void fb_pool_init(bool auto_cleanup) { assert(fb_pool == nullptr); fb_pool = slice_pool_new(FB_SIZE, 256); assert(fb_pool != nullptr); fb_cleanup_timer.Init(600, fb_pool_cleanup, nullptr); if (auto_cleanup) fb_cleanup_timer.Enable(); } void fb_pool_deinit(void) { assert(fb_pool != nullptr); fb_cleanup_timer.Deinit(); slice_pool_free(fb_pool); fb_pool = nullptr; } void fb_pool_fork_cow(bool inherit) { assert(fb_pool != nullptr); slice_pool_fork_cow(*fb_pool, inherit); } SlicePool & fb_pool_get() { return *fb_pool; } void fb_pool_disable(void) { assert(fb_pool != nullptr); fb_cleanup_timer.Disable(); } void fb_pool_compress(void) { assert(fb_pool != nullptr); slice_pool_compress(fb_pool); }
/* * An allocator for fifo_buffer objects that can return unused memory * back to the kernel. * * author: Max Kellermann <[email protected]> */ #include "fb_pool.hxx" #include "SlicePool.hxx" #include "event/CleanupTimer.hxx" #include <assert.h> static constexpr size_t FB_SIZE = 8192; static SlicePool *fb_pool; static CleanupTimer fb_cleanup_timer; static bool fb_pool_cleanup(gcc_unused void *ctx) { fb_pool_compress(); return true; } void fb_pool_init(bool auto_cleanup) { assert(fb_pool == nullptr); fb_pool = slice_pool_new(FB_SIZE, 256); assert(fb_pool != nullptr); if (auto_cleanup) { fb_cleanup_timer.Init(600, fb_pool_cleanup, nullptr); fb_cleanup_timer.Enable(); } } void fb_pool_deinit(void) { assert(fb_pool != nullptr); if (fb_cleanup_timer.IsInitialized()) fb_cleanup_timer.Deinit(); slice_pool_free(fb_pool); fb_pool = nullptr; } void fb_pool_fork_cow(bool inherit) { assert(fb_pool != nullptr); slice_pool_fork_cow(*fb_pool, inherit); } SlicePool & fb_pool_get() { return *fb_pool; } void fb_pool_disable(void) { assert(fb_pool != nullptr); fb_cleanup_timer.Disable(); } void fb_pool_compress(void) { assert(fb_pool != nullptr); slice_pool_compress(fb_pool); }
initialize the CleanupTimer only if requested
fb_pool: initialize the CleanupTimer only if requested Fixes some libevent warnings in unit tests.
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
dfedea1079979d7ef82eb81130c31c7631e7051d
src/hal/hal.cpp
src/hal/hal.cpp
/******************************************************************************* * Copyright (c) 2015 Matthijs Kooijman * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This the HAL to run LMIC on top of the Arduino environment. *******************************************************************************/ #include <Arduino.h> #include <SPI.h> #include "../lmic.h" #include "hal.h" #include <stdio.h> // ----------------------------------------------------------------------------- // I/O static void hal_io_init () { pinMode(pins.nss, OUTPUT); pinMode(pins.rxtx, OUTPUT); pinMode(pins.rst, OUTPUT); pinMode(pins.dio[0], INPUT); pinMode(pins.dio[1], INPUT); pinMode(pins.dio[2], INPUT); } // val == 1 => tx 1 void hal_pin_rxtx (u1_t val) { digitalWrite(pins.rxtx, val); } // set radio RST pin to given value (or keep floating!) void hal_pin_rst (u1_t val) { if(val == 0 || val == 1) { // drive pin pinMode(pins.rst, OUTPUT); digitalWrite(pins.rst, val); } else { // keep pin floating pinMode(pins.rst, INPUT); } } static bool dio_states[NUM_DIO] = {0}; static void hal_io_check() { uint8_t i; for (i = 0; i < NUM_DIO; ++i) { if (dio_states[i] != digitalRead(pins.dio[i])) { dio_states[i] = !dio_states[i]; if (dio_states[i]) radio_irq_handler(i); } } } // ----------------------------------------------------------------------------- // SPI static const SPISettings settings(10E6, MSBFIRST, SPI_MODE0); static void hal_spi_init () { SPI.begin(); } void hal_pin_nss (u1_t val) { if (!val) SPI.beginTransaction(settings); else SPI.endTransaction(); //Serial.println(val?">>":"<<"); digitalWrite(pins.nss, val); } // perform SPI transaction with radio u1_t hal_spi (u1_t out) { u1_t res = SPI.transfer(out); /* Serial.print(">"); Serial.print(out, HEX); Serial.print("<"); Serial.println(res, HEX); */ return res; } // ----------------------------------------------------------------------------- // TIME static void hal_time_init () { // Nothing to do } u4_t hal_ticks () { // Because micros() is scaled down in this function, micros() will // overflow before the tick timer should, causing the tick timer to // miss a significant part of its values if not corrected. To fix // this, the "overflow" serves as an overflow area for the micros() // counter. It consists of three parts: // - The US_PER_OSTICK upper bits are effectively an extension for // the micros() counter and are added to the result of this // function. // - The next bit overlaps with the most significant bit of // micros(). This is used to detect micros() overflows. // - The remaining bits are always zero. // // By comparing the overlapping bit with the corresponding bit in // the micros() return value, overflows can be detected and the // upper bits are incremented. This is done using some clever // bitwise operations, to remove the need for comparisons and a // jumps, which should result in efficient code. By avoiding shifts // other than by multiples of 8 as much as possible, this is also // efficient on AVR (which only has 1-bit shifts). static uint8_t overflow = 0; // Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0, // the others will be the lower bits of our return value. uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT; // Most significant byte of scaled uint8_t msb = scaled >> 24; // Mask pointing to the overlapping bit in msb and overflow. const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT)); // Update overflow. If the overlapping bit is different // between overflow and msb, it is added to the stored value, // so the overlapping bit becomes equal again and, if it changed // from 1 to 0, the upper bits are incremented. overflow += (msb ^ overflow) & mask; // Return the scaled value with the upper bits of stored added. The // overlapping bit will be equal and the lower bits will be 0, so // bitwise or is a no-op for them. return scaled | ((uint32_t)overflow << 24); // 0 leads to correct, but overly complex code (it could just return // micros() unmodified), 8 leaves no room for the overlapping bit. static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value"); } // Returns the number of ticks until time. Negative values indicate that // time has already passed. static s4_t delta_time(u4_t time) { return (s4_t)(time - hal_ticks()); } void hal_waitUntil (u4_t time) { s4_t delta = delta_time(time); // From delayMicroseconds docs: Currently, the largest value that // will produce an accurate delay is 16383. while (delta > (16000 / US_PER_OSTICK)) { delay(16); delta -= (16000 / US_PER_OSTICK); } if (delta > 0) delayMicroseconds(delta * US_PER_OSTICK); } // check and rewind for target time u1_t hal_checkTimer (u4_t time) { // No need to schedule wakeup, since we're not sleeping return delta_time(time) <= 0; } static uint8_t irqlevel = 0; void hal_disableIRQs () { cli(); irqlevel++; } void hal_enableIRQs () { if(--irqlevel == 0) { sei(); // Instead of using proper interrupts (which are a bit tricky // and/or not available on all pins on AVR), just poll the pin // values. Since os_runloop disables and re-enables interrupts, // putting this here makes sure we check at least once every // loop. // // As an additional bonus, this prevents the can of worms that // we would otherwise get for running SPI transfers inside ISRs hal_io_check(); } } void hal_sleep () { // Not implemented } // ----------------------------------------------------------------------------- #if defined(LMIC_PRINTF_TO) static int uart_putchar (char c, FILE *) { LMIC_PRINTF_TO.write(c) ; return 0 ; } void hal_printf_init() { // create a FILE structure to reference our UART output function static FILE uartout; memset(&uartout, 0, sizeof(uartout)); // fill in the UART file descriptor with pointer to writer. fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); // The uart is the standard output device STDOUT. stdout = &uartout ; } #endif // defined(LMIC_PRINTF_TO) void hal_init () { // configure radio I/O and interrupt handler hal_io_init(); // configure radio SPI hal_spi_init(); // configure timer and interrupt handler hal_time_init(); #if defined(LMIC_PRINTF_TO) // printf support hal_printf_init(); #endif } void hal_failed (const char *file, u2_t line) { #if defined(LMIC_PRINTF_TO) printf("FAILURE %s:%u\n", file, (int)line); LMIC_PRINTF_TO.flush(); #endif hal_disableIRQs(); while(1); }
/******************************************************************************* * Copyright (c) 2015 Matthijs Kooijman * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This the HAL to run LMIC on top of the Arduino environment. *******************************************************************************/ #include <Arduino.h> #include <SPI.h> #include "../lmic.h" #include "hal.h" #include <stdio.h> // ----------------------------------------------------------------------------- // I/O static void hal_io_init () { pinMode(pins.nss, OUTPUT); pinMode(pins.rxtx, OUTPUT); pinMode(pins.rst, OUTPUT); pinMode(pins.dio[0], INPUT); pinMode(pins.dio[1], INPUT); pinMode(pins.dio[2], INPUT); } // val == 1 => tx 1 void hal_pin_rxtx (u1_t val) { digitalWrite(pins.rxtx, val); } // set radio RST pin to given value (or keep floating!) void hal_pin_rst (u1_t val) { if(val == 0 || val == 1) { // drive pin pinMode(pins.rst, OUTPUT); digitalWrite(pins.rst, val); } else { // keep pin floating pinMode(pins.rst, INPUT); } } static bool dio_states[NUM_DIO] = {0}; static void hal_io_check() { uint8_t i; for (i = 0; i < NUM_DIO; ++i) { if (dio_states[i] != digitalRead(pins.dio[i])) { dio_states[i] = !dio_states[i]; if (dio_states[i]) radio_irq_handler(i); } } } // ----------------------------------------------------------------------------- // SPI static const SPISettings settings(10E6, MSBFIRST, SPI_MODE0); static void hal_spi_init () { SPI.begin(); } void hal_pin_nss (u1_t val) { if (!val) SPI.beginTransaction(settings); else SPI.endTransaction(); //Serial.println(val?">>":"<<"); digitalWrite(pins.nss, val); } // perform SPI transaction with radio u1_t hal_spi (u1_t out) { u1_t res = SPI.transfer(out); /* Serial.print(">"); Serial.print(out, HEX); Serial.print("<"); Serial.println(res, HEX); */ return res; } // ----------------------------------------------------------------------------- // TIME static void hal_time_init () { // Nothing to do } u4_t hal_ticks () { // Because micros() is scaled down in this function, micros() will // overflow before the tick timer should, causing the tick timer to // miss a significant part of its values if not corrected. To fix // this, the "overflow" serves as an overflow area for the micros() // counter. It consists of three parts: // - The US_PER_OSTICK upper bits are effectively an extension for // the micros() counter and are added to the result of this // function. // - The next bit overlaps with the most significant bit of // micros(). This is used to detect micros() overflows. // - The remaining bits are always zero. // // By comparing the overlapping bit with the corresponding bit in // the micros() return value, overflows can be detected and the // upper bits are incremented. This is done using some clever // bitwise operations, to remove the need for comparisons and a // jumps, which should result in efficient code. By avoiding shifts // other than by multiples of 8 as much as possible, this is also // efficient on AVR (which only has 1-bit shifts). static uint8_t overflow = 0; // Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0, // the others will be the lower bits of our return value. uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT; // Most significant byte of scaled uint8_t msb = scaled >> 24; // Mask pointing to the overlapping bit in msb and overflow. const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT)); // Update overflow. If the overlapping bit is different // between overflow and msb, it is added to the stored value, // so the overlapping bit becomes equal again and, if it changed // from 1 to 0, the upper bits are incremented. overflow += (msb ^ overflow) & mask; // Return the scaled value with the upper bits of stored added. The // overlapping bit will be equal and the lower bits will be 0, so // bitwise or is a no-op for them. return scaled | ((uint32_t)overflow << 24); // 0 leads to correct, but overly complex code (it could just return // micros() unmodified), 8 leaves no room for the overlapping bit. static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value"); } // Returns the number of ticks until time. Negative values indicate that // time has already passed. static s4_t delta_time(u4_t time) { return (s4_t)(time - hal_ticks()); } void hal_waitUntil (u4_t time) { s4_t delta = delta_time(time); // From delayMicroseconds docs: Currently, the largest value that // will produce an accurate delay is 16383. while (delta > (16000 / US_PER_OSTICK)) { delay(16); delta -= (16000 / US_PER_OSTICK); } if (delta > 0) delayMicroseconds(delta * US_PER_OSTICK); } // check and rewind for target time u1_t hal_checkTimer (u4_t time) { // No need to schedule wakeup, since we're not sleeping return delta_time(time) <= 0; } static uint8_t irqlevel = 0; void hal_disableIRQs () { noInterrupts(); irqlevel++; } void hal_enableIRQs () { if(--irqlevel == 0) { interrupts(); // Instead of using proper interrupts (which are a bit tricky // and/or not available on all pins on AVR), just poll the pin // values. Since os_runloop disables and re-enables interrupts, // putting this here makes sure we check at least once every // loop. // // As an additional bonus, this prevents the can of worms that // we would otherwise get for running SPI transfers inside ISRs hal_io_check(); } } void hal_sleep () { // Not implemented } // ----------------------------------------------------------------------------- #if defined(LMIC_PRINTF_TO) static int uart_putchar (char c, FILE *) { LMIC_PRINTF_TO.write(c) ; return 0 ; } void hal_printf_init() { // create a FILE structure to reference our UART output function static FILE uartout; memset(&uartout, 0, sizeof(uartout)); // fill in the UART file descriptor with pointer to writer. fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); // The uart is the standard output device STDOUT. stdout = &uartout ; } #endif // defined(LMIC_PRINTF_TO) void hal_init () { // configure radio I/O and interrupt handler hal_io_init(); // configure radio SPI hal_spi_init(); // configure timer and interrupt handler hal_time_init(); #if defined(LMIC_PRINTF_TO) // printf support hal_printf_init(); #endif } void hal_failed (const char *file, u2_t line) { #if defined(LMIC_PRINTF_TO) printf("FAILURE %s:%u\n", file, (int)line); LMIC_PRINTF_TO.flush(); #endif hal_disableIRQs(); while(1); }
Use a more portable way to enable and disable interrupts
Use a more portable way to enable and disable interrupts Previously, the AVR-specific cli() and sei() were used, now the generic noInterrupts() and interrupts() provided by Arduino are used.
C++
mit
mcci-catena/arduino-lmic,mcci-catena/arduino-lmic,mcci-catena/arduino-lmic
73f42b70c8a3b73fd2b5d278be9be04d34ae64cd
src/transportserverasio_p.cpp
src/transportserverasio_p.cpp
/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <queue> #include <qi/log.hpp> #include <cerrno> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include "transportserver.hpp" #include "transportsocket.hpp" #include "tcptransportsocket.hpp" #include <qi/eventloop.hpp> #include "transportserverasio_p.hpp" qiLogCategory("qimessaging.transportserver"); namespace qi { const int ifsMonitoringTimeout = 5 * 1000 * 1000; // in usec void _onAccept(TransportServerImplPtr p, const boost::system::error_code& erc, #ifdef WITH_SSL boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s #else boost::asio::ip::tcp::socket* s #endif ) { boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p); ts->onAccept(erc, s); } void TransportServerAsioPrivate::onAccept(const boost::system::error_code& erc, #ifdef WITH_SSL boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s #else boost::asio::ip::tcp::socket* s #endif ) { qiLogDebug() << this << " onAccept"; if (!_live) { delete s; return; } if (erc) { qiLogDebug() << "accept error " << erc.message(); delete s; self->acceptError(erc.value()); delete &_acceptor; return; } qi::TransportSocketPtr socket = qi::TcpTransportSocketPtr(new TcpTransportSocket(context, _ssl, s)); self->newConnection(socket); if (socket.unique()) { qiLogError() << "bug: socket not stored by the newConnection handler (usecount:" << socket.use_count() << ")"; } #ifdef WITH_SSL _s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); #else _s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service()); #endif _acceptor.async_accept(_s->lowest_layer(), boost::bind(_onAccept, shared_from_this(), _1, _s)); } void TransportServerAsioPrivate::close() { qiLogDebug() << this << " close"; try { _asyncEndpoints.cancel(); } catch (const std::runtime_error& e) { qiLogDebug() << e.what(); } _live = false; _acceptor.close(); } /* * This asynchronous call will keep a shared ptr on the object to prevent * its destruction. */ void _updateEndpoints(TransportServerImplPtr p) { boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p); ts->updateEndpoints(); } /* * This function is used to detect and update endpoints when the transport * server is listening on 0.0.0.0. */ void TransportServerAsioPrivate::updateEndpoints() { if (!_live) { return; } // TODO: implement OS networking notifications qiLogDebug() << "Checking endpoints..."; std::vector<qi::Url> currentEndpoints; std::map<std::string, std::vector<std::string> > ifsMap = qi::os::hostIPAddrs(); if (ifsMap.empty()) { const char* s = "Cannot get host addresses"; qiLogWarning() << s; } std::string protocol = _ssl ? "tcps://" : "tcp://"; { for (std::map<std::string, std::vector<std::string> >::iterator interfaceIt = ifsMap.begin(); interfaceIt != ifsMap.end(); ++interfaceIt) { for (std::vector<std::string>::iterator addressIt = (*interfaceIt).second.begin(); addressIt != (*interfaceIt).second.end(); ++addressIt) { std::stringstream ss; ss << protocol << (*addressIt) << ":" << _port; currentEndpoints.push_back(ss.str()); } } } { boost::mutex::scoped_lock l(_endpointsMutex); if (_endpoints.size() != currentEndpoints.size() || !std::equal(_endpoints.begin(), _endpoints.end(), currentEndpoints.begin())) { qiLogVerbose() << "Updating endpoints..."; _endpoints = currentEndpoints; _self->endpointsChanged(); } } _asyncEndpoints = context->async(boost::bind(_updateEndpoints, shared_from_this()), ifsMonitoringTimeout); } qi::Future<void> TransportServerAsioPrivate::listen(const qi::Url& url) { qi::Url listenUrl = url; _ssl = listenUrl.protocol() == "tcps"; using namespace boost::asio; #ifndef ANDROID // resolve endpoint ip::tcp::resolver r(_acceptor.get_io_service()); ip::tcp::resolver::query q(listenUrl.host(), boost::lexical_cast<std::string>(listenUrl.port()), boost::asio::ip::tcp::resolver::query::all_matching); ip::tcp::resolver::iterator it = r.resolve(q); if (it == ip::tcp::resolver::iterator()) { const char* s = "Listen error: no endpoint."; qiLogError() << s; return qi::makeFutureError<void>(s); } ip::tcp::endpoint ep = *it; #else ip::tcp::endpoint ep(boost::asio::ip::address::from_string(url.host()), url.port()); #endif // #ifndef ANDROID qiLogDebug() << "Will listen on " << ep.address().to_string() << ' ' << ep.port(); _acceptor.open(ep.protocol()); #ifdef _WIN32 boost::asio::socket_base::reuse_address option(false); #else boost::asio::socket_base::reuse_address option(true); fcntl(_acceptor.native(), F_SETFD, FD_CLOEXEC); #endif _acceptor.set_option(option); _acceptor.bind(ep); boost::system::error_code ec; _acceptor.listen(socket_base::max_connections, ec); if (ec) { qiLogError("qimessaging.server.listen") << ec.message(); return qi::makeFutureError<void>(ec.message()); } _port = _acceptor.local_endpoint().port();// already in host byte orde qiLogDebug() << "Effective port io_service" << _port; if (listenUrl.port() == 0) { listenUrl = Url(listenUrl.protocol() + "://" + listenUrl.host() + ":" + boost::lexical_cast<std::string>(_port)); } /* Set endpoints */ if (listenUrl.host() != "0.0.0.0") { boost::mutex::scoped_lock l(_endpointsMutex); _endpoints.push_back(listenUrl.str()); } else { updateEndpoints(); } { boost::mutex::scoped_lock l(_endpointsMutex); for (std::vector<qi::Url>::const_iterator it = _endpoints.begin(); it != _endpoints.end(); it++) { qiLogInfo() << "TransportServer will listen on: " << it->str(); } } #ifdef WITH_SSL if (_ssl) { if (self->_identityCertificate.empty() || self->_identityKey.empty()) { const char* s = "SSL certificates missing, please call Session::setIdentity first"; qiLogError("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } _sslContext.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2); _sslContext.use_certificate_chain_file(self->_identityCertificate.c_str()); _sslContext.use_private_key_file(self->_identityKey.c_str(), boost::asio::ssl::context::pem); } _s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); #else _s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service()); #endif _acceptor.async_accept(_s->lowest_layer(), boost::bind(_onAccept, shared_from_this(), _1, _s)); _connectionPromise.setValue(0); return _connectionPromise.future(); } TransportServerAsioPrivate::TransportServerAsioPrivate(TransportServer* self, EventLoop* ctx) : TransportServerImpl(self, ctx) , _self(self) , _acceptor(*new boost::asio::ip::tcp::acceptor(*(boost::asio::io_service*)ctx->nativeHandle())) , _live(true) #ifdef WITH_SSL , _sslContext(*(boost::asio::io_service*)ctx->nativeHandle(), boost::asio::ssl::context::sslv23) #endif , _ssl(false) { } TransportServerAsioPrivate::~TransportServerAsioPrivate() { } }
/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <queue> #include <qi/log.hpp> #include <cerrno> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include "transportserver.hpp" #include "transportsocket.hpp" #include "tcptransportsocket.hpp" #include <qi/eventloop.hpp> #include "transportserverasio_p.hpp" qiLogCategory("qimessaging.transportserver"); namespace qi { const int ifsMonitoringTimeout = 5 * 1000 * 1000; // in usec void _onAccept(TransportServerImplPtr p, const boost::system::error_code& erc, #ifdef WITH_SSL boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s #else boost::asio::ip::tcp::socket* s #endif ) { boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p); ts->onAccept(erc, s); } void TransportServerAsioPrivate::onAccept(const boost::system::error_code& erc, #ifdef WITH_SSL boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s #else boost::asio::ip::tcp::socket* s #endif ) { qiLogDebug() << this << " onAccept"; if (!_live) { delete s; return; } if (erc) { qiLogDebug() << "accept error " << erc.message(); delete s; self->acceptError(erc.value()); delete &_acceptor; return; } qi::TransportSocketPtr socket = qi::TcpTransportSocketPtr(new TcpTransportSocket(context, _ssl, s)); self->newConnection(socket); if (socket.unique()) { qiLogError() << "bug: socket not stored by the newConnection handler (usecount:" << socket.use_count() << ")"; } #ifdef WITH_SSL _s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); #else _s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service()); #endif _acceptor.async_accept(_s->lowest_layer(), boost::bind(_onAccept, shared_from_this(), _1, _s)); } void TransportServerAsioPrivate::close() { qiLogDebug() << this << " close"; try { _asyncEndpoints.cancel(); } catch (const std::runtime_error& e) { qiLogDebug() << e.what(); } _live = false; _acceptor.close(); } /* * This asynchronous call will keep a shared ptr on the object to prevent * its destruction. */ void _updateEndpoints(TransportServerImplPtr p) { boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p); ts->updateEndpoints(); } /* * This function is used to detect and update endpoints when the transport * server is listening on 0.0.0.0. */ void TransportServerAsioPrivate::updateEndpoints() { if (!_live) { return; } // TODO: implement OS networking notifications qiLogDebug() << "Checking endpoints..."; std::vector<qi::Url> currentEndpoints; std::map<std::string, std::vector<std::string> > ifsMap = qi::os::hostIPAddrs(); if (ifsMap.empty()) { const char* s = "Cannot get host addresses"; qiLogWarning() << s; } std::string protocol = _ssl ? "tcps://" : "tcp://"; { for (std::map<std::string, std::vector<std::string> >::iterator interfaceIt = ifsMap.begin(); interfaceIt != ifsMap.end(); ++interfaceIt) { for (std::vector<std::string>::iterator addressIt = (*interfaceIt).second.begin(); addressIt != (*interfaceIt).second.end(); ++addressIt) { std::stringstream ss; ss << protocol << (*addressIt) << ":" << _port; currentEndpoints.push_back(ss.str()); } } } { boost::mutex::scoped_lock l(_endpointsMutex); if (_endpoints.size() != currentEndpoints.size() || !std::equal(_endpoints.begin(), _endpoints.end(), currentEndpoints.begin())) { std::stringstream ss; std::vector<qi::Url>::iterator it; for (it = currentEndpoints.begin(); it != currentEndpoints.end(); ++it) ss << "ep: " << it->str() << std::endl; qiLogVerbose() << "Updating endpoints..." << this << std::endl << ss.str(); _endpoints = currentEndpoints; _self->endpointsChanged(); } } _asyncEndpoints = context->async(boost::bind(_updateEndpoints, shared_from_this()), ifsMonitoringTimeout); } qi::Future<void> TransportServerAsioPrivate::listen(const qi::Url& url) { qi::Url listenUrl = url; _ssl = listenUrl.protocol() == "tcps"; using namespace boost::asio; #ifndef ANDROID // resolve endpoint ip::tcp::resolver r(_acceptor.get_io_service()); ip::tcp::resolver::query q(listenUrl.host(), boost::lexical_cast<std::string>(listenUrl.port()), boost::asio::ip::tcp::resolver::query::all_matching); ip::tcp::resolver::iterator it = r.resolve(q); if (it == ip::tcp::resolver::iterator()) { const char* s = "Listen error: no endpoint."; qiLogError() << s; return qi::makeFutureError<void>(s); } ip::tcp::endpoint ep = *it; #else ip::tcp::endpoint ep(boost::asio::ip::address::from_string(url.host()), url.port()); #endif // #ifndef ANDROID qiLogDebug() << "Will listen on " << ep.address().to_string() << ' ' << ep.port(); _acceptor.open(ep.protocol()); #ifdef _WIN32 boost::asio::socket_base::reuse_address option(false); #else boost::asio::socket_base::reuse_address option(true); fcntl(_acceptor.native(), F_SETFD, FD_CLOEXEC); #endif _acceptor.set_option(option); _acceptor.bind(ep); boost::system::error_code ec; _acceptor.listen(socket_base::max_connections, ec); if (ec) { qiLogError("qimessaging.server.listen") << ec.message(); return qi::makeFutureError<void>(ec.message()); } _port = _acceptor.local_endpoint().port();// already in host byte orde qiLogDebug() << "Effective port io_service" << _port; if (listenUrl.port() == 0) { listenUrl = Url(listenUrl.protocol() + "://" + listenUrl.host() + ":" + boost::lexical_cast<std::string>(_port)); } /* Set endpoints */ if (listenUrl.host() != "0.0.0.0") { boost::mutex::scoped_lock l(_endpointsMutex); _endpoints.push_back(listenUrl.str()); } else { updateEndpoints(); } { boost::mutex::scoped_lock l(_endpointsMutex); for (std::vector<qi::Url>::const_iterator it = _endpoints.begin(); it != _endpoints.end(); it++) { qiLogInfo() << "TransportServer will listen on: " << it->str(); } } #ifdef WITH_SSL if (_ssl) { if (self->_identityCertificate.empty() || self->_identityKey.empty()) { const char* s = "SSL certificates missing, please call Session::setIdentity first"; qiLogError("qimessaging.server.listen") << s; return qi::makeFutureError<void>(s); } _sslContext.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2); _sslContext.use_certificate_chain_file(self->_identityCertificate.c_str()); _sslContext.use_private_key_file(self->_identityKey.c_str(), boost::asio::ssl::context::pem); } _s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext); #else _s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service()); #endif _acceptor.async_accept(_s->lowest_layer(), boost::bind(_onAccept, shared_from_this(), _1, _s)); _connectionPromise.setValue(0); return _connectionPromise.future(); } TransportServerAsioPrivate::TransportServerAsioPrivate(TransportServer* self, EventLoop* ctx) : TransportServerImpl(self, ctx) , _self(self) , _acceptor(*new boost::asio::ip::tcp::acceptor(*(boost::asio::io_service*)ctx->nativeHandle())) , _live(true) #ifdef WITH_SSL , _sslContext(*(boost::asio::io_service*)ctx->nativeHandle(), boost::asio::ssl::context::sslv23) #endif , _ssl(false) { } TransportServerAsioPrivate::~TransportServerAsioPrivate() { } }
improve the logverbose for endpoints update
TransportServerAsio: improve the logverbose for endpoints update Change-Id: I028adb2e21f8156b80e11884c4f9a3305dd2b6dc
C++
bsd-3-clause
aldebaran/libqi,aldebaran/libqi,vbarbaresi/libqi,bsautron/libqi,aldebaran/libqi
1babd2ca86df222e9dd9a187c65ea98ea4fab351
src/trusted/gdb_rsp/target.cc
src/trusted/gdb_rsp/target.cc
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can * be found in the LICENSE file. */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "native_client/src/trusted/gdb_rsp/abi.h" #include "native_client/src/trusted/gdb_rsp/packet.h" #include "native_client/src/trusted/gdb_rsp/target.h" #include "native_client/src/trusted/gdb_rsp/session.h" #include "native_client/src/trusted/gdb_rsp/util.h" #include "native_client/src/trusted/port/platform.h" #include "native_client/src/trusted/port/thread.h" #ifdef WIN32 #define snprintf sprintf_s #endif using std::string; using port::IEvent; using port::IMutex; using port::IPlatform; using port::IThread; using port::MutexLock; namespace gdb_rsp { Target::Target(const Abi* abi) : abi_(abi), mutex_(NULL), sig_start_(NULL), sig_done_(NULL), send_done_(false), ctx_(NULL), cur_signal_(-1), sig_thread_(0), run_thread_(-1), reg_thread_(-1) { if (NULL == abi_) abi_ = Abi::Get(); } Target::~Target() { Destroy(); } bool Target::Init() { string targ_xml = "l<target><architecture>"; targ_xml += abi_->GetName(); targ_xml += "</architecture></target>"; // Set a more specific result which won't change. properties_["target.xml"] = targ_xml; properties_["Supported"] = "PacketSize=7cf;qXfer:libraries:read+;qXfer:features:read+"; mutex_ = IMutex::Allocate(); sig_start_ = IEvent::Allocate(); sig_done_ = IEvent::Allocate(); ctx_ = new uint8_t[abi_->GetContextSize()]; if ((NULL == mutex_) || (NULL == sig_start_) || (NULL == sig_done_) || (NULL == ctx_)) { Destroy(); return false; } // Allow one exception to happen sig_start_->Signal(); return true; } void Target::Destroy() { if (mutex_) IMutex::Free(mutex_); if (sig_start_) IEvent::Free(sig_start_); if (sig_done_) IEvent::Free(sig_done_); delete[] ctx_; } void Target::Signal(uint32_t id, int8_t sig, bool wait) { // Wait for this signal's turn in the signal Q. sig_start_->Wait(); { // Now lock the target, sleeping all active threads MutexLock lock(mutex_); // Suspend all threads except this one uint32_t curId; bool more = GetFirstThreadId(&curId); while (more) { if (curId != id) { IThread *thread = threads_[id]; thread->Suspend(); } more = GetNextThreadId(&curId); } // Signal the stub (Run thread) that we are ready to process // a trap, by updating the signal information and releasing // the lock. reg_thread_ = id; run_thread_ = id; cur_signal_ = sig; } // Wait for permission to continue if (wait) sig_done_->Wait(); } void Target::Run(Session *ses) { do { // Give everyone else a chance to use the lock IPlatform::Relinquish(100); // Lock to prevent anyone else from modifying threads // or updating the signal information. MutexLock lock(mutex_); Packet recv, reply; uint32_t id = 0; // If no signal is waiting for this iteration... if (-1 == cur_signal_) { // but the debugger is talking to us then force a break if (ses->DataAvailable()) { // set signal to 0 to signify paused cur_signal_ = 0; // put all the threads to sleep. uint32_t curId; bool more = GetFirstThreadId(&curId); while (more) { if (curId != id) { IThread *thread = threads_[id]; thread->Suspend(); } more = GetNextThreadId(&curId); } } else { // otherwise, nothing to do so try again. continue; } } else { // otherwise there really is an exception so get the id of the thread id = GetRegThreadId(); } // If we got this far, then there is some kind of signal char tmp[16]; snprintf(tmp, sizeof(tmp), "QC%x", id); properties_["C"] = tmp; // Loop through packets until we process a continue // packet. do { if (ses->GetPacket(&recv)) { reply.Clear(); if (ProcessPacket(&recv, &reply)) { // If this is a continue command, break out of this loop break; } else { // Othwerise send the reponse ses->SendPacket(&reply); } } } while (ses->Connected()); // Now that we are done, we want to continue in the "correct order". // This means letting the active thread go first, in case we are single // stepping and want to catch it again. This is a desired behavior but // it is not gaurrenteed since another thread may already be in an // exception state and next in line to notify the target. // If the run thread is not the exception thread, wake it up now. if (GetRunThreadId() != id) { IThread* thread = threads_[id]; thread->Resume(); } // Next, wake up the exception thread, if there is one and it needs // to wake up. if (id && send_done_) sig_done_->Signal(); // Now wake up everyone else uint32_t curId; bool more = GetFirstThreadId(&curId); while (more) { if ((curId != id) && (curId != GetRunThreadId())) { IThread *thread = threads_[id]; thread->Resume(); } more = GetNextThreadId(&curId); } // Finally, allow the exception to be reported. sig_start_->Signal(); // Continue running until the connection is lost. } while (ses->Connected()); } bool Target::GetFirstThreadId(uint32_t *id) { threadItr_ = threads_.begin(); return GetNextThreadId(id); } bool Target::GetNextThreadId(uint32_t *id) { if (threadItr_ == threads_.end()) return false; *id = (*threadItr_).first; threadItr_++; return true; } bool Target::ProcessPacket(Packet* pktIn, Packet* pktOut) { char cmd; int32_t seq = -1; ErrDef err = NONE; // Clear the outbound message pktOut->Clear(); // Pull out the sequence. pktIn->GetSequence(&seq); if (seq != -1) pktOut->SetSequence(seq); // Find the command pktIn->GetRawChar(&cmd); switch (cmd) { // IN : $? // OUT: $Sxx case '?': pktOut->AddRawChar('S'); pktOut->AddWord8(cur_signal_); break; // IN : $d // OUT: -NONE- case 'd': Detach(); break; // IN : $g // OUT: $xx...xx case 'g': { uint32_t id = GetRegThreadId(); if (0 == id) { err = BAD_ARGS; break; } IThread *thread = GetThread(id); if (NULL == thread) { err = BAD_ARGS; break; } // Copy OS preserved registers to GDB payload for (uint32_t a = 0; a < abi_->GetRegisterCount(); a++) { const Abi::RegDef *def = abi_->GetRegisterDef(a); thread->GetRegister(a, &ctx_[def->offset_], def->bytes_); } pktOut->AddBlock(ctx_, abi_->GetContextSize()); break; } // IN : $Gxx..xx // OUT: $OK case 'G': { uint32_t id = GetRegThreadId(); if (0 == id) { err = BAD_ARGS; break; } IThread *thread = threads_[id]; if (NULL == thread) { err = BAD_ARGS; break; } // GDB payload to OS registers for (uint32_t a = 0; a < abi_->GetRegisterCount(); a++) { const Abi::RegDef *def = abi_->GetRegisterDef(a); thread->SetRegister(a, &ctx_[def->offset_], def->bytes_); } pktOut->AddBlock(ctx_, abi_->GetContextSize()); break; } // IN : $H(c/g)(-1,0,xxxx) // OUT: $OK case 'H': { char type; uint64_t id; if (!pktIn->GetRawChar(&type)) { err = BAD_FORMAT; break; } if (!pktIn->GetNumberSep(&id, 0)) { err = BAD_FORMAT; break; } if (threads_.begin() == threads_.end()) { err = BAD_ARGS; break; } // If we are using "any" get the first thread if (id == static_cast<uint64_t>(-1)) id = threads_.begin()->first; // Verify that we have the thread if (threads_.find(static_cast<uint32_t>(id)) == threads_.end()) { err = BAD_ARGS; break; } pktOut->AddString("OK"); switch (type) { case 'g': reg_thread_ = static_cast<uint32_t>(id); break; case 'c': run_thread_ = static_cast<uint32_t>(id); break; default: err = BAD_ARGS; break; } break; } // IN : $maaaa,llll // OUT: $xx..xx case 'm': { uint64_t addr; uint64_t wlen; uint32_t len; if (!pktIn->GetNumberSep(&addr, 0)) { err = BAD_FORMAT; break; } if (!pktIn->GetNumberSep(&wlen, 0)) { err = BAD_FORMAT; break; } len = static_cast<uint32_t>(wlen); uint8_t *block = new uint8_t[len]; if (!port::IPlatform::GetMemory(addr, len, block)) err = FAILED; pktOut->AddBlock(block, len); break; } // IN : $Maaaa,llll:xx..xx // OUT: $OK case 'M': { uint64_t addr; uint64_t wlen; uint32_t len; if (!pktIn->GetNumberSep(&addr, 0)) { err = BAD_FORMAT; break; } if (!pktIn->GetNumberSep(&wlen, 0)) { err = BAD_FORMAT; break; } len = static_cast<uint32_t>(wlen); uint8_t *block = new uint8_t[len]; pktIn->GetBlock(block, len); if (!port::IPlatform::SetMemory(addr, len, block)) err = FAILED; pktOut->AddString("OK"); break; } case 'q': { string tmp; const char *str = &pktIn->GetPayload()[1]; PropertyMap_t::const_iterator itr = properties_.find(str); // If this is a thread query if (!strcmp(str, "fThreadInfo") || !strcmp(str, "sThreadInfo")) { uint32_t curr; bool more = false; if (str[0] == 'f') { more = GetFirstThreadId(&curr); } else { more = GetNextThreadId(&curr); } if (!more) { pktOut->AddString("l"); } else { pktOut->AddString("m"); pktOut->AddNumberSep(curr, 0); } break; } // Check for architecture query tmp = "Xfer:features:read:target.xml"; if (!strncmp(str, tmp.data(), tmp.length())) { stringvec args = StringSplit(&str[tmp.length()+1], ","); if (args.size() != 2) break; const char *out = properties_["target.xml"].data(); int offs = strtol(args[0].data(), NULL, 16); int max = strtol(args[1].data(), NULL, 16) + offs; int len = static_cast<int>(strlen(out)); if (max >= len) max = len; while (offs < max) { pktOut->AddRawChar(out[offs]); offs++; } break; } // Check the property cache if (itr != properties_.end()) { pktOut->AddString(itr->second.data()); } break; } case 'T': { uint64_t id; if (!pktIn->GetNumberSep(&id, 0)) { err = BAD_FORMAT; break; } if (GetThread(static_cast<uint32_t>(id)) == NULL) { err = BAD_ARGS; break; } pktOut->AddString("OK"); break; } case 's': { IThread *thread = GetThread(GetRunThreadId()); if (thread) thread->SetStep(true); return true; } case 'c': return true; default: { // If the command is not recognzied, ignore it by sending an // empty reply. string str; pktIn->GetString(&str); port::IPlatform::LogError("Unknown command: %s", str.data()); return false; } } // If there is an error, return the error code instead of a payload if (err) { pktOut->Clear(); pktOut->AddRawChar('E'); pktOut->AddWord8(err); } return false; } void Target::TrackThread(IThread* thread) { uint32_t id = thread->GetId(); mutex_->Lock(); threads_[id] = thread; mutex_->Unlock(); } void Target::IgnoreThread(IThread* thread) { uint32_t id = thread->GetId(); mutex_->Lock(); ThreadMap_t::iterator itr = threads_.find(id); if (itr != threads_.end()) threads_.erase(itr); mutex_->Lock(); } void Target::Detach() { port::IPlatform::LogInfo("Requested Detach.\n"); } uint32_t Target::GetRegThreadId() const { ThreadMap_t::const_iterator itr; switch (reg_thread_) { // If we wany "any" then try the signal'd thread first case 0: case 0xFFFFFFFF: itr = threads_.begin(); break; default: itr = threads_.find(reg_thread_); break; } if (itr == threads_.end()) return 0; return itr->first; } uint32_t Target::GetRunThreadId() const { return run_thread_; } IThread* Target::GetThread(uint32_t id) { ThreadMap_t::const_iterator itr; itr = threads_.find(id); if (itr != threads_.end()) return itr->second; return NULL; } } // namespace gdb_rsp
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can * be found in the LICENSE file. */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "native_client/src/trusted/gdb_rsp/abi.h" #include "native_client/src/trusted/gdb_rsp/packet.h" #include "native_client/src/trusted/gdb_rsp/target.h" #include "native_client/src/trusted/gdb_rsp/session.h" #include "native_client/src/trusted/gdb_rsp/util.h" #include "native_client/src/trusted/port/platform.h" #include "native_client/src/trusted/port/thread.h" #ifdef WIN32 #define snprintf sprintf_s #endif using std::string; using port::IEvent; using port::IMutex; using port::IPlatform; using port::IThread; using port::MutexLock; namespace gdb_rsp { Target::Target(const Abi* abi) : abi_(abi), mutex_(NULL), sig_start_(NULL), sig_done_(NULL), send_done_(false), ctx_(NULL), cur_signal_(-1), sig_thread_(0), run_thread_(-1), reg_thread_(-1) { if (NULL == abi_) abi_ = Abi::Get(); } Target::~Target() { Destroy(); } bool Target::Init() { string targ_xml = "l<target><architecture>"; targ_xml += abi_->GetName(); targ_xml += "</architecture></target>"; // Set a more specific result which won't change. properties_["target.xml"] = targ_xml; properties_["Supported"] = "PacketSize=7cf;qXfer:libraries:read+;qXfer:features:read+"; mutex_ = IMutex::Allocate(); sig_start_ = IEvent::Allocate(); sig_done_ = IEvent::Allocate(); ctx_ = new uint8_t[abi_->GetContextSize()]; if ((NULL == mutex_) || (NULL == sig_start_) || (NULL == sig_done_) || (NULL == ctx_)) { Destroy(); return false; } // Allow one exception to happen sig_start_->Signal(); return true; } void Target::Destroy() { if (mutex_) IMutex::Free(mutex_); if (sig_start_) IEvent::Free(sig_start_); if (sig_done_) IEvent::Free(sig_done_); delete[] ctx_; } void Target::Signal(uint32_t id, int8_t sig, bool wait) { // Wait for this signal's turn in the signal Q. sig_start_->Wait(); { // Now lock the target, sleeping all active threads MutexLock lock(mutex_); // Suspend all threads except this one uint32_t curId; bool more = GetFirstThreadId(&curId); while (more) { if (curId != id) { IThread *thread = threads_[id]; thread->Suspend(); } more = GetNextThreadId(&curId); } // Signal the stub (Run thread) that we are ready to process // a trap, by updating the signal information and releasing // the lock. reg_thread_ = id; run_thread_ = id; cur_signal_ = sig; } // Wait for permission to continue if (wait) sig_done_->Wait(); } void Target::Run(Session *ses) { do { // Give everyone else a chance to use the lock IPlatform::Relinquish(100); // Lock to prevent anyone else from modifying threads // or updating the signal information. MutexLock lock(mutex_); Packet recv, reply; uint32_t id = 0; // If no signal is waiting for this iteration... if (-1 == cur_signal_) { // but the debugger is talking to us then force a break if (ses->DataAvailable()) { // set signal to 0 to signify paused cur_signal_ = 0; // put all the threads to sleep. uint32_t curId; bool more = GetFirstThreadId(&curId); while (more) { if (curId != id) { IThread *thread = threads_[curId]; thread->Suspend(); } more = GetNextThreadId(&curId); } } else { // otherwise, nothing to do so try again. continue; } } else { // otherwise there really is an exception so get the id of the thread id = GetRegThreadId(); } // If we got this far, then there is some kind of signal char tmp[16]; snprintf(tmp, sizeof(tmp), "QC%x", id); properties_["C"] = tmp; // Loop through packets until we process a continue // packet. do { if (ses->GetPacket(&recv)) { reply.Clear(); if (ProcessPacket(&recv, &reply)) { // If this is a continue command, break out of this loop break; } else { // Othwerise send the reponse ses->SendPacket(&reply); } } } while (ses->Connected()); // Now that we are done, we want to continue in the "correct order". // This means letting the active thread go first, in case we are single // stepping and want to catch it again. This is a desired behavior but // it is not guaranteed since another thread may already be in an // exception state and next in line to notify the target. // If the run thread is not the exception thread, wake it up now. uint32_t run_thread = GetRunThreadId(); if (run_thread != id && run_thread != static_cast<uint32_t>(-1)) { IThread* thread = threads_[id]; thread->Resume(); } // Next, wake up the exception thread, if there is one and it needs // to wake up. if (id && send_done_) sig_done_->Signal(); // Now wake up everyone else uint32_t curId; bool more = GetFirstThreadId(&curId); while (more) { if ((curId != id) && (curId != GetRunThreadId())) { IThread *thread = threads_[curId]; thread->Resume(); } more = GetNextThreadId(&curId); } // Finally, allow the exception to be reported. sig_start_->Signal(); // Continue running until the connection is lost. } while (ses->Connected()); } bool Target::GetFirstThreadId(uint32_t *id) { threadItr_ = threads_.begin(); return GetNextThreadId(id); } bool Target::GetNextThreadId(uint32_t *id) { if (threadItr_ == threads_.end()) return false; *id = (*threadItr_).first; threadItr_++; return true; } bool Target::ProcessPacket(Packet* pktIn, Packet* pktOut) { char cmd; int32_t seq = -1; ErrDef err = NONE; // Clear the outbound message pktOut->Clear(); // Pull out the sequence. pktIn->GetSequence(&seq); if (seq != -1) pktOut->SetSequence(seq); // Find the command pktIn->GetRawChar(&cmd); switch (cmd) { // IN : $? // OUT: $Sxx case '?': pktOut->AddRawChar('S'); pktOut->AddWord8(cur_signal_); break; // IN : $d // OUT: -NONE- case 'd': Detach(); break; // IN : $g // OUT: $xx...xx case 'g': { uint32_t id = GetRegThreadId(); if (0 == id) { err = BAD_ARGS; break; } IThread *thread = GetThread(id); if (NULL == thread) { err = BAD_ARGS; break; } // Copy OS preserved registers to GDB payload for (uint32_t a = 0; a < abi_->GetRegisterCount(); a++) { const Abi::RegDef *def = abi_->GetRegisterDef(a); thread->GetRegister(a, &ctx_[def->offset_], def->bytes_); } pktOut->AddBlock(ctx_, abi_->GetContextSize()); break; } // IN : $Gxx..xx // OUT: $OK case 'G': { uint32_t id = GetRegThreadId(); if (0 == id) { err = BAD_ARGS; break; } IThread *thread = threads_[id]; if (NULL == thread) { err = BAD_ARGS; break; } // GDB payload to OS registers for (uint32_t a = 0; a < abi_->GetRegisterCount(); a++) { const Abi::RegDef *def = abi_->GetRegisterDef(a); thread->SetRegister(a, &ctx_[def->offset_], def->bytes_); } pktOut->AddBlock(ctx_, abi_->GetContextSize()); break; } // IN : $H(c/g)(-1,0,xxxx) // OUT: $OK case 'H': { char type; uint64_t id; if (!pktIn->GetRawChar(&type)) { err = BAD_FORMAT; break; } if (!pktIn->GetNumberSep(&id, 0)) { err = BAD_FORMAT; break; } if (threads_.begin() == threads_.end()) { err = BAD_ARGS; break; } // If we are using "any" get the first thread if (id == static_cast<uint64_t>(-1)) id = threads_.begin()->first; // Verify that we have the thread if (threads_.find(static_cast<uint32_t>(id)) == threads_.end()) { err = BAD_ARGS; break; } pktOut->AddString("OK"); switch (type) { case 'g': reg_thread_ = static_cast<uint32_t>(id); break; case 'c': run_thread_ = static_cast<uint32_t>(id); break; default: err = BAD_ARGS; break; } break; } // IN : $maaaa,llll // OUT: $xx..xx case 'm': { uint64_t addr; uint64_t wlen; uint32_t len; if (!pktIn->GetNumberSep(&addr, 0)) { err = BAD_FORMAT; break; } if (!pktIn->GetNumberSep(&wlen, 0)) { err = BAD_FORMAT; break; } len = static_cast<uint32_t>(wlen); uint8_t *block = new uint8_t[len]; if (!port::IPlatform::GetMemory(addr, len, block)) err = FAILED; pktOut->AddBlock(block, len); break; } // IN : $Maaaa,llll:xx..xx // OUT: $OK case 'M': { uint64_t addr; uint64_t wlen; uint32_t len; if (!pktIn->GetNumberSep(&addr, 0)) { err = BAD_FORMAT; break; } if (!pktIn->GetNumberSep(&wlen, 0)) { err = BAD_FORMAT; break; } len = static_cast<uint32_t>(wlen); uint8_t *block = new uint8_t[len]; pktIn->GetBlock(block, len); if (!port::IPlatform::SetMemory(addr, len, block)) err = FAILED; pktOut->AddString("OK"); break; } case 'q': { string tmp; const char *str = &pktIn->GetPayload()[1]; PropertyMap_t::const_iterator itr = properties_.find(str); // If this is a thread query if (!strcmp(str, "fThreadInfo") || !strcmp(str, "sThreadInfo")) { uint32_t curr; bool more = false; if (str[0] == 'f') { more = GetFirstThreadId(&curr); } else { more = GetNextThreadId(&curr); } if (!more) { pktOut->AddString("l"); } else { pktOut->AddString("m"); pktOut->AddNumberSep(curr, 0); } break; } // Check for architecture query tmp = "Xfer:features:read:target.xml"; if (!strncmp(str, tmp.data(), tmp.length())) { stringvec args = StringSplit(&str[tmp.length()+1], ","); if (args.size() != 2) break; const char *out = properties_["target.xml"].data(); int offs = strtol(args[0].data(), NULL, 16); int max = strtol(args[1].data(), NULL, 16) + offs; int len = static_cast<int>(strlen(out)); if (max >= len) max = len; while (offs < max) { pktOut->AddRawChar(out[offs]); offs++; } break; } // Check the property cache if (itr != properties_.end()) { pktOut->AddString(itr->second.data()); } break; } case 'T': { uint64_t id; if (!pktIn->GetNumberSep(&id, 0)) { err = BAD_FORMAT; break; } if (GetThread(static_cast<uint32_t>(id)) == NULL) { err = BAD_ARGS; break; } pktOut->AddString("OK"); break; } case 's': { IThread *thread = GetThread(GetRunThreadId()); if (thread) thread->SetStep(true); return true; } case 'c': return true; default: { // If the command is not recognzied, ignore it by sending an // empty reply. string str; pktIn->GetString(&str); port::IPlatform::LogError("Unknown command: %s", str.data()); return false; } } // If there is an error, return the error code instead of a payload if (err) { pktOut->Clear(); pktOut->AddRawChar('E'); pktOut->AddWord8(err); } return false; } void Target::TrackThread(IThread* thread) { uint32_t id = thread->GetId(); mutex_->Lock(); threads_[id] = thread; mutex_->Unlock(); } void Target::IgnoreThread(IThread* thread) { uint32_t id = thread->GetId(); mutex_->Lock(); ThreadMap_t::iterator itr = threads_.find(id); if (itr != threads_.end()) threads_.erase(itr); mutex_->Lock(); } void Target::Detach() { port::IPlatform::LogInfo("Requested Detach.\n"); } uint32_t Target::GetRegThreadId() const { ThreadMap_t::const_iterator itr; switch (reg_thread_) { // If we wany "any" then try the signal'd thread first case 0: case 0xFFFFFFFF: itr = threads_.begin(); break; default: itr = threads_.find(reg_thread_); break; } if (itr == threads_.end()) return 0; return itr->first; } uint32_t Target::GetRunThreadId() const { return run_thread_; } IThread* Target::GetThread(uint32_t id) { ThreadMap_t::const_iterator itr; itr = threads_.find(id); if (itr != threads_.end()) return itr->second; return NULL; } } // namespace gdb_rsp
Fix a couple of minor bugs in target.cc that prevented the debugger from attaching and reattaching properly.
Fix a couple of minor bugs in target.cc that prevented the debugger from attaching and reattaching properly. Review URL: http://codereview.chromium.org/3472005 git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@3349 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
C++
bsd-3-clause
sbc100/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,nacl-webkit/native_client,nacl-webkit/native_client,sbc100/native_client,sbc100/native_client
ceb79403275728562dc7aca11311fbba87b2aa09
src/util/memory/arena-test.cc
src/util/memory/arena-test.cc
// Copyright (c) 2013, Cloudera, inc. #include <boost/foreach.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/thread/thread.hpp> #include <gflags/gflags.h> #include <gtest/gtest.h> #include <glog/logging.h> #include <vector> #include "gutil/stringprintf.h" #include "util/memory/arena.h" DEFINE_int32(num_threads, 16, "Number of threads to test"); DEFINE_int32(allocs_per_thread, 10000, "Number of allocations each thread should do"); DEFINE_int32(alloc_size, 4, "number of bytes in each allocation"); namespace kudu { static void AllocateThread(Arena *arena, uint8_t thread_index) { std::vector<void *> ptrs; ptrs.reserve(FLAGS_allocs_per_thread); char buf[FLAGS_alloc_size]; memset(buf, thread_index, FLAGS_alloc_size); for (int i = 0; i < FLAGS_allocs_per_thread; i++) { void *alloced = arena->AllocateBytes(FLAGS_alloc_size); CHECK(alloced); memcpy(alloced, buf, FLAGS_alloc_size); ptrs.push_back(alloced); } BOOST_FOREACH(void *p, ptrs) { if (memcmp(buf, p, FLAGS_alloc_size) != 0) { FAIL() << StringPrintf("overwritten pointer at %p", p); } } } TEST(TestArena, TestSingleThreaded) { Arena arena(128, 128); AllocateThread(&arena, 0); } TEST(TestArena, TestMultiThreaded) { CHECK(FLAGS_num_threads < 256); Arena arena(1024, 1024); boost::ptr_vector<boost::thread> threads; for (uint8_t i = 0; i < FLAGS_num_threads; i++) { threads.push_back(new boost::thread(AllocateThread, &arena, (uint8_t)i)); } BOOST_FOREACH(boost::thread &thr, threads) { thr.join(); } } }
// Copyright (c) 2013, Cloudera, inc. #include <boost/foreach.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/thread/thread.hpp> #include <gflags/gflags.h> #include <gtest/gtest.h> #include <glog/logging.h> #include <vector> #include "gutil/stringprintf.h" #include "util/memory/arena.h" DEFINE_int32(num_threads, 16, "Number of threads to test"); DEFINE_int32(allocs_per_thread, 10000, "Number of allocations each thread should do"); DEFINE_int32(alloc_size, 4, "number of bytes in each allocation"); namespace kudu { template<class ArenaType> static void AllocateThread(ArenaType *arena, uint8_t thread_index) { std::vector<void *> ptrs; ptrs.reserve(FLAGS_allocs_per_thread); char buf[FLAGS_alloc_size]; memset(buf, thread_index, FLAGS_alloc_size); for (int i = 0; i < FLAGS_allocs_per_thread; i++) { void *alloced = arena->AllocateBytes(FLAGS_alloc_size); CHECK(alloced); memcpy(alloced, buf, FLAGS_alloc_size); ptrs.push_back(alloced); } BOOST_FOREACH(void *p, ptrs) { if (memcmp(buf, p, FLAGS_alloc_size) != 0) { FAIL() << StringPrintf("overwritten pointer at %p", p); } } } // Non-templated function to forward to above -- simplifies // boost::thread creation static void AllocateThreadTSArena(ThreadSafeArena *arena, uint8_t thread_index) { AllocateThread(arena, thread_index); } TEST(TestArena, TestSingleThreaded) { Arena arena(128, 128); AllocateThread(&arena, 0); } TEST(TestArena, TestMultiThreaded) { CHECK(FLAGS_num_threads < 256); ThreadSafeArena arena(1024, 1024); boost::ptr_vector<boost::thread> threads; for (uint8_t i = 0; i < FLAGS_num_threads; i++) { threads.push_back(new boost::thread(AllocateThreadTSArena, &arena, (uint8_t)i)); } BOOST_FOREACH(boost::thread &thr, threads) { thr.join(); } } }
fix to use a ThreadSafeArena for the threaded test
arena-test: fix to use a ThreadSafeArena for the threaded test
C++
apache-2.0
andrwng/kudu,helifu/kudu,EvilMcJerkface/kudu,helifu/kudu,InspurUSA/kudu,helifu/kudu,andrwng/kudu,cloudera/kudu,EvilMcJerkface/kudu,cloudera/kudu,cloudera/kudu,EvilMcJerkface/kudu,helifu/kudu,InspurUSA/kudu,andrwng/kudu,InspurUSA/kudu,EvilMcJerkface/kudu,InspurUSA/kudu,EvilMcJerkface/kudu,cloudera/kudu,InspurUSA/kudu,helifu/kudu,EvilMcJerkface/kudu,EvilMcJerkface/kudu,andrwng/kudu,helifu/kudu,cloudera/kudu,InspurUSA/kudu,andrwng/kudu,InspurUSA/kudu,helifu/kudu,andrwng/kudu,helifu/kudu,EvilMcJerkface/kudu,andrwng/kudu,helifu/kudu,andrwng/kudu,andrwng/kudu,InspurUSA/kudu,cloudera/kudu,EvilMcJerkface/kudu,cloudera/kudu,InspurUSA/kudu,cloudera/kudu,cloudera/kudu
1f429d31bd281f5268ffd0759d688186c60337d5
libtest/port.cc
libtest/port.cc
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "libtest/yatlcon.h" #include <libtest/common.h> #include <cassert> #include <cstdlib> #include <cstring> #include <ctime> #include <fnmatch.h> #include <iostream> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <utility> #include <vector> #include <signal.h> #include <libtest/signal.h> #ifndef SOCK_CLOEXEC # define SOCK_CLOEXEC 0 #endif #ifndef SOCK_NONBLOCK # define SOCK_NONBLOCK 0 #endif #ifndef FD_CLOEXEC # define FD_CLOEXEC 0 #endif #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wold-style-cast" #endif using namespace libtest; struct socket_st { typedef std::vector< std::pair< int, in_port_t> > socket_port_t; socket_port_t _pair; in_port_t last_port; socket_st(): last_port(0) { } void release(in_port_t _arg) { for (socket_port_t::iterator iter= _pair.begin(); iter != _pair.end(); ++iter) { if ((*iter).second == _arg) { shutdown((*iter).first, SHUT_RDWR); close((*iter).first); } } } ~socket_st() { for (socket_port_t::iterator iter= _pair.begin(); iter != _pair.end(); ++iter) { shutdown((*iter).first, SHUT_RDWR); close((*iter).first); } } }; static socket_st all_socket_fd; static in_port_t global_port= 0; static void initialize_default_port() { global_port= get_free_port(); } static pthread_once_t default_port_once= PTHREAD_ONCE_INIT; namespace libtest { in_port_t default_port() { { int ret; if ((ret= pthread_once(&default_port_once, initialize_default_port)) != 0) { FATAL(strerror(ret)); } } return global_port; } void release_port(in_port_t arg) { all_socket_fd.release(arg); } in_port_t get_free_port() { const in_port_t default_port= in_port_t(-1); int retries= 1024; in_port_t ret_port; while (--retries) { ret_port= default_port; int sd; if ((sd= socket(AF_INET, SOCK_STREAM, 0)) != SOCKET_ERROR) { int optval= 1; if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) != SOCKET_ERROR) { struct sockaddr_in sin; sin.sin_port= 0; sin.sin_addr.s_addr= 0; sin.sin_addr.s_addr= INADDR_ANY; sin.sin_family= AF_INET; int bind_ret; do { if ((bind_ret= bind(sd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in) )) != SOCKET_ERROR) { socklen_t addrlen= sizeof(sin); if (getsockname(sd, (struct sockaddr *)&sin, &addrlen) != -1) { ret_port= sin.sin_port; } } else { if (errno != EADDRINUSE) { Error << strerror(errno); } } if (errno == EADDRINUSE) { libtest::dream(2, 0); } } while (bind_ret == -1 and errno == EADDRINUSE); all_socket_fd._pair.push_back(std::make_pair(sd, ret_port)); } else { Error << strerror(errno); } } else { Error << strerror(errno); } if (ret_port == default_port) { Error << "no ret_port set:" << strerror(errno); } else if (ret_port > 1024 and ret_port != all_socket_fd.last_port) { break; } } // We handle the case where if we max out retries, we still abort. if (retries == 0) { FATAL("No port could be found, exhausted retry"); } if (ret_port == 0) { FATAL("No port could be found"); } if (ret_port == default_port) { FATAL("No port could be found"); } if (ret_port <= 1024) { FATAL("No port could be found, though some where available below or at 1024"); } all_socket_fd.last_port= ret_port; release_port(ret_port); return ret_port; } } // namespace libtest
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "libtest/yatlcon.h" #include <libtest/common.h> #include <cassert> #include <cstdlib> #include <cstring> #include <ctime> #include <fnmatch.h> #include <iostream> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <utility> #include <vector> #include <signal.h> #include <libtest/signal.h> #ifndef SOCK_CLOEXEC # define SOCK_CLOEXEC 0 #endif #ifndef SOCK_NONBLOCK # define SOCK_NONBLOCK 0 #endif #ifndef FD_CLOEXEC # define FD_CLOEXEC 0 #endif #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wold-style-cast" #endif using namespace libtest; struct socket_st { typedef std::vector< std::pair< int, in_port_t> > socket_port_t; socket_port_t _pair; in_port_t last_port; socket_st(): last_port(0) { } void release(in_port_t _arg) { for (socket_port_t::iterator iter= _pair.begin(); iter != _pair.end(); ++iter) { if ((*iter).second == _arg) { shutdown((*iter).first, SHUT_RDWR); close((*iter).first); } } } ~socket_st() { for (socket_port_t::iterator iter= _pair.begin(); iter != _pair.end(); ++iter) { shutdown((*iter).first, SHUT_RDWR); close((*iter).first); } } }; static socket_st all_socket_fd; static in_port_t global_port= 0; static void initialize_default_port() { global_port= get_free_port(); } static pthread_once_t default_port_once= PTHREAD_ONCE_INIT; namespace libtest { in_port_t default_port() { { int ret; if ((ret= pthread_once(&default_port_once, initialize_default_port)) != 0) { FATAL(strerror(ret)); } } return global_port; } void release_port(in_port_t arg) { all_socket_fd.release(arg); } in_port_t get_free_port() { const in_port_t default_port= in_port_t(-1); int retries= 1024; in_port_t ret_port; while (--retries) { ret_port= default_port; int sd; if ((sd= socket(AF_INET, SOCK_STREAM, 0)) != SOCKET_ERROR) { int optval= 1; if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) != SOCKET_ERROR) { struct sockaddr_in sin; sin.sin_port= 0; sin.sin_addr.s_addr= INADDR_ANY; sin.sin_family= AF_INET; int bind_ret; do { if ((bind_ret= bind(sd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in) )) != SOCKET_ERROR) { socklen_t addrlen= sizeof(sin); if (getsockname(sd, (struct sockaddr *)&sin, &addrlen) != -1) { ret_port= sin.sin_port; } } else { if (errno != EADDRINUSE) { Error << strerror(errno); } } if (errno == EADDRINUSE) { libtest::dream(2, 0); } } while (bind_ret == -1 and errno == EADDRINUSE); all_socket_fd._pair.push_back(std::make_pair(sd, ret_port)); } else { Error << strerror(errno); } } else { Error << strerror(errno); } if (ret_port == default_port) { Error << "no ret_port set:" << strerror(errno); } else if (ret_port > 1024 and ret_port != all_socket_fd.last_port) { break; } } // We handle the case where if we max out retries, we still abort. if (retries == 0) { FATAL("No port could be found, exhausted retry"); } if (ret_port == 0) { FATAL("No port could be found"); } if (ret_port == default_port) { FATAL("No port could be found"); } if (ret_port <= 1024) { FATAL("No port could be found, though some where available below or at 1024"); } all_socket_fd.last_port= ret_port; release_port(ret_port); return ret_port; } } // namespace libtest
fix get_free_port: remove redundant initialisation
fix get_free_port: remove redundant initialisation
C++
bsd-3-clause
dm/gearmand,dm/gearmand,dm/gearmand,dm/gearmand
7b2703258bbbb3b8ec3a6ff72a06eeb600f38728
option_test.cc
option_test.cc
// Copyright (c) 2017 Kai Luo <[email protected]>. All rights reserved. // Use of this source code is governed by the BSD license that can be found in // the LICENSE file. #include <iostream> #include <memory> #include <string> #include "option.h" #include "testkit.h" class O {}; kl::Option<int> Foo() { return kl::Some(13); } kl::Option<int> Spam() { return kl::None(); } TEST(O, foo) { auto foo = Foo(); ASSERT(foo); ASSERT(*foo == 13); } TEST(O, spam) { auto spam = Spam(); ASSERT(!spam); } struct Imfao { std::string s; }; kl::Option<std::string> Bar() { auto f = std::make_unique<Imfao>(); return f->s; } TEST(O, PassByValue) { auto f = Bar(); ASSERT(f); } class Foobar { public: int Value() { return 7; } }; TEST(O, MethodAccess) { auto f = kl::Some(Foobar()); ASSERT(f->Value() == 7); } int main() { return KL_TEST(); }
// Copyright (c) 2017 Kai Luo <[email protected]>. All rights reserved. // Use of this source code is governed by the BSD license that can be found in // the LICENSE file. #include <iostream> #include <memory> #include <string> #include "option.h" #include "testkit.h" class O {}; kl::Option<int> Foo() { return kl::Some(13); } kl::Option<int> Spam() { return kl::None(); } TEST(O, foo) { auto foo = Foo(); ASSERT(foo); ASSERT(*foo == 13); } TEST(O, spam) { auto spam = Spam(); ASSERT(!spam); } struct Imfao { std::string s; }; kl::Option<std::string> Bar() { auto f = std::make_unique<Imfao>(); return f->s; } TEST(O, PassByValue) { auto f = Bar(); ASSERT(f); } class Foobar { public: int Value() { return 7; } std::string String() const { return "Foobar"; } }; TEST(O, MethodAccess) { auto f = kl::Some(Foobar()); ASSERT(f->Value() == 7); ASSERT(f->String() == "Foobar"); } int main() { return KL_TEST(); }
add test for member access
add test for member access
C++
bsd-3-clause
bzEq/kl,bzEq/kl
8879f5708d16384e3c7702cf1a21479a4be08bb0
Modules/Numerics/Optimizersv4/include/itkGradientDescentLineSearchOptimizerv4.hxx
Modules/Numerics/Optimizersv4/include/itkGradientDescentLineSearchOptimizerv4.hxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkGradientDescentLineSearchOptimizerv4_hxx #define itkGradientDescentLineSearchOptimizerv4_hxx #include "itkGradientDescentLineSearchOptimizerv4.h" namespace itk { /** * Default constructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GradientDescentLineSearchOptimizerv4Template() { this->m_MaximumLineSearchIterations = 20; this->m_LineSearchIterations = NumericTraits<unsigned int>::ZeroValue(); this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue(); this->m_UpperLimit = 5.0; this->m_Phi = 1.618034; this->m_Resphi = 2 - this->m_Phi; this->m_Epsilon = 0.01; this->m_ReturnBestParametersAndValue = true; } /** * Destructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::~GradientDescentLineSearchOptimizerv4Template() {} /** *PrintSelf */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } /** * Advance one Step following the gradient direction */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::AdvanceOneStep() { itkDebugMacro("AdvanceOneStep"); /* Modify the gradient by scales once at the begin */ this->ModifyGradientByScales(); /* This will estimate the learning rate (m_LearningRate) * if the options are set to do so. We only ever want to * estimate at the first step for this class. */ if ( this->m_CurrentIteration == 0 ) { this->EstimateLearningRate(); } this->m_LineSearchIterations = 0; this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit , this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit ); /* Begin threaded gradient modification of m_Gradient variable. */ this->ModifyGradientByLearningRate(); try { /* Pass gradient to transform and let it do its own updating */ this->m_Metric->UpdateTransformParameters( this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; this->m_StopConditionDescription << "UpdateTransformParameters error"; this->StopOptimization(); // Pass exception to caller throw err; } this->InvokeEvent( IterationEvent() ); } // a and c are the current bounds; the minimum is between them. // b is a center point // f(x) is some mathematical function elsewhere defined // a corresponds to x1; b corresponds to x2; c corresponds to x3 // x corresponds to x4 template<typename TInternalComputationValueType> TInternalComputationValueType GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c ) { if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations ) { return ( c + a ) / 2; } this->m_LineSearchIterations++; TInternalComputationValueType x; if ( c - b > b - a ) { x = b + this->m_Resphi * ( c - b ); } else { x = b - this->m_Resphi * ( b - a ); } if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) ) { return ( c + a ) / 2; } TInternalComputationValueType metricx, metricb; { // Cache the learning rate , parameters , gradient // Contain this in a block so these variables go out of // scope before we call recursively below. With dense transforms // we would otherwise eat up a lot of memory unnecessarily. TInternalComputationValueType baseLearningRate = this->m_LearningRate; DerivativeType baseGradient( this->m_Gradient ); ParametersType baseParameters( this->GetCurrentPosition() ); this->m_LearningRate = x; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricx = this->GetMetric()->GetValue( ); /** reset position of transform and gradient */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = b; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricb = this->GetMetric()->GetValue( ); /** reset position of transform and learning rate */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = baseLearningRate; } /** golden section */ if ( metricx < metricb ) { if (c - b > b - a) { return this->GoldenSectionSearch( b, x, c ); } else { return this->GoldenSectionSearch( a, x, b ); } } else { if ( c - b > b - a ) { return this->GoldenSectionSearch( a, b, x ); } else { return this->GoldenSectionSearch( x, b, c ); } } } }//namespace itk #endif
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkGradientDescentLineSearchOptimizerv4_hxx #define itkGradientDescentLineSearchOptimizerv4_hxx #include "itkGradientDescentLineSearchOptimizerv4.h" namespace itk { /** * Default constructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GradientDescentLineSearchOptimizerv4Template() { this->m_MaximumLineSearchIterations = 20; this->m_LineSearchIterations = NumericTraits<unsigned int>::ZeroValue(); this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue(); this->m_UpperLimit = 5.0; this->m_Phi = 1.618034; this->m_Resphi = 2 - this->m_Phi; this->m_Epsilon = 0.01; this->m_ReturnBestParametersAndValue = true; } /** * Destructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::~GradientDescentLineSearchOptimizerv4Template() {} /** *PrintSelf */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } /** * Advance one Step following the gradient direction */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::AdvanceOneStep() { itkDebugMacro("AdvanceOneStep"); /* Modify the gradient by scales once at the begin */ this->ModifyGradientByScales(); /* This will estimate the learning rate (m_LearningRate) * if the options are set to do so. We only ever want to * estimate at the first step for this class. */ if ( this->m_CurrentIteration == 0 ) { this->EstimateLearningRate(); } this->m_LineSearchIterations = 0; this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit , this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit ); /* Begin threaded gradient modification of m_Gradient variable. */ this->ModifyGradientByLearningRate(); try { /* Pass gradient to transform and let it do its own updating */ this->m_Metric->UpdateTransformParameters( this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; this->m_StopConditionDescription << "UpdateTransformParameters error"; this->StopOptimization(); // Pass exception to caller throw err; } this->InvokeEvent( IterationEvent() ); } // a and c are the current bounds; the minimum is between them. // b is a center point // f(x) is some mathematical function elsewhere defined // a corresponds to x1; b corresponds to x2; c corresponds to x3 // x corresponds to x4 template<typename TInternalComputationValueType> TInternalComputationValueType GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c ) { if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations ) { return ( c + a ) / 2; } this->m_LineSearchIterations++; TInternalComputationValueType x; if ( c - b > b - a ) { x = b + this->m_Resphi * ( c - b ); } else { x = b - this->m_Resphi * ( b - a ); } if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) ) { return ( c + a ) / 2; } TInternalComputationValueType metricx, metricb; { // Cache the learning rate , parameters , gradient // Contain this in a block so these variables go out of // scope before we call recursively below. With dense transforms // we would otherwise eat up a lot of memory unnecessarily. TInternalComputationValueType baseLearningRate = this->m_LearningRate; DerivativeType baseGradient( this->m_Gradient ); ParametersType baseParameters( this->GetCurrentPosition() ); this->m_LearningRate = x; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricx = this->GetMetric()->GetValue( ); /** reset position of transform and gradient */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = b; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricb = this->GetMetric()->GetValue( ); /** reset position of transform and learning rate */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = baseLearningRate; } /** golden section */ if ( metricx < metricb ) { if (c - b > b - a) { return this->GoldenSectionSearch( b, x, c ); } else { return this->GoldenSectionSearch( a, x, b ); } } else { if ( c - b > b - a ) { return this->GoldenSectionSearch( a, b, x ); } else if ( metricx == NumericTraits<TInternalComputationValueType>::max() ) { // Keep the lower bounds when metricx and metricb are both max, // likely due to no valid sample points, from too large of a // learning rate. return this->GoldenSectionSearch( a, x, b ); } else { return this->GoldenSectionSearch( x, b, c ); } } } }//namespace itk #endif
Handle boundary case with max metric
BUG: Handle boundary case with max metric This addresses issues in registration optimization encountered where the GradientDescentLineSearch algorithm would take a too large step, such that there were no valid points. This can occur with large amounts of smoothing, or a solution being very close to an optimal value causing small gradients and large learning rate. In the GoldenSectionSearch method when both points b and x resulted in no valid points then x==b==max. The line search would advance to x being the lower boundary. This case is now explicitly handled to preserve the lower boundary. Change-Id: Icf1a0f31dda0c988b7f52fa40a3a8dcef1e62637
C++
apache-2.0
BRAINSia/ITK,spinicist/ITK,hjmjohnson/ITK,fbudin69500/ITK,hjmjohnson/ITK,richardbeare/ITK,richardbeare/ITK,malaterre/ITK,blowekamp/ITK,richardbeare/ITK,LucasGandel/ITK,thewtex/ITK,Kitware/ITK,malaterre/ITK,LucasGandel/ITK,LucasGandel/ITK,malaterre/ITK,Kitware/ITK,vfonov/ITK,spinicist/ITK,malaterre/ITK,Kitware/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,blowekamp/ITK,blowekamp/ITK,blowekamp/ITK,fbudin69500/ITK,spinicist/ITK,Kitware/ITK,LucasGandel/ITK,fbudin69500/ITK,thewtex/ITK,fbudin69500/ITK,vfonov/ITK,fbudin69500/ITK,malaterre/ITK,malaterre/ITK,hjmjohnson/ITK,blowekamp/ITK,richardbeare/ITK,thewtex/ITK,spinicist/ITK,LucasGandel/ITK,BRAINSia/ITK,blowekamp/ITK,LucasGandel/ITK,thewtex/ITK,Kitware/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,spinicist/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,LucasGandel/ITK,vfonov/ITK,BRAINSia/ITK,hjmjohnson/ITK,fbudin69500/ITK,BRAINSia/ITK,hjmjohnson/ITK,spinicist/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,thewtex/ITK,blowekamp/ITK,richardbeare/ITK,Kitware/ITK,hjmjohnson/ITK,spinicist/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,thewtex/ITK,blowekamp/ITK,vfonov/ITK,BRAINSia/ITK,malaterre/ITK,spinicist/ITK,vfonov/ITK,richardbeare/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,BRAINSia/ITK,malaterre/ITK,fbudin69500/ITK,vfonov/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,spinicist/ITK
dde5202e071de6dd09db1b37482b3560ac32ae2d
src/XSLTransformer.cpp
src/XSLTransformer.cpp
#include <string> extern "C" { #include <libxml/globals.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxslt/xslt.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> } #include "AlpinoCorpus/Error.hh" #include "XSLTransformer.hh" namespace alpinocorpus { XSLTransformer::XSLTransformer(std::string const &xsl) { initWithStylesheet(xsl); } XSLTransformer::~XSLTransformer() { xsltFreeStylesheet(d_xslPtr); } void XSLTransformer::initWithStylesheet(std::string const &xsl) { xmlDocPtr xslDoc = xmlReadMemory(xsl.c_str(), xsl.size(), 0, 0, 0); d_xslPtr = xsltParseStylesheetDoc(xslDoc); } std::string XSLTransformer::transform(std::string const &xml) const { // Read XML data intro an xmlDoc. xmlDocPtr doc = xmlReadMemory(xml.c_str(), xml.size(), 0, 0, 0); if (!doc) throw Error("XSLTransformer::transform: Could not open XML data"); xsltTransformContextPtr ctx = xsltNewTransformContext(d_xslPtr, doc); // Transform... xmlDocPtr res = xsltApplyStylesheetUser(d_xslPtr, doc, NULL, NULL, NULL, ctx); if (!res) { xsltFreeTransformContext(ctx); xmlFreeDoc(doc); throw Error("XSLTransformer::transform: Could not apply transformation!"); } else if (ctx->state != XSLT_STATE_OK) { xsltFreeTransformContext(ctx); xmlFreeDoc(res); xmlFreeDoc(doc); throw Error("XSLTransformer::transform: Transformation error, check your query!"); } xsltFreeTransformContext(ctx); xmlChar *output = 0; int outputLen = -1; xsltSaveResultToString(&output, &outputLen, res, d_xslPtr); if (!output) { xmlFreeDoc(res); xmlFreeDoc(doc); throw Error("Could not apply stylesheet!"); } std::string result(reinterpret_cast<char const *>(output)); // Deallocate memory used for libxml2/libxslt. xmlFree(output); xmlFreeDoc(res); xmlFreeDoc(doc); return result; } }
#include <string> extern "C" { #include <libxml/globals.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxslt/xslt.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> } #include "AlpinoCorpus/Error.hh" #include "XSLTransformer.hh" namespace alpinocorpus { XSLTransformer::XSLTransformer(std::string const &xsl) { initWithStylesheet(xsl); } XSLTransformer::~XSLTransformer() { xsltFreeStylesheet(d_xslPtr); } void XSLTransformer::initWithStylesheet(std::string const &xsl) { xmlDocPtr xslDoc = xmlReadMemory(xsl.c_str(), xsl.size(), 0, 0, XSLT_PARSE_OPTIONS); d_xslPtr = xsltParseStylesheetDoc(xslDoc); } std::string XSLTransformer::transform(std::string const &xml) const { // Read XML data intro an xmlDoc. xmlDocPtr doc = xmlReadMemory(xml.c_str(), xml.size(), 0, 0, 0); if (!doc) throw Error("XSLTransformer::transform: Could not open XML data"); xsltTransformContextPtr ctx = xsltNewTransformContext(d_xslPtr, doc); xsltSetCtxtParseOptions(ctx, XSLT_PARSE_OPTIONS); // Transform... xmlDocPtr res = xsltApplyStylesheetUser(d_xslPtr, doc, NULL, NULL, NULL, ctx); if (!res) { xsltFreeTransformContext(ctx); xmlFreeDoc(doc); throw Error("XSLTransformer::transform: Could not apply transformation!"); } else if (ctx->state != XSLT_STATE_OK) { xsltFreeTransformContext(ctx); xmlFreeDoc(res); xmlFreeDoc(doc); throw Error("XSLTransformer::transform: Transformation error, check your query!"); } xsltFreeTransformContext(ctx); xmlChar *output = 0; int outputLen = -1; xsltSaveResultToString(&output, &outputLen, res, d_xslPtr); if (!output) { xmlFreeDoc(res); xmlFreeDoc(doc); throw Error("Could not apply stylesheet!"); } std::string result(reinterpret_cast<char const *>(output)); // Deallocate memory used for libxml2/libxslt. xmlFree(output); xmlFreeDoc(res); xmlFreeDoc(doc); return result; } }
Use libxslt's default options for parsing stylesheets.
Use libxslt's default options for parsing stylesheets.
C++
lgpl-2.1
evdmade01/alpinocorpus,rug-compling/alpinocorpus,evdmade01/alpinocorpus,rug-compling/alpinocorpus,rug-compling/alpinocorpus
e572cf93ee411ef40acdb64eb3073231619862ed
src/arch/arm/faults.cc
src/arch/arm/faults.cc
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi * Gabe Black */ #include "arch/arm/faults.hh" #include "cpu/thread_context.hh" #include "cpu/base.hh" #include "base/trace.hh" namespace ArmISA { template<> ArmFault::FaultVals ArmFaultVals<Reset>::vals = {"reset", 0x00, MODE_SVC, 0, 0, true, true}; template<> ArmFault::FaultVals ArmFaultVals<UndefinedInstruction>::vals = {"Undefined Instruction", 0x04, MODE_UNDEFINED, 4 ,2, false, false} ; template<> ArmFault::FaultVals ArmFaultVals<SupervisorCall>::vals = {"Supervisor Call", 0x08, MODE_SVC, 4, 2, false, false}; template<> ArmFault::FaultVals ArmFaultVals<PrefetchAbort>::vals = {"Prefetch Abort", 0x0C, MODE_ABORT, 4, 4, true, false}; template<> ArmFault::FaultVals ArmFaultVals<DataAbort>::vals = {"Data Abort", 0x10, MODE_ABORT, 8, 8, true, false}; template<> ArmFault::FaultVals ArmFaultVals<Interrupt>::vals = {"IRQ", 0x18, MODE_IRQ, 4, 4, true, false}; template<> ArmFault::FaultVals ArmFaultVals<FastInterrupt>::vals = {"FIQ", 0x1C, MODE_FIQ, 4, 4, true, true}; template<> ArmFault::FaultVals ArmFaultVals<FlushPipe>::vals = {"Pipe Flush", 0x00, MODE_SVC, 0, 0, true, true}; // some dummy values Addr ArmFault::getVector(ThreadContext *tc) { // ARM ARM B1-3 SCTLR sctlr = tc->readMiscReg(MISCREG_SCTLR); // panic if SCTLR.VE because I have no idea what to do with vectored // interrupts assert(!sctlr.ve); if (!sctlr.v) return offset(); return offset() + HighVecs; } #if FULL_SYSTEM void ArmFault::invoke(ThreadContext *tc, StaticInstPtr inst) { // ARM ARM B1.6.3 FaultBase::invoke(tc); countStat()++; SCTLR sctlr = tc->readMiscReg(MISCREG_SCTLR); CPSR cpsr = tc->readMiscReg(MISCREG_CPSR); CPSR saved_cpsr = tc->readMiscReg(MISCREG_CPSR) | tc->readIntReg(INTREG_CONDCODES); Addr curPc M5_VAR_USED = tc->pcState().pc(); cpsr.mode = nextMode(); cpsr.it1 = cpsr.it2 = 0; cpsr.j = 0; cpsr.t = sctlr.te; cpsr.a = cpsr.a | abortDisable(); cpsr.f = cpsr.f | fiqDisable(); cpsr.i = 1; cpsr.e = sctlr.ee; tc->setMiscReg(MISCREG_CPSR, cpsr); tc->setIntReg(INTREG_LR, curPc + (saved_cpsr.t ? thumbPcOffset() : armPcOffset())); switch (nextMode()) { case MODE_FIQ: tc->setMiscReg(MISCREG_SPSR_FIQ, saved_cpsr); break; case MODE_IRQ: tc->setMiscReg(MISCREG_SPSR_IRQ, saved_cpsr); break; case MODE_SVC: tc->setMiscReg(MISCREG_SPSR_SVC, saved_cpsr); break; case MODE_UNDEFINED: tc->setMiscReg(MISCREG_SPSR_UND, saved_cpsr); break; case MODE_ABORT: tc->setMiscReg(MISCREG_SPSR_ABT, saved_cpsr); break; default: panic("unknown Mode\n"); } Addr newPc = getVector(tc); DPRINTF(Faults, "Invoking Fault:%s cpsr:%#x PC:%#x lr:%#x newVec: %#x\n", name(), cpsr, curPc, tc->readIntReg(INTREG_LR), newPc); PCState pc(newPc); pc.thumb(cpsr.t); pc.nextThumb(pc.thumb()); pc.jazelle(cpsr.j); pc.nextJazelle(pc.jazelle()); tc->pcState(pc); } void Reset::invoke(ThreadContext *tc, StaticInstPtr inst) { tc->getCpuPtr()->clearInterrupts(); tc->clearArchRegs(); ArmFault::invoke(tc); } #else void UndefinedInstruction::invoke(ThreadContext *tc, StaticInstPtr inst) { // If the mnemonic isn't defined this has to be an unknown instruction. assert(unknown || mnemonic != NULL); if (disabled) { panic("Attempted to execute disabled instruction " "'%s' (inst 0x%08x)", mnemonic, machInst); } else if (unknown) { panic("Attempted to execute unknown instruction (inst 0x%08x)", machInst); } else { panic("Attempted to execute unimplemented instruction " "'%s' (inst 0x%08x)", mnemonic, machInst); } } void SupervisorCall::invoke(ThreadContext *tc, StaticInstPtr inst) { // As of now, there isn't a 32 bit thumb version of this instruction. assert(!machInst.bigThumb); uint32_t callNum; if (machInst.thumb) { callNum = bits(machInst, 7, 0); } else { callNum = bits(machInst, 23, 0); } if (callNum == 0) { callNum = tc->readIntReg(INTREG_R7); } tc->syscall(callNum); // Advance the PC since that won't happen automatically. PCState pc = tc->pcState(); assert(inst); inst->advancePC(pc); tc->pcState(pc); } #endif // FULL_SYSTEM template<class T> void AbortFault<T>::invoke(ThreadContext *tc, StaticInstPtr inst) { ArmFaultVals<T>::invoke(tc); FSR fsr = 0; fsr.fsLow = bits(status, 3, 0); fsr.fsHigh = bits(status, 4); fsr.domain = domain; fsr.wnr = (write ? 1 : 0); fsr.ext = 0; tc->setMiscReg(T::FsrIndex, fsr); tc->setMiscReg(T::FarIndex, faultAddr); } void FlushPipe::invoke(ThreadContext *tc, StaticInstPtr inst) { DPRINTF(Faults, "Invoking FlushPipe Fault\n"); // Set the PC to the next instruction of the faulting instruction. // Net effect is simply squashing all instructions behind and // start refetching from the next instruction. PCState pc = tc->pcState(); assert(inst); inst->advancePC(pc); tc->pcState(pc); } template void AbortFault<PrefetchAbort>::invoke(ThreadContext *tc, StaticInstPtr inst); template void AbortFault<DataAbort>::invoke(ThreadContext *tc, StaticInstPtr inst); // return via SUBS pc, lr, xxx; rfe, movs, ldm } // namespace ArmISA
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi * Gabe Black */ #include "arch/arm/faults.hh" #include "cpu/thread_context.hh" #include "cpu/base.hh" #include "base/trace.hh" namespace ArmISA { template<> ArmFault::FaultVals ArmFaultVals<Reset>::vals = {"reset", 0x00, MODE_SVC, 0, 0, true, true}; template<> ArmFault::FaultVals ArmFaultVals<UndefinedInstruction>::vals = {"Undefined Instruction", 0x04, MODE_UNDEFINED, 4 ,2, false, false} ; template<> ArmFault::FaultVals ArmFaultVals<SupervisorCall>::vals = {"Supervisor Call", 0x08, MODE_SVC, 4, 2, false, false}; template<> ArmFault::FaultVals ArmFaultVals<PrefetchAbort>::vals = {"Prefetch Abort", 0x0C, MODE_ABORT, 4, 4, true, false}; template<> ArmFault::FaultVals ArmFaultVals<DataAbort>::vals = {"Data Abort", 0x10, MODE_ABORT, 8, 8, true, false}; template<> ArmFault::FaultVals ArmFaultVals<Interrupt>::vals = {"IRQ", 0x18, MODE_IRQ, 4, 4, true, false}; template<> ArmFault::FaultVals ArmFaultVals<FastInterrupt>::vals = {"FIQ", 0x1C, MODE_FIQ, 4, 4, true, true}; template<> ArmFault::FaultVals ArmFaultVals<FlushPipe>::vals = {"Pipe Flush", 0x00, MODE_SVC, 0, 0, true, true}; // some dummy values Addr ArmFault::getVector(ThreadContext *tc) { // ARM ARM B1-3 SCTLR sctlr = tc->readMiscReg(MISCREG_SCTLR); // panic if SCTLR.VE because I have no idea what to do with vectored // interrupts assert(!sctlr.ve); if (!sctlr.v) return offset(); return offset() + HighVecs; } #if FULL_SYSTEM void ArmFault::invoke(ThreadContext *tc, StaticInstPtr inst) { // ARM ARM B1.6.3 FaultBase::invoke(tc); countStat()++; SCTLR sctlr = tc->readMiscReg(MISCREG_SCTLR); CPSR cpsr = tc->readMiscReg(MISCREG_CPSR); CPSR saved_cpsr = tc->readMiscReg(MISCREG_CPSR) | tc->readIntReg(INTREG_CONDCODES); Addr curPc M5_VAR_USED = tc->pcState().pc(); cpsr.mode = nextMode(); cpsr.it1 = cpsr.it2 = 0; cpsr.j = 0; cpsr.t = sctlr.te; cpsr.a = cpsr.a | abortDisable(); cpsr.f = cpsr.f | fiqDisable(); cpsr.i = 1; cpsr.e = sctlr.ee; tc->setMiscReg(MISCREG_CPSR, cpsr); tc->setIntReg(INTREG_LR, curPc + (saved_cpsr.t ? thumbPcOffset() : armPcOffset())); switch (nextMode()) { case MODE_FIQ: tc->setMiscReg(MISCREG_SPSR_FIQ, saved_cpsr); break; case MODE_IRQ: tc->setMiscReg(MISCREG_SPSR_IRQ, saved_cpsr); break; case MODE_SVC: tc->setMiscReg(MISCREG_SPSR_SVC, saved_cpsr); break; case MODE_UNDEFINED: tc->setMiscReg(MISCREG_SPSR_UND, saved_cpsr); break; case MODE_ABORT: tc->setMiscReg(MISCREG_SPSR_ABT, saved_cpsr); break; default: panic("unknown Mode\n"); } Addr newPc = getVector(tc); DPRINTF(Faults, "Invoking Fault:%s cpsr:%#x PC:%#x lr:%#x newVec: %#x\n", name(), cpsr, curPc, tc->readIntReg(INTREG_LR), newPc); PCState pc(newPc); pc.thumb(cpsr.t); pc.nextThumb(pc.thumb()); pc.jazelle(cpsr.j); pc.nextJazelle(pc.jazelle()); tc->pcState(pc); } void Reset::invoke(ThreadContext *tc, StaticInstPtr inst) { tc->getCpuPtr()->clearInterrupts(); tc->clearArchRegs(); ArmFault::invoke(tc); } #else void UndefinedInstruction::invoke(ThreadContext *tc, StaticInstPtr inst) { // If the mnemonic isn't defined this has to be an unknown instruction. assert(unknown || mnemonic != NULL); if (disabled) { panic("Attempted to execute disabled instruction " "'%s' (inst 0x%08x)", mnemonic, machInst); } else if (unknown) { panic("Attempted to execute unknown instruction (inst 0x%08x)", machInst); } else { panic("Attempted to execute unimplemented instruction " "'%s' (inst 0x%08x)", mnemonic, machInst); } } void SupervisorCall::invoke(ThreadContext *tc, StaticInstPtr inst) { // As of now, there isn't a 32 bit thumb version of this instruction. assert(!machInst.bigThumb); uint32_t callNum; callNum = tc->readIntReg(INTREG_R7); tc->syscall(callNum); // Advance the PC since that won't happen automatically. PCState pc = tc->pcState(); assert(inst); inst->advancePC(pc); tc->pcState(pc); } #endif // FULL_SYSTEM template<class T> void AbortFault<T>::invoke(ThreadContext *tc, StaticInstPtr inst) { ArmFaultVals<T>::invoke(tc); FSR fsr = 0; fsr.fsLow = bits(status, 3, 0); fsr.fsHigh = bits(status, 4); fsr.domain = domain; fsr.wnr = (write ? 1 : 0); fsr.ext = 0; tc->setMiscReg(T::FsrIndex, fsr); tc->setMiscReg(T::FarIndex, faultAddr); } void FlushPipe::invoke(ThreadContext *tc, StaticInstPtr inst) { DPRINTF(Faults, "Invoking FlushPipe Fault\n"); // Set the PC to the next instruction of the faulting instruction. // Net effect is simply squashing all instructions behind and // start refetching from the next instruction. PCState pc = tc->pcState(); assert(inst); inst->advancePC(pc); tc->pcState(pc); } template void AbortFault<PrefetchAbort>::invoke(ThreadContext *tc, StaticInstPtr inst); template void AbortFault<DataAbort>::invoke(ThreadContext *tc, StaticInstPtr inst); // return via SUBS pc, lr, xxx; rfe, movs, ldm } // namespace ArmISA
Delete OABI syscall handling.
ARM: Delete OABI syscall handling. We only support EABI binaries, so there is no reason to support OABI syscalls. The loader detects OABI calls and fatal() so there is no reason to even check here.
C++
bsd-3-clause
markoshorro/gem5,TUD-OS/gem5-dtu,samueldotj/TeeRISC-Simulator,SanchayanMaity/gem5,samueldotj/TeeRISC-Simulator,qizenguf/MLC-STT,briancoutinho0905/2dsampling,joerocklin/gem5,yb-kim/gemV,austinharris/gem5-riscv,gem5/gem5,aclifton/cpeg853-gem5,powerjg/gem5-ci-test,zlfben/gem5,samueldotj/TeeRISC-Simulator,TUD-OS/gem5-dtu,gem5/gem5,kaiyuanl/gem5,gedare/gem5,yb-kim/gemV,Weil0ng/gem5,powerjg/gem5-ci-test,rallylee/gem5,cancro7/gem5,samueldotj/TeeRISC-Simulator,SanchayanMaity/gem5,KuroeKurose/gem5,cancro7/gem5,aclifton/cpeg853-gem5,kaiyuanl/gem5,rallylee/gem5,cancro7/gem5,KuroeKurose/gem5,TUD-OS/gem5-dtu,aclifton/cpeg853-gem5,cancro7/gem5,KuroeKurose/gem5,qizenguf/MLC-STT,gem5/gem5,rallylee/gem5,aclifton/cpeg853-gem5,TUD-OS/gem5-dtu,markoshorro/gem5,rjschof/gem5,zlfben/gem5,joerocklin/gem5,zlfben/gem5,zlfben/gem5,aclifton/cpeg853-gem5,rjschof/gem5,SanchayanMaity/gem5,powerjg/gem5-ci-test,Weil0ng/gem5,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,Weil0ng/gem5,HwisooSo/gemV-update,rjschof/gem5,zlfben/gem5,rallylee/gem5,SanchayanMaity/gem5,TUD-OS/gem5-dtu,zlfben/gem5,rjschof/gem5,markoshorro/gem5,gem5/gem5,qizenguf/MLC-STT,cancro7/gem5,Weil0ng/gem5,KuroeKurose/gem5,briancoutinho0905/2dsampling,joerocklin/gem5,aclifton/cpeg853-gem5,austinharris/gem5-riscv,powerjg/gem5-ci-test,gem5/gem5,austinharris/gem5-riscv,yb-kim/gemV,gedare/gem5,briancoutinho0905/2dsampling,austinharris/gem5-riscv,HwisooSo/gemV-update,rjschof/gem5,sobercoder/gem5,yb-kim/gemV,samueldotj/TeeRISC-Simulator,joerocklin/gem5,Weil0ng/gem5,joerocklin/gem5,kaiyuanl/gem5,briancoutinho0905/2dsampling,gedare/gem5,rjschof/gem5,sobercoder/gem5,SanchayanMaity/gem5,HwisooSo/gemV-update,yb-kim/gemV,Weil0ng/gem5,KuroeKurose/gem5,HwisooSo/gemV-update,briancoutinho0905/2dsampling,gem5/gem5,powerjg/gem5-ci-test,samueldotj/TeeRISC-Simulator,briancoutinho0905/2dsampling,austinharris/gem5-riscv,joerocklin/gem5,yb-kim/gemV,joerocklin/gem5,yb-kim/gemV,zlfben/gem5,sobercoder/gem5,markoshorro/gem5,rallylee/gem5,austinharris/gem5-riscv,Weil0ng/gem5,gem5/gem5,cancro7/gem5,powerjg/gem5-ci-test,kaiyuanl/gem5,SanchayanMaity/gem5,qizenguf/MLC-STT,rallylee/gem5,gedare/gem5,TUD-OS/gem5-dtu,cancro7/gem5,sobercoder/gem5,sobercoder/gem5,sobercoder/gem5,gedare/gem5,markoshorro/gem5,qizenguf/MLC-STT,yb-kim/gemV,sobercoder/gem5,markoshorro/gem5,gedare/gem5,rjschof/gem5,HwisooSo/gemV-update,austinharris/gem5-riscv,qizenguf/MLC-STT,powerjg/gem5-ci-test,gedare/gem5,aclifton/cpeg853-gem5,HwisooSo/gemV-update,qizenguf/MLC-STT,markoshorro/gem5,KuroeKurose/gem5,kaiyuanl/gem5,rallylee/gem5,briancoutinho0905/2dsampling,joerocklin/gem5,TUD-OS/gem5-dtu,kaiyuanl/gem5,kaiyuanl/gem5,SanchayanMaity/gem5,HwisooSo/gemV-update
5c73ce0a8539a7bccbff6e65a65231bf8d941e53
src/archive_manager.cc
src/archive_manager.cc
/** * Copyright (c) 2020, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 archive_manager.cc */ #include "config.h" #include <glob.h> #include <unistd.h> #if HAVE_ARCHIVE_H #include "archive.h" #include "archive_entry.h" #endif #include "auto_fd.hh" #include "auto_mem.hh" #include "fmt/format.h" #include "base/lnav_log.hh" #include "archive_manager.hh" namespace fs = ghc::filesystem; namespace archive_manager { const static size_t MIN_FREE_SPACE = 32 * 1024 * 1024; class archive_lock { public: class guard { public: explicit guard(archive_lock& arc_lock) : g_lock(arc_lock) { this->g_lock.lock(); }; ~guard() { this->g_lock.unlock(); }; private: archive_lock &g_lock; }; void lock() const { lockf(this->lh_fd, F_LOCK, 0); }; void unlock() const { lockf(this->lh_fd, F_ULOCK, 0); }; explicit archive_lock(const ghc::filesystem::path& archive_path) { auto lock_path = archive_path; lock_path += ".lck"; this->lh_fd = open(lock_path.c_str(), O_CREAT | O_RDWR, 0600); log_perror(fcntl(this->lh_fd, F_SETFD, FD_CLOEXEC)); }; auto_fd lh_fd; }; bool is_archive(const std::string &filename) { #if HAVE_ARCHIVE_H auto_mem<archive> arc(archive_read_free); arc = archive_read_new(); archive_read_support_filter_all(arc); archive_read_support_format_all(arc); auto r = archive_read_open_filename(arc, filename.c_str(), 16384); if (r == ARCHIVE_OK) { struct archive_entry *entry; if (archive_read_next_header(arc, &entry) == ARCHIVE_OK) { log_info("detected archive: %s -- %s", filename.c_str(), archive_format_name(arc)); return true; } else { log_info("archive read header failed: %s -- %s", filename.c_str(), archive_error_string(arc)); } } else { log_info("archive open failed: %s -- %s", filename.c_str(), archive_error_string(arc)); } #endif return false; } fs::path filename_to_tmp_path(const std::string &filename) { auto fn_path = fs::path(filename); auto basename = fn_path.filename(); auto subdir_name = fmt::format("lnav-{}-archives", getuid()); auto tmp_path = fs::temp_directory_path(); // TODO include a content-hash in the path name return tmp_path / fs::path(subdir_name) / basename; } #if HAVE_ARCHIVE_H static walk_result_t copy_data(const std::string& filename, struct archive *ar, struct archive_entry *entry, struct archive *aw, const ghc::filesystem::path &entry_path, struct extract_progress *ep) { int r; const void *buff; size_t size, last_space_check = 0, total = 0; la_int64_t offset; for (;;) { r = archive_read_data_block(ar, &buff, &size, &offset); if (r == ARCHIVE_EOF) { return Ok(); } if (r != ARCHIVE_OK) { return Err(fmt::format("failed to read file: {} >> {} -- {}", filename, archive_entry_pathname_utf8(entry), archive_error_string(ar))); } r = archive_write_data_block(aw, buff, size, offset); if (r != ARCHIVE_OK) { return Err(fmt::format("failed to write file: {} -- {}", entry_path.string(), archive_error_string(aw))); } total += size; ep->ep_out_size.fetch_add(size); if ((total - last_space_check) > (1024 * 1024)) { auto tmp_space = ghc::filesystem::space(entry_path); if (tmp_space.available < MIN_FREE_SPACE) { return Err(fmt::format( "{} -- available space too low: %lld", entry_path.string(), tmp_space.available)); } } } } static walk_result_t extract(const std::string &filename, const extract_cb &cb) { static int FLAGS = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS; auto tmp_path = filename_to_tmp_path(filename); auto arc_lock = archive_lock(tmp_path); auto lock_guard = archive_lock::guard(arc_lock); auto done_path = tmp_path; done_path += ".done"; if (ghc::filesystem::exists(done_path)) { ghc::filesystem::last_write_time( done_path, std::chrono::system_clock::now()); log_debug("already extracted! %s", done_path.c_str()); return Ok(); } auto_mem<archive> arc(archive_free); auto_mem<archive> ext(archive_free); arc = archive_read_new(); archive_read_support_format_all(arc); archive_read_support_filter_all(arc); ext = archive_write_disk_new(); archive_write_disk_set_options(ext, FLAGS); archive_write_disk_set_standard_lookup(ext); if (archive_read_open_filename(arc, filename.c_str(), 10240) != ARCHIVE_OK) { return Err(fmt::format("unable to open archive: {} -- {}", filename, archive_error_string(arc))); } log_info("extracting %s to %s", filename.c_str(), tmp_path.c_str()); while (true) { struct archive_entry *entry; auto r = archive_read_next_header(arc, &entry); if (r == ARCHIVE_EOF) { log_info("all done"); break; } if (r != ARCHIVE_OK) { return Err(fmt::format("unable to read entry header: {} -- {}", filename, archive_error_string(arc))); } auto_mem<archive_entry> wentry(archive_entry_free); wentry = archive_entry_clone(entry); auto entry_path = tmp_path / fs::path(archive_entry_pathname(entry)); auto prog = cb(entry_path, archive_entry_size_is_set(entry) ? archive_entry_size(entry) : -1); archive_entry_copy_pathname(wentry, entry_path.c_str()); auto entry_mode = archive_entry_mode(wentry); archive_entry_set_perm( wentry, S_IRUSR | (S_ISDIR(entry_mode) ? S_IXUSR|S_IWUSR : 0)); r = archive_write_header(ext, wentry); if (r < ARCHIVE_OK) { return Err(fmt::format("unable to write entry: {} -- {}", entry_path.string(), archive_error_string(ext))); } else if (archive_entry_size(entry) > 0) { TRY(copy_data(filename, arc, entry, ext, entry_path, prog)); } r = archive_write_finish_entry(ext); if (r != ARCHIVE_OK) { return Err(fmt::format("unable to finish entry: {} -- {}", entry_path.string(), archive_error_string(ext))); } } archive_read_close(arc); archive_write_close(ext); auto_fd(open(done_path.c_str(), O_CREAT | O_WRONLY, 0600)); return Ok(); } #endif walk_result_t walk_archive_files( const std::string &filename, const extract_cb &cb, const std::function<void( const fs::path&, const fs::directory_entry &)>& callback) { #if HAVE_ARCHIVE_H auto tmp_path = filename_to_tmp_path(filename); TRY(extract(filename, cb)); for (const auto& entry : fs::recursive_directory_iterator(tmp_path)) { if (!entry.is_regular_file()) { continue; } callback(tmp_path, entry); } return Ok(); #else return Err("not compiled with libarchive"); #endif } }
/** * Copyright (c) 2020, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 archive_manager.cc */ #include "config.h" #include <glob.h> #include <unistd.h> #if HAVE_ARCHIVE_H #include "archive.h" #include "archive_entry.h" #endif #include "auto_fd.hh" #include "auto_mem.hh" #include "fmt/format.h" #include "base/lnav_log.hh" #include "archive_manager.hh" namespace fs = ghc::filesystem; namespace archive_manager { const static size_t MIN_FREE_SPACE = 32 * 1024 * 1024; class archive_lock { public: class guard { public: explicit guard(archive_lock& arc_lock) : g_lock(arc_lock) { this->g_lock.lock(); }; ~guard() { this->g_lock.unlock(); }; private: archive_lock &g_lock; }; void lock() const { lockf(this->lh_fd, F_LOCK, 0); }; void unlock() const { lockf(this->lh_fd, F_ULOCK, 0); }; explicit archive_lock(const ghc::filesystem::path& archive_path) { auto lock_path = archive_path; lock_path += ".lck"; this->lh_fd = open(lock_path.c_str(), O_CREAT | O_RDWR, 0600); log_perror(fcntl(this->lh_fd, F_SETFD, FD_CLOEXEC)); }; auto_fd lh_fd; }; bool is_archive(const std::string &filename) { #if HAVE_ARCHIVE_H auto_mem<archive> arc(archive_read_free); arc = archive_read_new(); archive_read_support_filter_all(arc); archive_read_support_format_all(arc); auto r = archive_read_open_filename(arc, filename.c_str(), 16384); if (r == ARCHIVE_OK) { struct archive_entry *entry; if (archive_read_next_header(arc, &entry) == ARCHIVE_OK) { log_info("detected archive: %s -- %s", filename.c_str(), archive_format_name(arc)); return true; } else { log_info("archive read header failed: %s -- %s", filename.c_str(), archive_error_string(arc)); } } else { log_info("archive open failed: %s -- %s", filename.c_str(), archive_error_string(arc)); } #endif return false; } fs::path filename_to_tmp_path(const std::string &filename) { auto fn_path = fs::path(filename); auto basename = fn_path.filename(); auto subdir_name = fmt::format("lnav-{}-archives", getuid()); auto tmp_path = fs::temp_directory_path(); // TODO include a content-hash in the path name return tmp_path / fs::path(subdir_name) / basename; } #if HAVE_ARCHIVE_H static walk_result_t copy_data(const std::string& filename, struct archive *ar, struct archive_entry *entry, struct archive *aw, const ghc::filesystem::path &entry_path, struct extract_progress *ep) { int r; const void *buff; size_t size, last_space_check = 0, total = 0; la_int64_t offset; for (;;) { r = archive_read_data_block(ar, &buff, &size, &offset); if (r == ARCHIVE_EOF) { return Ok(); } if (r != ARCHIVE_OK) { return Err(fmt::format("failed to read file: {} >> {} -- {}", filename, archive_entry_pathname_utf8(entry), archive_error_string(ar))); } r = archive_write_data_block(aw, buff, size, offset); if (r != ARCHIVE_OK) { return Err(fmt::format("failed to write file: {} -- {}", entry_path.string(), archive_error_string(aw))); } total += size; ep->ep_out_size.fetch_add(size); if ((total - last_space_check) > (1024 * 1024)) { auto tmp_space = ghc::filesystem::space(entry_path); if (tmp_space.available < MIN_FREE_SPACE) { return Err(fmt::format( "{} -- available space too low: %lld", entry_path.string(), tmp_space.available)); } } } } static walk_result_t extract(const std::string &filename, const extract_cb &cb) { static int FLAGS = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS; auto tmp_path = filename_to_tmp_path(filename); auto arc_lock = archive_lock(tmp_path); auto lock_guard = archive_lock::guard(arc_lock); auto done_path = tmp_path; done_path += ".done"; if (ghc::filesystem::exists(done_path)) { ghc::filesystem::last_write_time( done_path, std::chrono::system_clock::now()); log_debug("already extracted! %s", done_path.c_str()); return Ok(); } auto_mem<archive> arc(archive_free); auto_mem<archive> ext(archive_free); arc = archive_read_new(); archive_read_support_format_all(arc); archive_read_support_filter_all(arc); ext = archive_write_disk_new(); archive_write_disk_set_options(ext, FLAGS); archive_write_disk_set_standard_lookup(ext); if (archive_read_open_filename(arc, filename.c_str(), 10240) != ARCHIVE_OK) { return Err(fmt::format("unable to open archive: {} -- {}", filename, archive_error_string(arc))); } log_info("extracting %s to %s", filename.c_str(), tmp_path.c_str()); while (true) { struct archive_entry *entry; auto r = archive_read_next_header(arc, &entry); if (r == ARCHIVE_EOF) { log_info("all done"); break; } if (r != ARCHIVE_OK) { return Err(fmt::format("unable to read entry header: {} -- {}", filename, archive_error_string(arc))); } auto_mem<archive_entry> wentry(archive_entry_free); wentry = archive_entry_clone(entry); auto entry_path = tmp_path / fs::path(archive_entry_pathname(entry)); auto prog = cb(entry_path, archive_entry_size_is_set(entry) ? archive_entry_size(entry) : -1); archive_entry_copy_pathname(wentry, entry_path.c_str()); auto entry_mode = archive_entry_mode(wentry); archive_entry_set_perm( wentry, S_IRUSR | (S_ISDIR(entry_mode) ? S_IXUSR|S_IWUSR : 0)); r = archive_write_header(ext, wentry); if (r < ARCHIVE_OK) { return Err(fmt::format("unable to write entry: {} -- {}", entry_path.string(), archive_error_string(ext))); } else if (archive_entry_size(entry) > 0) { TRY(copy_data(filename, arc, entry, ext, entry_path, prog)); } r = archive_write_finish_entry(ext); if (r != ARCHIVE_OK) { return Err(fmt::format("unable to finish entry: {} -- {}", entry_path.string(), archive_error_string(ext))); } } archive_read_close(arc); archive_write_close(ext); auto_fd(open(done_path.c_str(), O_CREAT | O_WRONLY, 0600)); return Ok(); } #endif walk_result_t walk_archive_files( const std::string &filename, const extract_cb &cb, const std::function<void( const fs::path&, const fs::directory_entry &)>& callback) { #if HAVE_ARCHIVE_H auto tmp_path = filename_to_tmp_path(filename); TRY(extract(filename, cb)); for (const auto& entry : fs::recursive_directory_iterator(tmp_path)) { if (!entry.is_regular_file()) { continue; } callback(tmp_path, entry); } return Ok(); #else return Err(std::string("not compiled with libarchive")); #endif } }
fix noarchive build
[build] fix noarchive build
C++
bsd-2-clause
tstack/lnav,tstack/lnav,sureshsundriyal/lnav,tstack/lnav,sureshsundriyal/lnav,tstack/lnav,sureshsundriyal/lnav,sureshsundriyal/lnav
515a51dac32ba8a50d697a5b52e432fb717dc472
src/SMESH_I/SMESH_PythonDump.hxx
src/SMESH_I/SMESH_PythonDump.hxx
// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.salome-platform.org/ or email : [email protected] // #ifndef _SMESH_PYTHONDUMP_HXX_ #define _SMESH_PYTHONDUMP_HXX_ #include "SMESH.hxx" #include <SALOMEconfig.h> #include CORBA_SERVER_HEADER(SMESH_Mesh) #include CORBA_SERVER_HEADER(SALOMEDS) #include <sstream> #include <vector> #include <set> class SMESH_Gen_i; class SMESH_MeshEditor_i; class TCollection_AsciiString; class Resource_DataMapOfAsciiStringAsciiString; // =========================================================================================== /*! * \brief Tool converting SMESH engine calls into commands defined in smeshDC.py * * Implementation is in SMESH_2smeshpy.cxx */ // =========================================================================================== class SMESH_2smeshpy { public: /*! * \brief Convert a python script using commands of smeshBuilder.py * \param theScript - Input script * \param theEntry2AccessorMethod - returns method names to access to * objects wrapped with python class * \param theObjectNames - names of objects * \param theRemovedObjIDs - entries of objects whose created commands were removed * \param theHistoricalDump - true means to keep all commands, false means * to exclude commands relating to objects removed from study * \retval TCollection_AsciiString - Convertion result */ static TCollection_AsciiString ConvertScript(const TCollection_AsciiString& theScript, Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod, Resource_DataMapOfAsciiStringAsciiString& theObjectNames, std::set< TCollection_AsciiString >& theRemovedObjIDs, SALOMEDS::Study_ptr& theStudy, const bool theHistoricalDump); /*! * \brief Return the name of the python file wrapping IDL API * \retval const char* - the file name */ static const char* SmeshpyName() { return "smesh"; } static const char* GenName() { return "smesh"; } }; namespace SMESH { class FilterLibrary_i; class FilterManager_i; class Filter_i; class Functor_i; class Measurements_i; // =========================================================================================== /*! * \brief Object used to make TPythonDump know that its held value can be a varible * * TPythonDump substitute TVar with names of notebook variables if any. */ // =========================================================================================== struct SMESH_I_EXPORT TVar { std::vector< std::string > myVals; TVar(CORBA::Double value); TVar(CORBA::Long value); TVar(CORBA::Short value); TVar(const SMESH::double_array& value); // string used to temporary quote variable names in order // not to confuse variables with string arguments static char Quote() { return '$'; } // string preceding an entry of object storing the attribute holding var names static const char* ObjPrefix() { return " # OBJ: "; } }; // =========================================================================================== /*! * \brief Utility helping in storing SMESH engine calls as python commands */ // =========================================================================================== class SMESH_I_EXPORT TPythonDump { std::ostringstream myStream; static size_t myCounter; int myVarsCounter; // counts stored TVar's public: TPythonDump(); virtual ~TPythonDump(); TPythonDump& operator<<(const TVar& theVariableValue); TPythonDump& operator<<(long int theArg); TPythonDump& operator<<(int theArg); TPythonDump& operator<<(double theArg); TPythonDump& operator<<(float theArg); TPythonDump& operator<<(const void* theArg); TPythonDump& operator<<(const char* theArg); TPythonDump& operator<<(const SMESH::ElementType& theArg); TPythonDump& operator<<(const SMESH::GeometryType& theArg); TPythonDump& operator<<(const SMESH::EntityType& theArg); TPythonDump& operator<<(const SMESH::long_array& theArg); TPythonDump& operator<<(const SMESH::double_array& theArg); TPythonDump& operator<<(const SMESH::string_array& theArg); TPythonDump& operator<<(SMESH::SMESH_Hypothesis_ptr theArg); TPythonDump& operator<<(SMESH::SMESH_IDSource_ptr theArg); TPythonDump& operator<<(SALOMEDS::SObject_ptr theArg); TPythonDump& operator<<(CORBA::Object_ptr theArg); TPythonDump& operator<<(SMESH::FilterLibrary_i* theArg); TPythonDump& operator<<(SMESH::FilterManager_i* theArg); TPythonDump& operator<<(SMESH::Filter_i* theArg); TPythonDump& operator<<(SMESH::Functor_i* theArg); TPythonDump& operator<<(SMESH::Measurements_i* theArg); TPythonDump& operator<<(SMESH_Gen_i* theArg); TPythonDump& operator<<(SMESH_MeshEditor_i* theArg); TPythonDump& operator<<(SMESH::MED_VERSION theArg); TPythonDump& operator<<(const SMESH::AxisStruct & theAxis); TPythonDump& operator<<(const SMESH::DirStruct & theDir); TPythonDump& operator<<(const SMESH::PointStruct & P); TPythonDump& operator<<(const TCollection_AsciiString & theArg); TPythonDump& operator<<(const SMESH::ListOfGroups& theList); TPythonDump& operator<<(const SMESH::ListOfGroups * theList); TPythonDump& operator<<(const SMESH::ListOfIDSources& theList); static const char* SMESHGenName() { return "smeshgen"; } static const char* MeshEditorName() { return "mesh_editor"; } static const char* NotPublishedObjectName(); /*! * \brief Return marker of long string literal beginning * \param type - a name of functionality producing the string literal * \retval TCollection_AsciiString - the marker string to be written into * a raw python script */ static TCollection_AsciiString LongStringStart(const char* type); /*! * \brief Return marker of long string literal end * \retval TCollection_AsciiString - the marker string to be written into * a raw python script */ static TCollection_AsciiString LongStringEnd(); /*! * \brief Cut out a long string literal from a string * \param theText - text possibly containing string literals * \param theFrom - position in the text to search from * \param theLongString - the retrieved literal * \param theStringType - a name of functionality produced the literal * \retval bool - true if a string literal found * * The literal is removed from theText; theFrom points position right after * the removed literal */ static bool CutoutLongString( TCollection_AsciiString & theText, int & theFrom, TCollection_AsciiString & theLongString, TCollection_AsciiString & theStringType); }; } #endif
// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.salome-platform.org/ or email : [email protected] // #ifndef _SMESH_PYTHONDUMP_HXX_ #define _SMESH_PYTHONDUMP_HXX_ #include "SMESH.hxx" #include <SALOMEconfig.h> #include CORBA_SERVER_HEADER(SMESH_Mesh) #include CORBA_SERVER_HEADER(SALOMEDS) #include <sstream> #include <vector> #include <set> class SMESH_Gen_i; class SMESH_MeshEditor_i; class TCollection_AsciiString; class Resource_DataMapOfAsciiStringAsciiString; // =========================================================================================== /*! * \brief Tool converting SMESH engine calls into commands defined in smeshBuilder.py * * Implementation is in SMESH_2smeshpy.cxx */ // =========================================================================================== class SMESH_2smeshpy { public: /*! * \brief Convert a python script using commands of smeshBuilder.py * \param theScript - Input script * \param theEntry2AccessorMethod - returns method names to access to * objects wrapped with python class * \param theObjectNames - names of objects * \param theRemovedObjIDs - entries of objects whose created commands were removed * \param theHistoricalDump - true means to keep all commands, false means * to exclude commands relating to objects removed from study * \retval TCollection_AsciiString - Convertion result */ static TCollection_AsciiString ConvertScript(const TCollection_AsciiString& theScript, Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod, Resource_DataMapOfAsciiStringAsciiString& theObjectNames, std::set< TCollection_AsciiString >& theRemovedObjIDs, SALOMEDS::Study_ptr& theStudy, const bool theHistoricalDump); /*! * \brief Return the name of the python file wrapping IDL API * \retval const char* - the file name */ static const char* SmeshpyName() { return "smesh"; } static const char* GenName() { return "smesh"; } }; namespace SMESH { class FilterLibrary_i; class FilterManager_i; class Filter_i; class Functor_i; class Measurements_i; // =========================================================================================== /*! * \brief Object used to make TPythonDump know that its held value can be a varible * * TPythonDump substitute TVar with names of notebook variables if any. */ // =========================================================================================== struct SMESH_I_EXPORT TVar { std::vector< std::string > myVals; TVar(CORBA::Double value); TVar(CORBA::Long value); TVar(CORBA::Short value); TVar(const SMESH::double_array& value); // string used to temporary quote variable names in order // not to confuse variables with string arguments static char Quote() { return '$'; } // string preceding an entry of object storing the attribute holding var names static const char* ObjPrefix() { return " # OBJ: "; } }; // =========================================================================================== /*! * \brief Utility helping in storing SMESH engine calls as python commands */ // =========================================================================================== class SMESH_I_EXPORT TPythonDump { std::ostringstream myStream; static size_t myCounter; int myVarsCounter; // counts stored TVar's public: TPythonDump(); virtual ~TPythonDump(); TPythonDump& operator<<(const TVar& theVariableValue); TPythonDump& operator<<(long int theArg); TPythonDump& operator<<(int theArg); TPythonDump& operator<<(double theArg); TPythonDump& operator<<(float theArg); TPythonDump& operator<<(const void* theArg); TPythonDump& operator<<(const char* theArg); TPythonDump& operator<<(const SMESH::ElementType& theArg); TPythonDump& operator<<(const SMESH::GeometryType& theArg); TPythonDump& operator<<(const SMESH::EntityType& theArg); TPythonDump& operator<<(const SMESH::long_array& theArg); TPythonDump& operator<<(const SMESH::double_array& theArg); TPythonDump& operator<<(const SMESH::string_array& theArg); TPythonDump& operator<<(SMESH::SMESH_Hypothesis_ptr theArg); TPythonDump& operator<<(SMESH::SMESH_IDSource_ptr theArg); TPythonDump& operator<<(SALOMEDS::SObject_ptr theArg); TPythonDump& operator<<(CORBA::Object_ptr theArg); TPythonDump& operator<<(SMESH::FilterLibrary_i* theArg); TPythonDump& operator<<(SMESH::FilterManager_i* theArg); TPythonDump& operator<<(SMESH::Filter_i* theArg); TPythonDump& operator<<(SMESH::Functor_i* theArg); TPythonDump& operator<<(SMESH::Measurements_i* theArg); TPythonDump& operator<<(SMESH_Gen_i* theArg); TPythonDump& operator<<(SMESH_MeshEditor_i* theArg); TPythonDump& operator<<(SMESH::MED_VERSION theArg); TPythonDump& operator<<(const SMESH::AxisStruct & theAxis); TPythonDump& operator<<(const SMESH::DirStruct & theDir); TPythonDump& operator<<(const SMESH::PointStruct & P); TPythonDump& operator<<(const TCollection_AsciiString & theArg); TPythonDump& operator<<(const SMESH::ListOfGroups& theList); TPythonDump& operator<<(const SMESH::ListOfGroups * theList); TPythonDump& operator<<(const SMESH::ListOfIDSources& theList); static const char* SMESHGenName() { return "smeshgen"; } static const char* MeshEditorName() { return "mesh_editor"; } static const char* NotPublishedObjectName(); /*! * \brief Return marker of long string literal beginning * \param type - a name of functionality producing the string literal * \retval TCollection_AsciiString - the marker string to be written into * a raw python script */ static TCollection_AsciiString LongStringStart(const char* type); /*! * \brief Return marker of long string literal end * \retval TCollection_AsciiString - the marker string to be written into * a raw python script */ static TCollection_AsciiString LongStringEnd(); /*! * \brief Cut out a long string literal from a string * \param theText - text possibly containing string literals * \param theFrom - position in the text to search from * \param theLongString - the retrieved literal * \param theStringType - a name of functionality produced the literal * \retval bool - true if a string literal found * * The literal is removed from theText; theFrom points position right after * the removed literal */ static bool CutoutLongString( TCollection_AsciiString & theText, int & theFrom, TCollection_AsciiString & theLongString, TCollection_AsciiString & theStringType); }; } #endif
update documentation of class SMESH_2smeshpy
PR: update documentation of class SMESH_2smeshpy
C++
lgpl-2.1
FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh
cb71df300585e4be23ff462caad5618dca723c4a
3RVX/MeterWnd/Meters/Bitstrip.cpp
3RVX/MeterWnd/Meters/Bitstrip.cpp
#include "Bitstrip.h" Bitstrip::Bitstrip(std::wstring bitmapName, int x, int y, int units) : Meter(bitmapName, x, y, units) { _rect.Width = _bitmap->GetWidth(); _rect.Height = _bitmap->GetHeight() / _units; } void Bitstrip::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) { int units = CalcUnits(); int stripY = (units - 1) * _rect.Height; if (units == 0) { /* The mute OSD should be shown here, but we'll do something sane * rather than go negative. */ stripY = 0; } Gdiplus::Rect drawRect(X(), Y(), Width(), Height()); graphics->DrawImage(_bitmap, drawRect, 0, stripY, Width(), Height(), Gdiplus::UnitPixel); _lastValue = Value(); _lastUnits = units; }
#include "Bitstrip.h" Bitstrip::Bitstrip(std::wstring bitmapName, int x, int y, int units) : Meter(bitmapName, x, y, units) { _rect.Height = _bitmap->GetHeight() / _units; } void Bitstrip::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) { int units = CalcUnits(); int stripY = (units - 1) * _rect.Height; if (units == 0) { /* The mute OSD should be shown here, but we'll do something sane * rather than go negative. */ stripY = 0; } Gdiplus::Rect drawRect(X(), Y(), Width(), Height()); graphics->DrawImage(_bitmap, drawRect, 0, stripY, Width(), Height(), Gdiplus::UnitPixel); _lastValue = Value(); _lastUnits = units; }
Remove unnecessary GetWidth() call.
Remove unnecessary GetWidth() call.
C++
bsd-2-clause
Soulflare3/3RVX,malensek/3RVX,Soulflare3/3RVX,malensek/3RVX,Soulflare3/3RVX,malensek/3RVX
d2aae2d73482bd06e281195cee32b74d1aa853d3
src/enum_generator.cpp
src/enum_generator.cpp
#include <iostream> #include <algorithm> #include "dota2api/apirequest.hpp" #include "json/json.h" const std::string indent1 = " "; const std::string indent2 = indent1 + indent1; const std::string indent3 = indent2 + indent1; std::string toUpper(std::string str) { std::transform(str.begin(), str.end(),str.begin(), ::toupper); return str; } std::string toLower(std::string str) { std::transform(str.begin(), str.end(),str.begin(), ::tolower); return str; } std::string toEnumName(std::string str) { auto replace = [](char c) { return c == ' ' || c == '-'; }; std::replace_if(str.begin(), str.end(), replace, '_'); auto invalid = [](char c) {return c != '_' && !isalpha(c);}; str.erase(std::remove_if(str.begin(), str.end(), invalid), str.end()); return str; } void print(std::initializer_list<std::string> const& args) { for(const auto &arg : args) { std::cout << arg; } std::cout << std::endl; } namespace std { std::string to_string(std::string s) { return s; } } template<class... Args> void print(Args... args) { print({std::to_string(args)...}); } void generateConversionInt(std::string name, std::string displayName) { std::string variableName = toLower(displayName); print(indent1, "inline ", displayName, " ", variableName, "FromInt(int ", variableName, ")"); print(indent1, "{"); print(indent2, "const auto iter = ", name, ".find(", variableName, ");"); print(indent2, "if(iter == ", name, ".end())"); print(indent3, "return ", displayName, "::Unknown;"); print(indent2, "return iter->second;"); print(indent1, "}"); } void generateEnum(Json::Value json, std::string name, std::string displayName) { std::map<int, std::string> enumItems; for(const auto& value : json["result"][name]) enumItems[value["id"].asInt()] = toEnumName(value["localized_name"].asString()); print("#ifndef ", toUpper(name), "_HPP_GENERATED"); print("#define ", toUpper(name), "_HPP_GENERATED"); print(); print("#include <map>"); print(); print("namespace dota2"); print("{"); print(indent1, "enum class ", displayName); print(indent1, "{"); print(indent2, "Unknown = 0,"); for(const auto& value : enumItems) { print(indent2, value.second, " = ", value.first, ","); } print(indent1, "};"); print(); print(indent1, "const std::map<int, ", displayName, "> ", name, "({"); for(const auto& value : enumItems) { print(indent2, "{", value.first, ", ", displayName, "::", value.second, "},"); } print(indent1, "});"); generateConversionInt(name, displayName); print("}"); print("#endif"); } int main(int argc, char *argv[]) { if(argc < 3) { std::cerr << "Expected query type and key" << std::endl; return EXIT_FAILURE; } std::string query = argv[1]; std::string key = argv[2]; std::string lang = "en_us"; std::map<std::string, std::string> modes = { {"heroes" , dota2::HEROES_API}, {"items" , dota2::ITEMS_API}, }; std::map<std::string, std::string> classes = { {"heroes" , "Hero"}, {"items" , "Item"}, }; auto mode = modes.find(query); if(mode == modes.end()) { std::cerr << query << " is not a valid query. Valid values are" << std::endl; for(const auto &mode : modes) { std::cerr << " " << mode.first << std::endl; } return EXIT_FAILURE; } dota2::APIRequest request(mode->second, key, {{std::string("language"), lang}}); try { generateEnum(request.runRequest(), mode->first, classes[query]); } catch(const std::exception &e) { std::cout << e.what() << std::endl; return 1; } return EXIT_SUCCESS; }
#include <iostream> #include <algorithm> #include "dota2api/apirequest.hpp" #include "json/json.h" const std::string indent1 = " "; const std::string indent2 = indent1 + indent1; const std::string indent3 = indent2 + indent1; std::string toUpper(std::string str) { std::transform(str.begin(), str.end(),str.begin(), ::toupper); return str; } std::string toLower(std::string str) { std::transform(str.begin(), str.end(),str.begin(), ::tolower); return str; } std::string toEnumName(std::string str) { auto replace = [](char c) { return c == ' ' || c == '-'; }; std::replace_if(str.begin(), str.end(), replace, '_'); auto invalid = [](char c) {return c != '_' && !isalpha(c);}; str.erase(std::remove_if(str.begin(), str.end(), invalid), str.end()); return str; } void print(std::initializer_list<std::string> const& args) { for(const auto &arg : args) { std::cout << arg; } std::cout << std::endl; } namespace std { std::string to_string(std::string s) { return s; } } template<class... Args> void print(Args... args) { print({std::to_string(args)...}); } void generateConversionInt(std::string name, std::string displayName) { std::string variableName = toLower(displayName); print(indent1, "inline ", displayName, " ", variableName, "FromInt(int ", variableName, ")"); print(indent1, "{"); print(indent2, "const auto iter = ", name, ".find(", variableName, ");"); print(indent2, "if(iter == ", name, ".end())"); print(indent3, "return ", displayName, "::Unknown;"); print(indent2, "return iter->second;"); print(indent1, "}"); } void generateEnum(Json::Value json, std::string name, std::string displayName) { std::map<int, std::string> enumItems; for(const auto& value : json["result"][name]) enumItems[value["id"].asInt()] = toEnumName(value["localized_name"].asString()); print("#ifndef ", toUpper(name), "_HPP_GENERATED"); print("#define ", toUpper(name), "_HPP_GENERATED"); print(); print("#include <map>"); print(); print("namespace dota2"); print("{"); print(indent1, "enum class ", displayName); print(indent1, "{"); print(indent2, "Unknown = 0,"); for(const auto& value : enumItems) { print(indent2, value.second, " = ", value.first, ","); } print(indent1, "};"); print(); print(indent1, "const std::map<int, ", displayName, "> ", name, "({"); for(const auto& value : enumItems) { print(indent2, "{", "(int)", displayName, "::", value.second, ",", displayName, "::", value.second, "},"); } print(indent1, "});"); generateConversionInt(name, displayName); print("}"); print("#endif"); } int main(int argc, char *argv[]) { if(argc < 3) { std::cerr << "Expected query type and key" << std::endl; return EXIT_FAILURE; } std::string query = argv[1]; std::string key = argv[2]; std::string lang = "en_us"; std::map<std::string, std::string> modes = { {"heroes" , dota2::HEROES_API}, {"items" , dota2::ITEMS_API}, }; std::map<std::string, std::string> classes = { {"heroes" , "Hero"}, {"items" , "Item"}, }; auto mode = modes.find(query); if(mode == modes.end()) { std::cerr << query << " is not a valid query. Valid values are" << std::endl; for(const auto &mode : modes) { std::cerr << " " << mode.first << std::endl; } return EXIT_FAILURE; } dota2::APIRequest request(mode->second, key, {{std::string("language"), lang}}); try { generateEnum(request.runRequest(), mode->first, classes[query]); } catch(const std::exception &e) { std::cout << e.what() << std::endl; return 1; } return EXIT_SUCCESS; }
Convert the enum value to int for key
Convert the enum value to int for key This is more obviously correct and does not rely on some magic numbers. This also maskes the resulting diff easier to read.
C++
apache-2.0
UnrealQuester/dota2Cmd
d4f28d94bedd64b3cd0426db44b02130ebd49184
load_service.cc
load_service.cc
#include "service.h" #include <string> #include <fstream> #include <locale> #include <iostream> typedef std::string string; typedef std::string::iterator string_iterator; // Utility function to skip white space. Returns an iterator at the // first non-white-space position (or at end). static string_iterator skipws(string_iterator i, string_iterator end) { using std::locale; using std::isspace; while (i != end) { if (! isspace(*i, locale::classic())) { break; } ++i; } return i; } // Read a setting name. static string read_setting_name(string_iterator & i, string_iterator end) { using std::locale; using std::ctype; using std::use_facet; const ctype<char> & facet = use_facet<ctype<char> >(locale::classic()); string rval; // Allow alphabetical characters, and dash (-) in setting name while (i != end && (*i == '-' || facet.is(ctype<char>::alpha, *i))) { rval += *i; ++i; } return rval; } // Read a setting value // // In general a setting value is a single-line string. It may contain multiple parts // separated by white space (which is normally collapsed). A hash mark - # - denotes // the end of the value and the beginning of a comment (it should be preceded by // whitespace). // // Part of a value may be quoted using double quote marks, which prevents collapse // of whitespace and interpretation of most special characters (the quote marks will // not be considered part of the value). A backslash can precede a character (such // as '#' or '"' or another backslash) to remove its special meaning. Newline // characters are not allowed in values and cannot be quoted. // // This function expects the string to be in an ASCII-compatible, single byte // encoding (the "classic" locale). // // Params: // i - reference to string iterator through the line // end - iterator at end of line // part_positions - list of <int,int> to which the position of each setting value // part will be added as [start,end). May be null. static string read_setting_value(string_iterator & i, string_iterator end, std::list<std::pair<int,int>> * part_positions = nullptr) { using std::locale; using std::isspace; i = skipws(i, end); string rval; bool new_part = true; int part_start; while (i != end) { char c = *i; if (c == '\"') { if (new_part) { part_start = rval.length(); new_part = false; } // quoted string ++i; while (i != end) { c = *i; if (c == '\"') break; if (c == '\n') { // TODO error here. } else if (c == '\\') { // A backslash escapes the following character. ++i; if (i != end) { c = *i; if (c == '\n') { // TODO error here. } rval += c; } } else { rval += c; } ++i; } if (i == end) { // String wasn't terminated // TODO error here break; } } else if (c == '\\') { if (new_part) { part_start = rval.length(); new_part = false; } // A backslash escapes the next character ++i; if (i != end) { rval += *i; } else { // TODO error here } } else if (isspace(c, locale::classic())) { if (! new_part && part_positions != nullptr) { part_positions->emplace_back(part_start, rval.length()); new_part = true; } i = skipws(i, end); if (i == end) break; if (*i == '#') break; // comment rval += ' '; // collapse ws to a single space continue; } else if (c == '#') { // hmm... comment? Probably, though they should have put a space // before it really. TODO throw an exception, and document // that '#' for comments must be preceded by space, and in values // must be quoted. break; } else { if (new_part) { part_start = rval.length(); new_part = false; } rval += c; } ++i; } return rval; } // Find a service record, or load it from file. If the service has // dependencies, load those also. // // Might throw a ServiceLoadExc exception if a dependency cycle is found or if another // problem occurs (I/O error, service description not found etc). ServiceRecord * ServiceSet::loadServiceRecord(const char * name) { using std::string; using std::ifstream; using std::ios; using std::ios_base; using std::locale; using std::isspace; // First try and find an existing record... ServiceRecord * rval = findService(string(name)); if (rval != 0) { if (rval->isDummy()) { throw ServiceCyclicDependency(name); } return rval; } // Couldn't find one. Have to load it. string service_filename = service_dir; if (*(service_filename.rbegin()) != '/') { service_filename += '/'; } service_filename += name; string command; int service_type = SVC_PROCESS; std::list<ServiceRecord *> depends_on; std::list<ServiceRecord *> depends_soft; string logfile; // TODO catch I/O exceptions, wrap & re-throw? string line; bool auto_restart = false; ifstream service_file; service_file.exceptions(ios::badbit | ios::failbit); try { service_file.open(service_filename.c_str(), ios::in); } catch (std::ios_base::failure &exc) { throw ServiceNotFound(name); } // Add a dummy service record now to prevent cyclic dependencies rval = new ServiceRecord(this, string(name)); records.push_back(rval); // getline can set failbit if it reaches end-of-file, we don't want an exception in that case: service_file.exceptions(ios::badbit); while (! (service_file.rdstate() & ios::eofbit)) { getline(service_file, line); string::iterator i = line.begin(); string::iterator end = line.end(); i = skipws(i, end); if (i != end) { if (*i == '#') { continue; // comment line } string setting = read_setting_name(i, end); i = skipws(i, end); if (i == end || (*i != '=' && *i != ':')) { throw ServiceDescriptionExc(name, "Badly formed line."); } i = skipws(++i, end); if (setting == "command") { command = read_setting_value(i, end); } else if (setting == "depends-on") { string dependency_name = read_setting_value(i, end); depends_on.push_back(loadServiceRecord(dependency_name.c_str())); } else if (setting == "waits-for") { string dependency_name = read_setting_value(i, end); depends_soft.push_back(loadServiceRecord(dependency_name.c_str())); } else if (setting == "logfile") { logfile = read_setting_value(i, end); } else if (setting == "restart") { string restart = read_setting_value(i, end); auto_restart = (restart == "yes" || restart == "true"); } else if (setting == "type") { string type_str = read_setting_value(i, end); if (type_str == "scripted") { service_type = SVC_SCRIPTED; } else if (type_str == "process") { service_type = SVC_PROCESS; } else if (type_str == "internal") { service_type = SVC_INTERNAL; } else { throw ServiceDescriptionExc(name, "Service type must be \"scripted\"" " or \"process\" or \"internal\""); } } else { throw ServiceDescriptionExc(name, "Unknown setting: " + setting); } } } service_file.close(); // TODO check we actually have all the settings - type, command // Now replace the dummy service record with a real record: for (auto iter = records.begin(); iter != records.end(); iter++) { if (*iter == rval) { // We've found the dummy record delete rval; rval = new ServiceRecord(this, string(name), service_type, command, & depends_on, & depends_soft); rval->setLogfile(logfile); rval->setAutoRestart(auto_restart); *iter = rval; break; } } return rval; }
#include "service.h" #include <string> #include <fstream> #include <locale> #include <iostream> typedef std::string string; typedef std::string::iterator string_iterator; // Utility function to skip white space. Returns an iterator at the // first non-white-space position (or at end). static string_iterator skipws(string_iterator i, string_iterator end) { using std::locale; using std::isspace; while (i != end) { if (! isspace(*i, locale::classic())) { break; } ++i; } return i; } // Read a setting name. static string read_setting_name(string_iterator & i, string_iterator end) { using std::locale; using std::ctype; using std::use_facet; const ctype<char> & facet = use_facet<ctype<char> >(locale::classic()); string rval; // Allow alphabetical characters, and dash (-) in setting name while (i != end && (*i == '-' || facet.is(ctype<char>::alpha, *i))) { rval += *i; ++i; } return rval; } // Read a setting value // // In general a setting value is a single-line string. It may contain multiple parts // separated by white space (which is normally collapsed). A hash mark - # - denotes // the end of the value and the beginning of a comment (it should be preceded by // whitespace). // // Part of a value may be quoted using double quote marks, which prevents collapse // of whitespace and interpretation of most special characters (the quote marks will // not be considered part of the value). A backslash can precede a character (such // as '#' or '"' or another backslash) to remove its special meaning. Newline // characters are not allowed in values and cannot be quoted. // // This function expects the string to be in an ASCII-compatible, single byte // encoding (the "classic" locale). // // Params: // i - reference to string iterator through the line // end - iterator at end of line // part_positions - list of <int,int> to which the position of each setting value // part will be added as [start,end). May be null. static string read_setting_value(string_iterator & i, string_iterator end, std::list<std::pair<int,int>> * part_positions = nullptr) { using std::locale; using std::isspace; i = skipws(i, end); string rval; bool new_part = true; int part_start; while (i != end) { char c = *i; if (c == '\"') { if (new_part) { part_start = rval.length(); new_part = false; } // quoted string ++i; while (i != end) { c = *i; if (c == '\"') break; if (c == '\n') { // TODO error here. } else if (c == '\\') { // A backslash escapes the following character. ++i; if (i != end) { c = *i; if (c == '\n') { // TODO error here. } rval += c; } } else { rval += c; } ++i; } if (i == end) { // String wasn't terminated // TODO error here break; } } else if (c == '\\') { if (new_part) { part_start = rval.length(); new_part = false; } // A backslash escapes the next character ++i; if (i != end) { rval += *i; } else { // TODO error here } } else if (isspace(c, locale::classic())) { if (! new_part && part_positions != nullptr) { part_positions->emplace_back(part_start, rval.length()); new_part = true; } i = skipws(i, end); if (i == end) break; if (*i == '#') break; // comment rval += ' '; // collapse ws to a single space continue; } else if (c == '#') { // hmm... comment? Probably, though they should have put a space // before it really. TODO throw an exception, and document // that '#' for comments must be preceded by space, and in values // must be quoted. break; } else { if (new_part) { part_start = rval.length(); new_part = false; } rval += c; } ++i; } return rval; } // Find a service record, or load it from file. If the service has // dependencies, load those also. // // Might throw a ServiceLoadExc exception if a dependency cycle is found or if another // problem occurs (I/O error, service description not found etc). ServiceRecord * ServiceSet::loadServiceRecord(const char * name) { using std::string; using std::ifstream; using std::ios; using std::ios_base; using std::locale; using std::isspace; // First try and find an existing record... ServiceRecord * rval = findService(string(name)); if (rval != 0) { if (rval->isDummy()) { throw ServiceCyclicDependency(name); } return rval; } // Couldn't find one. Have to load it. string service_filename = service_dir; if (*(service_filename.rbegin()) != '/') { service_filename += '/'; } service_filename += name; string command; int service_type = SVC_PROCESS; std::list<ServiceRecord *> depends_on; std::list<ServiceRecord *> depends_soft; string logfile; string line; bool auto_restart = false; ifstream service_file; service_file.exceptions(ios::badbit | ios::failbit); try { service_file.open(service_filename.c_str(), ios::in); } catch (std::ios_base::failure &exc) { throw ServiceNotFound(name); } // Add a dummy service record now to prevent infinite recursion in case of cyclic dependency rval = new ServiceRecord(this, string(name)); records.push_back(rval); // getline can set failbit if it reaches end-of-file, we don't want an exception in that case: service_file.exceptions(ios::badbit); while (! (service_file.rdstate() & ios::eofbit)) { getline(service_file, line); string::iterator i = line.begin(); string::iterator end = line.end(); i = skipws(i, end); if (i != end) { if (*i == '#') { continue; // comment line } string setting = read_setting_name(i, end); i = skipws(i, end); if (i == end || (*i != '=' && *i != ':')) { throw ServiceDescriptionExc(name, "Badly formed line."); } i = skipws(++i, end); if (setting == "command") { command = read_setting_value(i, end); // TODO check for valid command } else if (setting == "depends-on") { string dependency_name = read_setting_value(i, end); depends_on.push_back(loadServiceRecord(dependency_name.c_str())); } else if (setting == "waits-for") { string dependency_name = read_setting_value(i, end); depends_soft.push_back(loadServiceRecord(dependency_name.c_str())); } else if (setting == "logfile") { logfile = read_setting_value(i, end); } else if (setting == "restart") { string restart = read_setting_value(i, end); auto_restart = (restart == "yes" || restart == "true"); } else if (setting == "type") { string type_str = read_setting_value(i, end); if (type_str == "scripted") { service_type = SVC_SCRIPTED; } else if (type_str == "process") { service_type = SVC_PROCESS; } else if (type_str == "internal") { service_type = SVC_INTERNAL; } else { throw ServiceDescriptionExc(name, "Service type must be \"scripted\"" " or \"process\" or \"internal\""); } } else { throw ServiceDescriptionExc(name, "Unknown setting: " + setting); } } } service_file.close(); // TODO check we actually have all the settings - type, command // Now replace the dummy service record with a real record: for (auto iter = records.begin(); iter != records.end(); iter++) { if (*iter == rval) { // We've found the dummy record delete rval; rval = new ServiceRecord(this, string(name), service_type, command, & depends_on, & depends_soft); rval->setLogfile(logfile); rval->setAutoRestart(auto_restart); *iter = rval; break; } } return rval; }
Improve comments - remove no longer relevant comment, add some new comments.
Improve comments - remove no longer relevant comment, add some new comments.
C++
apache-2.0
davmac314/dinit,davmac314/dinit,davmac314/dinit
fd02ec467df8406e0b185880aa7a43ce69864981
src/game/leveldata.cpp
src/game/leveldata.cpp
/* Copyright 2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "leveldata.hpp" #include "graphics.hpp" #include "../defs.hpp" #include <cstdio> #include <errno.h> namespace game { using ::graphics::sprite; struct spawninfo { char name[8]; int width; int height; int order; sprite sp; }; static const spawninfo SPAWN_TYPES[leveldata::NTYPE] = { { "player", 16, 24, 30, sprite::PLAYER }, { "door", 24, 32, 10, sprite::DOOR2 }, { "chest", 24, 24, 10, sprite::CHEST }, { "slime", 16, 16, 20, sprite::SLIME1 }, { "prof", 16, 24, 20, sprite::PROFESSOR }, { "woman", 16, 24, 20, sprite::WOMAN }, { "priest", 16, 24, 20, sprite::PRIEST } }; static const spawninfo &get_spawninfo(spawntype type) { int i = static_cast<int>(type); if (i < 0 || i >= leveldata::NTYPE) core::die("Invalid spawn type"); return SPAWN_TYPES[i]; } void spawnpoint::draw(::graphics::system &gr) const { auto &s = get_spawninfo(type); gr.add_sprite( s.sp, vec2(x - s.width/2, y - s.height/2), ::sprite::orientation::NORMAL); } irect spawnpoint::bounds() const { auto &s = get_spawninfo(type); return irect::centered(s.width, s.height).offset(x, y); } int spawnpoint::order() const { return get_spawninfo(type).order; } bool spawnpoint::operator<(const struct spawnpoint &other) const { return order() < other.order(); } const char *leveldata::type_to_string(spawntype type) { return get_spawninfo(type).name; } spawntype leveldata::type_from_string(const std::string &type) { for (int i = 0; i < NTYPE; i++) { if (type == SPAWN_TYPES[i].name) return static_cast<spawntype>(i); } std::printf("Unknown entity type: %s\n", type.c_str()); core::die("Could not read level"); } std::vector<spawnpoint> leveldata::read_level( const std::string &levelname) { std::vector<spawnpoint> data; std::string path = level_path(levelname); FILE *fp = std::fopen(path.c_str(), "r"); if (!fp) { if (errno == ENOENT) { std::printf("Level file is missing: %s\n", path.c_str()); return data; } else { core::die("Error when loading level"); } } char linebuf[256], *linep; std::string whitespace = " \n\t\r"; while ((linep = std::fgets(linebuf, sizeof(linebuf), fp)) != nullptr) { std::string line(linebuf); std::size_t pos = line.find_first_not_of(whitespace), end; if (pos == std::string::npos || line[pos] == '#') continue; std::string fields[4]; // std::puts("parseline"); for (int i = 0; i < 3; i++) { end = line.find_first_of(whitespace, pos); // std::printf("pos = %d..%d\n", (int)pos, (int)end); fields[i] = line.substr(pos, end - pos); if (end == std::string::npos) break; pos = line.find_first_not_of(whitespace, end); if (pos == std::string::npos) break; } if (pos != std::string::npos) { end = line.find_last_not_of(whitespace); // std::printf("pos = %d..%d\n", (int)pos, (int)end); if (end > pos) { if (end != std::string::npos) fields[3] = line.substr(pos, end + 1 - pos); else fields[3] = line.substr(pos); } } if (false) { std::puts("LINE:"); for (int i = 0; i < 4; i++) { if (!fields[i].empty()) std::printf(" %d: %s\n", i + 1, fields[i].c_str()); } } for (int i = 0; i < 3; i++) { if (fields[i].empty()) { std::puts("Not enough fields"); core::die("Could not read level"); } } spawnpoint s; s.x = std::stoi(fields[0]); s.y = std::stoi(fields[1]); s.type = type_from_string(fields[2]); s.data = std::move(fields[3]); data.push_back(std::move(s)); } if (std::ferror(fp)) core::die("Error when loading level"); std::fclose(fp); return std::move(data); } void leveldata::write_level( const std::string &levelname, const std::vector<spawnpoint>& data) { auto path = level_path(levelname); FILE *fp = std::fopen(path.c_str(), "w"); std::fprintf(fp, "# Level: %s\n", path.c_str()); for (auto i = data.begin(), e = data.end(); i != e; i++) { std::fprintf( fp, "%+5d %+5d %s", i->x, i->y, type_to_string(i->type)); if (!i->data.empty()) { std::fputc(' ', fp); std::fputs(i->data.c_str(), fp); } std::fputc('\n', fp); } std::fclose(fp); } std::string leveldata::level_path(const std::string &levelname) { if (levelname.empty()) core::die("Empty level name"); std::string path("level/"); path += levelname; path += ".txt"; return path; } }
/* Copyright 2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "leveldata.hpp" #include "graphics.hpp" #include "../defs.hpp" #include <cstdio> #include <errno.h> namespace game { using ::graphics::sprite; struct spawninfo { char name[8]; int width; int height; int order; sprite sp; }; static const spawninfo SPAWN_TYPES[leveldata::NTYPE] = { { "player", 16, 24, 30, sprite::PLAYER }, { "door", 24, 32, 10, sprite::DOOR2 }, { "chest", 24, 24, 10, sprite::CHEST }, { "slime", 16, 16, 20, sprite::SLIME1 }, { "prof", 12, 24, 20, sprite::PROFESSOR }, { "woman", 12, 24, 20, sprite::WOMAN }, { "priest", 12, 24, 20, sprite::PRIEST } }; static const spawninfo &get_spawninfo(spawntype type) { int i = static_cast<int>(type); if (i < 0 || i >= leveldata::NTYPE) core::die("Invalid spawn type"); return SPAWN_TYPES[i]; } void spawnpoint::draw(::graphics::system &gr) const { auto &s = get_spawninfo(type); gr.add_sprite( s.sp, vec2(x - s.width/2, y - s.height/2), ::sprite::orientation::NORMAL); } irect spawnpoint::bounds() const { auto &s = get_spawninfo(type); return irect::centered(s.width, s.height).offset(x, y); } int spawnpoint::order() const { return get_spawninfo(type).order; } bool spawnpoint::operator<(const struct spawnpoint &other) const { return order() < other.order(); } const char *leveldata::type_to_string(spawntype type) { return get_spawninfo(type).name; } spawntype leveldata::type_from_string(const std::string &type) { for (int i = 0; i < NTYPE; i++) { if (type == SPAWN_TYPES[i].name) return static_cast<spawntype>(i); } std::printf("Unknown entity type: %s\n", type.c_str()); core::die("Could not read level"); } std::vector<spawnpoint> leveldata::read_level( const std::string &levelname) { std::vector<spawnpoint> data; std::string path = level_path(levelname); FILE *fp = std::fopen(path.c_str(), "r"); if (!fp) { if (errno == ENOENT) { std::printf("Level file is missing: %s\n", path.c_str()); return data; } else { core::die("Error when loading level"); } } char linebuf[256], *linep; std::string whitespace = " \n\t\r"; while ((linep = std::fgets(linebuf, sizeof(linebuf), fp)) != nullptr) { std::string line(linebuf); std::size_t pos = line.find_first_not_of(whitespace), end; if (pos == std::string::npos || line[pos] == '#') continue; std::string fields[4]; // std::puts("parseline"); for (int i = 0; i < 3; i++) { end = line.find_first_of(whitespace, pos); // std::printf("pos = %d..%d\n", (int)pos, (int)end); fields[i] = line.substr(pos, end - pos); if (end == std::string::npos) break; pos = line.find_first_not_of(whitespace, end); if (pos == std::string::npos) break; } if (pos != std::string::npos) { end = line.find_last_not_of(whitespace); // std::printf("pos = %d..%d\n", (int)pos, (int)end); if (end > pos) { if (end != std::string::npos) fields[3] = line.substr(pos, end + 1 - pos); else fields[3] = line.substr(pos); } } if (false) { std::puts("LINE:"); for (int i = 0; i < 4; i++) { if (!fields[i].empty()) std::printf(" %d: %s\n", i + 1, fields[i].c_str()); } } for (int i = 0; i < 3; i++) { if (fields[i].empty()) { std::puts("Not enough fields"); core::die("Could not read level"); } } spawnpoint s; s.x = std::stoi(fields[0]); s.y = std::stoi(fields[1]); s.type = type_from_string(fields[2]); s.data = std::move(fields[3]); data.push_back(std::move(s)); } if (std::ferror(fp)) core::die("Error when loading level"); std::fclose(fp); return std::move(data); } void leveldata::write_level( const std::string &levelname, const std::vector<spawnpoint>& data) { auto path = level_path(levelname); FILE *fp = std::fopen(path.c_str(), "w"); std::fprintf(fp, "# Level: %s\n", path.c_str()); for (auto i = data.begin(), e = data.end(); i != e; i++) { std::fprintf( fp, "%+5d %+5d %s", i->x, i->y, type_to_string(i->type)); if (!i->data.empty()) { std::fputc(' ', fp); std::fputs(i->data.c_str(), fp); } std::fputc('\n', fp); } std::fclose(fp); } std::string leveldata::level_path(const std::string &levelname) { if (levelname.empty()) core::die("Empty level name"); std::string path("level/"); path += levelname; path += ".txt"; return path; } }
Fix enemy sprite sizes
Fix enemy sprite sizes
C++
bsd-2-clause
depp/oubliette,depp/oubliette,depp/oubliette,depp/oubliette
093981cb1fa2ef9c6e4c4baaebbcc10493015a6d
BALLS/BALLS/model/OpenGLState.hpp
BALLS/BALLS/model/OpenGLState.hpp
#ifndef OPENGLSTATE_HPP #define OPENGLSTATE_HPP #include <QColor> #include <QObject> #include <QOpenGLContext> #include <glm/fwd.hpp> #include "gl/OpenGLPointers.hpp" namespace balls { using glm::bvec4; class OpenGLState : public QObject { Q_OBJECT /* Categories of OpenGL state: * - Blend State (DONE) * - Implementation info (vendors, etc.) * - Limits (GL_MAX_VARYING_COMPONENTS, etc.) * - Hints * - Stencil * - Depth (DONE) * - Color * - View (scissor, viewport) * */ Q_ENUMS(CullFace) Q_ENUMS(FrontFace) Q_ENUMS(LogicOperation) Q_ENUMS(PolygonMode) Q_ENUMS(ProvokeMode) Q_ENUMS(SpriteCoordOrigin) // clang-format off Q_PROPERTY(bool clampColor READ clampColor WRITE setClampColor STORED false FINAL) Q_PROPERTY(QColor clearColor READ clearColor WRITE setClearColor STORED false FINAL) Q_PROPERTY(int clearStencil READ clearSTencil WRITE setClearStencil STORED false FINAL) Q_PROPERTY(bvec4 colorMask READ colorMask WRITE setColorMask STORED false FINAL) Q_PROPERTY(CullFace cullFace READ cullFace WRITE setCullFace STORED false FINAL) Q_PROPERTY(FrontFace frontFace READ frontFace WRITE setFrontFace STORED false FINAL) Q_PROPERTY(bool invertSampleCoverage READ invertSampleCoverage WRITE setInvertSampleCoverage STORED false FINAL) Q_PROPERTY(float lineWidth READ lineWidth WRITE setLineWidth STORED false FINAL) Q_PROPERTY(float pointFadeThresholdSize READ pointFadeThresholdSize WRITE setPointFadeThresholdSize STORED false FINAL) Q_PROPERTY(float pointSize READ pointSize WRITE setPointSize STORED false FINAL) Q_PROPERTY(PolygonMode polygonMode READ polygonMode WRITE setPolygonMode STORED false FINAL) Q_PROPERTY(float polygonOffsetFactor READ polygonOffsetFactor WRITE setPolygonOffsetFactor STORED false FINAL) Q_PROPERTY(float polygonOffsetUnits READ polygonOffsetUnits WRITE setPolygonOffsetUnits STORED false FINAL) Q_PROPERTY(uint primitiveRestartIndex READ primitiveRestartIndex WRITE setPrimitiveRestartIndex STORED false FINAL) Q_PROPERTY(ProvokeMode provokingVertex READ provokingVertex WRITE setProvokingIndex STORED false FINAL) Q_PROPERTY(float sampleCoverage READ sampleCoverage WRITE setSampleCoverage STORED false FINAL) Q_PROPERTY(SpriteCoordOrigin spriteCoordOrigin READ spriteCoordOrigin WRITE setSpriteCoordOrigin STORED false FINAL) // clang-format on public /* enums */: enum CullFace { None, Front = GL_FRONT, Back = GL_BACK, FrontAndBack = GL_FRONT_AND_BACK, }; enum FrontFace { Clockwise = GL_CW, CounterClockwise = GL_CCW, }; enum LogicOperation { Clear = GL_CLEAR, Set = GL_SET, Copy = GL_COPY, CopyInverted = GL_COPY_INVERTED, Noop = GL_NOOP, Invert = GL_INVERT, And = GL_AND, Nand = GL_NAND, Or = GL_OR, Xor = GL_XOR, Equivalent = GL_EQUIV, AndReverse = GL_AND_REVERSE, AndInverted = GL_AND_INVERTED, OrReverse = GL_OR_REVERSE, OrInverted = GL_OR_INVERTED, }; enum PolygonMode { Point = GL_POINT, Line = GL_LINE, Fill = GL_FILL, }; enum ProvokeMode { FirstVertexConvention = GL_FIRST_VERTEX_CONVENTION, LastVertexConvention = GL_LAST_VERTEX_CONVENTION, }; enum SpriteCoordOrigin { UpperLeft = GL_UPPER_LEFT, LowerLeft = GL_LOWER_LEFT, }; public: explicit OpenGLState(QOpenGLContext*, QObject* = nullptr); private /* members */: OpenGLPointers m_gl; }; } #endif // OPENGLSTATE_HPP
#ifndef OPENGLSTATE_HPP #define OPENGLSTATE_HPP #include <QColor> #include <QObject> #include <QOpenGLContext> #include <glm/fwd.hpp> #include "gl/OpenGLPointers.hpp" namespace balls { using glm::bvec4; class OpenGLState : public QObject { Q_OBJECT /* Categories of OpenGL state: * - Blend State (DONE) * - Implementation info (DONE), except extensions * - Limits (GL_MAX_VARYING_COMPONENTS, etc.) * - Hints (DONE) * - Stencil * - Depth (DONE) * - Color * - View (scissor, viewport) * */ Q_ENUMS(CullFace) Q_ENUMS(FrontFace) Q_ENUMS(LogicOperation) Q_ENUMS(PolygonMode) Q_ENUMS(ProvokeMode) Q_ENUMS(SpriteCoordOrigin) // clang-format off Q_PROPERTY(bool clampColor READ clampColor WRITE setClampColor STORED false FINAL) Q_PROPERTY(QColor clearColor READ clearColor WRITE setClearColor STORED false FINAL) Q_PROPERTY(int clearStencil READ clearSTencil WRITE setClearStencil STORED false FINAL) Q_PROPERTY(bvec4 colorMask READ colorMask WRITE setColorMask STORED false FINAL) Q_PROPERTY(CullFace cullFace READ cullFace WRITE setCullFace STORED false FINAL) Q_PROPERTY(FrontFace frontFace READ frontFace WRITE setFrontFace STORED false FINAL) Q_PROPERTY(bool invertSampleCoverage READ invertSampleCoverage WRITE setInvertSampleCoverage STORED false FINAL) Q_PROPERTY(float lineWidth READ lineWidth WRITE setLineWidth STORED false FINAL) Q_PROPERTY(float pointFadeThresholdSize READ pointFadeThresholdSize WRITE setPointFadeThresholdSize STORED false FINAL) Q_PROPERTY(float pointSize READ pointSize WRITE setPointSize STORED false FINAL) Q_PROPERTY(PolygonMode polygonMode READ polygonMode WRITE setPolygonMode STORED false FINAL) Q_PROPERTY(float polygonOffsetFactor READ polygonOffsetFactor WRITE setPolygonOffsetFactor STORED false FINAL) Q_PROPERTY(float polygonOffsetUnits READ polygonOffsetUnits WRITE setPolygonOffsetUnits STORED false FINAL) Q_PROPERTY(uint primitiveRestartIndex READ primitiveRestartIndex WRITE setPrimitiveRestartIndex STORED false FINAL) Q_PROPERTY(ProvokeMode provokingVertex READ provokingVertex WRITE setProvokingIndex STORED false FINAL) Q_PROPERTY(float sampleCoverage READ sampleCoverage WRITE setSampleCoverage STORED false FINAL) Q_PROPERTY(SpriteCoordOrigin spriteCoordOrigin READ spriteCoordOrigin WRITE setSpriteCoordOrigin STORED false FINAL) // clang-format on public /* enums */: enum CullFace { None, Front = GL_FRONT, Back = GL_BACK, FrontAndBack = GL_FRONT_AND_BACK, }; enum FrontFace { Clockwise = GL_CW, CounterClockwise = GL_CCW, }; enum LogicOperation { Clear = GL_CLEAR, Set = GL_SET, Copy = GL_COPY, CopyInverted = GL_COPY_INVERTED, Noop = GL_NOOP, Invert = GL_INVERT, And = GL_AND, Nand = GL_NAND, Or = GL_OR, Xor = GL_XOR, Equivalent = GL_EQUIV, AndReverse = GL_AND_REVERSE, AndInverted = GL_AND_INVERTED, OrReverse = GL_OR_REVERSE, OrInverted = GL_OR_INVERTED, }; enum PolygonMode { Point = GL_POINT, Line = GL_LINE, Fill = GL_FILL, }; enum ProvokeMode { FirstVertexConvention = GL_FIRST_VERTEX_CONVENTION, LastVertexConvention = GL_LAST_VERTEX_CONVENTION, }; enum SpriteCoordOrigin { UpperLeft = GL_UPPER_LEFT, LowerLeft = GL_LOWER_LEFT, }; public: explicit OpenGLState(QOpenGLContext*, QObject* = nullptr); private /* members */: OpenGLPointers m_gl; }; } #endif // OPENGLSTATE_HPP
Mark Hints and ImplementationInfo as done
Mark Hints and ImplementationInfo as done
C++
apache-2.0
JesseTG/BALLS,JesseTG/BALLS,JesseTG/BALLS
073d59cf2910261b6e09a9c07d156f810b944569
harness.cpp
harness.cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <map> #include <set> #include <bitset> #include <algorithm> #include <sstream> #include <iostream> #include <cassert> #include <fstream> #include <future> #include <thread> #include <chrono> #include <iomanip> #include <numeric> #include <thread> #include <atomic> #include <random> using namespace std; typedef int64_t int64; #define be(coll) std::begin(coll), std::end(coll) // functional form of next value in a stream template<typename T> T nextValue(std::istream &in) { T i; in >> i; return i; } // reads a vector (of integral values) from an input stream template<typename T> std::vector<T> readVector(std::istream &in, int n) { std::vector<T> c; std::generate_n(std::back_inserter(c), n, [&in]() { return nextValue<T>(in); }); return c; } std::chrono::time_point<std::chrono::system_clock> now() { return std::chrono::system_clock::now(); } double since(const std::chrono::time_point<std::chrono::system_clock> &t0) { return std::chrono::duration<double>(std::chrono::system_clock::now() - t0).count(); } // base class: override with a specific problem class SolverBase { std::ostringstream out_; public: virtual void read(std::istream &in) = 0; // read input for a single test case virtual void solve() { out_.str(""); saw(out_); } // solve a single test case virtual void write(std::ostream &out) { out << out_.str(); } // write output (after "Case: #N: ") string str() { return out_.str(); } operator string() { return out_.str(); } protected: virtual void saw(std::ostream &out) = 0; // solve and write }; class Solver : public SolverBase { // fill in member variables public: virtual void read(std::istream &in); protected: virtual void saw(std::ostream &out); }; void Solver::read(std::istream &in) { // read problem data // in >> n >> a >> b; // v = readVector<int>(in, n); } void Solver::saw(std::ostream &out) { // solution code // out << answer; } int main() { // comment these out to use console i/o freopen("A.in.txt", "r", stdin); freopen("A.out.txt", "w", stdout); auto t00 = std::chrono::system_clock::now(); int nTestCases ; cin >> nTestCases; // number of processors const int nThreads = min(1, min(max(int(thread::hardware_concurrency()), 1), nTestCases)); if (nThreads <= 1) { // sequential processing: less memory and useful for debugging Solver s; for (int it = 0; it < nTestCases; ++it) { auto t0 = now(); s.read(cin); s.solve(); double t = since(t0); cout << "Case #" << (it + 1) << ": " << s.str() << endl; if (t > 0.01) fprintf(stderr, "%3d : %3d / %d = %.2f | %.2f\n", it + 1, int(it + 1), nTestCases, t, since(t00) / (it+1) * nTestCases); } } else { // parallel processing with simple thread pool vector<Solver> s(nTestCases); // read all input sequentially for (int it = 0; it < nTestCases; ++it) { s[it].read(cin); } atomic<int> next(0); // the next case that needs a worker thread atomic<int> done(0); // only used for progress reporting auto work = [&next, &done, &s, &nTestCases, t00](void) { while (true) { int i = next++; // this atomic operation is how the threads synchronize with each other if (i >= nTestCases) return; //fprintf(stderr, "start %3d\n", i + 1); auto t0 = now(); s[i].solve(); double t = since(t0); done++; if (t > 0.01) fprintf(stderr, "%3d : %3d / %d = %.2f | %.2f\n", i + 1, int(done), nTestCases, t, since(t00) / done * nTestCases); } }; vector<thread> workers; // start worker threads for (int i = 0; i < nThreads; ++i) { workers.push_back(thread(work)); } // wait for all workers to complete for (int i = 0; i < nThreads; ++i) { workers[i].join(); } // report results for (int it = 0; it < nTestCases; ++it) { cout << "Case #" << (it + 1) << ": " << s[it].str() << endl; } } fprintf(stderr, "%.2f\n", since(t00)); return 0; }
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <map> #include <set> #include <bitset> #include <algorithm> #include <sstream> #include <iostream> #include <cassert> #include <fstream> #include <future> #include <thread> #include <chrono> #include <iomanip> #include <numeric> #include <thread> #include <atomic> #include <random> using namespace std; typedef int64_t int64; #define be(coll) std::begin(coll), std::end(coll) // functional form of next value in a stream template<typename T> T nextValue(std::istream &in) { T i; in >> i; return i; } // reads a vector (of integral values) from an input stream template<typename T> std::vector<T> readVector(std::istream &in, int n) { std::vector<T> c; std::generate_n(std::back_inserter(c), n, [&in]() { return nextValue<T>(in); }); return c; } std::chrono::time_point<std::chrono::system_clock> now() { return std::chrono::system_clock::now(); } double since(const std::chrono::time_point<std::chrono::system_clock> &t0) { return std::chrono::duration<double>(std::chrono::system_clock::now() - t0).count(); } // base class: override with a specific problem class SolverBase { std::ostringstream out_; public: virtual void read(std::istream &in) = 0; // read input for a single test case virtual void solve() { out_.str(""); saw(out_); } // solve a single test case virtual void write(std::ostream &out) { out << out_.str(); } // write output (after "Case: #N: ") string str() { return out_.str(); } operator string() { return out_.str(); } protected: virtual void saw(std::ostream &out) = 0; // solve and write }; class Solver : public SolverBase { // fill in member variables public: virtual void read(std::istream &in); protected: virtual void saw(std::ostream &out); }; void Solver::read(std::istream &in) { // read problem data // in >> n >> a >> b; // v = readVector<int>(in, n); } void Solver::saw(std::ostream &out) { // solution code // out << answer; } int main() { // comment these out to use console i/o freopen("A.in.txt", "r", stdin); freopen("A.out.txt", "w", stdout); auto t00 = std::chrono::system_clock::now(); int nTestCases ; cin >> nTestCases; // number of processors const int nThreads = min(max(int(thread::hardware_concurrency()), 1), nTestCases); if (nThreads <= 1) { // sequential processing: less memory and useful for debugging Solver s; for (int it = 0; it < nTestCases; ++it) { auto t0 = now(); s.read(cin); s.solve(); double t = since(t0); cout << "Case #" << (it + 1) << ": " << s.str() << endl; if (t > 0.01) fprintf(stderr, "%3d : %3d / %d = %.2f | %.2f\n", it + 1, int(it + 1), nTestCases, t, since(t00) / (it+1) * nTestCases); } } else { // parallel processing with simple thread pool vector<Solver> s(nTestCases); // read all input sequentially for (int it = 0; it < nTestCases; ++it) { s[it].read(cin); } atomic<int> next(0); // the next case that needs a worker thread atomic<int> done(0); // only used for progress reporting auto work = [&next, &done, &s, &nTestCases, t00](void) { while (true) { int i = next++; // this atomic operation is how the threads synchronize with each other if (i >= nTestCases) return; //fprintf(stderr, "start %3d\n", i + 1); auto t0 = now(); s[i].solve(); double t = since(t0); done++; if (t > 0.01) fprintf(stderr, "%3d : %3d / %d = %.2f | %.2f\n", i + 1, int(done), nTestCases, t, since(t00) / done * nTestCases); } }; vector<thread> workers; // start worker threads for (int i = 0; i < nThreads; ++i) { workers.push_back(thread(work)); } // wait for all workers to complete for (int i = 0; i < nThreads; ++i) { workers[i].join(); } // report results for (int it = 0; it < nTestCases; ++it) { cout << "Case #" << (it + 1) << ": " << s[it].str() << endl; } } fprintf(stderr, "%.2f\n", since(t00)); return 0; }
remove debugging code
remove debugging code
C++
unlicense
xangregg/parallelcodejam
c1bb74afc336835494e8322964654dc087fe284f
src/cgi/cgi_launch.cxx
src/cgi/cgi_launch.cxx
/* * Run a CGI script. * * author: Max Kellermann <[email protected]> */ #include "cgi_launch.hxx" #include "cgi_address.hxx" #include "istream/istream.hxx" #include "fork.hxx" #include "strmap.hxx" #include "system/sigutil.h" #include "product.h" #include "spawn/Spawn.hxx" #include "spawn/Prepared.hxx" #include "PrefixLogger.hxx" #include "util/ConstBuffer.hxx" #include "util/CharUtil.hxx" #include "util/Error.hxx" #include <daemon/log.h> #include <sys/wait.h> #include <assert.h> #include <string.h> struct cgi_ctx { http_method_t method; const struct cgi_address *address; const char *uri; off_t available; const char *remote_addr; struct strmap *headers; sigset_t signals; int stderr_pipe; cgi_ctx(http_method_t _method, const struct cgi_address &_address, const char *_uri, off_t _available, const char *_remote_addr, struct strmap *_headers, int _stderr_pipe) :method(_method), address(&_address), uri(_uri), available(_available), remote_addr(_remote_addr), headers(_headers), stderr_pipe(_stderr_pipe) {} }; static void gcc_noreturn cgi_run(const JailParams *jail, const char *interpreter, const char *action, const char *path, ConstBuffer<const char *> args, http_method_t method, const char *uri, const char *script_name, const char *path_info, const char *query_string, const char *document_root, const char *remote_addr, const struct strmap *headers, off_t content_length, ConstBuffer<const char *> env) { const char *arg = nullptr; assert(path != nullptr); assert(http_method_is_valid(method)); assert(uri != nullptr); if (script_name == nullptr) script_name = ""; if (path_info == nullptr) path_info = ""; if (query_string == nullptr) query_string = ""; if (document_root == nullptr) document_root = "/var/www"; PreparedChildProcess e; for (auto i : env) e.PutEnv(i); e.SetEnv("GATEWAY_INTERFACE", "CGI/1.1"); e.SetEnv("SERVER_PROTOCOL", "HTTP/1.1"); e.SetEnv("REQUEST_METHOD", http_method_to_string(method)); e.SetEnv("SCRIPT_FILENAME", path); e.SetEnv("PATH_TRANSLATED", path); e.SetEnv("REQUEST_URI", uri); e.SetEnv("SCRIPT_NAME", script_name); e.SetEnv("PATH_INFO", path_info); e.SetEnv("QUERY_STRING", query_string); e.SetEnv("DOCUMENT_ROOT", document_root); e.SetEnv("SERVER_SOFTWARE", PRODUCT_TOKEN); if (remote_addr != nullptr) e.SetEnv("REMOTE_ADDR", remote_addr); if (jail != nullptr && jail->enabled) { e.SetEnv("JAILCGI_FILENAME", path); path = "/usr/lib/cm4all/jailcgi/bin/wrapper"; if (jail->home_directory != nullptr) e.SetEnv("JETSERV_HOME", jail->home_directory); if (interpreter != nullptr) e.SetEnv("JAILCGI_INTERPRETER", interpreter); if (action != nullptr) e.SetEnv("JAILCGI_ACTION", action); } else { if (action != nullptr) path = action; if (interpreter != nullptr) { arg = path; path = interpreter; } } const char *content_type = nullptr; if (headers != nullptr) { for (const auto &pair : *headers) { if (strcmp(pair.key, "content-type") == 0) { content_type = pair.value; continue; } char buffer[512] = "HTTP_"; size_t i; for (i = 0; 5 + i < sizeof(buffer) - 1 && pair.key[i] != 0; ++i) { if (IsLowerAlphaASCII(pair.key[i])) buffer[5 + i] = (char)(pair.key[i] - 'a' + 'A'); else if (IsUpperAlphaASCII(pair.key[i]) || IsDigitASCII(pair.key[i])) buffer[5 + i] = pair.key[i]; else buffer[5 + i] = '_'; } buffer[5 + i] = 0; e.SetEnv(buffer, pair.value); } } if (content_type != nullptr) e.SetEnv("CONTENT_TYPE", content_type); if (content_length >= 0) { char value[32]; snprintf(value, sizeof(value), "%llu", (unsigned long long)content_length); e.SetEnv("CONTENT_LENGTH", value); } e.Append(path); for (auto i : args) e.Append(i); if (arg != nullptr) e.Append(arg); Exec(std::move(e)); } static int cgi_fn(void *ctx) { struct cgi_ctx *c = (struct cgi_ctx *)ctx; const struct cgi_address *address = c->address; install_default_signal_handlers(); leave_signal_section(&c->signals); if (c->stderr_pipe >= 0) dup2(c->stderr_pipe, STDERR_FILENO); address->options.Apply(); cgi_run(&address->options.jail, address->interpreter, address->action, address->path, { address->args.values, address->args.n }, c->method, c->uri, address->script_name, address->path_info, address->query_string, address->document_root, c->remote_addr, c->headers, c->available, { address->options.env.values, address->options.env.n }); } static void cgi_child_callback(int status, void *ctx gcc_unused) { int exit_status = WEXITSTATUS(status); if (WIFSIGNALED(status)) { int level = 1; if (!WCOREDUMP(status) && WTERMSIG(status) == SIGTERM) level = 4; daemon_log(level, "CGI died from signal %d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); } else if (exit_status != 0) daemon_log(1, "CGI exited with status %d\n", exit_status); } static const char * cgi_address_name(const struct cgi_address *address) { if (address->interpreter != nullptr) return address->interpreter; if (address->action != nullptr) return address->action; if (address->path != nullptr) return address->path; return "CGI"; } Istream * cgi_launch(struct pool *pool, http_method_t method, const struct cgi_address *address, const char *remote_addr, struct strmap *headers, Istream *body, GError **error_r) { const auto prefix_logger = CreatePrefixLogger(IgnoreError()); struct cgi_ctx c(method, *address, address->GetURI(pool), body != nullptr ? body->GetAvailable(false) : -1, remote_addr, headers, prefix_logger.second); const int clone_flags = address->options.ns.GetCloneFlags(SIGCHLD); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&c.signals); Istream *input; pid_t pid = beng_fork(pool, cgi_address_name(address), body, &input, clone_flags, cgi_fn, &c, cgi_child_callback, nullptr, error_r); if (prefix_logger.second >= 0) close(prefix_logger.second); if (pid < 0) { leave_signal_section(&c.signals); DeletePrefixLogger(prefix_logger.first); return nullptr; } leave_signal_section(&c.signals); if (prefix_logger.first != nullptr) PrefixLoggerSetPid(*prefix_logger.first, pid); return input; }
/* * Run a CGI script. * * author: Max Kellermann <[email protected]> */ #include "cgi_launch.hxx" #include "cgi_address.hxx" #include "istream/istream.hxx" #include "fork.hxx" #include "strmap.hxx" #include "system/sigutil.h" #include "product.h" #include "spawn/Spawn.hxx" #include "spawn/Prepared.hxx" #include "PrefixLogger.hxx" #include "util/ConstBuffer.hxx" #include "util/CharUtil.hxx" #include "util/Error.hxx" #include <daemon/log.h> #include <sys/wait.h> #include <assert.h> #include <string.h> struct CgiLaunchContext { http_method_t method; const struct cgi_address *address; const char *uri; off_t available; const char *remote_addr; struct strmap *headers; sigset_t signals; int stderr_pipe; CgiLaunchContext(http_method_t _method, const struct cgi_address &_address, const char *_uri, off_t _available, const char *_remote_addr, struct strmap *_headers, int _stderr_pipe) :method(_method), address(&_address), uri(_uri), available(_available), remote_addr(_remote_addr), headers(_headers), stderr_pipe(_stderr_pipe) {} }; static void gcc_noreturn cgi_run(const JailParams *jail, const char *interpreter, const char *action, const char *path, ConstBuffer<const char *> args, http_method_t method, const char *uri, const char *script_name, const char *path_info, const char *query_string, const char *document_root, const char *remote_addr, const struct strmap *headers, off_t content_length, ConstBuffer<const char *> env) { const char *arg = nullptr; assert(path != nullptr); assert(http_method_is_valid(method)); assert(uri != nullptr); if (script_name == nullptr) script_name = ""; if (path_info == nullptr) path_info = ""; if (query_string == nullptr) query_string = ""; if (document_root == nullptr) document_root = "/var/www"; PreparedChildProcess e; for (auto i : env) e.PutEnv(i); e.SetEnv("GATEWAY_INTERFACE", "CGI/1.1"); e.SetEnv("SERVER_PROTOCOL", "HTTP/1.1"); e.SetEnv("REQUEST_METHOD", http_method_to_string(method)); e.SetEnv("SCRIPT_FILENAME", path); e.SetEnv("PATH_TRANSLATED", path); e.SetEnv("REQUEST_URI", uri); e.SetEnv("SCRIPT_NAME", script_name); e.SetEnv("PATH_INFO", path_info); e.SetEnv("QUERY_STRING", query_string); e.SetEnv("DOCUMENT_ROOT", document_root); e.SetEnv("SERVER_SOFTWARE", PRODUCT_TOKEN); if (remote_addr != nullptr) e.SetEnv("REMOTE_ADDR", remote_addr); if (jail != nullptr && jail->enabled) { e.SetEnv("JAILCGI_FILENAME", path); path = "/usr/lib/cm4all/jailcgi/bin/wrapper"; if (jail->home_directory != nullptr) e.SetEnv("JETSERV_HOME", jail->home_directory); if (interpreter != nullptr) e.SetEnv("JAILCGI_INTERPRETER", interpreter); if (action != nullptr) e.SetEnv("JAILCGI_ACTION", action); } else { if (action != nullptr) path = action; if (interpreter != nullptr) { arg = path; path = interpreter; } } const char *content_type = nullptr; if (headers != nullptr) { for (const auto &pair : *headers) { if (strcmp(pair.key, "content-type") == 0) { content_type = pair.value; continue; } char buffer[512] = "HTTP_"; size_t i; for (i = 0; 5 + i < sizeof(buffer) - 1 && pair.key[i] != 0; ++i) { if (IsLowerAlphaASCII(pair.key[i])) buffer[5 + i] = (char)(pair.key[i] - 'a' + 'A'); else if (IsUpperAlphaASCII(pair.key[i]) || IsDigitASCII(pair.key[i])) buffer[5 + i] = pair.key[i]; else buffer[5 + i] = '_'; } buffer[5 + i] = 0; e.SetEnv(buffer, pair.value); } } if (content_type != nullptr) e.SetEnv("CONTENT_TYPE", content_type); if (content_length >= 0) { char value[32]; snprintf(value, sizeof(value), "%llu", (unsigned long long)content_length); e.SetEnv("CONTENT_LENGTH", value); } e.Append(path); for (auto i : args) e.Append(i); if (arg != nullptr) e.Append(arg); Exec(std::move(e)); } static int cgi_fn(void *ctx) { auto *c = (CgiLaunchContext *)ctx; const struct cgi_address *address = c->address; install_default_signal_handlers(); leave_signal_section(&c->signals); if (c->stderr_pipe >= 0) dup2(c->stderr_pipe, STDERR_FILENO); address->options.Apply(); cgi_run(&address->options.jail, address->interpreter, address->action, address->path, { address->args.values, address->args.n }, c->method, c->uri, address->script_name, address->path_info, address->query_string, address->document_root, c->remote_addr, c->headers, c->available, { address->options.env.values, address->options.env.n }); } static void cgi_child_callback(int status, void *ctx gcc_unused) { int exit_status = WEXITSTATUS(status); if (WIFSIGNALED(status)) { int level = 1; if (!WCOREDUMP(status) && WTERMSIG(status) == SIGTERM) level = 4; daemon_log(level, "CGI died from signal %d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); } else if (exit_status != 0) daemon_log(1, "CGI exited with status %d\n", exit_status); } static const char * cgi_address_name(const struct cgi_address *address) { if (address->interpreter != nullptr) return address->interpreter; if (address->action != nullptr) return address->action; if (address->path != nullptr) return address->path; return "CGI"; } Istream * cgi_launch(struct pool *pool, http_method_t method, const struct cgi_address *address, const char *remote_addr, struct strmap *headers, Istream *body, GError **error_r) { const auto prefix_logger = CreatePrefixLogger(IgnoreError()); CgiLaunchContext c(method, *address, address->GetURI(pool), body != nullptr ? body->GetAvailable(false) : -1, remote_addr, headers, prefix_logger.second); const int clone_flags = address->options.ns.GetCloneFlags(SIGCHLD); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&c.signals); Istream *input; pid_t pid = beng_fork(pool, cgi_address_name(address), body, &input, clone_flags, cgi_fn, &c, cgi_child_callback, nullptr, error_r); if (prefix_logger.second >= 0) close(prefix_logger.second); if (pid < 0) { leave_signal_section(&c.signals); DeletePrefixLogger(prefix_logger.first); return nullptr; } leave_signal_section(&c.signals); if (prefix_logger.first != nullptr) PrefixLoggerSetPid(*prefix_logger.first, pid); return input; }
rename struct to CamelCase
cgi/launch: rename struct to CamelCase
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
9dce9472b2cc7c8ce8407d643ed595d7c162dcda
src/char/src/party.cpp
src/char/src/party.cpp
#include "party.h" #include "user.h" #include "ccharserver.h" #include "logconsole.h" std::shared_ptr<Party> cache_fetch_party(uint32_t charId) { auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; Core::PartyMembersTable partyMembersTable{}; auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from( partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id)) .where(partyMembersTable.memberId == charId)); if (res.empty()) { return {}; } auto& result = res.front(); Party party; party.id = result.id; party.name = result.name; party.leader = result.leaderId; party.options = result.options; party.level = result.level; party.last_got_item_index = result.lastGotItemIndex; party.last_got_zuly_index = result.lastGotZulyIndex; party.last_got_etc_index = result.lastGotEtcIndex; // now we fetch all party members auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable) .where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc())); if (res.empty()) { return {}; } for (const auto& r : res2) { party.members.push_back(r.memberId); } return std::make_shared<Party>(party); } void cache_create_party(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; conn(sqlpp::insert_into(partyTable) .set(partyTable.name = party->name, partyTable.leaderId = party->leader, partyTable.options = party->options, partyTable.level = party->level, partyTable.lastGotItemIndex = party->last_got_item_index, partyTable.lastGotEtcIndex = party->last_got_etc_index, partyTable.lastGotZulyIndex = party->last_got_zuly_index)); } void cache_write_party(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; conn(sqlpp::update(partyTable) .set(partyTable.name = party->name, partyTable.leaderId = party->leader, partyTable.options = party->options, partyTable.level = party->level, partyTable.lastGotItemIndex = party->last_got_item_index, partyTable.lastGotEtcIndex = party->last_got_etc_index, partyTable.lastGotZulyIndex = party->last_got_zuly_index) .where(partyTable.id == party->id)); } void cache_write_party_members(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyMembersTable partyMembersTable{}; conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id)); auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId); for (auto m : party-> members) { insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = static_cast<int>(m)); } conn(insert); } void cache_remove_party(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id)); } void party_request(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("party_request({})", user.get_name()); using namespace RoseCommon::Packet; switch (packet.get_type()) { case CliPartyReq::CREATE: // idXorTag == id { auto other = server.get_user(packet.get_target(), user.get_mapId()); if (!other) { logger->warn("User ({}, {}) doesn't exist", packet.get_target(), user.get_mapId()); return; } logger->debug("{} wants to make a party with {}", user.get_name(), other.value()->get_name()); break; } case CliPartyReq::JOIN: // idXorTag == id { auto other = server.get_user(packet.get_target(), user.get_mapId()); if (!other) { logger->warn("User ({}, {}) doesn't exist", packet.get_target(), user.get_mapId()); return; } logger->debug("{} wants to join {}'s party", user.get_name(), other.value()->get_name()); break; } case CliPartyReq::LEAVE: // idXorTag == tag { logger->debug("{} left the party", user.get_name()); break; } case CliPartyReq::CHANGE_OWNER: // idXorTag == tag { auto other = server.get_user(packet.get_target()); if (!other) { logger->warn("User {} doesn't exist", packet.get_target()); return; } logger->debug("{} wants to make {} the owner", user.get_name(), other.value()->get_name()); break; } case CliPartyReq::BAN: // idXorTag == tag { auto other = server.get_user(packet.get_target()); if (!other) { logger->warn("User {} doesn't exist", packet.get_target()); return; } logger->debug("{} wants to kick {}", user.get_name(), other.value()->get_name()); break; } default: logger->warn("Client {} sent a non valid request code {}", charId, packet.get_request()); } } void party_reply(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("party_reply({})", user.get_name()); auto* other; if (auto tmp = server.get_user(packet.get_target(), user.get_mapId()); !tmp) { logger->warn("Client {} replied to a party request of the non existing char {}", user.get_name(), packet.get_idXorTag()); return; } using namespace RoseCommon::Packet; switch (packet.get_type()) { case CliPartyReply::BUSY: case CliPartyReply::REJECT_JOIN: logger->debug("{} refused {}'s party", other.value()->get_name(), user.get_name()); break; case CliPartyReply::ACCEPT_CREATE: case CliPartyReply::ACCEPT_JOIN: logger->debug("{} accepted {}'s party", other.value()->get_name(), user.get_name()); break; default: logger->debug("{} replied {}", user.get_name(), packet.get_type()); break; } }
#include "party.h" #include "user.h" #include "ccharserver.h" #include "logconsole.h" std::shared_ptr<Party> cache_fetch_party(uint32_t charId) { auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; Core::PartyMembersTable partyMembersTable{}; auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from( partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id)) .where(partyMembersTable.memberId == charId)); if (res.empty()) { return {}; } auto& result = res.front(); Party party; party.id = result.id; party.name = result.name; party.leader = result.leaderId; party.options = result.options; party.level = result.level; party.last_got_item_index = result.lastGotItemIndex; party.last_got_zuly_index = result.lastGotZulyIndex; party.last_got_etc_index = result.lastGotEtcIndex; // now we fetch all party members auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable) .where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc())); if (res.empty()) { return {}; } for (const auto& r : res2) { party.members.push_back(r.memberId); } return std::make_shared<Party>(party); } void cache_create_party(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; conn(sqlpp::insert_into(partyTable) .set(partyTable.name = party->name, partyTable.leaderId = party->leader, partyTable.options = party->options, partyTable.level = party->level, partyTable.lastGotItemIndex = party->last_got_item_index, partyTable.lastGotEtcIndex = party->last_got_etc_index, partyTable.lastGotZulyIndex = party->last_got_zuly_index)); } void cache_write_party(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; conn(sqlpp::update(partyTable) .set(partyTable.name = party->name, partyTable.leaderId = party->leader, partyTable.options = party->options, partyTable.level = party->level, partyTable.lastGotItemIndex = party->last_got_item_index, partyTable.lastGotEtcIndex = party->last_got_etc_index, partyTable.lastGotZulyIndex = party->last_got_zuly_index) .where(partyTable.id == party->id)); } void cache_write_party_members(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyMembersTable partyMembersTable{}; conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id)); auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId); for (auto m : party-> members) { insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = static_cast<int>(m)); } conn(insert); } void cache_remove_party(std::shared_ptr<Party> party) { if (!party) return; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); Core::PartyTable partyTable{}; conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id)); } void party_request(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("party_request({})", user.get_name()); using namespace RoseCommon::Packet; switch (packet.get_type()) { case CliPartyReq::CREATE: // idXorTag == id { auto other = server.get_user(packet.get_target(), user.get_mapId()); if (!other) { logger->warn("User ({}, {}) doesn't exist", packet.get_target(), user.get_mapId()); return; } logger->debug("{} wants to make a party with {}", user.get_name(), other.value()->get_name()); break; } case CliPartyReq::JOIN: // idXorTag == id { auto other = server.get_user(packet.get_target(), user.get_mapId()); if (!other) { logger->warn("User ({}, {}) doesn't exist", packet.get_target(), user.get_mapId()); return; } logger->debug("{} wants to join {}'s party", user.get_name(), other.value()->get_name()); break; } case CliPartyReq::LEAVE: // idXorTag == tag { logger->debug("{} left the party", user.get_name()); break; } case CliPartyReq::CHANGE_OWNER: // idXorTag == tag { auto other = server.get_user(packet.get_target()); if (!other) { logger->warn("User {} doesn't exist", packet.get_target()); return; } logger->debug("{} wants to make {} the owner", user.get_name(), other.value()->get_name()); break; } case CliPartyReq::BAN: // idXorTag == tag { auto other = server.get_user(packet.get_target()); if (!other) { logger->warn("User {} doesn't exist", packet.get_target()); return; } logger->debug("{} wants to kick {}", user.get_name(), other.value()->get_name()); break; } default: logger->warn("Client {} sent a non valid request code {}", user.get_name(), packet.get_target()); } } void party_reply(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("party_reply({})", user.get_name()); User*const other; if (auto tmp = server.get_user(packet.get_target(), user.get_mapId()); tmp) { other = tmp.value(); } else { logger->warn("Client {} replied to a party request of the non existing char {}", user.get_name(), packet.get_target()); return; } using namespace RoseCommon::Packet; switch (packet.get_type()) { case CliPartyReply::BUSY: case CliPartyReply::REJECT_JOIN: logger->debug("{} refused {}'s party", other.value()->get_name(), user.get_name()); break; case CliPartyReply::ACCEPT_CREATE: case CliPartyReply::ACCEPT_JOIN: logger->debug("{} accepted {}'s party", other.value()->get_name(), user.get_name()); break; default: logger->debug("{} replied {}", user.get_name(), packet.get_type()); break; } }
Update party.cpp
Update party.cpp
C++
apache-2.0
RavenX8/osIROSE-new,dev-osrose/osIROSE-new,dev-osrose/osIROSE-new,RavenX8/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new
7fb0d1c5c7208084890e9bffe6c85b187bf1b483
mower.cpp
mower.cpp
#include <iostream> #include <QNetworkRequest> #include "mower.h" Mower::Mower(QNetworkAccessManager* net, std::string username, std::string password) : _net(net), _username(username), _password(password) { } Mower::State Mower::getState() { return _state; } void Mower::getStatus() { _state = GettingStatus; QNetworkRequest req(QUrl("https://auth.lawn.gatech.edu/login_status.php")); _net->get(req); } Mower::Status Mower::strToStatus(std::string s) { s = s.substr(0, s.find(',')); if (s == "logged_in") { return Mower::LoggedIn; } else if (s == "not_authenticated") { return Mower::LoggedOut; } else if (s == "pending_login") { return Mower::PendingLogIn; } else if (s == "pending_logout") { return Mower::PendingLogOut; } else if (s == "not_on_LAWN") { return Mower::NotOnLAWN; } std::cerr << "LAWN ERROR: " << s; return Mower::Error; } void Mower::login() { _state = LoggingIn; QNetworkRequest req(QUrl("https://auth.lawn.gatech.edu/index.php")); QByteArray data("output=text&username="); data += QUrl::toPercentEncoding(_username.c_str()); data += QString("&password="); data += QUrl::toPercentEncoding(_password.c_str()); _net->post(req, data); } void Mower::logout() { _state = LoggingOut; QNetworkRequest req(QUrl("https://auth.lawn.gatech.edu/index.php")); QByteArray data("output=text&username="); data += QUrl::toPercentEncoding(_username.c_str()); data += QString("&password="); data += QUrl::toPercentEncoding(_password.c_str()); _net->post(req, data); }
#include <iostream> #include <QNetworkRequest> #include "mower.h" Mower::Mower(QNetworkAccessManager* net, std::string username, std::string password) : _net(net), _username(username), _password(password) { } Mower::State Mower::getState() { return _state; } void Mower::getStatus() { _state = GettingStatus; QNetworkRequest req(QUrl("https://auth.lawn.gatech.edu/login_status.php")); _net->get(req); } Mower::Status Mower::strToStatus(std::string s) { s = s.substr(0, s.find(',')); if (s == "logged_in") { return Mower::LoggedIn; } else if (s == "not_authenticated") { return Mower::LoggedOut; } else if (s == "pending_login") { return Mower::PendingLogIn; } else if (s == "pending_logout") { return Mower::PendingLogOut; } else if (s == "not_on_LAWN") { return Mower::NotOnLAWN; } std::cerr << "LAWN ERROR: " << s; return Mower::Error; } void Mower::login() { _state = LoggingIn; QNetworkRequest req(QUrl("https://auth.lawn.gatech.edu/index.php")); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QByteArray data("output=text&username="); data += QUrl::toPercentEncoding(_username.c_str()); data += QString("&password="); data += QUrl::toPercentEncoding(_password.c_str()); _net->post(req, data); } void Mower::logout() { _state = LoggingOut; QNetworkRequest req(QUrl("https://auth.lawn.gatech.edu/index.php")); QByteArray data("output=text&username="); data += QUrl::toPercentEncoding(_username.c_str()); data += QString("&password="); data += QUrl::toPercentEncoding(_password.c_str()); _net->post(req, data); }
Fix for Qt 4.8, set a Content-Type
Fix for Qt 4.8, set a Content-Type
C++
bsd-3-clause
thelastnode/LAWNMower
79d9718d643cc72940e95d61598173e77cc666ed
src/common/str_list.cc
src/common/str_list.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2009-2010 Dreamhost * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <list> #include <set> using std::string; static bool get_next_token(const std::string &s, size_t& pos, string& token) { int start = s.find_first_not_of(" \t", pos); int end; if (start < 0) return false; if (s[start]== ',') end = start + 1; else end = s.find_first_of(";,= \t", start+1); if (end < 0) end = s.size(); token = s.substr(start, end - start); pos = end; return true; } bool get_str_list(const std::string& str, std::list<string>& str_list) { size_t pos = 0; string token; str_list.clear(); while (pos < str.size()) { if (get_next_token(str, pos, token)) { if (token.compare(",") != 0 && token.size() > 0) { str_list.push_back(token); } } } return true; } bool get_str_set(const std::string& str, std::set<std::string>& str_set) { size_t pos = 0; string token; str_set.clear(); while (pos < str.size()) { if (get_next_token(str, pos, token)) { if (token.compare(",") != 0 && token.size() > 0) { str_set.insert(token); } } } return true; }
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2009-2010 Dreamhost * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include <list> #include <set> using std::string; static bool get_next_token(const std::string &s, size_t& pos, string& token) { int start = s.find_first_not_of(" \t", pos); int end; if (start < 0) return false; if (s[start] == ',') { end = start + 1; pos = end; } else { end = s.find_first_of(";,= \t", start+1); if (end >= 0) pos = end + 1; } if (end < 0) { end = s.size(); pos = end; } token = s.substr(start, end - start); return true; } bool get_str_list(const std::string& str, std::list<string>& str_list) { size_t pos = 0; string token; str_list.clear(); while (pos < str.size()) { if (get_next_token(str, pos, token)) { if (token.size() > 0) { str_list.push_back(token); } } } return true; } bool get_str_set(const std::string& str, std::set<std::string>& str_set) { size_t pos = 0; string token; str_set.clear(); while (pos < str.size()) { if (get_next_token(str, pos, token)) { if (token.size() > 0) { str_set.insert(token); } } } return true; }
make get_str_list work with other delimiters, and skip the
common: make get_str_list work with other delimiters, and skip the Signed-off-by: Sage Weil <[email protected]>
C++
lgpl-2.1
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
2e0cf57804ab803a0af6059c8f74926d10af505b
src/messages.cc
src/messages.cc
// Copyright 2011 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/api.h" #include "src/execution.h" #include "src/heap/spaces-inl.h" #include "src/messages.h" #include "src/string-builder.h" namespace v8 { namespace internal { // If no message listeners have been registered this one is called // by default. void MessageHandler::DefaultMessageReport(Isolate* isolate, const MessageLocation* loc, Handle<Object> message_obj) { SmartArrayPointer<char> str = GetLocalizedMessage(isolate, message_obj); if (loc == NULL) { PrintF("%s\n", str.get()); } else { HandleScope scope(isolate); Handle<Object> data(loc->script()->name(), isolate); SmartArrayPointer<char> data_str; if (data->IsString()) data_str = Handle<String>::cast(data)->ToCString(DISALLOW_NULLS); PrintF("%s:%i: %s\n", data_str.get() ? data_str.get() : "<unknown>", loc->start_pos(), str.get()); } } Handle<JSMessageObject> MessageHandler::MakeMessageObject( Isolate* isolate, const char* type, MessageLocation* loc, Vector< Handle<Object> > args, Handle<JSArray> stack_frames) { Factory* factory = isolate->factory(); Handle<String> type_handle = factory->InternalizeUtf8String(type); Handle<FixedArray> arguments_elements = factory->NewFixedArray(args.length()); for (int i = 0; i < args.length(); i++) { arguments_elements->set(i, *args[i]); } Handle<JSArray> arguments_handle = factory->NewJSArrayWithElements(arguments_elements); int start = 0; int end = 0; Handle<Object> script_handle = factory->undefined_value(); if (loc) { start = loc->start_pos(); end = loc->end_pos(); script_handle = Script::GetWrapper(loc->script()); } Handle<Object> stack_frames_handle = stack_frames.is_null() ? Handle<Object>::cast(factory->undefined_value()) : Handle<Object>::cast(stack_frames); Handle<JSMessageObject> message = factory->NewJSMessageObject(type_handle, arguments_handle, start, end, script_handle, stack_frames_handle); return message; } void MessageHandler::ReportMessage(Isolate* isolate, MessageLocation* loc, Handle<Object> message) { // We are calling into embedder's code which can throw exceptions. // Thus we need to save current exception state, reset it to the clean one // and ignore scheduled exceptions callbacks can throw. // We pass the exception object into the message handler callback though. Object* exception_object = isolate->heap()->undefined_value(); if (isolate->has_pending_exception()) { exception_object = isolate->pending_exception(); } Handle<Object> exception_handle(exception_object, isolate); Isolate::ExceptionScope exception_scope(isolate); isolate->clear_pending_exception(); isolate->set_external_caught_exception(false); v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message); v8::Local<v8::Value> api_exception_obj = v8::Utils::ToLocal(exception_handle); v8::NeanderArray global_listeners(isolate->factory()->message_listeners()); int global_length = global_listeners.length(); if (global_length == 0) { DefaultMessageReport(isolate, loc, message); if (isolate->has_scheduled_exception()) { isolate->clear_scheduled_exception(); } } else { for (int i = 0; i < global_length; i++) { HandleScope scope(isolate); if (global_listeners.get(i)->IsUndefined()) continue; v8::NeanderObject listener(JSObject::cast(global_listeners.get(i))); Handle<Foreign> callback_obj(Foreign::cast(listener.get(0))); v8::MessageCallback callback = FUNCTION_CAST<v8::MessageCallback>(callback_obj->foreign_address()); Handle<Object> callback_data(listener.get(1), isolate); { // Do not allow exceptions to propagate. v8::TryCatch try_catch; callback(api_message_obj, callback_data->IsUndefined() ? api_exception_obj : v8::Utils::ToLocal(callback_data)); } if (isolate->has_scheduled_exception()) { isolate->clear_scheduled_exception(); } } } } Handle<String> MessageHandler::GetMessage(Isolate* isolate, Handle<Object> data) { Factory* factory = isolate->factory(); Handle<String> fmt_str = factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("FormatMessage")); Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty( isolate->js_builtins_object(), fmt_str).ToHandleChecked()); Handle<JSMessageObject> message = Handle<JSMessageObject>::cast(data); Handle<Object> argv[] = { Handle<Object>(message->type(), isolate), Handle<Object>(message->arguments(), isolate) }; MaybeHandle<Object> maybe_result = Execution::TryCall( fun, isolate->js_builtins_object(), arraysize(argv), argv); Handle<Object> result; if (!maybe_result.ToHandle(&result) || !result->IsString()) { return factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("<error>")); } Handle<String> result_string = Handle<String>::cast(result); // A string that has been obtained from JS code in this way is // likely to be a complicated ConsString of some sort. We flatten it // here to improve the efficiency of converting it to a C string and // other operations that are likely to take place (see GetLocalizedMessage // for example). result_string = String::Flatten(result_string); return result_string; } SmartArrayPointer<char> MessageHandler::GetLocalizedMessage( Isolate* isolate, Handle<Object> data) { HandleScope scope(isolate); return GetMessage(isolate, data)->ToCString(DISALLOW_NULLS); } MaybeHandle<String> MessageTemplate::FormatMessage(int template_index, Handle<String> arg0, Handle<String> arg1, Handle<String> arg2) { const char* template_string; switch (template_index) { #define CASE(NAME, STRING) \ case k##NAME: \ template_string = STRING; \ break; MESSAGE_TEMPLATES(CASE) #undef CASE case kLastMessage: default: UNREACHABLE(); template_string = ""; break; } Isolate* isolate = arg0->GetIsolate(); IncrementalStringBuilder builder(isolate); int i = 0; Handle<String> args[] = {arg0, arg1, arg2}; for (const char* c = template_string; *c != '\0'; c++) { if (*c == '%') { builder.AppendString(args[i++]); DCHECK(i < arraysize(args)); } else { builder.AppendCharacter(*c); } } return builder.Finish(); } } } // namespace v8::internal
// Copyright 2011 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/api.h" #include "src/execution.h" #include "src/heap/spaces-inl.h" #include "src/messages.h" #include "src/string-builder.h" namespace v8 { namespace internal { // If no message listeners have been registered this one is called // by default. void MessageHandler::DefaultMessageReport(Isolate* isolate, const MessageLocation* loc, Handle<Object> message_obj) { SmartArrayPointer<char> str = GetLocalizedMessage(isolate, message_obj); if (loc == NULL) { PrintF("%s\n", str.get()); } else { HandleScope scope(isolate); Handle<Object> data(loc->script()->name(), isolate); SmartArrayPointer<char> data_str; if (data->IsString()) data_str = Handle<String>::cast(data)->ToCString(DISALLOW_NULLS); PrintF("%s:%i: %s\n", data_str.get() ? data_str.get() : "<unknown>", loc->start_pos(), str.get()); } } Handle<JSMessageObject> MessageHandler::MakeMessageObject( Isolate* isolate, const char* type, MessageLocation* loc, Vector< Handle<Object> > args, Handle<JSArray> stack_frames) { Factory* factory = isolate->factory(); Handle<String> type_handle = factory->InternalizeUtf8String(type); Handle<FixedArray> arguments_elements = factory->NewFixedArray(args.length()); for (int i = 0; i < args.length(); i++) { arguments_elements->set(i, *args[i]); } Handle<JSArray> arguments_handle = factory->NewJSArrayWithElements(arguments_elements); int start = 0; int end = 0; Handle<Object> script_handle = factory->undefined_value(); if (loc) { start = loc->start_pos(); end = loc->end_pos(); script_handle = Script::GetWrapper(loc->script()); } Handle<Object> stack_frames_handle = stack_frames.is_null() ? Handle<Object>::cast(factory->undefined_value()) : Handle<Object>::cast(stack_frames); Handle<JSMessageObject> message = factory->NewJSMessageObject(type_handle, arguments_handle, start, end, script_handle, stack_frames_handle); return message; } void MessageHandler::ReportMessage(Isolate* isolate, MessageLocation* loc, Handle<Object> message) { // We are calling into embedder's code which can throw exceptions. // Thus we need to save current exception state, reset it to the clean one // and ignore scheduled exceptions callbacks can throw. // We pass the exception object into the message handler callback though. Object* exception_object = isolate->heap()->undefined_value(); if (isolate->has_pending_exception()) { exception_object = isolate->pending_exception(); } Handle<Object> exception_handle(exception_object, isolate); Isolate::ExceptionScope exception_scope(isolate); isolate->clear_pending_exception(); isolate->set_external_caught_exception(false); v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message); v8::Local<v8::Value> api_exception_obj = v8::Utils::ToLocal(exception_handle); v8::NeanderArray global_listeners(isolate->factory()->message_listeners()); int global_length = global_listeners.length(); if (global_length == 0) { DefaultMessageReport(isolate, loc, message); if (isolate->has_scheduled_exception()) { isolate->clear_scheduled_exception(); } } else { for (int i = 0; i < global_length; i++) { HandleScope scope(isolate); if (global_listeners.get(i)->IsUndefined()) continue; v8::NeanderObject listener(JSObject::cast(global_listeners.get(i))); Handle<Foreign> callback_obj(Foreign::cast(listener.get(0))); v8::MessageCallback callback = FUNCTION_CAST<v8::MessageCallback>(callback_obj->foreign_address()); Handle<Object> callback_data(listener.get(1), isolate); { // Do not allow exceptions to propagate. v8::TryCatch try_catch; callback(api_message_obj, callback_data->IsUndefined() ? api_exception_obj : v8::Utils::ToLocal(callback_data)); } if (isolate->has_scheduled_exception()) { isolate->clear_scheduled_exception(); } } } } Handle<String> MessageHandler::GetMessage(Isolate* isolate, Handle<Object> data) { Factory* factory = isolate->factory(); Handle<String> fmt_str = factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("FormatMessage")); Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty( isolate->js_builtins_object(), fmt_str).ToHandleChecked()); Handle<JSMessageObject> message = Handle<JSMessageObject>::cast(data); Handle<Object> argv[] = { Handle<Object>(message->type(), isolate), Handle<Object>(message->arguments(), isolate) }; MaybeHandle<Object> maybe_result = Execution::TryCall( fun, isolate->js_builtins_object(), arraysize(argv), argv); Handle<Object> result; if (!maybe_result.ToHandle(&result) || !result->IsString()) { return factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("<error>")); } Handle<String> result_string = Handle<String>::cast(result); // A string that has been obtained from JS code in this way is // likely to be a complicated ConsString of some sort. We flatten it // here to improve the efficiency of converting it to a C string and // other operations that are likely to take place (see GetLocalizedMessage // for example). result_string = String::Flatten(result_string); return result_string; } SmartArrayPointer<char> MessageHandler::GetLocalizedMessage( Isolate* isolate, Handle<Object> data) { HandleScope scope(isolate); return GetMessage(isolate, data)->ToCString(DISALLOW_NULLS); } MaybeHandle<String> MessageTemplate::FormatMessage(int template_index, Handle<String> arg0, Handle<String> arg1, Handle<String> arg2) { const char* template_string; switch (template_index) { #define CASE(NAME, STRING) \ case k##NAME: \ template_string = STRING; \ break; MESSAGE_TEMPLATES(CASE) #undef CASE case kLastMessage: default: UNREACHABLE(); template_string = ""; break; } Isolate* isolate = arg0->GetIsolate(); IncrementalStringBuilder builder(isolate); unsigned int i = 0; Handle<String> args[] = {arg0, arg1, arg2}; for (const char* c = template_string; *c != '\0'; c++) { if (*c == '%') { builder.AppendString(args[i++]); DCHECK(i < arraysize(args)); } else { builder.AppendCharacter(*c); } } return builder.Finish(); } } } // namespace v8::internal
Fix signed/unsigned compare in messages.cc
Fix signed/unsigned compare in messages.cc [email protected] NOTREECHECKS=true NOTRY=true Review URL: https://codereview.chromium.org/1089363002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#27865}
C++
mit
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
5ccb6cf086f580725145e438e6444fe2c84cc5fa
sources/instance/instance.cpp
sources/instance/instance.cpp
/* * Covariant Script Instance * * Licensed under the Covariant Innovation General Public License, * Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://covariant.cn/licenses/LICENSE-1.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2019 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee */ #include <covscript/covscript.hpp> #include <fcntl.h> #include <stdio.h> #if defined(_WIN32) || defined(WIN32) #include <io.h> #else #include <unistd.h> #endif #if defined(__APPLE__) || defined(__MACH__) #include <mach-o/loader.h> #endif namespace cs { const std::string &statement_base::get_file_path() const noexcept { return context->file_path; } const std::string &statement_base::get_package_name() const noexcept { return context->package_name; } const std::string &statement_base::get_raw_code() const noexcept { return context->file_buff.at(line_num - 1); } namespace_t instance_type::source_import(const std::string &path) { int fd = open(path.c_str(), O_RDONLY); if (fd < 0) { throw fatal_error("Failed to open file."); } #if defined(_WIN32) || defined(WIN32) char header[2] = {0}; #elif defined(__APPLE__) || defined(__MACH__) uint32_t header; #elif defined(linux) || defined(__linux) || defined(__linux__) char header[4] = {0}; #endif int nread = read(fd, reinterpret_cast<void*>(&header), sizeof(header)); close(fd); if (nread < 0) { throw fatal_error("Failed to read file header."); } #if defined(_WIN32) || defined(WIN32) if (header[0] == 'M' && header[1] == 'Z') { #elif defined(__APPLE__) || defined(__MACH__) if (header == MH_MAGIC || header == MH_CIGAM || header == MH_MAGIC_64 || header == MH_CIGAM_64) { #elif defined(linux) || defined(__linux) || defined(__linux__) if (header[0] == 0x7f && header[1] == 'E' && header[2] == 'L' && header[3] == 'F') { #endif // is extension file return std::make_shared<extension>(path); } else { // is package file context_t rt = create_subcontext(context); rt->compiler->swap_context(rt); try { rt->instance->compile(path); } catch (...) { context->compiler->swap_context(context); throw; } context->compiler->swap_context(context); rt->instance->interpret(); if (rt->package_name.empty()) throw runtime_error("Target file is not a package."); return std::make_shared<name_space>(rt->instance->storage.get_global()); } } namespace_t instance_type::import(const std::string &path, const std::string &name) { std::vector<std::string> collection; { std::string tmp; for (auto &ch:path) { if (ch == cs::path_delimiter) { collection.push_back(tmp); tmp.clear(); } else tmp.push_back(ch); } collection.push_back(tmp); } for (auto &it:collection) { std::string package_path = it + path_separator + name; if (std::ifstream(package_path + ".csp")) { context_t rt = create_subcontext(context); rt->compiler->swap_context(rt); try { rt->instance->compile(package_path + ".csp"); } catch (...) { context->compiler->swap_context(context); throw; } context->compiler->swap_context(context); rt->instance->interpret(); if (rt->package_name.empty()) throw runtime_error("Target file is not a package."); if (rt->package_name != name) throw runtime_error("Package name is different from file name."); return std::make_shared<name_space>(rt->instance->storage.get_global()); } else if (std::ifstream(package_path + ".cse")) return std::make_shared<extension>(package_path + ".cse"); } throw fatal_error("No such file or directory."); } void instance_type::compile(const std::string &path) { context->file_path = path; // Read from file std::deque<char> buff; std::ifstream in(path); if (!in.is_open()) throw fatal_error(path + ": No such file or directory"); for (int ch = in.get(); ch != std::char_traits<char>::eof(); ch = in.get()) buff.push_back(ch); std::deque<std::deque<token_base *>> ast; // Compile context->compiler->clear_metadata(); context->compiler->build_ast(buff, ast); context->compiler->code_gen(ast, statements); context->compiler->utilize_metadata(); } void instance_type::interpret() { // Run the instruction for (auto &ptr:statements) { try { ptr->run(); } catch (const lang_error &le) { throw fatal_error(std::string("Uncaught exception: ") + le.what()); } catch (const cs::exception &e) { throw e; } catch (const std::exception &e) { throw exception(ptr->get_line_num(), ptr->get_file_path(), ptr->get_raw_code(), e.what()); } } } void instance_type::dump_ast(std::ostream &stream) { stream << "< Covariant Script AST Dump >\n< BeginMetaData >\n< Version: " << current_process->version << " >\n< Standard Version: " << current_process->std_version << " >\n< Import Path: \"" << current_process->import_path << "\" >\n"; #ifdef COVSCRIPT_PLATFORM_WIN32 stream << "< Platform: Win32 >\n"; #else stream << "< Platform: Unix >\n"; #endif stream << "< EndMetaData >\n"; for (auto &ptr:statements) ptr->dump(stream); stream << std::flush; } void repl::run(const string &code) { if (code.empty()) return; std::deque<char> buff; for (auto &ch:code) buff.push_back(ch); statement_base *statement = nullptr; try { std::deque<token_base *> line; context->compiler->clear_metadata(); context->compiler->build_line(buff, line); method_base *m = context->compiler->match_method(line); switch (m->get_type()) { case method_types::null: throw runtime_error("Null type of grammar."); break; case method_types::single: { if (level > 0) { if (m->get_target_type() == statement_types::end_) { context->instance->storage.remove_set(); context->instance->storage.remove_domain(); --level; } if (level == 0) { if (m->get_target_type() == statement_types::end_) statement = static_cast<method_end *>(m)->translate_end(method, context, tmp, line); else statement = method->translate(context, tmp); tmp.clear(); method = nullptr; } else { m->preprocess(context, {line}); tmp.push_back(line); } } else { if (m->get_target_type() == statement_types::end_) throw runtime_error("Hanging end statement."); else { m->preprocess(context, {line}); statement = m->translate(context, {line}); } } } break; case method_types::block: { if (level == 0) method = m; ++level; context->instance->storage.add_domain(); context->instance->storage.add_set(); m->preprocess(context, {line}); tmp.push_back(line); } break; case method_types::jit_command: m->translate(context, {line}); break; } if (statement != nullptr) statement->repl_run(); } catch (const lang_error &le) { reset_status(); throw fatal_error(std::string("Uncaught exception: ") + le.what()); } catch (const cs::exception &e) { reset_status(); throw e; } catch (const std::exception &e) { reset_status(); throw exception(line_num, context->file_path, code, e.what()); } context->compiler->utilize_metadata(); } void repl::exec(const string &code) { // Preprocess ++line_num; int mode = 0; for (auto &ch:code) { if (mode == 0) { if (!std::isspace(ch)) { switch (ch) { case '#': context->file_buff.emplace_back(); return; case '@': mode = 1; break; default: mode = -1; } } } else if (mode == 1) { if (!std::isspace(ch)) cmd_buff.push_back(ch); } else break; } switch (mode) { default: break; case 0: return; case 1: if (cmd_buff == "begin" && !multi_line) { multi_line = true; context->file_buff.emplace_back(); } else if (cmd_buff == "end" && multi_line) { multi_line = false; this->run(line_buff); line_buff.clear(); } else throw exception(line_num, context->file_path, cmd_buff, "Wrong grammar for preprocessor command."); cmd_buff.clear(); return; } if (multi_line) { context->file_buff.emplace_back(); line_buff.append(code); } else { context->file_buff.push_back(code); this->run(code); } } }
/* * Covariant Script Instance * * Licensed under the Covariant Innovation General Public License, * Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://covariant.cn/licenses/LICENSE-1.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2019 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee */ #include <covscript/covscript.hpp> #include <fcntl.h> #include <stdio.h> #if defined(_WIN32) || defined(WIN32) #include <io.h> #else #include <unistd.h> #endif #if defined(__APPLE__) || defined(__MACH__) #include <mach-o/loader.h> #endif namespace cs { const std::string &statement_base::get_file_path() const noexcept { return context->file_path; } const std::string &statement_base::get_package_name() const noexcept { return context->package_name; } const std::string &statement_base::get_raw_code() const noexcept { return context->file_buff.at(line_num - 1); } namespace_t instance_type::source_import(const std::string &path) { int fd = open(path.c_str(), O_RDONLY); if (fd < 0) { throw fatal_error("Failed to open file."); } #if defined(_WIN32) || defined(WIN32) char header[2] = {0}; #elif defined(__APPLE__) || defined(__MACH__) uint32_t header; #elif defined(linux) || defined(__linux) || defined(__linux__) char header[4] = {0}; #endif int nread = read(fd, reinterpret_cast<void*>(&header), sizeof(header)); close(fd); if (nread < 0) { throw fatal_error("Failed to read file header."); } #if defined(_WIN32) || defined(WIN32) if (header[0] == 'M' && header[1] == 'Z') { #elif defined(__APPLE__) || defined(__MACH__) if (header == MH_MAGIC || header == MH_CIGAM || header == MH_MAGIC_64 || header == MH_CIGAM_64) { #elif defined(linux) || defined(__linux) || defined(__linux__) if (header[0] == 0x7f && header[1] == 'E' && header[2] == 'L' && header[3] == 'F') { #endif // is extension file return std::make_shared<extension>(path); } else { // is package file context_t rt = create_subcontext(context); rt->compiler->swap_context(rt); try { rt->instance->compile(path); } catch (...) { context->compiler->swap_context(context); throw; } context->compiler->swap_context(context); rt->instance->interpret(); return std::make_shared<name_space>(rt->instance->storage.get_global()); } } namespace_t instance_type::import(const std::string &path, const std::string &name) { std::vector<std::string> collection; { std::string tmp; for (auto &ch:path) { if (ch == cs::path_delimiter) { collection.push_back(tmp); tmp.clear(); } else tmp.push_back(ch); } collection.push_back(tmp); } for (auto &it:collection) { std::string package_path = it + path_separator + name; if (std::ifstream(package_path + ".csp")) { context_t rt = create_subcontext(context); rt->compiler->swap_context(rt); try { rt->instance->compile(package_path + ".csp"); } catch (...) { context->compiler->swap_context(context); throw; } context->compiler->swap_context(context); rt->instance->interpret(); if (rt->package_name.empty()) throw runtime_error("Target file is not a package."); if (rt->package_name != name) throw runtime_error("Package name is different from file name."); return std::make_shared<name_space>(rt->instance->storage.get_global()); } else if (std::ifstream(package_path + ".cse")) return std::make_shared<extension>(package_path + ".cse"); } throw fatal_error("No such file or directory."); } void instance_type::compile(const std::string &path) { context->file_path = path; // Read from file std::deque<char> buff; std::ifstream in(path); if (!in.is_open()) throw fatal_error(path + ": No such file or directory"); for (int ch = in.get(); ch != std::char_traits<char>::eof(); ch = in.get()) buff.push_back(ch); std::deque<std::deque<token_base *>> ast; // Compile context->compiler->clear_metadata(); context->compiler->build_ast(buff, ast); context->compiler->code_gen(ast, statements); context->compiler->utilize_metadata(); } void instance_type::interpret() { // Run the instruction for (auto &ptr:statements) { try { ptr->run(); } catch (const lang_error &le) { throw fatal_error(std::string("Uncaught exception: ") + le.what()); } catch (const cs::exception &e) { throw e; } catch (const std::exception &e) { throw exception(ptr->get_line_num(), ptr->get_file_path(), ptr->get_raw_code(), e.what()); } } } void instance_type::dump_ast(std::ostream &stream) { stream << "< Covariant Script AST Dump >\n< BeginMetaData >\n< Version: " << current_process->version << " >\n< Standard Version: " << current_process->std_version << " >\n< Import Path: \"" << current_process->import_path << "\" >\n"; #ifdef COVSCRIPT_PLATFORM_WIN32 stream << "< Platform: Win32 >\n"; #else stream << "< Platform: Unix >\n"; #endif stream << "< EndMetaData >\n"; for (auto &ptr:statements) ptr->dump(stream); stream << std::flush; } void repl::run(const string &code) { if (code.empty()) return; std::deque<char> buff; for (auto &ch:code) buff.push_back(ch); statement_base *statement = nullptr; try { std::deque<token_base *> line; context->compiler->clear_metadata(); context->compiler->build_line(buff, line); method_base *m = context->compiler->match_method(line); switch (m->get_type()) { case method_types::null: throw runtime_error("Null type of grammar."); break; case method_types::single: { if (level > 0) { if (m->get_target_type() == statement_types::end_) { context->instance->storage.remove_set(); context->instance->storage.remove_domain(); --level; } if (level == 0) { if (m->get_target_type() == statement_types::end_) statement = static_cast<method_end *>(m)->translate_end(method, context, tmp, line); else statement = method->translate(context, tmp); tmp.clear(); method = nullptr; } else { m->preprocess(context, {line}); tmp.push_back(line); } } else { if (m->get_target_type() == statement_types::end_) throw runtime_error("Hanging end statement."); else { m->preprocess(context, {line}); statement = m->translate(context, {line}); } } } break; case method_types::block: { if (level == 0) method = m; ++level; context->instance->storage.add_domain(); context->instance->storage.add_set(); m->preprocess(context, {line}); tmp.push_back(line); } break; case method_types::jit_command: m->translate(context, {line}); break; } if (statement != nullptr) statement->repl_run(); } catch (const lang_error &le) { reset_status(); throw fatal_error(std::string("Uncaught exception: ") + le.what()); } catch (const cs::exception &e) { reset_status(); throw e; } catch (const std::exception &e) { reset_status(); throw exception(line_num, context->file_path, code, e.what()); } context->compiler->utilize_metadata(); } void repl::exec(const string &code) { // Preprocess ++line_num; int mode = 0; for (auto &ch:code) { if (mode == 0) { if (!std::isspace(ch)) { switch (ch) { case '#': context->file_buff.emplace_back(); return; case '@': mode = 1; break; default: mode = -1; } } } else if (mode == 1) { if (!std::isspace(ch)) cmd_buff.push_back(ch); } else break; } switch (mode) { default: break; case 0: return; case 1: if (cmd_buff == "begin" && !multi_line) { multi_line = true; context->file_buff.emplace_back(); } else if (cmd_buff == "end" && multi_line) { multi_line = false; this->run(line_buff); line_buff.clear(); } else throw exception(line_num, context->file_path, cmd_buff, "Wrong grammar for preprocessor command."); cmd_buff.clear(); return; } if (multi_line) { context->file_buff.emplace_back(); line_buff.append(code); } else { context->file_buff.push_back(code); this->run(code); } } }
remove package check in source_import
instance: remove package check in source_import
C++
apache-2.0
covscript/covscript,covscript/covscript,covscript/covscript
5e83b0227f024c63fd1adb7995d17a8a1604b10c
src/nix/main.cc
src/nix/main.cc
#include <algorithm> #include "command.hh" #include "common-args.hh" #include "eval.hh" #include "globals.hh" #include "legacy.hh" #include "shared.hh" #include "store-api.hh" #include "progress-bar.hh" #include "finally.hh" extern std::string chrootHelperName; void chrootHelper(int argc, char * * argv); namespace nix { std::string programPath; struct NixArgs : virtual MultiCommand, virtual MixCommonArgs { NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix") { mkFlag() .longName("help") .shortName('h') .description("show usage information") .handler([&]() { showHelpAndExit(); }); mkFlag() .longName("help-config") .description("show configuration options") .handler([&]() { std::cout << "The following configuration options are available:\n\n"; Table2 tbl; std::map<std::string, Config::SettingInfo> settings; globalConfig.getSettings(settings); for (const auto & s : settings) tbl.emplace_back(s.first, s.second.description); printTable(std::cout, tbl); throw Exit(); }); mkFlag() .longName("version") .description("show version information") .handler([&]() { printVersion(programName); }); } void printFlags(std::ostream & out) override { Args::printFlags(out); std::cout << "\n" "In addition, most configuration settings can be overriden using '--<name> <value>'.\n" "Boolean settings can be overriden using '--<name>' or '--no-<name>'. See 'nix\n" "--help-config' for a list of configuration settings.\n"; } void showHelpAndExit() { printHelp(programName, std::cout); std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n"; throw Exit(); } }; void mainWrapped(int argc, char * * argv) { verbosity = lvlError; settings.verboseBuild = false; /* The chroot helper needs to be run before any threads have been started. */ if (argc > 0 && argv[0] == chrootHelperName) { chrootHelper(argc, argv); return; } initNix(); initGC(); programPath = argv[0]; string programName = baseNameOf(programPath); { auto legacy = (*RegisterLegacyCommand::commands)[programName]; if (legacy) return legacy(argc, argv); } NixArgs args; args.parseCmdline(argvToStrings(argc, argv)); initPlugins(); if (!args.command) args.showHelpAndExit(); Finally f([]() { stopProgressBar(); }); if (isatty(STDERR_FILENO)) startProgressBar(); args.command->prepare(); args.command->run(); } } int main(int argc, char * * argv) { return nix::handleExceptions(argv[0], [&]() { nix::mainWrapped(argc, argv); }); }
#include <algorithm> #include "command.hh" #include "common-args.hh" #include "eval.hh" #include "globals.hh" #include "legacy.hh" #include "shared.hh" #include "store-api.hh" #include "progress-bar.hh" #include "finally.hh" extern std::string chrootHelperName; void chrootHelper(int argc, char * * argv); namespace nix { std::string programPath; struct NixArgs : virtual MultiCommand, virtual MixCommonArgs { NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix") { mkFlag() .longName("help") .description("show usage information") .handler([&]() { showHelpAndExit(); }); mkFlag() .longName("help-config") .description("show configuration options") .handler([&]() { std::cout << "The following configuration options are available:\n\n"; Table2 tbl; std::map<std::string, Config::SettingInfo> settings; globalConfig.getSettings(settings); for (const auto & s : settings) tbl.emplace_back(s.first, s.second.description); printTable(std::cout, tbl); throw Exit(); }); mkFlag() .longName("version") .description("show version information") .handler([&]() { printVersion(programName); }); } void printFlags(std::ostream & out) override { Args::printFlags(out); std::cout << "\n" "In addition, most configuration settings can be overriden using '--<name> <value>'.\n" "Boolean settings can be overriden using '--<name>' or '--no-<name>'. See 'nix\n" "--help-config' for a list of configuration settings.\n"; } void showHelpAndExit() { printHelp(programName, std::cout); std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n"; throw Exit(); } }; void mainWrapped(int argc, char * * argv) { verbosity = lvlError; settings.verboseBuild = false; /* The chroot helper needs to be run before any threads have been started. */ if (argc > 0 && argv[0] == chrootHelperName) { chrootHelper(argc, argv); return; } initNix(); initGC(); programPath = argv[0]; string programName = baseNameOf(programPath); { auto legacy = (*RegisterLegacyCommand::commands)[programName]; if (legacy) return legacy(argc, argv); } NixArgs args; args.parseCmdline(argvToStrings(argc, argv)); initPlugins(); if (!args.command) args.showHelpAndExit(); Finally f([]() { stopProgressBar(); }); if (isatty(STDERR_FILENO)) startProgressBar(); args.command->prepare(); args.command->run(); } } int main(int argc, char * * argv) { return nix::handleExceptions(argv[0], [&]() { nix::mainWrapped(argc, argv); }); }
Remove the -h flag
nix: Remove the -h flag
C++
lgpl-2.1
layus/nix,vcunat/nix,zimbatm/nix,rycee/nix,pikajude/nix,ehmry/nix,NixOS/nix,layus/nix,ehmry/nix,dtzWill/nix,NixOS/nix,rycee/nix,ehmry/nix,dtzWill/nix,vcunat/nix,rycee/nix,vcunat/nix,vcunat/nix,NixOS/nix,ehmry/nix,ehmry/nix,zimbatm/nix,dtzWill/nix,ehmry/nix,zimbatm/nix,layus/nix,rycee/nix,dtzWill/nix,NixOS/nix,layus/nix,pikajude/nix,pikajude/nix,rycee/nix,NixOS/nix,zimbatm/nix,dtzWill/nix,layus/nix
db128af83033ae1baa67f5560f39fe75912944d3
src/nyu/nyu.cpp
src/nyu/nyu.cpp
#include <nyu/cpp/builder.hpp> #include <nyu/options.hpp> #include <nyu/error/output_file.hpp> #include <nyu/error/grammar_not_found.hpp> #include <nyu/error/include_not_found.hpp> #include <chilon/print.hpp> #include <iostream> #include <stdexcept> // #define MOUSEBEAR_VERSION "1000 (just don't get in a car, and stay away from my family)" // #define MOUSEBEAR_VERSION "999 (she's also known as darwinius)" // #define MOUSEBEAR_VERSION "998 (grind machine)" // #define MOUSEBEAR_VERSION "997 (420 mishap)" // #define MOUSEBEAR_VERSION "996 (super mousebear 4)" // #define MOUSEBEAR_VERSION "995 (ibuki mousebear)" // #define MOUSEBEAR_VERSION "994 (maryam the butcher)" // #define MOUSEBEAR_VERSION "993 (friendly beard)" // #define MOUSEDEER_VERSION "992 (rose almost 3000 mousedear)" // #define MOUSEDEER_VERSION "991 (raging mousedeer)" // #define NYU_VERSION "0.1 (displacing nyu)" // #define NYU_VERSION "0.2 (sweet island)" // #define NYU_VERSION "0.3 (kuchenfest)" #define NYU_VERSION "0.4 (spesiel bee friend)" // #define NYU_VERSION "0.5 (suggested mouse name: crunchy)" namespace nyu { inline int main(int argc, char *argv[]) { options opts; char const header[] = "nyu " NYU_VERSION "\nusage: nyu [arguments] <grammar files to process>"; int nPositionals = opts.parse_command_line(header, argc, argv); if (0 == nPositionals) return 1; cpp::builder build_source(opts); try { for (int i = 1; i <= nPositionals; ++i) build_source.parse_file(argv[i]); build_source.generate_code(); if (opts.print_ast_) build_source.print_ast(); } catch (error::cannot_open_file const& e) { chilon::println(std::cerr, e.what(), ": ", e.file_path_); } catch (error::cannot_open_output_file const& e) { chilon::println(std::cerr, e.what(), ": ", e.file_path_); } catch (error::grammar_not_found const& e) { chilon::println(std::cerr, e.what(), ": ", e.id_); } catch (error::include_not_found const& e) { chilon::println(std::cerr, e.what(), ": ", e.id_); } catch (error::parsing const& e) { chilon::println(std::cerr, e.what(), ": ", e.file_path_); } catch (std::runtime_error const& e) { chilon::println(std::cerr, e.what()); return 1; } return 0; } } int main(int argc, char *argv[]) { return nyu::main(argc, argv); }
#include <nyu/cpp/builder.hpp> #include <nyu/options.hpp> #include <nyu/error/output_file.hpp> #include <nyu/error/grammar_not_found.hpp> #include <nyu/error/include_not_found.hpp> #include <chilon/print.hpp> #include <iostream> #include <stdexcept> // #define MOUSEBEAR_VERSION "1000 (just don't get in a car, and stay away from my family)" // #define MOUSEBEAR_VERSION "999 (she's also known as darwinius)" // #define MOUSEBEAR_VERSION "998 (grind machine)" // #define MOUSEBEAR_VERSION "997 (420 mishap)" // #define MOUSEBEAR_VERSION "996 (super mousebear 4)" // #define MOUSEBEAR_VERSION "995 (ibuki mousebear)" // #define MOUSEBEAR_VERSION "994 (maryam the butcher)" // #define MOUSEBEAR_VERSION "993 (friendly beard)" // #define MOUSEDEER_VERSION "992 (rose almost 3000 mousedear)" // #define MOUSEDEER_VERSION "991 (raging mousedeer)" // #define NYU_VERSION "0.1 (displacing nyu)" // #define NYU_VERSION "0.2 (sweet island)" // #define NYU_VERSION "0.3 (kuchenfest)" // #define NYU_VERSION "0.4 (spesiel bee friend)" #define NYU_VERSION "0.8 (suggested mouse name: crunchy)" namespace nyu { inline int main(int argc, char *argv[]) { options opts; char const header[] = "nyu " NYU_VERSION "\nusage: nyu [arguments] <grammar files to process>"; int nPositionals = opts.parse_command_line(header, argc, argv); if (0 == nPositionals) return 1; cpp::builder build_source(opts); try { for (int i = 1; i <= nPositionals; ++i) build_source.parse_file(argv[i]); build_source.generate_code(); if (opts.print_ast_) build_source.print_ast(); } catch (error::cannot_open_file const& e) { chilon::println(std::cerr, e.what(), ": ", e.file_path_); } catch (error::cannot_open_output_file const& e) { chilon::println(std::cerr, e.what(), ": ", e.file_path_); } catch (error::grammar_not_found const& e) { chilon::println(std::cerr, e.what(), ": ", e.id_); } catch (error::include_not_found const& e) { chilon::println(std::cerr, e.what(), ": ", e.id_); } catch (error::parsing const& e) { chilon::println(std::cerr, e.what(), ": ", e.file_path_); } catch (std::runtime_error const& e) { chilon::println(std::cerr, e.what()); return 1; } return 0; } } int main(int argc, char *argv[]) { return nyu::main(argc, argv); }
upgrade version to 0.8
upgrade version to 0.8
C++
mit
ohjames/nyu
a9a1f10bad310efa12663d4d757bca5f3e62aaab
src/pdb_file.cc
src/pdb_file.cc
#include "gmml/internal/pdb_file.h" #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include "gmml/internal/environment.h" #include "gmml/internal/geometry.h" #include "utilities.h" namespace gmml { using std::istringstream; using std::list; using std::string; using std::vector; void PdbAtomCard::write(std::ostream& out) const { string str(80, ' '); if (!is_hetatm_) { set_in_string(str, "ATOM", 0, 6, 'L'); } else { set_in_string(str, "HETATM", 0, 6, 'L'); } set_in_string(str, serial, 6, 5, 'R'); if (name.size() < 4) set_in_string(str, name, 13, 3, 'L'); else set_in_string(str, name, 12, 4, 'L'); str[16] = alt_loc; set_in_string(str, res_name, 17, 3, 'L'); str[21] = chain_id; set_in_string(str, res_seq, 22, 4, 'R'); str[26] = i_code; set_in_string(str, x, 30, 8, 'R', 3); set_in_string(str, y, 38, 8, 'R', 3); set_in_string(str, z, 46, 8, 'R', 3); if (is_set(occupancy)) set_in_string(str, occupancy, 54, 6, 'R', 2); if (is_set(temp_factor)) set_in_string(str, temp_factor, 60, 6, 'R', 2); set_in_string(str, element, 76, 2, 'R'); if (is_set(charge)) set_in_string(str, charge, 78, 2, 'R'); trim(str); out << str; } void PdbAtomCard::read(const string& line) { string input(line); if (input.size() < 80) input.resize(80, ' '); serial = convert_string<int>(input.substr(6, 5)); name = input.substr(12, 4); trim(name); alt_loc = input[16]; res_name = input.substr(17, 3); trim(res_name); chain_id = input[21]; res_seq = convert_string<int>(input.substr(22, 4)); i_code = input[26]; x = convert_string<double>(input.substr(30, 8)); y = convert_string<double>(input.substr(38, 8)); z = convert_string<double>(input.substr(46, 8)); try { occupancy = convert_string<double>(input.substr(54, 6)); } catch (const ConversionException& e) { occupancy = kNotSet; } try { temp_factor = convert_string<double>(input.substr(60, 6)); } catch (const ConversionException e) { temp_factor = kNotSet; } element = input.substr(76, 2); trim(element); if (element == "" && name.size() > 0) element = string(1, name[0]); try { charge = convert_string<double>(input.substr(78, 2)); } catch (const ConversionException& e) { charge = kNotSet; } } void PdbTerCard::write(std::ostream& out) const { out << "TER"; } void PdbConnectCard::write(std::ostream& out) const { string str(80, ' '); set_in_string(str, "CONECT", 0, 6, 'L'); if (is_set(connect1)) set_in_string(str, connect1, 6, 5, 'R'); if (is_set(connect2)) set_in_string(str, connect2, 11, 5, 'R'); if (is_set(connect3)) set_in_string(str, connect3, 16, 5, 'R'); if (is_set(connect4)) set_in_string(str, connect4, 21, 5, 'R'); if (is_set(connect5)) set_in_string(str, connect5, 26, 5, 'R'); trim(str); out << str; } void PdbConnectCard::read(const std::string& line) { string input(line); if (input.size() < 80) input.resize(80, ' '); connect1 = connect2 = connect3 = connect4 = connect5 = kNotSet; try { connect1 = convert_string<int>(input.substr(6, 5)); connect2 = convert_string<int>(input.substr(11, 5)); connect3 = convert_string<int>(input.substr(16, 5)); connect4 = convert_string<int>(input.substr(21, 5)); connect5 = convert_string<int>(input.substr(26, 5)); } catch (const ConversionException& /*e*/) { // Do nothing. If this occurs, the remaining connects will all // properly be set to kNotSet. } } void PdbEndCard::write(std::ostream& out) const { out << "END"; } void PdbLinkCard::read(const std::string& line) { string input(line); if (input.size() < 80) input.resize(80, ' '); name1 = input.substr(12, 4); trim(name1); res_name1 = input.substr(17, 3); trim(res_name1); res_seq1 = convert_string<int>(input.substr(22, 4)); name2 = input.substr(42, 4); trim(name2); res_name2 = input.substr(47, 3); trim(res_name2); res_seq2 = convert_string<int>(input.substr(52, 4)); } void PdbLinkCard::write(std::ostream& out) const { string str(80, ' '); set_in_string(str, "LINK", 0, 6, 'L'); if (name1.size() < 4) set_in_string(str, name1, 13, 3, 'L'); else set_in_string(str, name1, 12, 4, 'L'); set_in_string(str, res_name1, 17, 3, 'L'); set_in_string(str, res_seq1, 22, 4, 'L'); if (name2.size() < 4) set_in_string(str, name2, 43, 3, 'L'); else set_in_string(str, name2, 42, 4, 'L'); set_in_string(str, res_name2, 47, 3, 'L'); set_in_string(str, res_seq2, 52, 4, 'L'); trim(str); out << str; } void PdbUnknownCard::write(std::ostream& out) const { out << line; } void PdbFile::read(const string& file_name) { std::ifstream stream(find_file(file_name).c_str()); read(stream); stream.close(); } void PdbFile::print(const string& file) const { std::ofstream out; out.open(file.c_str()); write(out); out.close(); } void PdbFile::print() const { write(std::cout); } void PdbFile::read(std::istream& in) { string line; while (getline(in, line)) { lines_.push_back(line); string card_type = line.substr(0, 6); card_type.resize(6, ' '); boost::shared_ptr<PdbCard> card_ptr; switch (get_card_type(card_type)) { case ATOM: case HETATM: { boost::shared_ptr<PdbAtomCard> atom_card(new PdbAtomCard(line)); card_ptr = atom_card; atom_cards_.push_back(atom_card); break; } case TER: card_ptr.reset(new PdbTerCard(line)); break; case CONECT: { boost::shared_ptr<PdbConnectCard> connect_card( new PdbConnectCard(line) ); card_ptr = connect_card; connect_cards_.push_back(connect_card); break; } case END: card_ptr.reset(new PdbEndCard(line)); break; case LINK: card_ptr.reset(new PdbLinkCard(line)); break; default: // Ignore unknown card. card_ptr.reset(new PdbUnknownCard(line)); break; } cards_.push_back(card_ptr); } } PdbFile::CardType PdbFile::get_card_type(const string& line) { string first_six = line.substr(0, 6); first_six.resize(6, ' '); if (first_six == "ATOM " || first_six == "HETATM") return PdbFile::ATOM; else if (first_six == "TER ") return PdbFile::TER; else if (first_six == "CONECT") return PdbFile::CONECT; else if (first_six == "END ") return PdbFile::END; else if (first_six == "LINK ") return PdbFile::LINK; else return PdbFile::UNKNOWN; } void PdbFile::write(std::ostream& out) const { list<CardPtr>::const_iterator it; for (it = cards_.begin(); it != cards_.end(); ++it) { (*it)->write(out); out << std::endl; } } } //namespace gmml
#include "gmml/internal/pdb_file.h" #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include "gmml/internal/environment.h" #include "gmml/internal/geometry.h" #include "utilities.h" namespace gmml { using std::istringstream; using std::list; using std::string; using std::vector; void PdbAtomCard::write(std::ostream& out) const { string str(80, ' '); if (!is_hetatm_) { set_in_string(str, "ATOM", 0, 6, 'L'); } else { set_in_string(str, "HETATM", 0, 6, 'L'); } set_in_string(str, serial, 6, 5, 'R'); if (name.size() < 4) set_in_string(str, name, 13, 3, 'L'); else set_in_string(str, name, 12, 4, 'L'); str[16] = alt_loc; set_in_string(str, res_name, 17, 3, 'L'); str[21] = chain_id; set_in_string(str, res_seq, 22, 4, 'R'); str[26] = i_code; set_in_string(str, x, 30, 8, 'R', 3); set_in_string(str, y, 38, 8, 'R', 3); set_in_string(str, z, 46, 8, 'R', 3); if (is_set(occupancy)) set_in_string(str, occupancy, 54, 6, 'R', 2); if (is_set(temp_factor)) set_in_string(str, temp_factor, 60, 6, 'R', 2); set_in_string(str, element, 76, 2, 'R'); if (is_set(charge)) set_in_string(str, charge, 78, 2, 'R'); trim(str); out << str; } void PdbAtomCard::read(const string& line) { string input(line); if (input.size() < 80) input.resize(80, ' '); serial = convert_string<int>(input.substr(6, 5)); name = input.substr(12, 4); trim(name); alt_loc = input[16]; res_name = input.substr(17, 3); trim(res_name); chain_id = input[21]; res_seq = convert_string<int>(input.substr(22, 4)); i_code = input[26]; x = convert_string<double>(input.substr(30, 8)); y = convert_string<double>(input.substr(38, 8)); z = convert_string<double>(input.substr(46, 8)); try { occupancy = convert_string<double>(input.substr(54, 6)); } catch (const ConversionException& e) { occupancy = kNotSet; } try { temp_factor = convert_string<double>(input.substr(60, 6)); } catch (const ConversionException e) { temp_factor = kNotSet; } element = input.substr(76, 2); trim(element); if (element == "" && name.size() > 0) element = string(1, name[0]); try { charge = convert_string<double>(input.substr(78, 2)); } catch (const ConversionException& e) { charge = kNotSet; } } void PdbTerCard::write(std::ostream& out) const { out << "TER"; } void PdbConnectCard::write(std::ostream& out) const { string str(80, ' '); set_in_string(str, "CONECT", 0, 6, 'L'); if (is_set(connect1)) set_in_string(str, connect1, 6, 5, 'R'); if (is_set(connect2)) set_in_string(str, connect2, 11, 5, 'R'); if (is_set(connect3)) set_in_string(str, connect3, 16, 5, 'R'); if (is_set(connect4)) set_in_string(str, connect4, 21, 5, 'R'); if (is_set(connect5)) set_in_string(str, connect5, 26, 5, 'R'); trim(str); out << str; } void PdbConnectCard::read(const std::string& line) { string input(line); if (input.size() < 80) input.resize(80, ' '); connect1 = connect2 = connect3 = connect4 = connect5 = kNotSet; try { connect1 = convert_string<int>(input.substr(6, 5)); connect2 = convert_string<int>(input.substr(11, 5)); connect3 = convert_string<int>(input.substr(16, 5)); connect4 = convert_string<int>(input.substr(21, 5)); connect5 = convert_string<int>(input.substr(26, 5)); } catch (const ConversionException& /*e*/) { // Do nothing. If this occurs, the remaining connects will all // properly be set to kNotSet. } } void PdbEndCard::write(std::ostream& out) const { out << "END"; } void PdbLinkCard::read(const std::string& line) { string input(line); if (input.size() < 80) input.resize(80, ' '); name1 = input.substr(12, 4); trim(name1); res_name1 = input.substr(17, 3); trim(res_name1); res_seq1 = convert_string<int>(input.substr(22, 4)); name2 = input.substr(42, 4); trim(name2); res_name2 = input.substr(47, 3); trim(res_name2); res_seq2 = convert_string<int>(input.substr(52, 4)); } void PdbLinkCard::write(std::ostream& out) const { string str(80, ' '); set_in_string(str, "LINK", 0, 6, 'L'); if (name1.size() < 4) set_in_string(str, name1, 13, 3, 'L'); else set_in_string(str, name1, 12, 4, 'L'); set_in_string(str, res_name1, 17, 3, 'L'); set_in_string(str, res_seq1, 22, 4, 'R'); if (name2.size() < 4) set_in_string(str, name2, 43, 3, 'L'); else set_in_string(str, name2, 42, 4, 'L'); set_in_string(str, res_name2, 47, 3, 'L'); set_in_string(str, res_seq2, 52, 4, 'R'); trim(str); out << str; } void PdbUnknownCard::write(std::ostream& out) const { out << line; } void PdbFile::read(const string& file_name) { std::ifstream stream(find_file(file_name).c_str()); read(stream); stream.close(); } void PdbFile::print(const string& file) const { std::ofstream out; out.open(file.c_str()); write(out); out.close(); } void PdbFile::print() const { write(std::cout); } void PdbFile::read(std::istream& in) { string line; while (getline(in, line)) { lines_.push_back(line); string card_type = line.substr(0, 6); card_type.resize(6, ' '); boost::shared_ptr<PdbCard> card_ptr; switch (get_card_type(card_type)) { case ATOM: case HETATM: { boost::shared_ptr<PdbAtomCard> atom_card(new PdbAtomCard(line)); card_ptr = atom_card; atom_cards_.push_back(atom_card); break; } case TER: card_ptr.reset(new PdbTerCard(line)); break; case CONECT: { boost::shared_ptr<PdbConnectCard> connect_card( new PdbConnectCard(line) ); card_ptr = connect_card; connect_cards_.push_back(connect_card); break; } case END: card_ptr.reset(new PdbEndCard(line)); break; case LINK: card_ptr.reset(new PdbLinkCard(line)); break; default: // Ignore unknown card. card_ptr.reset(new PdbUnknownCard(line)); break; } cards_.push_back(card_ptr); } } PdbFile::CardType PdbFile::get_card_type(const string& line) { string first_six = line.substr(0, 6); first_six.resize(6, ' '); if (first_six == "ATOM " || first_six == "HETATM") return PdbFile::ATOM; else if (first_six == "TER ") return PdbFile::TER; else if (first_six == "CONECT") return PdbFile::CONECT; else if (first_six == "END ") return PdbFile::END; else if (first_six == "LINK ") return PdbFile::LINK; else return PdbFile::UNKNOWN; } void PdbFile::write(std::ostream& out) const { list<CardPtr>::const_iterator it; for (it = cards_.begin(); it != cards_.end(); ++it) { (*it)->write(out); out << std::endl; } } } //namespace gmml
Fix link card alignment.
Fix link card alignment.
C++
mit
rtdavis22/GMML,tectronics/gmml,tectronics/gmml,rtdavis22/GMML,tectronics/gmml,tectronics/gmml,rtdavis22/GMML
1e6ae7d2e48f30f57428edc7e3ae704f8e464548
gameserver/gameengine/src/world_factory.cc
gameserver/gameengine/src/world_factory.cc
/** * The MIT License (MIT) * * Copyright (c) 2018 Simon Sandström * * 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 "world_factory.h" #include <cstring> #include <fstream> #include <sstream> #include <utility> #include <vector> #include "logger.h" #include "world_loader.h" #include "item_manager.h" #include "item.h" #include "tile.h" #include "world.h" namespace gameengine { // TODO(simon): is this file/class/function even necessary now? std::unique_ptr<world::World> WorldFactory::createWorld(const std::string& world_filename, ItemManager* item_manager) { const auto create_item = [&item_manager](world::ItemTypeId item_type_id) { return item_manager->createItem(item_type_id); }; const auto get_item = [&item_manager](world::ItemUniqueId item_unique_id) { return item_manager->getItem(item_unique_id); }; auto world_data = io::world_loader::load(world_filename, create_item, get_item); if (world_data.tiles.empty()) { // io::world_loader::load should log error return {}; } LOG_INFO("World loaded, size: %d x %d", world_data.world_size_x, world_data.world_size_y); return std::make_unique<world::World>(world_data.world_size_x, world_data.world_size_y, std::move(world_data.tiles)); // NOLINT bug in clang-tidy used in Travis (?) } } // namespace gameengine
/** * The MIT License (MIT) * * Copyright (c) 2018 Simon Sandström * * 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 "world_factory.h" #include <cstring> #include <fstream> #include <sstream> #include <utility> #include <vector> #include "logger.h" #include "world_loader.h" #include "item_manager.h" #include "item.h" #include "tile.h" #include "world.h" namespace gameengine { // TODO(simon): is this file/class/function even necessary now? std::unique_ptr<world::World> WorldFactory::createWorld(const std::string& world_filename, ItemManager* item_manager) { const auto create_item = [&item_manager](world::ItemTypeId item_type_id) { return item_manager->createItem(item_type_id); }; const auto get_item = [&item_manager](world::ItemUniqueId item_unique_id) { return item_manager->getItem(item_unique_id); }; auto world_data = io::world_loader::load(world_filename, create_item, get_item); if (world_data.tiles.empty()) { // io::world_loader::load should log error return {}; } LOG_INFO("World loaded, size: %d x %d", world_data.world_size_x, world_data.world_size_y); return std::make_unique<world::World>(world_data.world_size_x, // NOLINT bug in clang-tidy used in Travis (?) world_data.world_size_y, std::move(world_data.tiles)); } } // namespace gameengine
Fix travis build error
Fix travis build error
C++
mit
gurka/gameserver,gurka/gameserver,gurka/gameserver
d884149e931289c1caca98cfb6e50562cf0bdfdf
src/crypto/lamport.cpp
src/crypto/lamport.cpp
// Copyright (c) 2016 Ansho Enigu #include "crypto/lamport.h" #include "crypto/ripemd160.h" #include "crypto/common.h" #include "uint256.h" using namespace std; typedef vector<unsigned char> valtype; bool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[]) { char exmerklewit[8][20]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/ char pubkey[20][2][20]; //start converting merkle wit to exmerklewit and public key char merklebuffer[800]; //size of publickey is the max size of the buffer unsigned int i; for(i = 0; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/ break; merklebuffer[i] = merklewit[i]; } memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer)); int o = 0; int r = 0; //number of times we have reset o count for(; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) { if(r == 8) break; //lim of exmerklewit memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer)); r++; i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle o = 0; //merklebuffer index } else { merklebuffer[o] = merklewit[i]; o++; } } //end decoding merkle wit format //start checking if new publickey is a part of the root key valtype& vch = pubkey; valtype tempverifyhash; valtype rootkeyval = rootkey; CRIPEMD160().Write(begin_ptr(vch), 800).Finalize(begin_ptr(tempverifyhash)); //first element is start of arrays address length pre-def for(int i = 0; true; i++) //to end if false we will use return to lower processing time { if(exmerklewit[i][0] == 0 && exmerklewit[i][1] == 0 && exmerklewit[i][2] == 0 && exmerklewit[i][3] == 0) { if(tempverifyhash == rootkeyval) { break; } else { return false; } } vch = exmerklewit; CRIPEMD160().Write(begin_ptr(vch), vch.size()).Write(begin_ptr(tempverifyhash), tempverifyhash.size()).Finalize(begin_ptr(tempverifyhash)); } //end checking if new publickey is a part of the root key /* unsigned char* datapart; unsigned char[(160/LAMPORT::chuncksize)]* datahashs; for(int i = 0; i < (160/LAMPORT::chuncksize); i++) { for(int o = 0; o < chuncksizeinbyte; o++) { datapart[o] = data[(i * LAMPORT::chuncksize) + o]; } CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i])); } */ return true; // if compleats all tests return true } char *LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey) { /* the signing will happen under this */ return &sig[0][0][0]; }
// Copyright (c) 2016 Ansho Enigu #include "crypto/lamport.h" #include "crypto/ripemd160.h" #include "crypto/common.h" #include "uint256.h" using namespace std; typedef vector<unsigned char> valtype; bool LAMPORT::checksig(vector<unsigned char> data, char sig[20][2][20], vector<unsigned char> rootkey, vector<unsigned char> merklewit) { valtype exmerklewit[8]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/ char pubkey[20][2][20]; valtype hashablepubkey; //start converting merkle wit to exmerklewit and public key char merklebuffer[800]; //size of publickey is the max size of the buffer unsigned int i; for(i = 0; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/ break; merklebuffer[i] = merklewit[i]; } memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer)); memcpy(&hashablepubkey, &merklebuffer, sizeof(merklebuffer)); int o = 0; int r = 0; //number of times we have reset o count for(; i < merklewit.size(); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) { if(r == 8) break; //lim of exmerklewit memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer)); r++; i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle o = 0; //merklebuffer index } else { merklebuffer[o] = merklewit[i]; o++; } } //end decoding merkle wit format //start checking if new publickey is a part of the root key char tempverifyhash[20]; CRIPEMD160().Write(begin_ptr(hashablepubkey), hashablepubkey.size()).Finalize(begin_ptr(tempverifyhash)); //first element is start of arrays address length pre-def for(int i = 0; true; i++) //to end if false we will use return to lower processing time { if(exmerklewit[i][0] == 0 && exmerklewit[i][1] == 0 && exmerklewit[i][2] == 0 && exmerklewit[i][3] == 0) { if(tempverifyhash == rootkey) { break; } else { return false; } } CRIPEMD160().Write(begin_ptr(tempverifyhash), tempverifyhash.size()).Write(begin_ptr(exmerklewit[i]), exmerklewit.size()).Finalize(begin_ptr(tempverifyhash)); } //end checking if new publickey is a part of the root key /* unsigned char* datapart; unsigned char[(160/LAMPORT::chuncksize)]* datahashs; for(int i = 0; i < (160/LAMPORT::chuncksize); i++) { for(int o = 0; o < chuncksizeinbyte; o++) { datapart[o] = data[(i * LAMPORT::chuncksize) + o]; } CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i])); } */ return true; // if compleats all tests return true } char *LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey) { /* the signing will happen under this */ return &sig[0][0][0]; }
Update lamport.cpp
Update lamport.cpp
C++
mit
Alonzo-Coeus/bitcoin,Alonzo-Coeus/bitcoin,Alonzo-Coeus/bitcoin,Alonzo-Coeus/bitcoin,Alonzo-Coeus/bitcoin,Alonzo-Coeus/bitcoin
dc0b2230ba6ea504aef1cc78cc46a1cf3d944cc6
src/date/buildDate.cxx
src/date/buildDate.cxx
/* bzflag * Copyright (c) 1993-2011 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <sstream> #include <string> #include <stdio.h> #include <string.h> // opaque version number increments on protocol incompatibility // update the following files (and their protocol implementations) to match: // misc/bzfquery.php // misc/bzfquery.pl // misc/bzfquery.py #ifndef BZ_PROTO_VERSION # define BZ_PROTO_VERSION "0221" #endif // version numbers - also update as needed: // ChangeLog // README // configure.ac // include/version.h // package/win32/nsis/BZFlag.nsi // tools/TextTool-W32/TextTool.rc #ifndef BZ_MAJOR_VERSION # define BZ_MAJOR_VERSION 2 #endif #ifndef BZ_MINOR_VERSION # define BZ_MINOR_VERSION 4 #endif #ifndef BZ_REV # define BZ_REV 1 #endif // DEVEL | RC# | STABLE | MAINT #ifndef BZ_BUILD_TYPE # define BZ_BUILD_TYPE "DEVEL" #endif const char *bzfcopyright = "Copyright (c) 1993-2011 Tim Riker"; // // Although the ./configure process will generate // -DBZ_BUILD_DATE for the build, here it's voided. // // Could someone explain the reason for the // inconvenience caused by the ./configure method? This // way is simple, touch the *.cxx to get a new time // stamp (no big recompiles). If this file is updated, // you are also forced to get a new timestamp. // // Using __DATE__ for all OSes is more consistent. // #undef BZ_BUILD_DATE #ifndef BZ_BUILD_DATE /* to get the version in the right format YYYYMMDD */ /* yes this is horrible but it needs to be done to get it right */ /* windows should pull from a resource */ /* *nix gets this from the passed from my the Makefile */ char buildDate[] = {__DATE__}; int getBuildDate() { int year = 1900, month = 0, day = 0; char monthStr[512]; sscanf(buildDate, "%s %d %d", monthStr, &day, &year); // we want it not as a name but a number if (strcmp(monthStr, "Jan") == 0) month = 1; else if (strcmp(monthStr, "Feb") == 0) month = 2; else if (strcmp(monthStr, "Mar") == 0) month = 3; else if (strcmp(monthStr, "Apr") == 0) month = 4; else if (strcmp(monthStr, "May") == 0) month = 5; else if (strcmp(monthStr, "Jun") == 0) month = 6; else if (strcmp(monthStr, "Jul") == 0) month = 7; else if (strcmp(monthStr, "Aug") == 0) month = 8; else if (strcmp(monthStr, "Sep") == 0) month = 9; else if (strcmp(monthStr, "Oct") == 0) month = 10; else if (strcmp(monthStr, "Nov") == 0) month = 11; else if (strcmp(monthStr, "Dec") == 0) month = 12; return (year*10000) + (month*100)+ day; } #endif // down here so above gets created #include "version.h" const char* getProtocolVersion() { static std::string protVersion = BZ_PROTO_VERSION; return protVersion.c_str(); } const char* getServerVersion() { static std::string serverVersion = std::string("BZFS") + getProtocolVersion(); return serverVersion.c_str(); } const char* getMajorMinorVersion() { static std::string version = ""; if (!version.size()){ std::ostringstream versionStream; versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION; version = versionStream.str(); } return version.c_str(); } const char* getMajorMinorRevVersion() { static std::string version = ""; if (!version.size()){ std::ostringstream versionStream; versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV; version = versionStream.str(); } return version.c_str(); } const char* getAppVersion() { static std::string appVersion = ""; if (!appVersion.size()){ std::ostringstream appVersionStream; // TODO add current platform, release, cpu, etc appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE << "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS; #ifdef HAVE_SDL appVersionStream << "-SDL"; #endif appVersion = appVersionStream.str(); } return appVersion.c_str(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
/* bzflag * Copyright (c) 1993-2011 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <sstream> #include <string> #include <stdio.h> #include <string.h> // opaque version number increments on protocol incompatibility // update the following files (and their protocol implementations) to match: // misc/bzfquery.php // misc/bzfquery.pl // misc/bzfquery.py // misc/bzls.lua #ifndef BZ_PROTO_VERSION # define BZ_PROTO_VERSION "0221" #endif // version numbers - also update as needed: // ChangeLog // README // configure.ac // include/version.h // package/win32/nsis/BZFlag.nsi // tools/TextTool-W32/TextTool.rc #ifndef BZ_MAJOR_VERSION # define BZ_MAJOR_VERSION 2 #endif #ifndef BZ_MINOR_VERSION # define BZ_MINOR_VERSION 4 #endif #ifndef BZ_REV # define BZ_REV 1 #endif // DEVEL | RC# | STABLE | MAINT #ifndef BZ_BUILD_TYPE # define BZ_BUILD_TYPE "DEVEL" #endif const char *bzfcopyright = "Copyright (c) 1993-2011 Tim Riker"; // // Although the ./configure process will generate // -DBZ_BUILD_DATE for the build, here it's voided. // // Could someone explain the reason for the // inconvenience caused by the ./configure method? This // way is simple, touch the *.cxx to get a new time // stamp (no big recompiles). If this file is updated, // you are also forced to get a new timestamp. // // Using __DATE__ for all OSes is more consistent. // #undef BZ_BUILD_DATE #ifndef BZ_BUILD_DATE /* to get the version in the right format YYYYMMDD */ /* yes this is horrible but it needs to be done to get it right */ /* windows should pull from a resource */ /* *nix gets this from the passed from my the Makefile */ char buildDate[] = {__DATE__}; int getBuildDate() { int year = 1900, month = 0, day = 0; char monthStr[512]; sscanf(buildDate, "%s %d %d", monthStr, &day, &year); // we want it not as a name but a number if (strcmp(monthStr, "Jan") == 0) month = 1; else if (strcmp(monthStr, "Feb") == 0) month = 2; else if (strcmp(monthStr, "Mar") == 0) month = 3; else if (strcmp(monthStr, "Apr") == 0) month = 4; else if (strcmp(monthStr, "May") == 0) month = 5; else if (strcmp(monthStr, "Jun") == 0) month = 6; else if (strcmp(monthStr, "Jul") == 0) month = 7; else if (strcmp(monthStr, "Aug") == 0) month = 8; else if (strcmp(monthStr, "Sep") == 0) month = 9; else if (strcmp(monthStr, "Oct") == 0) month = 10; else if (strcmp(monthStr, "Nov") == 0) month = 11; else if (strcmp(monthStr, "Dec") == 0) month = 12; return (year*10000) + (month*100)+ day; } #endif // down here so above gets created #include "version.h" const char* getProtocolVersion() { static std::string protVersion = BZ_PROTO_VERSION; return protVersion.c_str(); } const char* getServerVersion() { static std::string serverVersion = std::string("BZFS") + getProtocolVersion(); return serverVersion.c_str(); } const char* getMajorMinorVersion() { static std::string version = ""; if (!version.size()){ std::ostringstream versionStream; versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION; version = versionStream.str(); } return version.c_str(); } const char* getMajorMinorRevVersion() { static std::string version = ""; if (!version.size()){ std::ostringstream versionStream; versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV; version = versionStream.str(); } return version.c_str(); } const char* getAppVersion() { static std::string appVersion = ""; if (!appVersion.size()){ std::ostringstream appVersionStream; // TODO add current platform, release, cpu, etc appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE << "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS; #ifdef HAVE_SDL appVersionStream << "-SDL"; #endif appVersion = appVersionStream.str(); } return appVersion.c_str(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
Add bzls.lua to the list of files to be modified when BZ_PROTO_VERSION changes.
Add bzls.lua to the list of files to be modified when BZ_PROTO_VERSION changes.
C++
lgpl-2.1
kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1
f218bdbdc1f589d630d6318326bf7f1b40564f4a
src/delegate/Stock.cxx
src/delegate/Stock.cxx
/* * Delegate helper pooling. * * author: Max Kellermann <[email protected]> */ #include "Stock.hxx" #include "stock/MapStock.hxx" #include "stock/Stock.hxx" #include "stock/Item.hxx" #include "async.hxx" #include "failure.hxx" #include "system/fd_util.h" #include "system/sigutil.h" #include "pevent.hxx" #include "spawn/exec.hxx" #include "spawn/ChildOptions.hxx" #include "gerrno.h" #include "pool.hxx" #include <daemon/log.h> #include <assert.h> #include <unistd.h> #include <sched.h> #include <sys/un.h> #include <sys/socket.h> struct DelegateArgs { const char *helper; const ChildOptions *options; int fds[2]; sigset_t signals; }; struct DelegateProcess final : StockItem { const char *const uri; pid_t pid; int fd = -1; struct event event; explicit DelegateProcess(CreateStockItem c, const char *_uri) :StockItem(c), uri(_uri) {} ~DelegateProcess() override { if (fd >= 0) { p_event_del(&event, pool); close(fd); } } /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { p_event_del(&event, pool); return true; } void Release(gcc_unused void *ctx) override { static constexpr struct timeval tv = { .tv_sec = 60, .tv_usec = 0, }; p_event_add(&event, &tv, pool, "delegate_process"); } }; /* * libevent callback * */ static void delegate_stock_event(int fd, short event, void *ctx) { auto *process = (DelegateProcess *)ctx; assert(fd == process->fd); p_event_consumed(&process->event, process->pool); if ((event & EV_TIMEOUT) == 0) { assert((event & EV_READ) != 0); char buffer; ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle delegate process: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data from idle delegate process\n"); } stock_del(*process); pool_commit(); } /* * clone() function * */ static int delegate_stock_fn(void *ctx) { auto *info = (DelegateArgs *)ctx; install_default_signal_handlers(); leave_signal_section(&info->signals); info->options->Apply(true); dup2(info->fds[1], STDIN_FILENO); close(info->fds[0]); close(info->fds[1]); Exec e; info->options->jail.InsertWrapper(e, nullptr); e.Append(info->helper); e.DoExec(); } /* * stock class * */ static struct pool * delegate_stock_pool(void *ctx gcc_unused, struct pool &parent, const char *uri gcc_unused) { return pool_new_linear(&parent, "delegate_stock", 512); } static void delegate_stock_create(gcc_unused void *ctx, CreateStockItem c, const char *uri, void *_info, gcc_unused struct pool &caller_pool, gcc_unused struct async_operation_ref &async_ref) { auto *const info = (DelegateArgs *)_info; const auto *const options = info->options; auto *process = NewFromPool<DelegateProcess>(c.pool, c, uri); if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, info->fds) < 0) { GError *error = new_error_errno_msg("socketpair() failed: %s"); stock_item_failed(*process, error); return; } int clone_flags = SIGCHLD; clone_flags = options->ns.GetCloneFlags(clone_flags); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&info->signals); char stack[8192]; long pid = clone(delegate_stock_fn, stack + sizeof(stack), clone_flags, info); if (pid < 0) { GError *error = new_error_errno_msg("clone() failed"); leave_signal_section(&info->signals); close(info->fds[0]); close(info->fds[1]); stock_item_failed(*process, error); return; } leave_signal_section(&info->signals); close(info->fds[1]); process->pid = pid; process->fd = info->fds[0]; event_set(&process->event, process->fd, EV_READ|EV_TIMEOUT, delegate_stock_event, process); stock_item_available(*process); } static constexpr StockClass delegate_stock_class = { .pool = delegate_stock_pool, .create = delegate_stock_create, }; /* * interface * */ StockMap * delegate_stock_new(struct pool *pool) { return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16); } void delegate_stock_get(StockMap *delegate_stock, struct pool *pool, const char *helper, const ChildOptions &options, StockGetHandler &handler, struct async_operation_ref &async_ref) { const char *uri = helper; char options_buffer[4096]; *options.MakeId(options_buffer) = 0; if (*options_buffer != 0) uri = p_strcat(pool, helper, "|", options_buffer, nullptr); auto info = NewFromPool<DelegateArgs>(*pool); info->helper = helper; info->options = &options; hstock_get(*delegate_stock, *pool, uri, info, handler, async_ref); } void delegate_stock_put(StockMap *delegate_stock, StockItem &item, bool destroy) { auto *process = (DelegateProcess *)&item; hstock_put(*delegate_stock, process->uri, item, destroy); } int delegate_stock_item_get(StockItem &item) { auto *process = (DelegateProcess *)&item; return process->fd; }
/* * Delegate helper pooling. * * author: Max Kellermann <[email protected]> */ #include "Stock.hxx" #include "stock/MapStock.hxx" #include "stock/Stock.hxx" #include "stock/Item.hxx" #include "async.hxx" #include "failure.hxx" #include "system/fd_util.h" #include "system/sigutil.h" #include "event/Callback.hxx" #include "pevent.hxx" #include "spawn/exec.hxx" #include "spawn/ChildOptions.hxx" #include "gerrno.h" #include "pool.hxx" #include <daemon/log.h> #include <assert.h> #include <unistd.h> #include <sched.h> #include <sys/un.h> #include <sys/socket.h> struct DelegateArgs { const char *helper; const ChildOptions *options; int fds[2]; sigset_t signals; }; struct DelegateProcess final : StockItem { const char *const uri; pid_t pid; int fd = -1; struct event event; explicit DelegateProcess(CreateStockItem c, const char *_uri) :StockItem(c), uri(_uri) {} ~DelegateProcess() override { if (fd >= 0) { p_event_del(&event, pool); close(fd); } } void EventCallback(int fd, short event); /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { p_event_del(&event, pool); return true; } void Release(gcc_unused void *ctx) override { static constexpr struct timeval tv = { .tv_sec = 60, .tv_usec = 0, }; p_event_add(&event, &tv, pool, "delegate_process"); } }; /* * libevent callback * */ inline void DelegateProcess::EventCallback(gcc_unused int _fd, short events) { assert(_fd == fd); p_event_consumed(&event, pool); if ((events & EV_TIMEOUT) == 0) { assert((events & EV_READ) != 0); char buffer; ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle delegate process: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data from idle delegate process\n"); } stock_del(*this); pool_commit(); } /* * clone() function * */ static int delegate_stock_fn(void *ctx) { auto *info = (DelegateArgs *)ctx; install_default_signal_handlers(); leave_signal_section(&info->signals); info->options->Apply(true); dup2(info->fds[1], STDIN_FILENO); close(info->fds[0]); close(info->fds[1]); Exec e; info->options->jail.InsertWrapper(e, nullptr); e.Append(info->helper); e.DoExec(); } /* * stock class * */ static struct pool * delegate_stock_pool(void *ctx gcc_unused, struct pool &parent, const char *uri gcc_unused) { return pool_new_linear(&parent, "delegate_stock", 512); } static void delegate_stock_create(gcc_unused void *ctx, CreateStockItem c, const char *uri, void *_info, gcc_unused struct pool &caller_pool, gcc_unused struct async_operation_ref &async_ref) { auto *const info = (DelegateArgs *)_info; const auto *const options = info->options; auto *process = NewFromPool<DelegateProcess>(c.pool, c, uri); if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, info->fds) < 0) { GError *error = new_error_errno_msg("socketpair() failed: %s"); stock_item_failed(*process, error); return; } int clone_flags = SIGCHLD; clone_flags = options->ns.GetCloneFlags(clone_flags); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&info->signals); char stack[8192]; long pid = clone(delegate_stock_fn, stack + sizeof(stack), clone_flags, info); if (pid < 0) { GError *error = new_error_errno_msg("clone() failed"); leave_signal_section(&info->signals); close(info->fds[0]); close(info->fds[1]); stock_item_failed(*process, error); return; } leave_signal_section(&info->signals); close(info->fds[1]); process->pid = pid; process->fd = info->fds[0]; event_set(&process->event, process->fd, EV_READ|EV_TIMEOUT, MakeEventCallback(DelegateProcess, EventCallback), process); stock_item_available(*process); } static constexpr StockClass delegate_stock_class = { .pool = delegate_stock_pool, .create = delegate_stock_create, }; /* * interface * */ StockMap * delegate_stock_new(struct pool *pool) { return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16); } void delegate_stock_get(StockMap *delegate_stock, struct pool *pool, const char *helper, const ChildOptions &options, StockGetHandler &handler, struct async_operation_ref &async_ref) { const char *uri = helper; char options_buffer[4096]; *options.MakeId(options_buffer) = 0; if (*options_buffer != 0) uri = p_strcat(pool, helper, "|", options_buffer, nullptr); auto info = NewFromPool<DelegateArgs>(*pool); info->helper = helper; info->options = &options; hstock_get(*delegate_stock, *pool, uri, info, handler, async_ref); } void delegate_stock_put(StockMap *delegate_stock, StockItem &item, bool destroy) { auto *process = (DelegateProcess *)&item; hstock_put(*delegate_stock, process->uri, item, destroy); } int delegate_stock_item_get(StockItem &item) { auto *process = (DelegateProcess *)&item; return process->fd; }
use MakeEventCallback()
delegate/Stock: use MakeEventCallback()
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
d101e0162cc1afab5bbbc1d147f157f96ef3f051
glfw3_app/common/widgets/spring_damper.hpp
glfw3_app/common/widgets/spring_damper.hpp
#pragma once //=====================================================================// /*! @file @brief spring damper class @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "utils/vmath.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief スプリング・ダンパー・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class spring_damper { static constexpr float slip_gain_ = 0.5f; static constexpr float damping_ = 0.85f; static constexpr float speed_gain_ = 0.95f; ///< 速度の減衰 static constexpr float acc_gain_ = 0.15f; ///< ドラッグを離した時の加速度ゲイン float position_; float offset_; float speed_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// spring_damper() : position_(0.0f), offset_(0.0f), speed_(0.0f) { } //-----------------------------------------------------------------// /*! @brief アップデート @param[in] select_in 選択開始 (get_select_in) @param[in] select 選択 (get_select) @param[in] pos 現在位置 @param[in] scr スクロール制御量 @param[in] limit リミット @param[in] drag ドラッグ長 @return 更新位置 */ //-----------------------------------------------------------------// int32_t update(bool select_in, bool select, int32_t pos, int32_t scr, int32_t limit, int32_t drag) { if(select_in) { // 選択開始時 speed_ = 0.0f; offset_ = static_cast<float>(pos); } float lim = static_cast<float>(limit); if(select) { // 選択中の挙動 speed_ = static_cast<float>(drag); position_ = offset_ + speed_; speed_ *= acc_gain_; // 加速度の調整 if(position_ > 0.0f) { position_ *= slip_gain_; } else if(position_ < lim) { position_ -= lim; position_ *= slip_gain_; position_ += lim; } } else { position_ += speed_; speed_ *= speed_gain_; if(-0.5f < speed_ && speed_ < 0.5f) speed_ = 0.0f; if(position_ > 0.0f) { speed_ = 0.0f; position_ *= damping_; if(position_ < 1.0f) { position_ = 0.0f; } } else if(position_ < lim) { speed_ = 0.0f; position_ -= lim; position_ *= damping_; position_ += lim; if(position_ > (lim - 1.0f)) { position_ = lim; } } } return static_cast<int32_t>(position_); } }; }
#pragma once //=====================================================================// /*! @file @brief spring damper class @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "utils/vmath.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief スプリング・ダンパー・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class spring_damper { static constexpr float slip_gain_ = 0.5f; static constexpr float damping_ = 0.85f; static constexpr float speed_gain_ = 0.95f; ///< 速度の減衰 static constexpr float acc_gain_ = 0.15f; ///< ドラッグを離した時の加速度ゲイン float position_; float offset_; float speed_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// spring_damper() : position_(0.0f), offset_(0.0f), speed_(0.0f) { } //-----------------------------------------------------------------// /*! @brief アップデート @param[in] select_in 選択開始 (get_select_in) @param[in] select 選択 (get_select) @param[in] pos 現在位置 @param[in] scr スクロール制御量 @param[in] limit リミット @param[in] drag ドラッグ長 @return 更新位置 */ //-----------------------------------------------------------------// int32_t update(bool select_in, bool select, int32_t pos, int32_t scr, int32_t limit, int32_t drag) { if(select_in) { // 選択開始時 speed_ = 0.0f; offset_ = static_cast<float>(pos); } float lim = static_cast<float>(limit); if(select) { // 選択中の挙動 speed_ = static_cast<float>(drag); position_ = offset_ + speed_; speed_ *= acc_gain_; // 加速度の調整 if(position_ > 0.0f) { position_ *= slip_gain_; } else if(position_ < lim) { position_ -= lim; position_ *= slip_gain_; position_ += lim; } } else { position_ += scr; position_ += speed_; speed_ *= speed_gain_; if(-0.5f < speed_ && speed_ < 0.5f) speed_ = 0.0f; if(position_ > 0.0f) { speed_ = 0.0f; position_ *= damping_; if(position_ < 1.0f) { position_ = 0.0f; } } else if(position_ < lim) { speed_ = 0.0f; position_ -= lim; position_ *= damping_; position_ += lim; if(position_ > (lim - 1.0f)) { position_ = lim; } } } return static_cast<int32_t>(position_); } }; }
update scroll
update scroll
C++
bsd-3-clause
hirakuni45/glfw3_app,hirakuni45/glfw3_app,hirakuni45/glfw3_app
676a65aaac5308cf76b81a8e8d65a6c1ad4f747c
src/ranking.cpp
src/ranking.cpp
#include "ranking.hpp" extern int debug; Ranking::Ranking(ACOParameters *params, vector<Ant *> &ants) : params(params) , ants(ants) // copy constructor , best_solution(NULL) { no_ranking_ants = params->get_no_ranking_ants(); } void Ranking::update() { sort(ants.begin(), ants.end(), Ranking::ants_comparator); if (debug >= 5) { cout << "Ranking> Setting best" << endl; } if ((best_solution == NULL) || (solutions_comparator(best_solution, ants.front()->get_solution()))) { best_solution = new Solution(*ants.front()->get_solution()); } } void Ranking::free_memory() { if (debug >= 5) { cout << "Ranking> freeing solutions" << endl; } for (unsigned i = 0; i < no_ranking_ants; ++i) { if (debug >= 6) { cout << "Ranking> freeing #" << i << endl; } ants[i]->free_solution(); if (debug >= 6) { cout << "Ranking> freed #" << i << endl; } } if (debug >= 5) { cout << "Ranking> freed" << endl; } } void Ranking::prepare_pheromones() { for (unsigned i = 0; i < no_ranking_ants; ++i) { prepare_pheromones_for_one_solution(ants[i]->get_solution(), i); } if (params->get_amplify_best() > 0 && best_solution) { prepare_pheromones_for_one_solution(best_solution, (1.0 - params->get_amplify_best()) * ants.size()); } } double Ranking::calculate_additional_pheromones(Solution *solution, unsigned ranking_position) { double position_multiplier = ((double)(ants.size() - ranking_position)) * 2 / (ants.size() * (ants.size() + 1)); return params->get_q() * position_multiplier * solution->get_quality(); } void Ranking::prepare_pheromones_for_one_solution(Solution *solution, unsigned ranking_position) { double additional_pheromones = calculate_additional_pheromones(solution, ranking_position); if (debug >= 4) { cout << "Ranking> additional pheromones for ant#" << ranking_position << ":\t" << additional_pheromones << endl; } vector<Edge*> edges = solution->get_edges(); for (unsigned i = 0, len = edges.size(); i < len; ++i) { edges[i]->add_pheromones(additional_pheromones); } } bool Ranking::ants_comparator(Ant *a1, Ant *a2) { return solutions_comparator(a1->get_solution(), a2->get_solution()); } bool Ranking::solutions_comparator(Solution *s1, Solution *s2) { return s1->get_quality() < s2->get_quality(); }
#include "ranking.hpp" extern int debug; Ranking::Ranking(ACOParameters *params, vector<Ant *> &ants) : params(params) , ants(ants) // copy constructor , best_solution(NULL) { no_ranking_ants = params->get_no_ranking_ants(); } void Ranking::update() { sort(ants.begin(), ants.end(), Ranking::ants_comparator); if (debug >= 5) { cout << "Ranking> Setting best" << endl; } if ((best_solution == NULL) || (solutions_comparator(best_solution, ants.back()->get_solution()))) { best_solution = new Solution(*ants.back()->get_solution()); } } void Ranking::free_memory() { if (debug >= 5) { cout << "Ranking> freeing solutions" << endl; } for (unsigned i = 0; i < no_ranking_ants; ++i) { if (debug >= 6) { cout << "Ranking> freeing #" << i << endl; } ants[i]->free_solution(); if (debug >= 6) { cout << "Ranking> freed #" << i << endl; } } if (debug >= 5) { cout << "Ranking> freed" << endl; } } void Ranking::prepare_pheromones() { for (unsigned i = 0; i < no_ranking_ants; ++i) { prepare_pheromones_for_one_solution(ants[i]->get_solution(), i); } if (params->get_amplify_best() > 0 && best_solution) { prepare_pheromones_for_one_solution(best_solution, (1.0 - params->get_amplify_best()) * ants.size()); } } double Ranking::calculate_additional_pheromones(Solution *solution, unsigned ranking_position) { double position_multiplier = ((double)(ants.size() - ranking_position)) * 2 / (ants.size() * (ants.size() + 1)); return params->get_q() * position_multiplier * solution->get_quality(); } void Ranking::prepare_pheromones_for_one_solution(Solution *solution, unsigned ranking_position) { double additional_pheromones = calculate_additional_pheromones(solution, ranking_position); if (debug >= 4) { cout << "Ranking> additional pheromones for ant#" << ranking_position << ":\t" << additional_pheromones << endl; } vector<Edge*> edges = solution->get_edges(); for (unsigned i = 0, len = edges.size(); i < len; ++i) { edges[i]->add_pheromones(additional_pheromones); } } bool Ranking::ants_comparator(Ant *a1, Ant *a2) { return solutions_comparator(a1->get_solution(), a2->get_solution()); } bool Ranking::solutions_comparator(Solution *s1, Solution *s2) { return s1->get_quality() < s2->get_quality(); }
Choose best, not worst solution
Choose best, not worst solution
C++
mit
jedi1156/sequencing-ants
93c8b489df5232f9cd58387b0c35463ef4f8678d
test/testpoolingpropagate.cpp
test/testpoolingpropagate.cpp
// Copyright Hugh Perkins 2014 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "OpenCLHelper.h" #include "PoolingPropagate.h" #include "gtest/gtest.h" #include "test/gtest_supp.h" #include "test/WeightRandomizer.h" using namespace std; TEST( testpoolingpropagate, basic ) { int batchSize = 1; int numPlanes = 1; int boardSize = 4; int poolingSize = 2; OpenCLHelper cl; PoolingPropagate *poolingPropagate = PoolingPropagate::instanceForTest( &cl, false, numPlanes, boardSize, poolingSize ); float data[] = { 1, 2, 5, 3, 3, 8, 4, 1, 3, 33, 14,23, -1, -3.5f,37.4f,5 }; int outputSize = poolingPropagate->getResultsSize( batchSize ); int *selectors = new int[outputSize]; float *output = new float[outputSize]; poolingPropagate->propagate( batchSize, data, selectors, output ); EXPECT_EQ( selectors[0], 3 ); EXPECT_EQ( selectors[1], 0 ); EXPECT_EQ( selectors[2], 1 ); EXPECT_EQ( selectors[3], 2 ); EXPECT_EQ( output[0], 8 ); EXPECT_EQ( output[1], 5 ); EXPECT_EQ( output[2], 33 ); EXPECT_EQ( output[3], 37.4f ); delete poolingPropagate; delete[] selectors; delete[] output; } TEST( testpoolingpropagate, basic_2plane_batchsize2 ) { int batchSize = 2; int numPlanes = 2; int boardSize = 2; int poolingSize = 2; OpenCLHelper cl; PoolingPropagate *poolingPropagate = PoolingPropagate::instanceForTest( &cl, false, numPlanes, boardSize, poolingSize ); float data[] = { 1, 2, 5, 3, 3, 8, 4, 1, 3, 33, 14,23, -1, -3.5f, 37.4f,5 }; int outputSize = poolingPropagate->getResultsSize( batchSize ); int *selectors = new int[outputSize]; float *output = new float[outputSize]; poolingPropagate->propagate( batchSize, data, selectors, output ); EXPECT_EQ( selectors[0], 2 ); EXPECT_EQ( selectors[1], 1 ); EXPECT_EQ( selectors[2], 1 ); EXPECT_EQ( selectors[3], 2 ); EXPECT_EQ( output[0], 5 ); EXPECT_EQ( output[1], 8 ); EXPECT_EQ( output[2], 33 ); EXPECT_EQ( output[3], 37.4f ); delete poolingPropagate; delete[] selectors; delete[] output; } TEST( testpoolingpropagate, fromwrappers ) { int batchSize = 1; int numPlanes = 1; int boardSize = 4; int poolingSize = 2; OpenCLHelper cl; PoolingPropagate *poolingPropagate = PoolingPropagate::instanceSpecific( 1, &cl, false, numPlanes, boardSize, poolingSize ); float input[] = { 1, 2, 5, 3, 3, 8, 4, 1, 3, 33, 14,23, -1, -3.5f,37.4f,5 }; int outputSize = poolingPropagate->getResultsSize( batchSize ); int *selectors = new int[outputSize]; float *output = new float[outputSize]; const int inputSize = batchSize * numPlanes * boardSize * boardSize; CLWrapper *inputWrapper = cl.wrap( inputSize, input ); CLWrapper *selectorsWrapper = cl.wrap( outputSize, selectors ); CLWrapper *outputWrapper = cl.wrap( outputSize, output ); inputWrapper->copyToDevice(); poolingPropagate->propagate( batchSize, inputWrapper, selectorsWrapper, outputWrapper ); selectorsWrapper->copyToHost(); outputWrapper->copyToHost(); EXPECT_EQ( selectors[0], 3 ); EXPECT_EQ( selectors[1], 0 ); EXPECT_EQ( selectors[2], 1 ); EXPECT_EQ( selectors[3], 2 ); EXPECT_EQ( output[0], 8 ); EXPECT_EQ( output[1], 5 ); EXPECT_EQ( output[2], 33 ); EXPECT_EQ( output[3], 37.4f ); delete inputWrapper; delete selectorsWrapper; delete outputWrapper; delete poolingPropagate; delete[] selectors; delete[] output; } class CompareSpecificArgs{ public: static CompareSpecificArgs instance(){ CompareSpecificArgs args; return args; }; // [[[cog // floats= [] // ints = ['batchSize', 'numPlanes', 'boardSize', 'poolingSize', 'instance0', 'instance1', 'padZeros' ] // import cog_fluent // cog_fluent.gov2( 'CompareSpecificArgs', ints = ints, floats = floats ) // ]]] // generated, using cog: int _batchSize = 0; int _numPlanes = 0; int _boardSize = 0; int _poolingSize = 0; int _instance0 = 0; int _instance1 = 0; int _padZeros = 0; CompareSpecificArgs batchSize( int _batchSize ) { this->_batchSize = _batchSize; return *this; } CompareSpecificArgs numPlanes( int _numPlanes ) { this->_numPlanes = _numPlanes; return *this; } CompareSpecificArgs boardSize( int _boardSize ) { this->_boardSize = _boardSize; return *this; } CompareSpecificArgs poolingSize( int _poolingSize ) { this->_poolingSize = _poolingSize; return *this; } CompareSpecificArgs instance0( int _instance0 ) { this->_instance0 = _instance0; return *this; } CompareSpecificArgs instance1( int _instance1 ) { this->_instance1 = _instance1; return *this; } CompareSpecificArgs padZeros( int _padZeros ) { this->_padZeros = _padZeros; return *this; } // [[[end]]] }; void compareSpecific( CompareSpecificArgs args ) { int batchSize = args._batchSize; int numPlanes = args._numPlanes; int boardSize = args._boardSize; int poolingSize = args._poolingSize; OpenCLHelper cl; PoolingPropagate *poolingPropagate0 = PoolingPropagate::instanceSpecific( args._instance0, &cl, args._padZeros, numPlanes, boardSize, poolingSize ); PoolingPropagate *poolingPropagate1 = PoolingPropagate::instanceSpecific( args._instance1, &cl, args._padZeros, numPlanes, boardSize, poolingSize ); const int inputSize = batchSize * numPlanes * boardSize * boardSize; int outputSize = poolingPropagate0->getResultsSize( batchSize ); float *input = new float[ inputSize ]; int *selectors = new int[ outputSize ]; float *output = new float[ outputSize ]; CLWrapper *inputWrapper = cl.wrap( inputSize, input ); CLWrapper *selectorsWrapper = cl.wrap( outputSize, selectors ); CLWrapper *outputWrapper = cl.wrap( outputSize, output ); WeightRandomizer::randomize( input, inputSize ); memset( selectors, 99, sizeof(int) * outputSize ); memset( output, 99, sizeof(int) * outputSize ); inputWrapper->copyToDevice(); selectorsWrapper->copyToDevice(); outputWrapper->copyToDevice(); poolingPropagate0->propagate( batchSize, inputWrapper, selectorsWrapper, outputWrapper ); selectorsWrapper->copyToHost(); outputWrapper->copyToHost(); int *selectors0 = new int[ outputSize ]; float *output0 = new float[ outputSize ]; memcpy( selectors0, selectors, sizeof(int) * outputSize ); memcpy( output0, output, sizeof(float) * outputSize ); memset( selectors, 99, sizeof(int) * outputSize ); memset( output, 99, sizeof(int) * outputSize ); inputWrapper->copyToDevice(); selectorsWrapper->copyToDevice(); outputWrapper->copyToDevice(); poolingPropagate1->propagate( batchSize, inputWrapper, selectorsWrapper, outputWrapper ); selectorsWrapper->copyToHost(); outputWrapper->copyToHost(); int numErrors = 0; for( int i = 0; i < outputSize; i++ ) { if( selectors[i] != selectors0[i] ) { cout << "ERROR: selectors[" << i << "] instance0:" << selectors0[i] << " != instance1:" << selectors[i] << endl; numErrors++; } if( output[i] != output0[i] ) { cout << "ERROR: output[" << i << "] instance0:" << output0[i] << " != instance1:" << output[i] << endl; numErrors++; } if( numErrors >= 10 ) { cout << "More than 10 errors. Skipping the rest :-)" << endl; break; } } EXPECT_EQ( 0, numErrors ); if( numErrors > 0 ) { int num2dPlanes = inputSize / boardSize / boardSize; for( int plane = 0; plane < num2dPlanes; plane++ ) { cout << "2dplane " << plane << ":" << endl; for( int i = 0; i < boardSize; i++ ) { string line = ""; for( int j = 0; j < boardSize; j++ ) { line += toString( input[ plane * boardSize * boardSize + i * boardSize + j] ) + " "; } cout << line << endl; } cout << endl; } } delete inputWrapper; delete selectorsWrapper; delete outputWrapper; delete poolingPropagate0; delete poolingPropagate1; delete[] selectors0; delete[] output0; delete[] selectors; delete[] output; delete[] input; } TEST( testpoolingpropagate, comparespecific_0_1_pooling2 ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(2) .instance0(0).instance1(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3 ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(3) .instance0(0).instance1(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling2_pz ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(2) .instance0(0).instance1(1).padZeros(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3_pz ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(3) .instance0(0).instance1(1).padZeros(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3_small ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(1).numPlanes(1).boardSize(2).poolingSize(3) .instance0(0).instance1(1).padZeros(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3_small2 ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(2).numPlanes(1).boardSize(2).poolingSize(3) .instance0(0).instance1(1).padZeros(1) ); }
// Copyright Hugh Perkins 2014 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "OpenCLHelper.h" #include "PoolingPropagate.h" #include "gtest/gtest.h" #include "test/gtest_supp.h" #include "test/WeightRandomizer.h" using namespace std; namespace testpoolingpropagate { TEST( testpoolingpropagate, basic ) { int batchSize = 1; int numPlanes = 1; int boardSize = 4; int poolingSize = 2; OpenCLHelper cl; PoolingPropagate *poolingPropagate = PoolingPropagate::instanceForTest( &cl, false, numPlanes, boardSize, poolingSize ); float data[] = { 1, 2, 5, 3, 3, 8, 4, 1, 3, 33, 14,23, -1, -3.5f,37.4f,5 }; int outputSize = poolingPropagate->getResultsSize( batchSize ); int *selectors = new int[outputSize]; float *output = new float[outputSize]; poolingPropagate->propagate( batchSize, data, selectors, output ); EXPECT_EQ( selectors[0], 3 ); EXPECT_EQ( selectors[1], 0 ); EXPECT_EQ( selectors[2], 1 ); EXPECT_EQ( selectors[3], 2 ); EXPECT_EQ( output[0], 8 ); EXPECT_EQ( output[1], 5 ); EXPECT_EQ( output[2], 33 ); EXPECT_EQ( output[3], 37.4f ); delete poolingPropagate; delete[] selectors; delete[] output; } TEST( testpoolingpropagate, basic_2plane_batchsize2 ) { int batchSize = 2; int numPlanes = 2; int boardSize = 2; int poolingSize = 2; OpenCLHelper cl; PoolingPropagate *poolingPropagate = PoolingPropagate::instanceForTest( &cl, false, numPlanes, boardSize, poolingSize ); float data[] = { 1, 2, 5, 3, 3, 8, 4, 1, 3, 33, 14,23, -1, -3.5f, 37.4f,5 }; int outputSize = poolingPropagate->getResultsSize( batchSize ); int *selectors = new int[outputSize]; float *output = new float[outputSize]; poolingPropagate->propagate( batchSize, data, selectors, output ); EXPECT_EQ( selectors[0], 2 ); EXPECT_EQ( selectors[1], 1 ); EXPECT_EQ( selectors[2], 1 ); EXPECT_EQ( selectors[3], 2 ); EXPECT_EQ( output[0], 5 ); EXPECT_EQ( output[1], 8 ); EXPECT_EQ( output[2], 33 ); EXPECT_EQ( output[3], 37.4f ); delete poolingPropagate; delete[] selectors; delete[] output; } TEST( testpoolingpropagate, fromwrappers ) { int batchSize = 1; int numPlanes = 1; int boardSize = 4; int poolingSize = 2; OpenCLHelper cl; PoolingPropagate *poolingPropagate = PoolingPropagate::instanceSpecific( 1, &cl, false, numPlanes, boardSize, poolingSize ); float input[] = { 1, 2, 5, 3, 3, 8, 4, 1, 3, 33, 14,23, -1, -3.5f,37.4f,5 }; int outputSize = poolingPropagate->getResultsSize( batchSize ); int *selectors = new int[outputSize]; float *output = new float[outputSize]; const int inputSize = batchSize * numPlanes * boardSize * boardSize; CLWrapper *inputWrapper = cl.wrap( inputSize, input ); CLWrapper *selectorsWrapper = cl.wrap( outputSize, selectors ); CLWrapper *outputWrapper = cl.wrap( outputSize, output ); inputWrapper->copyToDevice(); poolingPropagate->propagate( batchSize, inputWrapper, selectorsWrapper, outputWrapper ); selectorsWrapper->copyToHost(); outputWrapper->copyToHost(); EXPECT_EQ( selectors[0], 3 ); EXPECT_EQ( selectors[1], 0 ); EXPECT_EQ( selectors[2], 1 ); EXPECT_EQ( selectors[3], 2 ); EXPECT_EQ( output[0], 8 ); EXPECT_EQ( output[1], 5 ); EXPECT_EQ( output[2], 33 ); EXPECT_EQ( output[3], 37.4f ); delete inputWrapper; delete selectorsWrapper; delete outputWrapper; delete poolingPropagate; delete[] selectors; delete[] output; } class CompareSpecificArgs{ public: static CompareSpecificArgs instance() { static CompareSpecificArgs args; return args; } // [[[cog // floats= [] // ints = ['batchSize', 'numPlanes', 'boardSize', 'poolingSize', 'instance0', 'instance1', 'padZeros' ] // import cog_fluent // cog_fluent.gov2( 'CompareSpecificArgs', ints = ints, floats = floats ) // ]]] // generated, using cog: int _batchSize = 0; int _numPlanes = 0; int _boardSize = 0; int _poolingSize = 0; int _instance0 = 0; int _instance1 = 0; int _padZeros = 0; CompareSpecificArgs batchSize( int _batchSize ) { this->_batchSize = _batchSize; return *this; } CompareSpecificArgs numPlanes( int _numPlanes ) { this->_numPlanes = _numPlanes; return *this; } CompareSpecificArgs boardSize( int _boardSize ) { this->_boardSize = _boardSize; return *this; } CompareSpecificArgs poolingSize( int _poolingSize ) { this->_poolingSize = _poolingSize; return *this; } CompareSpecificArgs instance0( int _instance0 ) { this->_instance0 = _instance0; return *this; } CompareSpecificArgs instance1( int _instance1 ) { this->_instance1 = _instance1; return *this; } CompareSpecificArgs padZeros( int _padZeros ) { this->_padZeros = _padZeros; return *this; } // [[[end]]] }; void compareSpecific( CompareSpecificArgs args ) { cout << "instance0: " << args._instance0 << endl; cout << "instance1: " << args._instance1 << endl; int batchSize = args._batchSize; int numPlanes = args._numPlanes; int boardSize = args._boardSize; int poolingSize = args._poolingSize; OpenCLHelper cl; PoolingPropagate *poolingPropagate0 = PoolingPropagate::instanceSpecific( args._instance0, &cl, args._padZeros, numPlanes, boardSize, poolingSize ); PoolingPropagate *poolingPropagate1 = PoolingPropagate::instanceSpecific( args._instance1, &cl, args._padZeros, numPlanes, boardSize, poolingSize ); const int inputSize = batchSize * numPlanes * boardSize * boardSize; int outputSize = poolingPropagate0->getResultsSize( batchSize ); float *input = new float[ inputSize ]; int *selectors = new int[ outputSize ]; float *output = new float[ outputSize ]; CLWrapper *inputWrapper = cl.wrap( inputSize, input ); CLWrapper *selectorsWrapper = cl.wrap( outputSize, selectors ); CLWrapper *outputWrapper = cl.wrap( outputSize, output ); WeightRandomizer::randomize( input, inputSize ); memset( selectors, 99, sizeof(int) * outputSize ); memset( output, 99, sizeof(int) * outputSize ); inputWrapper->copyToDevice(); selectorsWrapper->copyToDevice(); outputWrapper->copyToDevice(); poolingPropagate0->propagate( batchSize, inputWrapper, selectorsWrapper, outputWrapper ); selectorsWrapper->copyToHost(); outputWrapper->copyToHost(); int *selectors0 = new int[ outputSize ]; float *output0 = new float[ outputSize ]; memcpy( selectors0, selectors, sizeof(int) * outputSize ); memcpy( output0, output, sizeof(float) * outputSize ); memset( selectors, 99, sizeof(int) * outputSize ); memset( output, 99, sizeof(int) * outputSize ); inputWrapper->copyToDevice(); selectorsWrapper->copyToDevice(); outputWrapper->copyToDevice(); poolingPropagate1->propagate( batchSize, inputWrapper, selectorsWrapper, outputWrapper ); selectorsWrapper->copyToHost(); outputWrapper->copyToHost(); int numErrors = 0; for( int i = 0; i < outputSize; i++ ) { if( selectors[i] != selectors0[i] ) { cout << "ERROR: selectors[" << i << "] instance0:" << selectors0[i] << " != instance1:" << selectors[i] << endl; numErrors++; } if( output[i] != output0[i] ) { cout << "ERROR: output[" << i << "] instance0:" << output0[i] << " != instance1:" << output[i] << endl; numErrors++; } if( numErrors >= 10 ) { cout << "More than 10 errors. Skipping the rest :-)" << endl; break; } } EXPECT_EQ( 0, numErrors ); if( numErrors > 0 ) { int num2dPlanes = inputSize / boardSize / boardSize; for( int plane = 0; plane < num2dPlanes; plane++ ) { cout << "2dplane " << plane << ":" << endl; for( int i = 0; i < boardSize; i++ ) { string line = ""; for( int j = 0; j < boardSize; j++ ) { line += toString( input[ plane * boardSize * boardSize + i * boardSize + j] ) + " "; } cout << line << endl; } cout << endl; } } delete inputWrapper; delete selectorsWrapper; delete outputWrapper; delete poolingPropagate0; delete poolingPropagate1; delete[] selectors0; delete[] output0; delete[] selectors; delete[] output; delete[] input; } TEST( testpoolingpropagate, comparespecific_0_1_pooling2 ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(2) .instance0(0).instance1(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3 ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(3) .instance0(0).instance1(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling2_pz ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(2) .instance0(0).instance1(1).padZeros(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3_pz ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(10).numPlanes(5).boardSize(10).poolingSize(3) .instance0(0).instance1(1).padZeros(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3_small ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(1).numPlanes(1).boardSize(2).poolingSize(3) .instance0(0).instance1(1).padZeros(1) ); } TEST( testpoolingpropagate, comparespecific_0_1_pooling3_small2 ) { compareSpecific( CompareSpecificArgs::instance() .batchSize(2).numPlanes(1).boardSize(2).poolingSize(3) .instance0(0).instance1(1).padZeros(1) ); } }
fix namespaces bug
fix namespaces bug
C++
mpl-2.0
pimms/DeepCL,hughperkins/DeepCL,Peilong/DeepCL,MiniLight/DeepCL,mrgloom/DeepCL,Peilong/DeepCL,mrgloom/DeepCL,mrgloom/DeepCL,MiniLight/DeepCL,pimms/DeepCL,pimms/DeepCL,pimms/DeepCL,MiniLight/DeepCL,FighterLYL/DeepCL,Peilong/DeepCL,hughperkins/DeepCL,MiniLight/DeepCL,FighterLYL/DeepCL,mrgloom/DeepCL,hughperkins/DeepCL,hughperkins/DeepCL,FighterLYL/DeepCL,hughperkins/DeepCL,Peilong/DeepCL,FighterLYL/DeepCL,Peilong/DeepCL,FighterLYL/DeepCL,MiniLight/DeepCL,pimms/DeepCL,mrgloom/DeepCL
adec41b60c05ececf19007808e9328cc16d0b324
tests/api/test_simple_api.cpp
tests/api/test_simple_api.cpp
#include "gtest/gtest.h" #include "c7a/api/dia.hpp" #include "c7a/api/context.hpp" #include "c7a/api/function_stack.hpp" TEST(DISABLED_DIASimple, InputTest1ReadInt) { //auto read_int = [](std::string line) { return std::stoi(line); }; //c7a::Context ctx; // auto initial = ctx.ReadFromFileSystem("tests/inputs/test1", read_int); // assert(initial.NodeString() == "[DIANode/State:NEW/Type:i]"); // assert(initial.Size() == 4); } TEST(DISABLED_DIASimple, InputTest1ReadDouble) { //auto read_double = [](std::string line) { return std::stod(line); }; //c7a::Context ctx; // auto initial = ctx.ReadFromFileSystem("tests/inputs/test1", read_double); // assert(initial.NodeString() == "[DIANode/State:NEW/Type:d]"); // assert(initial.Size() == 4); } TEST(DISABLED_DIASimple, InputTest1Write) { //auto read_int = [](std::string line) { return std::stoi(line); }; //auto write_int = [](int element) { return element; }; //c7a::Context ctx; // auto initial = ctx.ReadFromFileSystem("tests/inputs/test1", read_int); // ctx.WriteToFileSystem(initial, "tests/inputs/test1_result", write_int); // auto copy = ctx.ReadFromFileSystem("tests/inputs/test1_result", read_int); // assert(copy.NodeString() == "[DIANode/State:NEW/Type:i]"); // assert(copy.Size() == 4); } TEST(DIASimple, ReduceStringEquality) { using c7a::DIA; using c7a::Context; using c7a::FunctionStack; // auto doubles = Context().ReadFromFileSystem("tests/inputs/test1", [](std::string line) { // return std::stod(line); // }); auto key_ex = [](double in) { return (int) in; }; auto red_fn = [](double in1, double in2) { return in1 + in2; }; auto map_fn = [](double input) { std::cout << "Map" << std::endl; return input; }; // auto map2_fn = [](double input) { // std::cout << "Map2" << std::endl; // return input; // }; auto fmap_fn = [](double input, std::function<void(double)> emit_func) { std::cout << "FlatMap" << std::endl; emit_func(input); emit_func(input); }; // auto duplicates = doubles.Map(map_fn); // auto duplicates2 = duplicates.Map(map_fn); // auto red_duplicates = duplicates2.Reduce(key_ex, red_fn); // auto red_duplicates2 = duplicates.Reduce(key_ex, red_fn); std::cout << "==============" << std::endl; std::cout << "FunctionStack" << std::endl; std::cout << "==============" << std::endl; FunctionStack<> stack; auto new_stack = stack.push( [](int i, std::function<void(double)> emit_func) { std::cout << "hello1" << std::endl; emit_func(i + 1); }); auto new_stack2 = new_stack.push( [](int i, std::function<void(double)> emit_func){ std::cout << "hello2" << std::endl; emit_func(i + 1); }); //auto new_stack2 = new_stack.push(map2_fn); //auto pair = new_stack2.pop(); auto composed_function = new_stack2.emit(); composed_function(42); return; // std::cout << "==============" << std::endl; // std::cout << "Tree" << std::endl; // std::cout << "==============" << std::endl; // duplicates.PrintNodes(); // std::cout << std::endl; // std::cout << "==============" << std::endl; // std::cout << "Execution" << std::endl; // std::cout << "==============" << std::endl; // std::cout << "First Reduce:" << std::endl; // (red_duplicates.get_node())->execute(); // std::cout << std::endl; // std::cout << "Second Reduce:" << std::endl; // (red_duplicates2.get_node())->execute(); // auto duplicates3 = red_duplicates.Map(map_fn); // auto red_duplicates2 = duplicates3.Reduce(key_ex, red_fn); }
#include "gtest/gtest.h" #include "c7a/api/dia.hpp" #include "c7a/api/context.hpp" #include "c7a/api/function_stack.hpp" TEST(DISABLED_DIASimple, InputTest1ReadInt) { //auto read_int = [](std::string line) { return std::stoi(line); }; //c7a::Context ctx; // auto initial = ctx.ReadFromFileSystem("tests/inputs/test1", read_int); // assert(initial.NodeString() == "[DIANode/State:NEW/Type:i]"); // assert(initial.Size() == 4); } TEST(DISABLED_DIASimple, InputTest1ReadDouble) { //auto read_double = [](std::string line) { return std::stod(line); }; //c7a::Context ctx; // auto initial = ctx.ReadFromFileSystem("tests/inputs/test1", read_double); // assert(initial.NodeString() == "[DIANode/State:NEW/Type:d]"); // assert(initial.Size() == 4); } TEST(DISABLED_DIASimple, InputTest1Write) { //auto read_int = [](std::string line) { return std::stoi(line); }; //auto write_int = [](int element) { return element; }; //c7a::Context ctx; // auto initial = ctx.ReadFromFileSystem("tests/inputs/test1", read_int); // ctx.WriteToFileSystem(initial, "tests/inputs/test1_result", write_int); // auto copy = ctx.ReadFromFileSystem("tests/inputs/test1_result", read_int); // assert(copy.NodeString() == "[DIANode/State:NEW/Type:i]"); // assert(copy.Size() == 4); } TEST(DIASimple, ReduceStringEquality) { using c7a::DIA; using c7a::Context; using c7a::FunctionStack; Context ctx; auto doubles = ctx.ReadFromFileSystem("tests/inputs/test1", [](std::string line) { return std::stod(line); }); auto key_ex = [](double in) { return (int) in; }; auto red_fn = [](double in1, double in2) { return in1 + in2; }; auto map_fn = [](double input) { std::cout << "Map" << std::endl; return input; }; // auto map2_fn = [](double input) { // std::cout << "Map2" << std::endl; // return input; // }; auto fmap_fn = [](double input, std::function<void(double)> emit_func) { std::cout << "FlatMap" << std::endl; emit_func(input); emit_func(input); }; // auto duplicates = doubles.Map(map_fn); // auto duplicates2 = duplicates.Map(map_fn); // auto red_duplicates = duplicates2.Reduce(key_ex, red_fn); // auto red_duplicates2 = duplicates.Reduce(key_ex, red_fn); std::cout << "==============" << std::endl; std::cout << "FunctionStack" << std::endl; std::cout << "==============" << std::endl; FunctionStack<> stack; auto new_stack = stack.push( [](int i, std::function<void(double)> emit_func) { std::cout << "hello1" << std::endl; emit_func(i + 1); }); auto new_stack2 = new_stack.push( [](int i, std::function<void(double)> emit_func){ std::cout << "hello2" << std::endl; emit_func(i + 1); }); //auto new_stack2 = new_stack.push(map2_fn); //auto pair = new_stack2.pop(); auto composed_function = new_stack2.emit(); composed_function(42); return; // std::cout << "==============" << std::endl; // std::cout << "Tree" << std::endl; // std::cout << "==============" << std::endl; // duplicates.PrintNodes(); // std::cout << std::endl; // std::cout << "==============" << std::endl; // std::cout << "Execution" << std::endl; // std::cout << "==============" << std::endl; // std::cout << "First Reduce:" << std::endl; // (red_duplicates.get_node())->execute(); // std::cout << std::endl; // std::cout << "Second Reduce:" << std::endl; // (red_duplicates2.get_node())->execute(); // auto duplicates3 = red_duplicates.Map(map_fn); // auto red_duplicates2 = duplicates3.Reduce(key_ex, red_fn); }
FIX THE EVIL BUG
FIX THE EVIL BUG
C++
bsd-2-clause
manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill
deaeff2bb732b7fce3818702e3da73087c0f291c
Modules/Core/ImageFunction/test/itkGaussianInterpolateImageFunctionTest.cxx
Modules/Core/ImageFunction/test/itkGaussianInterpolateImageFunctionTest.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <iostream> #include "itkImage.h" #include "itkVectorImage.h" #include "itkGaussianInterpolateImageFunction.h" /* VS 2015 has a bug when building release with the heavly nested for * loops iterating too many times. This turns off optimization to * allow the tests to pass. */ #if _MSC_VER == 1900 # pragma optimize( "", off ) #endif /* Allows testing up to TDimension=4 */ template< unsigned int TDimension > int RunTest( void ) { typedef float PixelType; const unsigned int Dimensions = TDimension; typedef itk::Image<PixelType, TDimension> ImageType; typedef typename ImageType::RegionType RegionType; typedef typename RegionType::SizeType SizeType; typedef typename ImageType::IndexType IndexType; typedef float CoordRepType; typedef typename itk::ContinuousIndex<CoordRepType, Dimensions> ContinuousIndexType; typedef typename ContinuousIndexType::ValueType AccumulatorType; typedef typename itk::Point<CoordRepType,Dimensions> PointType; typedef typename itk::GaussianInterpolateImageFunction< ImageType, CoordRepType > InterpolatorType; typename ImageType::Pointer image = ImageType::New(); IndexType start; start.Fill( 0 ); SizeType size; const int dimMaxLength = 3; size.Fill( dimMaxLength ); RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions( region ); image->Allocate(); typename ImageType::PointType origin; typename ImageType::SpacingType spacing; origin.Fill( 0.0 ); spacing.Fill( 1.0 ); image->SetOrigin( origin ); image->SetSpacing( spacing ); image->Print( std::cout ); // Setup for testing up to Dimension=4 unsigned int dimLengths[4] = {1,1,1,1}; for( unsigned int ind = 0; ind < Dimensions; ind++ ) { dimLengths[ind] = dimMaxLength; } // // Fill up the image values with the function // // Intensity = f(d1[,d2[,d3[,d4]]]) = 3*d1 [+ d2 [+ d3 [+ d4] ] ] // // IndexType index; unsigned int dimIt[4]; std::cout << "Image Data: " << std::endl; for (dimIt[3] = 0; dimIt[3] < dimLengths[3]; dimIt[3]++) { for (dimIt[2] = 0; dimIt[2] < dimLengths[2]; dimIt[2]++) { std::cout << "* dimIt[3], dimIt[2]: " << dimIt[3] << ", " << dimIt[2] << std::endl; for (dimIt[1] = 0; dimIt[1] < dimLengths[1]; dimIt[1]++) { for (dimIt[0] = 0; dimIt[0] < dimLengths[0]; dimIt[0]++) { PixelType value = 3*dimIt[0]; index[0] = dimIt[0]; for( unsigned int ind = 1; ind < Dimensions; ind++ ) { value += dimIt[ind]; index[ind]=dimIt[ind]; } image->SetPixel( index, value ); std::cout << value << " "; } std::cout << std::endl; } } } typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); double sigma[TDimension]; for( unsigned int d = 0; d < TDimension; d++ ) { sigma[d] = 1.0; } AccumulatorType alpha = 1.0; interpolator->SetParameters( sigma, alpha ); interpolator->Print( std::cout, 3 ); if( interpolator->GetSigma()[0] != 1.0 || interpolator->GetAlpha() != 1.0 ) { std::cerr << "Parameters were not returned correctly." << std::endl; } const AccumulatorType incr = 0.2; const AccumulatorType tolerance = 5e-6; PointType point; AccumulatorType testLengths[4] = {1,1,1,1}; for( unsigned int ind = 0; ind < Dimensions; ind++ ) { testLengths[ind] = dimMaxLength-1; } AccumulatorType steps[4]; AccumulatorType dimItf[4]; for (dimItf[3] = 0; dimItf[3] < testLengths[3]; dimItf[3]++) { for (dimItf[2] = 0; dimItf[2] < testLengths[2]; dimItf[2]++) { for (dimItf[1] = 0; dimItf[1] < testLengths[1]; dimItf[1]++) { for (dimItf[0] = 0; dimItf[0] < testLengths[0]; dimItf[0]++) { for (steps[3] = 0; steps[3] < dimItf[3] + 1.01; steps[3]+=incr) { for (steps[2] = 0; steps[2] < dimItf[2] + 1.01; steps[2]+=incr) { for (steps[1] = 0; steps[1] < dimItf[1] + 1.01; steps[1]+=incr) { for (steps[0] = 0; steps[0] < dimItf[0] + 1.01; steps[0]+=incr) { AccumulatorType expectedValue = 3*steps[0]; point[0] = steps[0]; for( unsigned int ind = 1; ind < Dimensions; ind++ ) { expectedValue += steps[ind]; point[ind]=steps[ind]; } if( interpolator->IsInsideBuffer( point ) ) { const AccumulatorType computedValue = interpolator->Evaluate( point ); const AccumulatorType difference = expectedValue - computedValue; if( std::fabs( difference ) > tolerance ) { std::cerr << "Error found while computing interpolation " << std::endl; std::cerr << "Point = " << point << std::endl; std::cerr << "Expected value = " << expectedValue << std::endl; std::cerr << "Computed value = " << computedValue << std::endl; std::cerr << "Difference = " << difference << std::endl; return EXIT_FAILURE; } } } } } } } } } } //for dims[3]... return EXIT_SUCCESS; }// RunTest() int itkGaussianInterpolateImageFunctionTest( int , char*[] ) { /* Test separately for images of 1 through 4 dimensions because this function * has optimized implementations for dimensionality of 1-3, and unoptimized * implementation for 4 and greater. */ int result = EXIT_SUCCESS; std::cout << "***** Testing dimensionality of 1 *****" << std::endl; if( RunTest<1>() == EXIT_FAILURE ) { result = EXIT_FAILURE; std::cout << "Failed for dimensionality 1." << std::endl; } std::cout << "***** Testing dimensionality of 2 *****" << std::endl; if( RunTest<2>() == EXIT_FAILURE ) { result = EXIT_FAILURE; std::cout << "Failed for dimensionality 2." << std::endl; } std::cout << "***** Testing dimensionality of 3 *****" << std::endl; if( RunTest<3>() == EXIT_FAILURE ) { result = EXIT_FAILURE; std::cout << "Failed for dimensionality 3." << std::endl; } std::cout << "***** Testing dimensionality of 4 *****" << std::endl; if( RunTest<4>() == EXIT_FAILURE ) { result = EXIT_FAILURE; std::cout << "Failed for dimensionality 4." << std::endl; } return result; }
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <iostream> #include "itkImage.h" #include "itkVectorImage.h" #include "itkGaussianInterpolateImageFunction.h" #include "itkMath.h" #include "itkTestingMacros.h" // VS 2015 has a bug when building release with the heavily nested for // loops iterating too many times. This turns off optimization to // allow the tests to pass. // #if _MSC_VER == 1900 # pragma optimize( "", off ) #endif // Allows testing up to TDimension = 4 template< unsigned int TDimension > int RunTest( void ) { typedef float PixelType; const unsigned int Dimensions = TDimension; typedef itk::Image<PixelType, TDimension> ImageType; typedef typename ImageType::RegionType RegionType; typedef typename RegionType::SizeType SizeType; typedef typename ImageType::IndexType IndexType; typedef float CoordRepType; typedef typename itk::ContinuousIndex<CoordRepType, Dimensions> ContinuousIndexType; typedef typename ContinuousIndexType::ValueType AccumulatorType; typedef typename itk::Point<CoordRepType, Dimensions> PointType; typedef typename itk::GaussianInterpolateImageFunction< ImageType, CoordRepType > InterpolatorType; typename ImageType::Pointer image = ImageType::New(); IndexType start; start.Fill( 0 ); SizeType size; const int dimMaxLength = 3; size.Fill( dimMaxLength ); RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions( region ); image->Allocate(); typename ImageType::PointType origin; typename ImageType::SpacingType spacing; origin.Fill( 0.0 ); spacing.Fill( 1.0 ); image->SetOrigin( origin ); image->SetSpacing( spacing ); image->Print( std::cout ); // Setup for testing up to Dimension = 4 unsigned int dimLengths[4] = {1,1,1,1}; for( unsigned int ind = 0; ind < Dimensions; ind++ ) { dimLengths[ind] = dimMaxLength; } // // Fill up the image values with the function // // Intensity = f(d1[,d2[,d3[,d4]]]) = 3*d1 [+ d2 [+ d3 [+ d4] ] ] // IndexType index; PixelType value; unsigned int dimIt[4]; std::cout << "Image Data: " << std::endl; for (dimIt[3] = 0; dimIt[3] < dimLengths[3]; dimIt[3]++) { for (dimIt[2] = 0; dimIt[2] < dimLengths[2]; dimIt[2]++) { std::cout << "* dimIt[3], dimIt[2]: " << dimIt[3] << ", " << dimIt[2] << std::endl; for (dimIt[1] = 0; dimIt[1] < dimLengths[1]; dimIt[1]++) { for (dimIt[0] = 0; dimIt[0] < dimLengths[0]; dimIt[0]++) { value = 3*dimIt[0]; index[0] = dimIt[0]; for( unsigned int ind = 1; ind < Dimensions; ind++ ) { value += dimIt[ind]; index[ind] = dimIt[ind]; } image->SetPixel( index, value ); std::cout << value << " "; } std::cout << std::endl; } } } typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); double sigma[TDimension]; for( unsigned int d = 0; d < TDimension; d++ ) { sigma[d] = 1.0; } AccumulatorType alpha = 1.0; interpolator->SetParameters( sigma, alpha ); for( unsigned int d = 0; d < TDimension; d++ ) { TEST_SET_GET_VALUE( sigma[d], interpolator->GetSigma()[d] ); } TEST_SET_GET_VALUE( alpha, interpolator->GetAlpha() ); // Test EvaluateAtContinuousIndex // Use the last index for convenience typename InterpolatorType::ContinuousIndexType cindex = index; if ( interpolator->IsInsideBuffer( index ) ) { typename InterpolatorType::OutputType interpolatedValue; interpolatedValue = interpolator->EvaluateAtContinuousIndex(cindex); itk::Math::FloatAlmostEqual( (float)interpolatedValue, (float)value ); } const AccumulatorType incr = 0.2; const AccumulatorType tolerance = 5e-6; PointType point; AccumulatorType testLengths[4] = {1,1,1,1}; for( unsigned int ind = 0; ind < Dimensions; ind++ ) { testLengths[ind] = dimMaxLength-1; } AccumulatorType steps[4]; AccumulatorType dimItf[4]; for (dimItf[3] = 0; dimItf[3] < testLengths[3]; dimItf[3]++) { for (dimItf[2] = 0; dimItf[2] < testLengths[2]; dimItf[2]++) { for (dimItf[1] = 0; dimItf[1] < testLengths[1]; dimItf[1]++) { for (dimItf[0] = 0; dimItf[0] < testLengths[0]; dimItf[0]++) { for (steps[3] = 0; steps[3] < dimItf[3] + 1.01; steps[3]+=incr) { for (steps[2] = 0; steps[2] < dimItf[2] + 1.01; steps[2]+=incr) { for (steps[1] = 0; steps[1] < dimItf[1] + 1.01; steps[1]+=incr) { for (steps[0] = 0; steps[0] < dimItf[0] + 1.01; steps[0]+=incr) { AccumulatorType expectedValue = 3*steps[0]; point[0] = steps[0]; for( unsigned int ind = 1; ind < Dimensions; ind++ ) { expectedValue += steps[ind]; point[ind]=steps[ind]; } if( interpolator->IsInsideBuffer( point ) ) { const AccumulatorType computedValue = interpolator->Evaluate( point ); if( ! itk::Math::FloatAlmostEqual( expectedValue, computedValue, 7, tolerance ) ) { return EXIT_FAILURE; } } } } } } } } } } return EXIT_SUCCESS; } int itkGaussianInterpolateImageFunctionTest( int, char*[] ) { typedef float PixelType; const unsigned int Dimension = 1; typedef itk::Image< PixelType, Dimension > ImageType; typedef float CoordRepType; typedef itk::GaussianInterpolateImageFunction< ImageType, CoordRepType > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); EXERCISE_BASIC_OBJECT_METHODS( interpolator, GaussianInterpolateImageFunction, InterpolateImageFunction ); // Test separately for images of 1 through 4 dimensions because this function // has optimized implementations for dimensionality of 1-3, and unoptimized // implementation for 4 and greater. int testResult = EXIT_SUCCESS; int testResult1 = EXIT_SUCCESS; int testResult2 = EXIT_SUCCESS; int testResult3 = EXIT_SUCCESS; int testResult4 = EXIT_SUCCESS; std::cout << "***** Testing dimensionality of 1 *****" << std::endl; if( RunTest<1>() == EXIT_FAILURE ) { testResult1 = EXIT_FAILURE; std::cout << "Failed for dimensionality 1." << std::endl; } std::cout << "***** Testing dimensionality of 2 *****" << std::endl; if( RunTest<2>() == EXIT_FAILURE ) { testResult2 = EXIT_FAILURE; std::cout << "Failed for dimensionality 2." << std::endl; } std::cout << "***** Testing dimensionality of 3 *****" << std::endl; if( RunTest<3>() == EXIT_FAILURE ) { testResult3 = EXIT_FAILURE; std::cout << "Failed for dimensionality 3." << std::endl; } std::cout << "***** Testing dimensionality of 4 *****" << std::endl; if( RunTest<4>() == EXIT_FAILURE ) { testResult4 = EXIT_FAILURE; std::cout << "Failed for dimensionality 4." << std::endl; } if( testResult1 == EXIT_SUCCESS && testResult2 == EXIT_SUCCESS && testResult3 == EXIT_SUCCESS && testResult4 == EXIT_SUCCESS ) { std::cout << "TEST FINISHED SUCCESSFULLY!" << std::endl; } else { std::cout << "TEST FAILED!" << std::endl; testResult = EXIT_FAILURE; } return testResult; }
Improve coverage for itkGaussianInterpolateImageFunction.
ENH: Improve coverage for itkGaussianInterpolateImageFunction. Exercise the basic object methods. Exercise the EvaluateAtContinuousIndex function. Refactor the test: use the TEST_GET_SET macro for object ivar value testing; and use the itk::Math::FloatAlmostEquals for comparing two float values. Change-Id: If8d64ead98dbd82691641c7c1e76cc2f620e70f9
C++
apache-2.0
thewtex/ITK,hjmjohnson/ITK,Kitware/ITK,blowekamp/ITK,Kitware/ITK,malaterre/ITK,stnava/ITK,spinicist/ITK,hjmjohnson/ITK,thewtex/ITK,malaterre/ITK,stnava/ITK,Kitware/ITK,blowekamp/ITK,Kitware/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,malaterre/ITK,fbudin69500/ITK,stnava/ITK,BRAINSia/ITK,BRAINSia/ITK,thewtex/ITK,Kitware/ITK,thewtex/ITK,spinicist/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,LucasGandel/ITK,spinicist/ITK,BRAINSia/ITK,blowekamp/ITK,blowekamp/ITK,hjmjohnson/ITK,LucasGandel/ITK,vfonov/ITK,spinicist/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,PlutoniumHeart/ITK,spinicist/ITK,malaterre/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,stnava/ITK,vfonov/ITK,LucasGandel/ITK,PlutoniumHeart/ITK,spinicist/ITK,blowekamp/ITK,vfonov/ITK,fbudin69500/ITK,vfonov/ITK,fbudin69500/ITK,fbudin69500/ITK,thewtex/ITK,malaterre/ITK,BRAINSia/ITK,spinicist/ITK,fbudin69500/ITK,stnava/ITK,malaterre/ITK,PlutoniumHeart/ITK,vfonov/ITK,richardbeare/ITK,stnava/ITK,richardbeare/ITK,PlutoniumHeart/ITK,vfonov/ITK,stnava/ITK,hjmjohnson/ITK,blowekamp/ITK,richardbeare/ITK,BRAINSia/ITK,PlutoniumHeart/ITK,malaterre/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,LucasGandel/ITK,stnava/ITK,LucasGandel/ITK,hjmjohnson/ITK,hjmjohnson/ITK,Kitware/ITK,richardbeare/ITK,richardbeare/ITK,vfonov/ITK,blowekamp/ITK,blowekamp/ITK,LucasGandel/ITK,hjmjohnson/ITK,PlutoniumHeart/ITK,richardbeare/ITK,thewtex/ITK,stnava/ITK,spinicist/ITK,spinicist/ITK,LucasGandel/ITK,BRAINSia/ITK,fbudin69500/ITK,vfonov/ITK,BRAINSia/ITK
c72bf300e1019a1a82059778a00b29b574580d30
src/http_tls_shared.cc
src/http_tls_shared.cc
// // http_tls_shared.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstring> #include <iostream> #include <sstream> #include <functional> #include <algorithm> #include <thread> #include <mutex> #include <memory> #include <string> #include <vector> #include <deque> #include <map> #include <openssl/crypto.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "io.h" #include "hex.h" #include "url.h" #include "log.h" #include "socket.h" #include "resolver.h" #include "config_parser.h" #include "config.h" #include "pollset.h" #include "protocol.h" #include "http_tls_shared.h" /* http_tls_shared */ bool http_tls_shared::tls_session_debug = true; std::mutex http_tls_shared::session_mutex; http_tls_session_map http_tls_shared::session_map; std::once_flag http_tls_shared::lock_init_flag; std::vector<std::shared_ptr<std::mutex>> http_tls_shared::locks; void http_tls_shared::tls_threadid_function(CRYPTO_THREADID *thread_id) { CRYPTO_THREADID_set_pointer(thread_id, (void*)pthread_self()); } void http_tls_shared::tls_locking_function(int mode, int n, const char *file, int line) { std::call_once(lock_init_flag, [](){ size_t num_locks = CRYPTO_num_locks(); locks.resize(CRYPTO_num_locks()); for (size_t i = 0; i < num_locks; i++) { locks[i] = std::make_shared<std::mutex>(); } }); if (mode & CRYPTO_LOCK) { locks[n]->lock(); } else if (mode & CRYPTO_UNLOCK) { locks[n]->unlock(); } } int http_tls_shared::tls_log_errors(const char *str, size_t len, void *bio) { fprintf(stderr, "%s", str); return 0; } int http_tls_shared::tls_new_session_cb(struct ssl_st *ssl, SSL_SESSION *sess) { unsigned int sess_id_len; const unsigned char *sess_id = SSL_SESSION_get_id(sess, &sess_id_len); std::string sess_key = hex::encode(sess_id, sess_id_len); session_mutex.lock(); size_t sess_der_len = i2d_SSL_SESSION(sess, NULL); unsigned char *sess_der = new unsigned char[sess_der_len]; if (sess_der) { unsigned char *p = sess_der; i2d_SSL_SESSION(sess, &p); auto si = session_map.insert(http_tls_session_entry(sess_key, std::make_shared<http_tls_session>(sess_der, sess_der_len))); auto &tls_sess = *si.first->second; session_mutex.unlock(); if (tls_session_debug) { log_debug("%s: added session: id=%s len=%lu", __func__, sess_key.c_str(), tls_sess.sess_der_len); } return 0; } else { if (tls_session_debug) { log_debug("%s: failed to add session: id=%s", __func__, sess_key.c_str()); } session_mutex.unlock(); return -1; } } void http_tls_shared::tls_remove_session_cb(struct ssl_ctx_st *ctx, SSL_SESSION *sess) { unsigned int sess_id_len; const unsigned char *sess_id = SSL_SESSION_get_id(sess, &sess_id_len); std::string sess_key = hex::encode(sess_id, sess_id_len); session_mutex.lock(); session_map.erase(sess_key); session_mutex.unlock(); if (tls_session_debug) { log_debug("%s: removed session: id=%s", __func__, sess_key.c_str()); } } SSL_SESSION * http_tls_shared::tls_get_session_cb(struct ssl_st *ssl, unsigned char *sess_id, int sess_id_len, int *copy) { *copy = 0; std::string sess_key = hex::encode(sess_id, sess_id_len); session_mutex.lock(); auto si = session_map.find(sess_key); if (si != session_map.end()) { auto &tls_sess = *si->second; session_mutex.unlock(); // TODO - implement session timeout if (tls_session_debug) { log_debug("%s: lookup session: cache hit: id=%s len=%lu", __func__, sess_key.c_str(), tls_sess.sess_der_len); } unsigned const char *p = tls_sess.sess_der; return d2i_SSL_SESSION(NULL, &p, tls_sess.sess_der_len); } session_mutex.unlock(); if (tls_session_debug) { log_debug("%s: lookup session: cache miss: id=%s", __func__, sess_key.c_str()); } return nullptr; } SSL_CTX* http_tls_shared::init_client(protocol *proto, config_ptr cfg) { SSL_library_init(); SSL_load_error_strings(); CRYPTO_set_locking_callback(http_tls_shared::tls_locking_function); CRYPTO_THREADID_set_callback(http_tls_shared::tls_threadid_function); SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method()); #ifdef SSL_OP_NO_SSLv2 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); #endif #ifdef SSL_OP_NO_SSLv3 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3); #endif #ifdef SSL_OP_NO_COMPRESSION SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); #endif if ((!SSL_CTX_load_verify_locations(ctx, cfg->tls_ca_file.c_str(), NULL)) || (!SSL_CTX_set_default_verify_paths(ctx))) { ERR_print_errors_cb(http_tls_shared::tls_log_errors, NULL); log_fatal_exit("%s failed to load cacert: %s", proto->name.c_str(), cfg->tls_ca_file.c_str()); } else { log_debug("%s loaded cacert: %s", proto->name.c_str(), cfg->tls_ca_file.c_str()); } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_verify_depth(ctx, 9); return ctx; } SSL_CTX* http_tls_shared::init_server(protocol *proto, config_ptr cfg) { SSL_library_init(); SSL_load_error_strings(); CRYPTO_set_locking_callback(http_tls_shared::tls_locking_function); CRYPTO_THREADID_set_callback(http_tls_shared::tls_threadid_function); SSL_CTX *ctx = SSL_CTX_new(SSLv23_server_method()); #ifdef SSL_OP_NO_SSLv2 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); #endif #ifdef SSL_OP_NO_SSLv3 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3); #endif #ifdef SSL_OP_NO_COMPRESSION SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); #endif #if 0 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_AUTO_CLEAR | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(ctx, http_tls_shared::tls_new_session_cb); SSL_CTX_sess_set_remove_cb(ctx, http_tls_shared::tls_remove_session_cb); SSL_CTX_sess_set_get_cb(ctx, http_tls_shared::tls_get_session_cb); #endif if (SSL_CTX_use_certificate_file(ctx, cfg->tls_cert_file.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_cb(http_tls_shared::tls_log_errors, NULL); log_fatal_exit("%s failed to load certificate: %s", proto->name.c_str(), cfg->tls_cert_file.c_str()); } else { log_info("%s loaded cert: %s", proto->name.c_str(), cfg->tls_cert_file.c_str()); } if (SSL_CTX_use_PrivateKey_file(ctx, cfg->tls_key_file.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_cb(http_tls_shared::tls_log_errors, NULL); log_fatal_exit("%s failed to load private key: %s", proto->name.c_str(), cfg->tls_key_file.c_str()); } else { log_info("%s loaded key: %s", proto->name.c_str(), cfg->tls_key_file.c_str()); } return ctx; }
// // http_tls_shared.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstring> #include <iostream> #include <sstream> #include <functional> #include <algorithm> #include <thread> #include <mutex> #include <memory> #include <string> #include <vector> #include <deque> #include <map> #include <openssl/crypto.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "io.h" #include "hex.h" #include "url.h" #include "log.h" #include "socket.h" #include "resolver.h" #include "config_parser.h" #include "config.h" #include "pollset.h" #include "protocol.h" #include "http_tls_shared.h" /* http_tls_shared */ bool http_tls_shared::tls_session_debug = true; std::mutex http_tls_shared::session_mutex; http_tls_session_map http_tls_shared::session_map; std::once_flag http_tls_shared::lock_init_flag; std::vector<std::shared_ptr<std::mutex>> http_tls_shared::locks; void http_tls_shared::tls_threadid_function(CRYPTO_THREADID *thread_id) { CRYPTO_THREADID_set_pointer(thread_id, (void*)pthread_self()); } void http_tls_shared::tls_locking_function(int mode, int n, const char *file, int line) { std::call_once(lock_init_flag, [](){ size_t num_locks = CRYPTO_num_locks(); locks.resize(CRYPTO_num_locks()); for (size_t i = 0; i < num_locks; i++) { locks[i] = std::make_shared<std::mutex>(); } }); if (mode & CRYPTO_LOCK) { locks[n]->lock(); } else if (mode & CRYPTO_UNLOCK) { locks[n]->unlock(); } } int http_tls_shared::tls_log_errors(const char *str, size_t len, void *bio) { fprintf(stderr, "%s", str); return 0; } int http_tls_shared::tls_new_session_cb(struct ssl_st *ssl, SSL_SESSION *sess) { unsigned int sess_id_len; const unsigned char *sess_id = SSL_SESSION_get_id(sess, &sess_id_len); std::string sess_key = hex::encode(sess_id, sess_id_len); session_mutex.lock(); size_t sess_der_len = i2d_SSL_SESSION(sess, NULL); unsigned char *sess_der = new unsigned char[sess_der_len]; if (sess_der) { unsigned char *p = sess_der; i2d_SSL_SESSION(sess, &p); auto si = session_map.insert(http_tls_session_entry(sess_key, std::make_shared<http_tls_session>(sess_der, sess_der_len))); auto &tls_sess = *si.first->second; session_mutex.unlock(); if (tls_session_debug) { log_debug("%s: added session: id=%s len=%lu", __func__, sess_key.c_str(), tls_sess.sess_der_len); } return 0; } else { if (tls_session_debug) { log_debug("%s: failed to add session: id=%s", __func__, sess_key.c_str()); } session_mutex.unlock(); return -1; } } void http_tls_shared::tls_remove_session_cb(struct ssl_ctx_st *ctx, SSL_SESSION *sess) { unsigned int sess_id_len; const unsigned char *sess_id = SSL_SESSION_get_id(sess, &sess_id_len); std::string sess_key = hex::encode(sess_id, sess_id_len); session_mutex.lock(); session_map.erase(sess_key); session_mutex.unlock(); if (tls_session_debug) { log_debug("%s: removed session: id=%s", __func__, sess_key.c_str()); } } SSL_SESSION * http_tls_shared::tls_get_session_cb(struct ssl_st *ssl, unsigned char *sess_id, int sess_id_len, int *copy) { *copy = 0; std::string sess_key = hex::encode(sess_id, sess_id_len); session_mutex.lock(); auto si = session_map.find(sess_key); if (si != session_map.end()) { auto &tls_sess = *si->second; session_mutex.unlock(); // TODO - implement session timeout if (tls_session_debug) { log_debug("%s: lookup session: cache hit: id=%s len=%lu", __func__, sess_key.c_str(), tls_sess.sess_der_len); } unsigned const char *p = tls_sess.sess_der; return d2i_SSL_SESSION(NULL, &p, tls_sess.sess_der_len); } session_mutex.unlock(); if (tls_session_debug) { log_debug("%s: lookup session: cache miss: id=%s", __func__, sess_key.c_str()); } return nullptr; } SSL_CTX* http_tls_shared::init_client(protocol *proto, config_ptr cfg) { SSL_library_init(); SSL_load_error_strings(); CRYPTO_set_locking_callback(http_tls_shared::tls_locking_function); CRYPTO_THREADID_set_callback(http_tls_shared::tls_threadid_function); SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method()); #ifdef SSL_OP_NO_SSLv2 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); #endif #ifdef SSL_OP_NO_SSLv3 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3); #endif #ifdef SSL_OP_NO_COMPRESSION SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); #endif if ((!SSL_CTX_load_verify_locations(ctx, cfg->tls_ca_file.c_str(), NULL)) || (!SSL_CTX_set_default_verify_paths(ctx))) { ERR_print_errors_cb(http_tls_shared::tls_log_errors, NULL); log_fatal_exit("%s failed to load cacert: %s", proto->name.c_str(), cfg->tls_ca_file.c_str()); } else { log_debug("%s loaded cacert: %s", proto->name.c_str(), cfg->tls_ca_file.c_str()); } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_verify_depth(ctx, 9); return ctx; } SSL_CTX* http_tls_shared::init_server(protocol *proto, config_ptr cfg) { SSL_library_init(); SSL_load_error_strings(); CRYPTO_set_locking_callback(http_tls_shared::tls_locking_function); CRYPTO_THREADID_set_callback(http_tls_shared::tls_threadid_function); SSL_CTX *ctx = SSL_CTX_new(SSLv23_server_method()); #ifdef SSL_OP_NO_SSLv2 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); #endif #ifdef SSL_OP_NO_SSLv3 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3); #endif #ifdef SSL_OP_NO_COMPRESSION SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); #endif SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET); SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_AUTO_CLEAR | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(ctx, http_tls_shared::tls_new_session_cb); SSL_CTX_sess_set_remove_cb(ctx, http_tls_shared::tls_remove_session_cb); SSL_CTX_sess_set_get_cb(ctx, http_tls_shared::tls_get_session_cb); if (SSL_CTX_use_certificate_file(ctx, cfg->tls_cert_file.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_cb(http_tls_shared::tls_log_errors, NULL); log_fatal_exit("%s failed to load certificate: %s", proto->name.c_str(), cfg->tls_cert_file.c_str()); } else { log_info("%s loaded cert: %s", proto->name.c_str(), cfg->tls_cert_file.c_str()); } if (SSL_CTX_use_PrivateKey_file(ctx, cfg->tls_key_file.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_cb(http_tls_shared::tls_log_errors, NULL); log_fatal_exit("%s failed to load private key: %s", proto->name.c_str(), cfg->tls_key_file.c_str()); } else { log_info("%s loaded key: %s", proto->name.c_str(), cfg->tls_key_file.c_str()); } return ctx; }
Disable session tickets
Disable session tickets
C++
isc
metaparadigm/latypus,metaparadigm/latypus,metaparadigm/latypus,metaparadigm/latypus
7875a103b76e457474c444f7a19e39a572ef2147
src/AttentionNoticeHandler.cc
src/AttentionNoticeHandler.cc
// AttentionNoticeHandler.cc for fluxbox // Copyright (c) 2006 Fluxbox Team (fluxgen at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id$ #include "AttentionNoticeHandler.hh" #include "WinClient.hh" #include "Screen.hh" #include "STLUtil.hh" #include "FbTk/Subject.hh" #include "FbTk/Timer.hh" #include "FbTk/Resource.hh" namespace { class ToggleFrameFocusCmd: public FbTk::Command { public: ToggleFrameFocusCmd(WinClient &client): m_client(client) {} void execute() { m_state ^= true; m_client.fbwindow()->setLabelButtonFocus(m_client, m_state); m_client.fbwindow()->setAttentionState(m_state); } private: WinClient& m_client; bool m_state; }; } // end anonymous namespace AttentionNoticeHandler::~AttentionNoticeHandler() { STLUtil::destroyAndClearSecond(m_attentions); } void AttentionNoticeHandler::addAttention(WinClient &client) { // no need to add already active client if (client.fbwindow()->isFocused() && &client.fbwindow()->winClient() == &client) return; // Already have a notice for it? NoticeMap::iterator it = m_attentions.find(&client); if (it != m_attentions.end()) { return; } using namespace FbTk; ResourceManager &res = client.screen().resourceManager(); std::string res_name = client.screen().name() + ".demandsAttentionTimeout"; std::string res_alt_name = client.screen().name() + ".DemandsAttentionTimeout"; Resource<int> *timeout_res = dynamic_cast<Resource<int>* >(res.findResource(res_name)); if (timeout_res == 0) { // no resource, create one and add it to managed resources timeout_res = new FbTk::Resource<int>(res, 500, res_name, res_alt_name); client.screen().addManagedResource(timeout_res); } // disable if timeout is zero if (**timeout_res == 0) return; Timer *timer = new Timer(); // setup timer timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = **timeout_res * 1000; RefCount<Command> cmd(new ToggleFrameFocusCmd(client)); timer->setCommand(cmd); timer->setTimeout(timeout); timer->fireOnce(false); // will repeat until window has focus timer->start(); m_attentions[&client] = timer; // attach signals that will make notice go away client.dieSig().attach(this); client.focusSig().attach(this); } void AttentionNoticeHandler::update(FbTk::Subject *subj) { // all signals results in destruction of the notice WinClient::WinClientSubj *winsubj = static_cast<WinClient::WinClientSubj *>(subj); delete m_attentions[&winsubj->winClient()]; m_attentions.erase(&winsubj->winClient()); }
// AttentionNoticeHandler.cc for fluxbox // Copyright (c) 2006 Fluxbox Team (fluxgen at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id$ #include "AttentionNoticeHandler.hh" #include "WinClient.hh" #include "Screen.hh" #include "STLUtil.hh" #include "FbTk/Subject.hh" #include "FbTk/Timer.hh" #include "FbTk/Resource.hh" namespace { class ToggleFrameFocusCmd: public FbTk::Command { public: ToggleFrameFocusCmd(WinClient &client): m_client(client), m_state(false) {} void execute() { m_state ^= true; m_client.fbwindow()->setLabelButtonFocus(m_client, m_state); m_client.fbwindow()->setAttentionState(m_state); } private: WinClient& m_client; bool m_state; }; } // end anonymous namespace AttentionNoticeHandler::~AttentionNoticeHandler() { STLUtil::destroyAndClearSecond(m_attentions); } void AttentionNoticeHandler::addAttention(WinClient &client) { // no need to add already active client if (client.fbwindow()->isFocused() && &client.fbwindow()->winClient() == &client) return; // Already have a notice for it? NoticeMap::iterator it = m_attentions.find(&client); if (it != m_attentions.end()) { return; } using namespace FbTk; ResourceManager &res = client.screen().resourceManager(); std::string res_name = client.screen().name() + ".demandsAttentionTimeout"; std::string res_alt_name = client.screen().name() + ".DemandsAttentionTimeout"; Resource<int> *timeout_res = dynamic_cast<Resource<int>* >(res.findResource(res_name)); if (timeout_res == 0) { // no resource, create one and add it to managed resources timeout_res = new FbTk::Resource<int>(res, 500, res_name, res_alt_name); client.screen().addManagedResource(timeout_res); } // disable if timeout is zero if (**timeout_res == 0) return; Timer *timer = new Timer(); // setup timer timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = **timeout_res * 1000; RefCount<Command> cmd(new ToggleFrameFocusCmd(client)); timer->setCommand(cmd); timer->setTimeout(timeout); timer->fireOnce(false); // will repeat until window has focus timer->start(); m_attentions[&client] = timer; // attach signals that will make notice go away client.dieSig().attach(this); client.focusSig().attach(this); } void AttentionNoticeHandler::update(FbTk::Subject *subj) { // all signals results in destruction of the notice WinClient::WinClientSubj *winsubj = static_cast<WinClient::WinClientSubj *>(subj); delete m_attentions[&winsubj->winClient()]; m_attentions.erase(&winsubj->winClient()); }
initialize m_state
initialize m_state
C++
mit
naimdjon/fluxbox,lukoko/fluxbox,lukoko/fluxbox,olivergondza/fluxbox,naimdjon/fluxbox,Arkq/fluxbox,naimdjon/fluxbox,olivergondza/fluxbox,luebking/fluxbox,lukoko/fluxbox,naimdjon/fluxbox,olivergondza/fluxbox,lukoko/fluxbox,luebking/fluxbox,luebking/fluxbox,Arkq/fluxbox,Arkq/fluxbox,naimdjon/fluxbox,olivergondza/fluxbox,Arkq/fluxbox,luebking/fluxbox,luebking/fluxbox,olivergondza/fluxbox,lukoko/fluxbox,Arkq/fluxbox
24db75038638e1727dd3b1702d51724f384d13ff
paddle/fluid/inference/tensorrt/trt_int8_calibrator.cc
paddle/fluid/inference/tensorrt/trt_int8_calibrator.cc
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/tensorrt/trt_int8_calibrator.h" #include "glog/logging.h" namespace paddle { namespace inference { namespace tensorrt { // set the batch size before constructing the thread to execute engine int TRTInt8Calibrator::getBatchSize() const { return batch_size_; } TRTInt8Calibrator::TRTInt8Calibrator( const std::unordered_map<std::string, size_t>& buffers, int batch_size, std::string engine_name, const platform::Place place) : batch_size_(batch_size), engine_name_(engine_name) { int i = 0; VLOG(4) << "Init a new calibrator: " << engine_name_; for (const auto it : buffers) { framework::Tensor temp_tensor; std::string input_name = it.first; int data_size = it.second; int num_ele = data_size / sizeof(int16_t); framework::DDim data_shape = framework::make_ddim({num_ele}); temp_tensor.Resize(data_shape); data_tensors_.push_back(temp_tensor); data_buffers_[input_name] = std::pair<void*, size_t>( static_cast<void*>(temp_tensor.mutable_data<int16_t>(place)), num_ele); i += 1; } } TRTInt8Calibrator::TRTInt8Calibrator(const std::string& calib_data) : batch_size_(0), calib_running_(false), data_is_set_(false), done_(true), calibration_table_(calib_data) {} void TRTInt8Calibrator::waitAndSetDone() { std::unique_lock<std::mutex> lk(mut_); while ((calib_running_ || data_is_set_) && !done_) cond_.wait(lk); if (!done_) { done_ = true; cond_.notify_all(); } } // There might be more than one input for trt subgraph, // So, we use a map to store input information. bool TRTInt8Calibrator::setBatch( const std::unordered_map<std::string, void*>& data) { VLOG(3) << "set batch: " << engine_name_; std::unique_lock<std::mutex> lk(mut_); // There is a producer and a consumer. The producer set the batch data and // the consumer get the batch data. The size of the data pool is one. // So, the producer has to wait for the consumer to finish processing before // they can set the data. while ((calib_running_ || data_is_set_) && (!done_)) cond_.wait(lk); // The done_ is set to true using waitAndSetDone, When all calibration data // are processed. if (done_) return false; // Sets the batch. for (const auto& it : data) { auto dataptr = data_buffers_.find(it.first); if (dataptr == data_buffers_.end()) { LOG(FATAL) << "FATAL " << engine_name_ << " input name '" << it.first << "' does not match with the buffer names"; } const auto& d = dataptr->second; PADDLE_ENFORCE( cudaMemcpy(d.first, it.second, d.second, cudaMemcpyDeviceToDevice), "Fail to cudaMemcpy %s for %s", engine_name_, it.first); } data_is_set_ = true; cond_.notify_all(); return true; } bool TRTInt8Calibrator::getBatch(void** bindings, const char** names, int num_bindings) { VLOG(4) << "get batch: " << engine_name_; std::unique_lock<std::mutex> lk(mut_); // The consumer has just finished processing a data. // The producer can set the data again. calib_running_ = false; cond_.notify_all(); // As long as there is data in the pool, the consumer can get it. while (!data_is_set_ && !done_) cond_.wait(lk); if (done_) return false; // Gets the batch for (int i = 0; i < num_bindings; i++) { auto it = data_buffers_.find(names[i]); if (it == data_buffers_.end()) { LOG(FATAL) << "Calibration engine asked for unknown tensor name '" << names[i] << "' at position " << i; } bindings[i] = it->second.first; } data_is_set_ = false; calib_running_ = true; VLOG(4) << "get batch done: " << engine_name_; return true; } void TRTInt8Calibrator::setDone() { std::unique_lock<std::mutex> lk(mut_); done_ = true; cond_.notify_all(); } const void* TRTInt8Calibrator::readCalibrationCache(size_t& length) { if (calibration_table_.empty()) return nullptr; length = calibration_table_.size(); return calibration_table_.data(); } void TRTInt8Calibrator::writeCalibrationCache(const void* ptr, std::size_t length) { calibration_table_ = std::string((const char*)ptr, length); VLOG(4) << "Got calibration data for " << engine_name_ << " " << ptr << " length=" << length; } TRTInt8Calibrator::~TRTInt8Calibrator() { VLOG(4) << "Destroying calibrator for " << engine_name_; } } // namespace tensorrt } // namespace inference } // namespace paddle
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/tensorrt/trt_int8_calibrator.h" #include "glog/logging.h" namespace paddle { namespace inference { namespace tensorrt { // set the batch size before constructing the thread to execute engine int TRTInt8Calibrator::getBatchSize() const { return batch_size_; } TRTInt8Calibrator::TRTInt8Calibrator( const std::unordered_map<std::string, size_t>& buffers, int batch_size, std::string engine_name, const platform::Place place) : batch_size_(batch_size), engine_name_(engine_name) { int i = 0; VLOG(4) << "Init a new calibrator: " << engine_name_; for (const auto it : buffers) { framework::Tensor temp_tensor; std::string input_name = it.first; int data_size = it.second; int num_ele = data_size / sizeof(int16_t); framework::DDim data_shape = framework::make_ddim({num_ele}); temp_tensor.Resize(data_shape); data_tensors_.push_back(temp_tensor); data_buffers_[input_name] = std::pair<void*, size_t>( static_cast<void*>(temp_tensor.mutable_data<int16_t>(place)), data_size); i += 1; } } TRTInt8Calibrator::TRTInt8Calibrator(const std::string& calib_data) : batch_size_(0), calib_running_(false), data_is_set_(false), done_(true), calibration_table_(calib_data) {} void TRTInt8Calibrator::waitAndSetDone() { std::unique_lock<std::mutex> lk(mut_); while ((calib_running_ || data_is_set_) && !done_) cond_.wait(lk); if (!done_) { done_ = true; cond_.notify_all(); } } // There might be more than one input for trt subgraph, // So, we use a map to store input information. bool TRTInt8Calibrator::setBatch( const std::unordered_map<std::string, void*>& data) { VLOG(3) << "set batch: " << engine_name_; std::unique_lock<std::mutex> lk(mut_); // There is a producer and a consumer. The producer set the batch data and // the consumer get the batch data. The size of the data pool is one. // So, the producer has to wait for the consumer to finish processing before // they can set the data. while ((calib_running_ || data_is_set_) && (!done_)) cond_.wait(lk); // The done_ is set to true using waitAndSetDone, When all calibration data // are processed. if (done_) return false; // Sets the batch. for (const auto& it : data) { auto dataptr = data_buffers_.find(it.first); if (dataptr == data_buffers_.end()) { LOG(FATAL) << "FATAL " << engine_name_ << " input name '" << it.first << "' does not match with the buffer names"; } const auto& d = dataptr->second; PADDLE_ENFORCE( cudaMemcpy(d.first, it.second, d.second, cudaMemcpyDeviceToDevice), "Fail to cudaMemcpy %s for %s", engine_name_, it.first); } data_is_set_ = true; cond_.notify_all(); return true; } bool TRTInt8Calibrator::getBatch(void** bindings, const char** names, int num_bindings) { VLOG(4) << "get batch: " << engine_name_; std::unique_lock<std::mutex> lk(mut_); // The consumer has just finished processing a data. // The producer can set the data again. calib_running_ = false; cond_.notify_all(); // As long as there is data in the pool, the consumer can get it. while (!data_is_set_ && !done_) cond_.wait(lk); if (done_) return false; // Gets the batch for (int i = 0; i < num_bindings; i++) { auto it = data_buffers_.find(names[i]); if (it == data_buffers_.end()) { LOG(FATAL) << "Calibration engine asked for unknown tensor name '" << names[i] << "' at position " << i; } bindings[i] = it->second.first; } data_is_set_ = false; calib_running_ = true; VLOG(4) << "get batch done: " << engine_name_; return true; } void TRTInt8Calibrator::setDone() { std::unique_lock<std::mutex> lk(mut_); done_ = true; cond_.notify_all(); } const void* TRTInt8Calibrator::readCalibrationCache(size_t& length) { if (calibration_table_.empty()) return nullptr; length = calibration_table_.size(); return calibration_table_.data(); } void TRTInt8Calibrator::writeCalibrationCache(const void* ptr, std::size_t length) { calibration_table_ = std::string((const char*)ptr, length); VLOG(4) << "Got calibration data for " << engine_name_ << " " << ptr << " length=" << length; } TRTInt8Calibrator::~TRTInt8Calibrator() { VLOG(4) << "Destroying calibrator for " << engine_name_; } } // namespace tensorrt } // namespace inference } // namespace paddle
fix trt int8 calib precision bug. test=develop (#23036)
fix trt int8 calib precision bug. test=develop (#23036)
C++
apache-2.0
PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle
e76569420571fc606b439ee0bca694659923ac05
src/widgets/restoredialog.cpp
src/widgets/restoredialog.cpp
#include "restoredialog.h" WARNINGS_DISABLE #include <QChar> #include <QCheckBox> #include <QDir> #include <QFileDialog> #include <QFileInfo> #include <QLabel> #include <QLineEdit> #include <QVariant> #include <Qt> #include "ui_restoredialog.h" WARNINGS_ENABLE #include "TSettings.h" #include "messages/archiverestoreoptions.h" #include "persistentmodel/archive.h" #include "tasks/tasks-defs.h" RestoreDialog::RestoreDialog(QWidget *parent, ArchivePtr archive, const QStringList &files) : QDialog(parent), _ui(new Ui::RestoreDialog), _archive(archive), _files(files) { _ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); // Set up download directory (default for "... to specified directory"). TSettings settings; _downDir = settings.value("app/downloads_dir", DEFAULT_DOWNLOADS).toString(); _ui->baseDirLineEdit->setText(_downDir); // Set up filename (default for "... uncompressed tar archive"). QString fileName(_archive->name() + ".tar"); // Replace chars that are problematic on common file systems but are allowed // in tarsnap archive names fileName = fileName.replace(QChar(':'), QChar('-')) .replace(QChar('/'), QChar('-')) .replace(QChar('\\'), QChar('-')); QFileInfo archiveFile(QDir(_downDir), fileName); archiveFile.makeAbsolute(); _ui->archiveLineEdit->setText(archiveFile.absoluteFilePath()); // Hide widgets not needed by default. _ui->baseDirLineEdit->hide(); _ui->changeDirButton->hide(); _ui->archiveLineEdit->hide(); _ui->changeArchiveButton->hide(); // Connections for basic UI operations. connect(_ui->cancelButton, &QPushButton::clicked, this, &QDialog::reject); connect(_ui->restoreButton, &QPushButton::clicked, [this]() { if(validate()) accept(); }); // Connections for the "restore archive to..." options. connect(_ui->optionRestoreRadio, &QRadioButton::toggled, this, &RestoreDialog::optionRestoreToggled); connect(_ui->optionBaseDirRadio, &QRadioButton::toggled, this, &RestoreDialog::optionBaseDirToggled); connect(_ui->optionTarArchiveRadio, &QRadioButton::toggled, this, &RestoreDialog::optionTarArchiveToggled); // Connections to modify the "restore archive to..." options. connect(_ui->baseDirLineEdit, &QLineEdit::textChanged, this, &RestoreDialog::validate); connect(_ui->changeDirButton, &QPushButton::clicked, this, &RestoreDialog::changeDir); connect(_ui->archiveLineEdit, &QLineEdit::textChanged, this, &RestoreDialog::validate); connect(_ui->changeArchiveButton, &QPushButton::clicked, this, &RestoreDialog::changeArchive); // Connection for other options. connect(_ui->overwriteCheckBox, &QCheckBox::toggled, [this](bool checked) { _ui->keepNewerCheckBox->setChecked(checked); _ui->keepNewerCheckBox->setEnabled(checked); }); // Was the archive created with the `tarsnap -P` option? bool canRestore = _archive->hasPreservePaths(); displayRestoreOption(canRestore); // Set the default location to which to restore. _ui->optionRestoreRadio->setChecked(canRestore); _ui->optionBaseDirRadio->setChecked(!canRestore); // If we have a specific list of files, display them. if(!_files.isEmpty()) { _ui->filesListWidget->addItems(_files); } else { if(_archive->contents().isEmpty()) { // If we have no files to display, hide the list. _ui->filesListWidget->hide(); adjustSize(); } else { // Add all the files to the list. _ui->filesListWidget->addItems( _archive->contents().split(QChar('\n'))); _ui->filesListWidget->show(); adjustSize(); } } } RestoreDialog::~RestoreDialog() { delete _ui; } ArchiveRestoreOptions RestoreDialog::getOptions() { // Set options based on the UI. ArchiveRestoreOptions options; options.optionRestore = _ui->optionRestoreRadio->isChecked(); options.optionRestoreDir = _ui->optionBaseDirRadio->isChecked(); options.optionTarArchive = _ui->optionTarArchiveRadio->isChecked(); options.overwriteFiles = _ui->overwriteCheckBox->isChecked(); options.keepNewerFiles = _ui->keepNewerCheckBox->isChecked(); options.preservePerms = _ui->preservePermCheckBox->isChecked(); options.files = _files; // The meaning of 'path' depends on 'optionRestoreDir' and // 'optionTarArchive'. if(options.optionRestoreDir) options.path = _ui->baseDirLineEdit->text(); else if(options.optionTarArchive) options.path = _ui->archiveLineEdit->text(); return options; } void RestoreDialog::displayRestoreOption(bool display) { _ui->optionRestoreRadio->setVisible(display); adjustSize(); } void RestoreDialog::displayTarOption(bool display) { _ui->optionTarArchiveRadio->setVisible(display); adjustSize(); } void RestoreDialog::optionBaseDirToggled(bool checked) { _ui->infoLabel->setText(tr("Restore from archive <b>%1</b> to specified" " directory? Any existing files will not be" " replaced by default. Use the options below to" " modify this behavior:") .arg(_archive->name())); _ui->baseDirLineEdit->setVisible(checked); _ui->changeDirButton->setVisible(checked); _ui->overwriteCheckBox->setVisible(checked); _ui->keepNewerCheckBox->setVisible(checked); _ui->preservePermCheckBox->setVisible(checked); adjustSize(); } void RestoreDialog::optionTarArchiveToggled(bool checked) { _ui->infoLabel->setText(tr("Download archive <b>%1</b> contents as an" " uncompressed TAR archive?") .arg(_archive->name())); _ui->archiveLineEdit->setVisible(checked); _ui->changeArchiveButton->setVisible(checked); adjustSize(); } void RestoreDialog::optionRestoreToggled(bool checked) { _ui->infoLabel->setText(tr("Restore from archive <b>%1</b> to original" " locations? Any existing files will not be" " replaced by default. Use the options below to" " modify this behavior:") .arg(_archive->name())); _ui->overwriteCheckBox->setVisible(checked); _ui->keepNewerCheckBox->setVisible(checked); _ui->preservePermCheckBox->setVisible(checked); adjustSize(); } void RestoreDialog::changeDir() { QString path = QFileDialog::getExistingDirectory(this, tr("Directory to restore to"), _downDir); if(!path.isEmpty()) _ui->baseDirLineEdit->setText(path); } void RestoreDialog::changeArchive() { QString path = QFileDialog::getSaveFileName(this, tr("Select tar archive file"), _ui->archiveLineEdit->text(), tr("Tar archives (*.tar)")); if(!path.isEmpty()) _ui->archiveLineEdit->setText(path); } bool RestoreDialog::validate() { bool valid = true; // Check that we have valid options, depending on which type of restore. if(_ui->optionBaseDirRadio->isChecked()) { QFileInfo dir(_ui->baseDirLineEdit->text()); if(dir.exists() && dir.isDir()) { _ui->baseDirLineEdit->setStyleSheet("QLineEdit{color:black;}"); _ui->baseDirLineEdit->setToolTip( tr("Set base directory to extract archive contents to")); } else { _ui->baseDirLineEdit->setStyleSheet("QLineEdit{color:red;}"); _ui->baseDirLineEdit->setToolTip( tr("Invalid base directory, please choose a different one")); valid = false; } } else if(_ui->optionTarArchiveRadio->isChecked()) { QFileInfo archive(_ui->archiveLineEdit->text()); if(archive.exists()) { _ui->archiveLineEdit->setStyleSheet("QLineEdit{color:red;}"); _ui->archiveLineEdit->setToolTip( tr("File exists, please choose a different file name")); valid = false; } else { _ui->archiveLineEdit->setStyleSheet("QLineEdit{color:black;}"); _ui->archiveLineEdit->setToolTip(tr("Set archive file name")); } } return valid; } ArchivePtr RestoreDialog::archive() const { return _archive; }
#include "restoredialog.h" WARNINGS_DISABLE #include <QChar> #include <QCheckBox> #include <QDir> #include <QFileDialog> #include <QFileInfo> #include <QLabel> #include <QLineEdit> #include <QVariant> #include <Qt> #include "ui_restoredialog.h" WARNINGS_ENABLE #include "TSettings.h" #include "messages/archiverestoreoptions.h" #include "persistentmodel/archive.h" #include "tasks/tasks-defs.h" RestoreDialog::RestoreDialog(QWidget *parent, ArchivePtr archive, const QStringList &files) : QDialog(parent), _ui(new Ui::RestoreDialog), _archive(archive), _files(files) { _ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); // Set up download directory (default for "... to specified directory"). TSettings settings; _downDir = settings.value("app/downloads_dir", DEFAULT_DOWNLOADS).toString(); _ui->baseDirLineEdit->setText(_downDir); // Set up filename (default for "... uncompressed tar archive"). QString fileName(_archive->name() + ".tar"); // Replace chars that are problematic on common file systems but are allowed // in tarsnap archive names fileName = fileName.replace(QChar(':'), QChar('-')) .replace(QChar('/'), QChar('-')) .replace(QChar('\\'), QChar('-')); QFileInfo archiveFile(QDir(_downDir), fileName); archiveFile.makeAbsolute(); _ui->archiveLineEdit->setText(archiveFile.absoluteFilePath()); // Hide widgets not needed by default. _ui->baseDirLineEdit->hide(); _ui->changeDirButton->hide(); _ui->archiveLineEdit->hide(); _ui->changeArchiveButton->hide(); // Connections for basic UI operations. connect(_ui->cancelButton, &QPushButton::clicked, this, &QDialog::reject); connect(_ui->restoreButton, &QPushButton::clicked, [this]() { if(validate()) accept(); }); // Connections for the "restore archive to..." options. connect(_ui->optionRestoreRadio, &QRadioButton::toggled, this, &RestoreDialog::optionRestoreToggled); connect(_ui->optionBaseDirRadio, &QRadioButton::toggled, this, &RestoreDialog::optionBaseDirToggled); connect(_ui->optionTarArchiveRadio, &QRadioButton::toggled, this, &RestoreDialog::optionTarArchiveToggled); // Connections to modify the "restore archive to..." options. connect(_ui->baseDirLineEdit, &QLineEdit::textChanged, this, &RestoreDialog::validate); connect(_ui->changeDirButton, &QPushButton::clicked, this, &RestoreDialog::changeDir); connect(_ui->archiveLineEdit, &QLineEdit::textChanged, this, &RestoreDialog::validate); connect(_ui->changeArchiveButton, &QPushButton::clicked, this, &RestoreDialog::changeArchive); // Connection for other options. connect(_ui->overwriteCheckBox, &QCheckBox::toggled, [this](bool checked) { _ui->keepNewerCheckBox->setChecked(checked); _ui->keepNewerCheckBox->setEnabled(checked); }); // Was the archive created with the `tarsnap -P` option? bool canRestore = _archive->hasPreservePaths(); displayRestoreOption(canRestore); // Set the default location to which to restore. _ui->optionRestoreRadio->setChecked(canRestore); _ui->optionBaseDirRadio->setChecked(!canRestore); // If we have a specific list of files, display them. if(!_files.isEmpty()) { _ui->filesListWidget->addItems(_files); } else { if(_archive->contents().isEmpty()) { // If we have no files to display, hide the list. _ui->filesListWidget->hide(); adjustSize(); } else { // Add all the files to the list. _ui->filesListWidget->addItems( _archive->contents().split(QChar('\n'))); _ui->filesListWidget->show(); adjustSize(); } } } RestoreDialog::~RestoreDialog() { delete _ui; } ArchiveRestoreOptions RestoreDialog::getOptions() { // Set options based on the UI. ArchiveRestoreOptions options; options.optionRestore = _ui->optionRestoreRadio->isChecked(); options.optionRestoreDir = _ui->optionBaseDirRadio->isChecked(); options.optionTarArchive = _ui->optionTarArchiveRadio->isChecked(); options.overwriteFiles = _ui->overwriteCheckBox->isChecked(); options.keepNewerFiles = _ui->keepNewerCheckBox->isChecked(); options.preservePerms = _ui->preservePermCheckBox->isChecked(); options.files = _files; // The meaning of 'path' depends on 'optionRestoreDir' and // 'optionTarArchive'. if(options.optionRestoreDir) options.path = _ui->baseDirLineEdit->text(); else if(options.optionTarArchive) options.path = _ui->archiveLineEdit->text(); else options.path = ""; // (should not be necessary, but clarifies code) return options; } void RestoreDialog::displayRestoreOption(bool display) { _ui->optionRestoreRadio->setVisible(display); adjustSize(); } void RestoreDialog::displayTarOption(bool display) { _ui->optionTarArchiveRadio->setVisible(display); adjustSize(); } void RestoreDialog::optionBaseDirToggled(bool checked) { _ui->infoLabel->setText(tr("Restore from archive <b>%1</b> to specified" " directory? Any existing files will not be" " replaced by default. Use the options below to" " modify this behavior:") .arg(_archive->name())); _ui->baseDirLineEdit->setVisible(checked); _ui->changeDirButton->setVisible(checked); _ui->overwriteCheckBox->setVisible(checked); _ui->keepNewerCheckBox->setVisible(checked); _ui->preservePermCheckBox->setVisible(checked); adjustSize(); } void RestoreDialog::optionTarArchiveToggled(bool checked) { _ui->infoLabel->setText(tr("Download archive <b>%1</b> contents as an" " uncompressed TAR archive?") .arg(_archive->name())); _ui->archiveLineEdit->setVisible(checked); _ui->changeArchiveButton->setVisible(checked); adjustSize(); } void RestoreDialog::optionRestoreToggled(bool checked) { _ui->infoLabel->setText(tr("Restore from archive <b>%1</b> to original" " locations? Any existing files will not be" " replaced by default. Use the options below to" " modify this behavior:") .arg(_archive->name())); _ui->overwriteCheckBox->setVisible(checked); _ui->keepNewerCheckBox->setVisible(checked); _ui->preservePermCheckBox->setVisible(checked); adjustSize(); } void RestoreDialog::changeDir() { QString path = QFileDialog::getExistingDirectory(this, tr("Directory to restore to"), _downDir); if(!path.isEmpty()) _ui->baseDirLineEdit->setText(path); } void RestoreDialog::changeArchive() { QString path = QFileDialog::getSaveFileName(this, tr("Select tar archive file"), _ui->archiveLineEdit->text(), tr("Tar archives (*.tar)")); if(!path.isEmpty()) _ui->archiveLineEdit->setText(path); } bool RestoreDialog::validate() { bool valid = true; // Check that we have valid options, depending on which type of restore. if(_ui->optionBaseDirRadio->isChecked()) { QFileInfo dir(_ui->baseDirLineEdit->text()); if(dir.exists() && dir.isDir()) { _ui->baseDirLineEdit->setStyleSheet("QLineEdit{color:black;}"); _ui->baseDirLineEdit->setToolTip( tr("Set base directory to extract archive contents to")); } else { _ui->baseDirLineEdit->setStyleSheet("QLineEdit{color:red;}"); _ui->baseDirLineEdit->setToolTip( tr("Invalid base directory, please choose a different one")); valid = false; } } else if(_ui->optionTarArchiveRadio->isChecked()) { QFileInfo archive(_ui->archiveLineEdit->text()); if(archive.exists()) { _ui->archiveLineEdit->setStyleSheet("QLineEdit{color:red;}"); _ui->archiveLineEdit->setToolTip( tr("File exists, please choose a different file name")); valid = false; } else { _ui->archiveLineEdit->setStyleSheet("QLineEdit{color:black;}"); _ui->archiveLineEdit->setToolTip(tr("Set archive file name")); } } return valid; } ArchivePtr RestoreDialog::archive() const { return _archive; }
clarify blank path
RestoreDialog: clarify blank path The 'path' should already be blank (as the default value of a QString), but this will clarify what's happening in the three different restore types.
C++
bsd-2-clause
Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui
2697ae6b2c112f28149c9b71b6d9f266a6809daa
src/xapian/database-write.cpp
src/xapian/database-write.cpp
/* database-write.cpp * * Copyright (C) 2012-2014 Matthias Klumpp <[email protected]> * * Licensed under the GNU Lesser General Public License Version 3 * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "database-write.hpp" #include <iostream> #include <string> #include <algorithm> #include <vector> #include <sstream> #include <iterator> #include <glib/gstdio.h> #include "database-common.hpp" #include "../as-utils.h" #include "../as-component-private.h" #include "../as-settings-private.h" using namespace std; using namespace Appstream; DatabaseWrite::DatabaseWrite () : m_rwXapianDB(0) { } DatabaseWrite::~DatabaseWrite () { if (m_rwXapianDB) { delete m_rwXapianDB; } } bool DatabaseWrite::initialize (const gchar *dbPath) { m_dbPath = string(dbPath); try { m_rwXapianDB = new Xapian::WritableDatabase (m_dbPath, Xapian::DB_CREATE_OR_OPEN); } catch (const Xapian::Error &error) { g_warning ("Exception: %s", error.get_msg ().c_str ()); return false; } return true; } bool DatabaseWrite::rebuild (GList *cpt_list) { string old_path = m_dbPath + "_old"; string rebuild_path = m_dbPath + "_rb"; // Create the rebuild directory if (!as_utils_touch_dir (rebuild_path.c_str ())) return false; // check if old unrequired version of db still exists on filesystem if (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) { g_warning ("Existing xapian old db was not previously cleaned: '%s'.", old_path.c_str ()); as_utils_delete_dir_recursive (old_path.c_str ()); } // check if old unrequired version of db still exists on filesystem if (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) { cout << "Removing old rebuild-dir from previous database rebuild." << endl; as_utils_delete_dir_recursive (rebuild_path.c_str ()); } Xapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE); Xapian::TermGenerator term_generator; term_generator.set_database(db); try { /* this tests if we have spelling suggestions (there must be * a better way?!?) - this is needed as inmemory does not have * spelling corrections, but it allows setting the flag and will * raise a exception much later */ db.add_spelling("test"); db.remove_spelling("test"); /* this enables the flag for it (we only reach this line if * the db supports spelling suggestions) */ term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING); } catch (const Xapian::UnimplementedError &error) { // Ignore } for (GList *list = cpt_list; list != NULL; list = list->next) { AsComponent *cpt = (AsComponent*) list->data; Xapian::Document doc; term_generator.set_document (doc); //! g_debug ("Adding component: %s", as_component_to_string (cpt)); doc.set_data (as_component_get_name (cpt)); // Package name string pkgname = as_component_get_pkgname (cpt); doc.add_value (XapianValues::PKGNAME, pkgname); doc.add_term("AP" + pkgname); if (pkgname.find ("-") != string::npos) { // we need this to work around xapian oddness string tmp = pkgname; replace (tmp.begin(), tmp.end(), '-', '_'); doc.add_term (tmp); } // add packagename as meta-data too term_generator.index_text_without_positions (pkgname, WEIGHT_PKGNAME); // Identifier string idname = as_component_get_idname (cpt); doc.add_value (XapianValues::IDENTIFIER, idname); doc.add_term("AI" + idname); term_generator.index_text_without_positions (idname, WEIGHT_PKGNAME); // Untranslated component name string cptNameGeneric = as_component_get_name_original (cpt); doc.add_value (XapianValues::CPTNAME_UNTRANSLATED, cptNameGeneric); term_generator.index_text_without_positions (cptNameGeneric, WEIGHT_DESKTOP_GENERICNAME); // Component name string cptName = as_component_get_name (cpt); doc.add_value (XapianValues::CPTNAME, cptName); // Type identifier string type_str = as_component_kind_to_string (as_component_get_kind (cpt)); doc.add_value (XapianValues::TYPE, type_str); // URL doc.add_value (XapianValues::URL_HOMEPAGE, as_component_get_homepage (cpt)); // Application icon doc.add_value (XapianValues::ICON, as_component_get_icon (cpt)); doc.add_value (XapianValues::ICON_URL, as_component_get_icon_url (cpt)); // Summary string cptSummary = as_component_get_summary (cpt); doc.add_value (XapianValues::SUMMARY, cptSummary); term_generator.index_text_without_positions (cptSummary, WEIGHT_DESKTOP_SUMMARY); // Long description string description = as_component_get_description (cpt); doc.add_value (XapianValues::DESCRIPTION, description); term_generator.index_text_without_positions (description, WEIGHT_DESKTOP_SUMMARY); // Categories gchar **categories = as_component_get_categories (cpt); string categories_str = ""; for (uint i = 0; categories[i] != NULL; i++) { if (categories[i] == NULL) continue; string cat = categories[i]; string tmp = cat; transform (tmp.begin (), tmp.end (), tmp.begin (), ::tolower); doc.add_term ("AC" + tmp); categories_str += cat + ";"; } doc.add_value (XapianValues::CATEGORIES, categories_str); // Add our keywords (with high priority) gchar **keywords = as_component_get_keywords (cpt); if (keywords != NULL) { for (uint i = 0; keywords[i] != NULL; i++) { if (keywords[i] == NULL) continue; string kword = keywords[i]; term_generator.index_text_without_positions (kword, WEIGHT_DESKTOP_KEYWORD); } } // Data of provided items gchar **provides_items = as_ptr_array_to_strv (as_component_get_provided_items (cpt)); gchar *provides_items_str = g_strjoinv ("\n", provides_items); doc.add_value (XapianValues::PROVIDED_ITEMS, string(provides_items_str)); g_strfreev (provides_items); g_free (provides_items_str); // Add screenshot information (XML data) doc.add_value (XapianValues::SCREENSHOT_DATA, as_component_dump_screenshot_data_xml (cpt)); // Add compulsory-for-desktop information gchar **compulsory = as_component_get_compulsory_for_desktops (cpt); string compulsory_str; if (compulsory != NULL) { gchar *str; str = g_strjoinv (";", compulsory); compulsory_str = string(str); g_free (str); } doc.add_value (XapianValues::COMPULSORY_FOR, compulsory_str); // Add project-license doc.add_value (XapianValues::LICENSE, as_component_get_project_license (cpt)); // Add project group doc.add_value (XapianValues::PROJECT_GROUP, as_component_get_project_group (cpt)); // Add releases information (XML data) doc.add_value (XapianValues::RELEASES_DATA, as_component_dump_releases_data_xml (cpt)); // TODO: Look at the SC Xapian database - there are still some values and terms missing! // Postprocess string docData = doc.get_data (); doc.add_term ("AA" + docData); term_generator.index_text_without_positions (docData, WEIGHT_DESKTOP_NAME); db.add_document (doc); } db.set_metadata("db-schema-version", AS_DB_SCHEMA_VERSION); db.commit (); if (g_rename (m_dbPath.c_str (), old_path.c_str ()) < 0) { g_critical ("Error while moving old database out of the way."); return false; } if (g_rename (rebuild_path.c_str (), m_dbPath.c_str ()) < 0) { g_critical ("Error while moving rebuilt database."); return false; } as_utils_delete_dir_recursive (old_path.c_str ()); return true; } bool DatabaseWrite::addComponent (AsComponent *cpt) { // TODO return false; }
/* database-write.cpp * * Copyright (C) 2012-2014 Matthias Klumpp <[email protected]> * * Licensed under the GNU Lesser General Public License Version 3 * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "database-write.hpp" #include <iostream> #include <string> #include <algorithm> #include <vector> #include <sstream> #include <iterator> #include <glib/gstdio.h> #include "database-common.hpp" #include "../as-utils.h" #include "../as-component-private.h" #include "../as-settings-private.h" using namespace std; using namespace Appstream; DatabaseWrite::DatabaseWrite () : m_rwXapianDB(0) { } DatabaseWrite::~DatabaseWrite () { if (m_rwXapianDB) { delete m_rwXapianDB; } } bool DatabaseWrite::initialize (const gchar *dbPath) { m_dbPath = string(dbPath); try { m_rwXapianDB = new Xapian::WritableDatabase (m_dbPath, Xapian::DB_CREATE_OR_OPEN); } catch (const Xapian::Error &error) { g_warning ("Exception: %s", error.get_msg ().c_str ()); return false; } return true; } bool DatabaseWrite::rebuild (GList *cpt_list) { string old_path = m_dbPath + "_old"; string rebuild_path = m_dbPath + "_rb"; // Create the rebuild directory if (!as_utils_touch_dir (rebuild_path.c_str ())) return false; // check if old unrequired version of db still exists on filesystem if (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) { g_warning ("Existing xapian old db was not previously cleaned: '%s'.", old_path.c_str ()); as_utils_delete_dir_recursive (old_path.c_str ()); } // check if old unrequired version of db still exists on filesystem if (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) { cout << "Removing old rebuild-dir from previous database rebuild." << endl; as_utils_delete_dir_recursive (rebuild_path.c_str ()); } Xapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE); Xapian::TermGenerator term_generator; term_generator.set_database(db); try { /* this tests if we have spelling suggestions (there must be * a better way?!?) - this is needed as inmemory does not have * spelling corrections, but it allows setting the flag and will * raise a exception much later */ db.add_spelling("test"); db.remove_spelling("test"); /* this enables the flag for it (we only reach this line if * the db supports spelling suggestions) */ term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING); } catch (const Xapian::UnimplementedError &error) { // Ignore } for (GList *list = cpt_list; list != NULL; list = list->next) { AsComponent *cpt = (AsComponent*) list->data; Xapian::Document doc; term_generator.set_document (doc); //! g_debug ("Adding component: %s", as_component_to_string (cpt)); doc.set_data (as_component_get_name (cpt)); // Package name string pkgname = as_component_get_pkgname (cpt); doc.add_value (XapianValues::PKGNAME, pkgname); doc.add_term("AP" + pkgname); if (pkgname.find ("-") != string::npos) { // we need this to work around xapian oddness string tmp = pkgname; replace (tmp.begin(), tmp.end(), '-', '_'); doc.add_term (tmp); } // add packagename as meta-data too term_generator.index_text_without_positions (pkgname, WEIGHT_PKGNAME); // Identifier string idname = as_component_get_idname (cpt); doc.add_value (XapianValues::IDENTIFIER, idname); doc.add_term("AI" + idname); term_generator.index_text_without_positions (idname, WEIGHT_PKGNAME); // Untranslated component name string cptNameGeneric = as_component_get_name_original (cpt); doc.add_value (XapianValues::CPTNAME_UNTRANSLATED, cptNameGeneric); term_generator.index_text_without_positions (cptNameGeneric, WEIGHT_DESKTOP_GENERICNAME); // Component name string cptName = as_component_get_name (cpt); doc.add_value (XapianValues::CPTNAME, cptName); // Type identifier string type_str = as_component_kind_to_string (as_component_get_kind (cpt)); doc.add_value (XapianValues::TYPE, type_str); // URL doc.add_value (XapianValues::URL_HOMEPAGE, as_component_get_homepage (cpt)); // Application icon doc.add_value (XapianValues::ICON, as_component_get_icon (cpt)); doc.add_value (XapianValues::ICON_URL, as_component_get_icon_url (cpt)); // Summary string cptSummary = as_component_get_summary (cpt); doc.add_value (XapianValues::SUMMARY, cptSummary); term_generator.index_text_without_positions (cptSummary, WEIGHT_DESKTOP_SUMMARY); // Long description string description = as_component_get_description (cpt); doc.add_value (XapianValues::DESCRIPTION, description); term_generator.index_text_without_positions (description, WEIGHT_DESKTOP_SUMMARY); // Categories gchar **categories = as_component_get_categories (cpt); string categories_str = ""; for (uint i = 0; categories[i] != NULL; i++) { if (categories[i] == NULL) continue; string cat = categories[i]; string tmp = cat; transform (tmp.begin (), tmp.end (), tmp.begin (), ::tolower); doc.add_term ("AC" + tmp); categories_str += cat + ";"; } doc.add_value (XapianValues::CATEGORIES, categories_str); // Add our keywords (with high priority) gchar **keywords = as_component_get_keywords (cpt); if (keywords != NULL) { for (uint i = 0; keywords[i] != NULL; i++) { if (keywords[i] == NULL) continue; string kword = keywords[i]; term_generator.index_text_without_positions (kword, WEIGHT_DESKTOP_KEYWORD); } } // Data of provided items gchar **provides_items = as_ptr_array_to_strv (as_component_get_provided_items (cpt)); if (provides_items != NULL) { gchar *provides_items_str = g_strjoinv ("\n", provides_items); doc.add_value (XapianValues::PROVIDED_ITEMS, string(provides_items_str)); for (uint i = 0; provides_items[i] != NULL; i++) { string item = provides_items[i]; doc.add_term ("AX" + item); } g_free (provides_items_str); } g_strfreev (provides_items); // Add screenshot information (XML data) doc.add_value (XapianValues::SCREENSHOT_DATA, as_component_dump_screenshot_data_xml (cpt)); // Add compulsory-for-desktop information gchar **compulsory = as_component_get_compulsory_for_desktops (cpt); string compulsory_str; if (compulsory != NULL) { gchar *str; str = g_strjoinv (";", compulsory); compulsory_str = string(str); g_free (str); } doc.add_value (XapianValues::COMPULSORY_FOR, compulsory_str); // Add project-license doc.add_value (XapianValues::LICENSE, as_component_get_project_license (cpt)); // Add project group doc.add_value (XapianValues::PROJECT_GROUP, as_component_get_project_group (cpt)); // Add releases information (XML data) doc.add_value (XapianValues::RELEASES_DATA, as_component_dump_releases_data_xml (cpt)); // TODO: Look at the SC Xapian database - there are still some values and terms missing! // Postprocess string docData = doc.get_data (); doc.add_term ("AA" + docData); term_generator.index_text_without_positions (docData, WEIGHT_DESKTOP_NAME); db.add_document (doc); } db.set_metadata("db-schema-version", AS_DB_SCHEMA_VERSION); db.commit (); if (g_rename (m_dbPath.c_str (), old_path.c_str ()) < 0) { g_critical ("Error while moving old database out of the way."); return false; } if (g_rename (rebuild_path.c_str (), m_dbPath.c_str ()) < 0) { g_critical ("Error while moving rebuilt database."); return false; } as_utils_delete_dir_recursive (old_path.c_str ()); return true; } bool DatabaseWrite::addComponent (AsComponent *cpt) { // TODO return false; }
Index terms for provided items
Index terms for provided items
C++
lgpl-2.1
ximion/appstream,ximion/appstream,ximion/appstream,ximion/appstream
ad119d8d867b435dbd8a51cb376625e9f84c26d2
histomicstk/segmentation/label/isbfcpp.cpp
histomicstk/segmentation/label/isbfcpp.cpp
/* C++ version of ISBF for TraceBounds */ #include <iostream> #include <math.h> #include "isbfcpp.h" using namespace std; isbfcpp::isbfcpp() { head = NULL; curr = NULL; } int isbfcpp::length() { node *cur = head; int len = 0; while(cur) { cur = cur->next; len++; } return len; } void isbfcpp::nth_from_last(int n, int &x, int &y) { node *cur = head; int count = 0; while(cur) { if (count == n) { x = cur->val_x; y = cur->val_y; } cur = cur->next; count++; } } bool isbfcpp::addList(int x, int y) { node *newNode = new node; newNode->val_x = x; newNode->val_y = y; newNode->next = NULL; if (head == NULL) { head = new node; curr = new node; head = curr = newNode; } else { curr-> next = newNode; curr = newNode; } count++; return true; } void isbfcpp::roateMatrix(int rows, int cols, int **input, int **output) { int i, j; for (i=0; i<rows; i++){ for (j=0;j<cols; j++){ output[j][rows-1-i] = input[i][j]; } } } void isbfcpp::clean() { for (int i = 0; i < nrows; i++) { delete[] matrix00[i]; delete[] matrix180[i]; } for (int i = 0; i < ncols; i++) { delete[] matrix90[i]; delete[] matrix270[i]; } delete[] matrix00; delete[] matrix90; delete[] matrix180; delete[] matrix270; } vector<int> isbfcpp::getList(int rows, int cols, int *size, int *mask, int startX, int startY, float inf) { addList(startX, startY); nrows = rows; ncols = cols; matrix00 = new int*[nrows]; for (int i = 0; i < nrows; i++) { matrix00[i] = new int[ncols]; } // copy mask to matrix00 for(int i=0; i< nrows; i++){ for(int j=0; j< ncols; j++){ matrix00[i][j] = mask[i*ncols+j]; } } matrix90 = new int*[ncols]; for (int i = 0; i < ncols; i++) { matrix90[i] = new int[nrows]; } matrix180 = new int*[nrows]; for (int i = 0; i < nrows; i++) { matrix180[i] = new int[ncols]; } matrix270 = new int*[ncols]; for (int i = 0; i < ncols; i++) { matrix270[i] = new int[nrows]; } // rotate Matrix for 90, 180, 270 degrees roateMatrix(nrows, ncols, matrix00, matrix270); roateMatrix(ncols, nrows, matrix270, matrix180); roateMatrix(nrows, ncols, matrix180, matrix90); // set defalut direction int DX = 1; int DY = 0; // set the number of rows and cols for ISBF int rowISBF = 3; int colISBF = 2; float angle; // set size of X: the size of X is equal to the size of Y int sizeofX; // loop until true while(1) { int x; int y; x = curr->val_x; y = curr->val_y; int **h = new int*[rowISBF]; for (int i = 0; i < rowISBF; i++) { h[i] = new int[colISBF]; } // initialize a and b which are indices of ISBF int a = 0; int b = 0; if((DX == 1)&&(DY == 0)){ for (int i = ncols-x-2; i < ncols-x+1; i++) { for (int j = y-1; j < y+1; j++) { h[a][b] = matrix90[i][j]; b++; } b = 0; a++; } angle = M_PI/2; } else if((DX == 0)&&(DY == -1)){ for (int i = y-1; i < y+2; i++) { for (int j = x-1; j < x+1; j++) { h[a][b] = matrix00[i][j]; b++; } b = 0; a++; } angle = 0; } else if((DX == -1)&&(DY == 0)){ for (int i = x-1; i < x+2; i++) { for (int j = nrows-y-2; j < nrows-y; j++) { h[a][b] = matrix270[i][j]; b++; } b = 0; a++; } angle = 3*M_PI/2; } else{ for (int i = nrows-y-2; i < nrows-y+1; i++) { for (int j = ncols-x-2; j < ncols-x; j++) { h[a][b] = matrix180[i][j]; b++; } b = 0; a++; } angle = M_PI; } // initialize cX and cY // cX and cY indicate directions for each ISBF vector<int> cX(1); vector<int> cY(1); cX.at(0)=0; cY.at(0)=0; if (h[1][0] == 1) { // 'left' neighbor cX.at(0) = -1; cY.at(0) = 0; DX = -1; DY = 0; } else{ if((h[2][0] == 1)&&(h[2][1] != 1)){ // inner-outer corner at left-rear cX.at(0) = -1; cY.at(0) = 1; DX = 0; DY = 1; } else{ if(h[0][0] == 1){ if(h[0][1] == 1){ // inner corner at front cX.at(0) = 0; cY.at(0) = -1; cX.resize(2,(int)-1); cY.resize(2,(int)0); DX = 0; DY = -1; } else{ // inner-outer corner at front-left cX.at(0) = -1; cY.at(0) = -1; DX = 0; DY = 1; } } else if(h[0][1] == 1){ // front neighbor cX.at(0) = 0; cY.at(0) = -1; DX = 1; DY = 0; } else{ // outer corner DX = 0; DY = 1; } } } // free ISBF matrix for (int i = 0; i < rowISBF; i++) { delete[] h[i]; } delete[] h; // transform points by incoming directions and add to contours float s = sin(angle); float c = cos(angle); if(!((cX.at(0)==0)&&(cY.at(0)==0))){ for(int t=0; t<int(cX.size()); t++){ float a, b; int cx = cX.at(t); int cy = cY.at(t); a = c*cx - s*cy; b = s*cx + c*cy; x = curr->val_x; y = curr->val_y; addList(x+roundf(a), y+roundf(b)); } } float i, j; i = c*DX-s*DY; j = s*DX+c*DY; DX = roundf(i); DY = roundf(j); // get length of the current linked list sizeofX = length(); if (sizeofX > 3) { int fx1 = head->val_x; int fx2 = head->next->val_x; int fy1 = head->val_y; int fy2 = head->next->val_y; int lx1 = curr->val_x; int ly1 = curr->val_y; int lx2, ly2; nth_from_last(sizeofX-2, lx2, ly2); // check if the first and the last x and y are equal if ((sizeofX > inf)|| \ ((lx1 == fx2)&&(lx2 == fx1)&&(ly1 == fy2)&&(ly2 == fy1))){ // delete the last node node *c = head; node *temp = head; while(c->next != NULL){ temp = c; c = c->next; } temp->next = NULL; break; } } } // allocate memory for return value vector<int> array(2*sizeofX-2); int index = 0; while (head != NULL) { array[index] = head->val_x; array[index+sizeofX-1] = head->val_y; head = head->next; index++; } // get size of x *size = sizeofX; clean(); return array; } isbfcpp::~isbfcpp() { node *c = head; while (c != NULL) { head = head->next; delete c; c = head; } curr = head = NULL; }
/* C++ version of ISBF for TraceBounds */ #include <iostream> #include <math.h> #include "isbfcpp.h" using namespace std; isbfcpp::isbfcpp() { head = NULL; curr = NULL; } int isbfcpp::length() { node *cur = head; int len = 0; while(cur) { cur = cur->next; len++; } return len; } void isbfcpp::nth_from_last(int n, int &x, int &y) { node *cur = head; int count = 0; while(cur) { if (count == n) { x = cur->val_x; y = cur->val_y; } cur = cur->next; count++; } } bool isbfcpp::addList(int x, int y) { node *newNode = new node; newNode->val_x = x; newNode->val_y = y; newNode->next = NULL; if (head == NULL) { head = new node; curr = new node; head = curr = newNode; } else { curr-> next = newNode; curr = newNode; } count++; return true; } void isbfcpp::rotateMatrix(int rows, int cols, int **input, int **output) { int i, j; for (i=0; i<rows; i++){ for (j=0;j<cols; j++){ output[j][rows-1-i] = input[i][j]; } } } void isbfcpp::clean() { for (int i = 0; i < nrows; i++) { delete[] matrix00[i]; delete[] matrix180[i]; } for (int i = 0; i < ncols; i++) { delete[] matrix90[i]; delete[] matrix270[i]; } delete[] matrix00; delete[] matrix90; delete[] matrix180; delete[] matrix270; } vector<int> isbfcpp::getList(int rows, int cols, int *size, int *mask, int startX, int startY, float inf) { addList(startX, startY); nrows = rows; ncols = cols; matrix00 = new int*[nrows]; for (int i = 0; i < nrows; i++) { matrix00[i] = new int[ncols]; } // copy mask to matrix00 for(int i=0; i< nrows; i++){ for(int j=0; j< ncols; j++){ matrix00[i][j] = mask[i*ncols+j]; } } matrix90 = new int*[ncols]; for (int i = 0; i < ncols; i++) { matrix90[i] = new int[nrows]; } matrix180 = new int*[nrows]; for (int i = 0; i < nrows; i++) { matrix180[i] = new int[ncols]; } matrix270 = new int*[ncols]; for (int i = 0; i < ncols; i++) { matrix270[i] = new int[nrows]; } // rotate Matrix for 90, 180, 270 degrees rotateMatrix(nrows, ncols, matrix00, matrix270); rotateMatrix(ncols, nrows, matrix270, matrix180); rotateMatrix(nrows, ncols, matrix180, matrix90); // set defalut direction int DX = 1; int DY = 0; // set the number of rows and cols for ISBF int rowISBF = 3; int colISBF = 2; float angle; // set size of X: the size of X is equal to the size of Y int sizeofX; // loop until true while(1) { int x; int y; x = curr->val_x; y = curr->val_y; int **h = new int*[rowISBF]; for (int i = 0; i < rowISBF; i++) { h[i] = new int[colISBF]; } // initialize a and b which are indices of ISBF int a = 0; int b = 0; if((DX == 1)&&(DY == 0)){ for (int i = ncols-x-2; i < ncols-x+1; i++) { for (int j = y-1; j < y+1; j++) { h[a][b] = matrix90[i][j]; b++; } b = 0; a++; } angle = M_PI/2; } else if((DX == 0)&&(DY == -1)){ for (int i = y-1; i < y+2; i++) { for (int j = x-1; j < x+1; j++) { h[a][b] = matrix00[i][j]; b++; } b = 0; a++; } angle = 0; } else if((DX == -1)&&(DY == 0)){ for (int i = x-1; i < x+2; i++) { for (int j = nrows-y-2; j < nrows-y; j++) { h[a][b] = matrix270[i][j]; b++; } b = 0; a++; } angle = 3*M_PI/2; } else{ for (int i = nrows-y-2; i < nrows-y+1; i++) { for (int j = ncols-x-2; j < ncols-x; j++) { h[a][b] = matrix180[i][j]; b++; } b = 0; a++; } angle = M_PI; } // initialize cX and cY // cX and cY indicate directions for each ISBF vector<int> cX(1); vector<int> cY(1); cX.at(0)=0; cY.at(0)=0; if (h[1][0] == 1) { // 'left' neighbor cX.at(0) = -1; cY.at(0) = 0; DX = -1; DY = 0; } else{ if((h[2][0] == 1)&&(h[2][1] != 1)){ // inner-outer corner at left-rear cX.at(0) = -1; cY.at(0) = 1; DX = 0; DY = 1; } else{ if(h[0][0] == 1){ if(h[0][1] == 1){ // inner corner at front cX.at(0) = 0; cY.at(0) = -1; cX.resize(2,(int)-1); cY.resize(2,(int)0); DX = 0; DY = -1; } else{ // inner-outer corner at front-left cX.at(0) = -1; cY.at(0) = -1; DX = 0; DY = 1; } } else if(h[0][1] == 1){ // front neighbor cX.at(0) = 0; cY.at(0) = -1; DX = 1; DY = 0; } else{ // outer corner DX = 0; DY = 1; } } } // free ISBF matrix for (int i = 0; i < rowISBF; i++) { delete[] h[i]; } delete[] h; // transform points by incoming directions and add to contours float s = sin(angle); float c = cos(angle); if(!((cX.at(0)==0)&&(cY.at(0)==0))){ for(int t=0; t<int(cX.size()); t++){ float a, b; int cx = cX.at(t); int cy = cY.at(t); a = c*cx - s*cy; b = s*cx + c*cy; x = curr->val_x; y = curr->val_y; addList(x+roundf(a), y+roundf(b)); } } float i, j; i = c*DX-s*DY; j = s*DX+c*DY; DX = roundf(i); DY = roundf(j); // get length of the current linked list sizeofX = length(); if (sizeofX > 3) { int fx1 = head->val_x; int fx2 = head->next->val_x; int fy1 = head->val_y; int fy2 = head->next->val_y; int lx1 = curr->val_x; int ly1 = curr->val_y; int lx2, ly2; nth_from_last(sizeofX-2, lx2, ly2); // check if the first and the last x and y are equal if ((sizeofX > inf)|| \ ((lx1 == fx2)&&(lx2 == fx1)&&(ly1 == fy2)&&(ly2 == fy1))){ // delete the last node node *c = head; node *temp = head; while(c->next != NULL){ temp = c; c = c->next; } temp->next = NULL; break; } } } // allocate memory for return value vector<int> array(2*sizeofX-2); int index = 0; while (head != NULL) { array[index] = head->val_x; array[index+sizeofX-1] = head->val_y; head = head->next; index++; } // get size of x *size = sizeofX; clean(); return array; } isbfcpp::~isbfcpp() { node *c = head; while (c != NULL) { head = head->next; delete c; c = head; } curr = head = NULL; }
Fix typo in isbfcpp.cpp
Fix typo in isbfcpp.cpp
C++
apache-2.0
DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK
dc5ab088ab4710c1e65925a3884fd675f2427b31
src/twister.cpp
src/twister.cpp
#include "twister.h" const unsigned CYCLE = 0x100; const unsigned C_TRANS_ = 0xff; int block_units[][0x10] = { 0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65 }; int triad_units[][0x03] = { 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73 }; const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee, 0xcf, 0xad, 0xdf, 0xff, 0xce, 0x32, 0x40, 0xd3, 0x27, 0x82, 0xda, 0xee, 0xff, 0xfc, 0xbf, 0x1c, 0x90, 0x13, 0x4a, 0xa5, 0xe0, 0x21, 0x9f, 0xe1, 0xc6, 0xe4, 0x38, 0x1f, 0x60, 0x24, 0x0c, 0x35, 0x51, 0x32, 0xcf, 0x12, 0x9a, 0x30, 0x44, 0x72, 0x04, 0x1c, 0x52, 0xca, 0xdf, 0x12, 0x0b, 0x30, 0xa0, 0x1e, 0x03, 0x14, 0x09, 0x73, 0x23, 0xf2, 0xca, 0xa2, 0x51, 0xc6, 0xcb, 0xbd, 0xba, 0xac, 0xdf, 0xdf, 0xde, 0xcd, 0xfd, 0xca }; int ENTRY_LINK__ = 0x05; int ENTRY_LINK__TEST = 0x09; unsigned reflect(unsigned center, unsigned (*r)(unsigned)) { return (*r)(center)^center; } unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos) { return (*s)(pos)^a; } void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^base(d, g, d); } data[i] = d; } } void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^(*g)(d); } data[i] = d; } } void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d); } data[i] = d; } } vector<double> f_dist(vector<unsigned char>& in) { vector<double> fdist; fdist.resize(256); for(unsigned i = 0; i<in.size(); i++) { fdist[in[i]]++; } for(unsigned i=0; i<fdist.size(); i++) { fdist[i] = (fdist[i] / in.size()) * 100; } return fdist; } double s_entropy(vector<double> v) { double entropy = 0; double p; for(unsigned i = 0; i < v.size(); i++) { p = v[i] / 100; if (p == 0) continue; entropy += p * std::log(p) / std::log(2); } return -entropy; } void rms(const string& s, string& r) { for(unsigned int i=0; i<s.size(); i++) { if(::isspace(s[i])) continue; r+= s[i]; } } double sw(double weight, int i, int j, int (*inv)(int, int)) { return weight*(*inv)(i, j); } void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int)) { if(s == 1) { (*p)(n); return; } for(int i=0; i< s; i++) { hPerm(s-1, n, p, inv); if(s%2 == 1) (*inv)(0, s-1); else (*inv)(i, s-1); } } double ic(const string& t) { string text; rms(t, text); vector<double> freq(256,0); for(unsigned int i=0; i<text.size(); i++) { if(text[i] == ' ') continue; freq[text[i]] ++; } double sum=0; for(unsigned int i=0; i<freq.size(); i++) { if(freq[i] != 0) { double c = freq[i]; if(c != 0) sum += c * (c - 1); } } double ic = 26 * sum / (text.size() * (text.size() - 1)); return ic; } void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m) { //test seq (*p)(transition_seq[ENTRY_LINK__], m); (*p)(transition_seq[ENTRY_LINK__TEST], m); }
#include "twister.h" const unsigned CYCLE = 0x100; const unsigned C_TRANS_ = 0xff; int block_units[][0x10] = { 0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65 }; int triad_units[][0x03] = { 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73 }; const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee, 0xcf, 0xad, 0xdf, 0xff, 0xce, 0x32, 0x40, 0xd3, 0x27, 0x82, 0xda, 0xee, 0xff, 0xfc, 0xbf, 0x1c, 0x90, 0x13, 0x4a, 0xa5, 0xe0, 0x21, 0x9f, 0xe1, 0xc6, 0xaf, 0x05, 0x81, 0xf0, 0xee, 0xe4, 0x38, 0x1f, 0x60, 0x24, 0x0c, 0x35, 0x51, 0x32, 0xcf, 0x12, 0x9a, 0x30, 0x44, 0x72, 0x04, 0x1c, 0x52, 0xca, 0xdf, 0x12, 0x0b, 0x30, 0xa0, 0x1e, 0x03, 0x14, 0x09, 0x73, 0x23, 0xf2, 0xca, 0xa2, 0x51, 0xc6, 0xcb, 0xbd, 0xba, 0xac, 0xdf, 0xdf, 0xde, 0xcd, 0xfd, 0xca }; int ENTRY_LINK__ = 0x05; int ENTRY_LINK__TEST = 0x09; unsigned reflect(unsigned center, unsigned (*r)(unsigned)) { return (*r)(center)^center; } unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos) { return (*s)(pos)^a; } void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^base(d, g, d); } data[i] = d; } } void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^(*g)(d); } data[i] = d; } } void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d); } data[i] = d; } } vector<double> f_dist(vector<unsigned char>& in) { vector<double> fdist; fdist.resize(256); for(unsigned i = 0; i<in.size(); i++) { fdist[in[i]]++; } for(unsigned i=0; i<fdist.size(); i++) { fdist[i] = (fdist[i] / in.size()) * 100; } return fdist; } double s_entropy(vector<double> v) { double entropy = 0; double p; for(unsigned i = 0; i < v.size(); i++) { p = v[i] / 100; if (p == 0) continue; entropy += p * std::log(p) / std::log(2); } return -entropy; } void rms(const string& s, string& r) { for(unsigned int i=0; i<s.size(); i++) { if(::isspace(s[i])) continue; r+= s[i]; } } double sw(double weight, int i, int j, int (*inv)(int, int)) { return weight*(*inv)(i, j); } void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int)) { if(s == 1) { (*p)(n); return; } for(int i=0; i< s; i++) { hPerm(s-1, n, p, inv); if(s%2 == 1) (*inv)(0, s-1); else (*inv)(i, s-1); } } double ic(const string& t) { string text; rms(t, text); vector<double> freq(256,0); for(unsigned int i=0; i<text.size(); i++) { if(text[i] == ' ') continue; freq[text[i]] ++; } double sum=0; for(unsigned int i=0; i<freq.size(); i++) { if(freq[i] != 0) { double c = freq[i]; if(c != 0) sum += c * (c - 1); } } double ic = 26 * sum / (text.size() * (text.size() - 1)); return ic; } void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m) { //test seq (*p)(transition_seq[ENTRY_LINK__], m); (*p)(transition_seq[ENTRY_LINK__TEST], m); }
test seq, extern
test seq, extern
C++
mit
IOCoin/DIONS,IOCoin/DIONS,IOCoin/DIONS,IOCoin/DIONS,IOCoin/DIONS,IOCoin/DIONS,IOCoin/DIONS,IOCoin/DIONS
60fb523d629daebf73e604dbb909c763b49cb959
src/line_and_column.hh
src/line_and_column.hh
#ifndef line_and_column_hh_INCLUDED #define line_and_column_hh_INCLUDED namespace Kakoune { template<typename EffectiveType> struct LineAndColumn { int line; int column; LineAndColumn(int line = 0, int column = 0) : line(line), column(column) {} EffectiveType operator+(const EffectiveType& other) const { return EffectiveType(line + other.line, column + other.column); } EffectiveType& operator+=(const EffectiveType& other) { line += other.line; column += other.column; return *static_cast<EffectiveType*>(this); } EffectiveType operator-(const EffectiveType& other) const { return EffectiveType(line - other.line, column - other.column); } EffectiveType& operator-=(const EffectiveType& other) { line -= other.line; column -= other.column; return *static_cast<EffectiveType*>(this); } bool operator< (const EffectiveType& other) const { if (line != other.line) return line < other.line; return column < other.column; } bool operator<= (const EffectiveType& other) const { if (line != other.line) return line < other.line; return column <= other.column; } bool operator== (const EffectiveType& other) const { return line == other.line and column == other.column; } }; } #endif // line_and_column_hh_INCLUDED
#ifndef line_and_column_hh_INCLUDED #define line_and_column_hh_INCLUDED namespace Kakoune { template<typename EffectiveType> struct LineAndColumn { int line; int column; LineAndColumn(int line = 0, int column = 0) : line(line), column(column) {} EffectiveType operator+(const EffectiveType& other) const { return EffectiveType(line + other.line, column + other.column); } EffectiveType& operator+=(const EffectiveType& other) { line += other.line; column += other.column; return *static_cast<EffectiveType*>(this); } EffectiveType operator-(const EffectiveType& other) const { return EffectiveType(line - other.line, column - other.column); } EffectiveType& operator-=(const EffectiveType& other) { line -= other.line; column -= other.column; return *static_cast<EffectiveType*>(this); } bool operator< (const EffectiveType& other) const { if (line != other.line) return line < other.line; return column < other.column; } bool operator<= (const EffectiveType& other) const { if (line != other.line) return line < other.line; return column <= other.column; } bool operator> (const EffectiveType& other) const { if (line != other.line) return line > other.line; return column > other.column; } bool operator>= (const EffectiveType& other) const { if (line != other.line) return line > other.line; return column >= other.column; } bool operator== (const EffectiveType& other) const { return line == other.line and column == other.column; } bool operator!= (const EffectiveType& other) const { return line != other.line or column != other.column; } }; } #endif // line_and_column_hh_INCLUDED
add some missing operators to LineAndColumn
add some missing operators to LineAndColumn
C++
unlicense
mawww/kakoune,casimir/kakoune,xificurC/kakoune,casimir/kakoune,flavius/kakoune,flavius/kakoune,alpha123/kakoune,alpha123/kakoune,elegios/kakoune,alexherbo2/kakoune,jjthrash/kakoune,danielma/kakoune,ekie/kakoune,ekie/kakoune,alexherbo2/kakoune,ekie/kakoune,flavius/kakoune,rstacruz/kakoune,alpha123/kakoune,zakgreant/kakoune,mawww/kakoune,xificurC/kakoune,jkonecny12/kakoune,elegios/kakoune,alpha123/kakoune,Asenar/kakoune,jkonecny12/kakoune,zakgreant/kakoune,danr/kakoune,elegios/kakoune,elegios/kakoune,casimir/kakoune,occivink/kakoune,occivink/kakoune,danielma/kakoune,ekie/kakoune,Somasis/kakoune,Asenar/kakoune,danielma/kakoune,Somasis/kakoune,Asenar/kakoune,rstacruz/kakoune,casimir/kakoune,rstacruz/kakoune,alexherbo2/kakoune,zakgreant/kakoune,lenormf/kakoune,mawww/kakoune,jkonecny12/kakoune,occivink/kakoune,Somasis/kakoune,occivink/kakoune,danr/kakoune,alexherbo2/kakoune,mawww/kakoune,xificurC/kakoune,rstacruz/kakoune,jjthrash/kakoune,Somasis/kakoune,lenormf/kakoune,danr/kakoune,Asenar/kakoune,jjthrash/kakoune,danielma/kakoune,lenormf/kakoune,lenormf/kakoune,flavius/kakoune,zakgreant/kakoune,danr/kakoune,xificurC/kakoune,jkonecny12/kakoune,jjthrash/kakoune
b8cea53fc9f85a8bf7b5be5c28666b02c9cdfb9c
src/uoj1109.cpp
src/uoj1109.cpp
#include <cstdio> #include <algorithm> #include <string> #include <map> #include <cstdlib> #include <iostream> #include <cstring> using namespace std; map <string ,int> dict; bool end=false; //debug #ifdef LOCAL #define fp stdin #else FILE *fp; #endif char last=0; char ch; string getword(){ string s; if (last){ s.push_back(last); last=0; } while((ch=getc(fp))!=EOF){ //printf("is :%c\n",ch); if(ch=='-'){ if((ch=getc(fp))=='\n'){ continue; }else{ last=ch; break; } } if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z') s.push_back(ch); else break; } if(ch==EOF) end=true; transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower); return s; } void printdict(){ map <string, int>::iterator dit; for ( dit = dict.begin( ); dit != dict.end( ); dit++ ){ cout<<dit->first<<endl; } } int main(int argc, char const *argv[]) { #ifndef LOCAL fp=fopen("case1.in","r"); #else printf("used LOCAL"); #endif string word; while(!end){ word=getword(); if(!dict.count(word)) dict[word]=0; else{ dict[word]++; } cout<<word<<endl; } printdict(); return 0; }
#include <cstdio> #include <algorithm> #include <string> #include <map> #include <cstdlib> #include <iostream> #include <cstring> using namespace std; map <string ,int> dict; bool end=false; //debug #ifdef LOCAL #define fp stdin #else FILE *fp; #endif char last=0; char ch; string getword(){ string s; if (last){ s.push_back(last); last=0; } while((ch=getc(fp))!=EOF){ //printf("is :%c\n",ch); if(ch=='-'){ if((ch=getc(fp))=='\n'){ continue; }else{ last=ch; break; } } if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z') s.push_back(ch); else break; } if(ch==EOF) end=true; transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower); return s; } void printdict(){ map <string, int>::iterator dit; for ( dit = dict.begin( ); dit != dict.end( ); dit++ ){ cout<<dit->first<<"="<<DIT->second<<endl; } } int main(int argc, char const *argv[]) { #ifndef LOCAL fp=fopen("case1.in","r"); #else printf("used LOCAL"); #endif string word; while(!end){ word=getword(); if(!dict.count(word)) dict[word]=0; else{ dict[word]++; } cout<<word<<endl; } printdict(); return 0; }
update uoj1109
update uoj1109
C++
mit
czfshine/my_oj,czfshine/my_oj,czfshine/my_oj,czfshine/my_oj