hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
710333d9b59b7b7c45ae70aa97ed0921c00c7e97
1,332
cpp
C++
src/fps_ros_bridge/fps_tracker_client_node.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
1
2017-12-01T14:57:16.000Z
2017-12-01T14:57:16.000Z
src/fps_ros_bridge/fps_tracker_client_node.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
null
null
null
src/fps_ros_bridge/fps_tracker_client_node.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
null
null
null
#include "fps_mapper/RichPointMsg.h" #include "fps_mapper/StampedCloudMsg.h" #include <ros/ros.h> #include "txt_io/message_writer.h" #include "tf/transform_listener.h" #include "fps_ros_msgs.h" using namespace fps_mapper; using namespace std; txt_io::MessageWriter writer; tf::TransformListener* _listener = 0; void cloudCallback(const StampedCloudMsgConstPtr& msg, Eigen::Isometry3f& pose, fps_mapper::Cloud& dest){ if (_listener) { tf::StampedTransform transform; try{ _listener->waitForTransform("tracker_origin_frame_id", msg->header.frame_id, msg->header.stamp, ros::Duration(0.1) ); _listener->lookupTransform ("tracker_origin_frame_id", msg->header.frame_id, msg->header.stamp, transform); } catch (tf::TransformException ex){ ROS_ERROR("%s",ex.what()); } pose = tfTransform2eigen(transform); msg2cloud(dest,msg->cloud); } } int main(int argc, char** argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; Eigen::Isometry3f ref_pose, curr_pose; fps_mapper::Cloud ref_cloud, curr_cloud; ros::Subscriber sub_curr = n.subscribe<fps_mapper::StampedCloudMsg>("/tracker/current_cloud", 10, boost::bind(cloudCallback, _1, curr_pose, curr_cloud)); _listener = new tf::TransformListener(n); ros::spin(); }
27.183673
155
0.70045
Lab-RoCoCo
710d1f47b82a57c1befddff0bda5eb106beeeb1a
240
cpp
C++
bitwise/bitwiseQs4.cpp
rrishabhj/ALGORITHM
a5204575b2e7417b5f5e1243687179294fdca290
[ "MIT" ]
null
null
null
bitwise/bitwiseQs4.cpp
rrishabhj/ALGORITHM
a5204575b2e7417b5f5e1243687179294fdca290
[ "MIT" ]
null
null
null
bitwise/bitwiseQs4.cpp
rrishabhj/ALGORITHM
a5204575b2e7417b5f5e1243687179294fdca290
[ "MIT" ]
null
null
null
/* Detect if two integers have opposite signs */ #include<iostream> #include<stdio.h> using namespace std; bool checkOppositeSign(int a, int b){ return ( (a^b) < 0); } int main() { cout<<checkOppositeSign(3,-4)<<endl; return(0); }
15
48
0.666667
rrishabhj
711020af09a3f06b18191dc1e7c0b122afa1cf7f
4,088
cpp
C++
src/plugin/xlog/xlog.cpp
willenchou/xservers
0f8b262571ed7c0465d90ef807a9a540e97de379
[ "Apache-2.0" ]
11
2016-12-11T02:17:58.000Z
2021-11-24T03:27:01.000Z
src/plugin/xlog/xlog.cpp
willenchou/xservers
0f8b262571ed7c0465d90ef807a9a540e97de379
[ "Apache-2.0" ]
null
null
null
src/plugin/xlog/xlog.cpp
willenchou/xservers
0f8b262571ed7c0465d90ef807a9a540e97de379
[ "Apache-2.0" ]
2
2016-12-11T10:48:00.000Z
2021-07-10T07:10:55.000Z
#include "xlog.h" #ifdef OS_WIN #include <windows.h> #endif #include <include/xservice_intf.h> namespace x { LogService* _logService = new LogService(); LogIocService* _logIocService = new LogIocService(); LogMngService* _logMngService = new LogMngService(); LogService::LogService(){ isSync_ = true; level_ = LOG_LEVEL_DEBUG; } LogService::~LogService(){ } void LogService::Init(){ CreateLogDir(); XMLElement* config = _logIocService->GetConfig(); if(config) { XMLElement* argsNode = config->FirstChildElement("args"); if(argsNode) { isSync_ = argsNode->BoolAttribute("sync"); level_ = argsNode->IntAttribute("level"); } } } void LogService::UnInit(){ } void LogService::Start(){ if(!isSync_){ Thread::Start(); } } void LogService::Stop(){ if(!isSync_){ Thread::Stop(); } } long LogService::Run(){ while(1){ { ScopedLock lock(mutex_); LogItem* item = queue_.Top(); while(item){ WriteLog(item->time, item->level, item->content); queue_.Pop(); item = queue_.Top(); } } event_.Wait(100); } return 0L; } void LogService::AddLog(char* owner, int level, const char* location, char* content){ if(level < level_) return; time_t currTime; time(&currTime); struct tm * timeinfo = localtime(&currTime); char logStr[1024]; snprintf(logStr, sizeof(logStr)-1, "[%02d:%02d:%02d][%d][%s][%s][%s]", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, level, owner, content, location); if(isSync_){ WriteLog(currTime, level, logStr); }else{ ScopedLock lock(mutex_); LogItem* item = queue_.Bottom(); if(item){ item->time = currTime; item->level = level; strncpy(item->content, logStr, sizeof(item->content)); } queue_.Push(); event_.Reset(); } } void LogService::CreateLogDir(){ if(ACCESS(LOG_DIR, 0) != 0){ MKDIR(LOG_DIR); } } void LogService::WriteLog(time_t time, int level, char* str){ struct tm * timeinfo = localtime(&time); char filePath[1024]; snprintf(filePath, sizeof(filePath), "%s/%04d-%02d-%02d-%s.log", LOG_DIR, timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, _logIocService->GetArg(ARGS_APP_NAME)); FILE* f = fopen(filePath, "a+"); if(f){ fputs(str, f); fputs("\n", f); fclose(f); } if(level == LOG_LEVEL_DEBUG) printf("%s\n", str); } LogIocService::LogIocService(){ } LogIocService::~LogIocService(){ } IContainer* LogIocService::GetContainer() { return container_; } XMLElement* LogIocService::GetConfig() { return config_; } const char* LogIocService::GetArg(const char* name) { ArgMap::iterator it = args_.find(std::string(name)); if(it != args_.end()){ return it->second.c_str(); } return NULL; } void LogIocService::SetContainer(IContainer* container) { container_ = container; } void LogIocService::SetConfig(XMLElement* config) { config_ = config; } void LogIocService::SetArg(const char* name, const char* value) { args_[std::string(name)] = std::string(value); } LogMngService::LogMngService(){ } LogMngService::~LogMngService(){ } void LogMngService::OnEvent(int eventType){ switch(eventType){ case MANAGER_EVENT_INIT : if(_logService) _logService->Init(); break; case MANAGER_EVENT_START : if(_logService) _logService->Start(); break; case MANAGER_EVENT_STOP : if(_logService) _logService->Stop(); break; case MANAGER_EVENT_UNINIT : if(_logService) _logService->UnInit(); break; } } }//namespace x void FUNC_CALL GetPluginInfo(x::PluginInfo& info){ info.caption = PLUGIN_LOG; info.version = __DATE__""__TIME__; } bool FUNC_CALL GetServiceInfo(int index, x::ServiceInfo& info){ switch(index){ case 0: info.id = SID_LOG; info.caption = ""; info.version = __DATE__":"__TIME__; return true; default:return false; } } x::IService* FUNC_CALL GetService(const char* id){ if(strcmp(id, SID_LOG) == 0){ return x::_logService; }else if(strcmp(id, SID_IOC) == 0){ return x::_logIocService; }else if(strcmp(id, SID_MANAGER) == 0){ return x::_logMngService; } return NULL; }
18.497738
85
0.670254
willenchou
7111a51a8969653c67e938d64d7a78de970f5b35
3,297
cpp
C++
src/obproxy/prometheus/ob_prometheus_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
74
2021-05-31T15:23:49.000Z
2022-03-12T04:46:39.000Z
src/obproxy/prometheus/ob_prometheus_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
16
2021-05-31T15:26:38.000Z
2022-03-30T06:02:43.000Z
src/obproxy/prometheus/ob_prometheus_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
64
2021-05-31T15:25:36.000Z
2022-02-23T08:43:58.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX PROXY #include "prometheus/ob_prometheus_utils.h" #include "lib/oblog/ob_log.h" namespace oceanbase { namespace obproxy { namespace prometheus { using namespace oceanbase::common; const char* ObProxyPrometheusUtils::get_metric_lable(ObPrometheusMetrics metric) { switch(metric) { case PROMETHEUS_PREPARE_SEND_REQUEST_TIME: return "prepare"; case PROMETHEUS_SERVER_PROCESS_REQUEST_TIME: return "server"; case PROMETHEUS_REQUEST_TOTAL_TIME: return "total"; default: return "UNKNOWN"; } } const char* ObProxyPrometheusUtils::get_type_lable(ObPrometheusEntryType type) { switch(type) { case TBALE_ENTRY: return "table_entry"; case PARTITION_ENTRY: return "partition_entry"; case ROUTE_ENTRY: return "route_entry"; default: return "UNKNOWN"; } } int ObProxyPrometheusUtils::calc_buf_size(ObVector<ObPrometheusLabel> *labels, uint32_t &buf_size) { int ret = OB_SUCCESS; buf_size = 0; for (int i = 0; i < labels->size(); i++) { ObPrometheusLabel &label = labels->at(i); if (label.is_value_need_alloc()) { buf_size += label.get_value().length(); } } return ret; } int ObProxyPrometheusUtils::copy_label_hash(ObVector<ObPrometheusLabel> *labels, ObVector<ObPrometheusLabel> &dst_labels, unsigned char *buf, uint32_t buf_len) { int ret = OB_SUCCESS; uint64_t offset = 0; for (int i = 0; i < labels->size() && OB_SUCC(ret); i++) { ObPrometheusLabel &label = labels->at(i); ObPrometheusLabel new_label; new_label.set_key(label.get_key()); if (label.is_value_need_alloc()) { if (buf != NULL && offset + label.get_value().length() <= buf_len) { ObString value; MEMCPY(buf + offset, label.get_value().ptr(), label.get_value().length()); value.assign_ptr(reinterpret_cast<char *>(buf + offset), label.get_value().length()); offset += label.get_value().length(); new_label.set_value(value); } else { ret = OB_ERR_UNEXPECTED; LOG_WARN("copy label meet unexpected error", K(offset), "value len", label.get_value().length(), K(buf_len)); } } else { new_label.set_value(label.get_value()); } if (OB_FAIL(dst_labels.push_back(new_label))) { LOG_WARN("put label into metric failed", K(new_label), K(ret)); } } return ret; } ObVector<ObPrometheusLabel>& ObProxyPrometheusUtils::get_thread_label_vector() { static __thread ObVector<ObPrometheusLabel> prometheus_thread_labels(10); return prometheus_thread_labels; } } // end of namespace prometheus } // end of namespace obproxy } // end of namespace oceanbase
28.669565
98
0.680619
stutiredboy
7115d1c31aa36071e9a5e88a4f00c823330369a0
3,636
cpp
C++
src/Button.cpp
18/PasswordManager
85a6fb03f1fea6a8494a13ccce5550ab9b414811
[ "Apache-2.0" ]
1
2018-12-06T00:45:23.000Z
2018-12-06T00:45:23.000Z
src/Button.cpp
18/PasswordManager
85a6fb03f1fea6a8494a13ccce5550ab9b414811
[ "Apache-2.0" ]
null
null
null
src/Button.cpp
18/PasswordManager
85a6fb03f1fea6a8494a13ccce5550ab9b414811
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 Krystian Stasiowski #include "Button.h" Button::Button(unsigned x, unsigned y, Color textcolor, Color backgroundcolor, Color selectedtextcolor, Color selectedbackgroundcolor, Color activatedtextcolor, const std::string& text, const std::string& selectedtext, const std::string& activatedtext, const std::function<void()>& activateaction, const std::function<void()>& deactivateaction, bool centered, bool show, bool activated) : Object(x, y, show), textcolor_(textcolor), backgroundcolor_(backgroundcolor), selectedtextcolor_(selectedtextcolor), selectedbackgroundcolor_(selectedbackgroundcolor), activatedtextcolor_(activatedtextcolor), text_(text), selectedtext_(selectedtext), activatedtext_(activatedtext), activateaction_(activateaction), deactivateaction_(deactivateaction), activated_(activated), selected_(false) { if (centered) x_ = (Console::GetSize().X - text.length()) / 2; if (show) Show(true); } void Button::Select() { Select(!selected_); } void Button::Select(bool select) { selected_ = select; if (!select) { if (activated_) { Console::ClearAt(x_, y_, activatedtext_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, backgroundcolor_); } else { Console::ClearAt(x_, y_, selectedtext_.length()); Console::WriteLineAt(x_, y_, text_, textcolor_, backgroundcolor_); } } else { if (activated_) { Console::ClearAt(x_, y_, selectedtext_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, selectedbackgroundcolor_); } else { Console::ClearAt(x_, y_, text_.length()); Console::WriteLineAt(x_, y_, selectedtext_, selectedtextcolor_, selectedbackgroundcolor_); } } } void Button::Press() { Press(!activated_); } bool Button::Hidden() const { return !show_; } void Button::Press(bool press) { activated_ = press; if (!press) { if (selected_) { Console::ClearAt(x_, y_, activatedtext_.length()); Console::WriteLineAt(x_, y_, selectedtext_, selectedtextcolor_, selectedbackgroundcolor_); } else { Console::ClearAt(x_, y_, activatedtext_.length()); Console::WriteLineAt(x_, y_, text_, textcolor_, backgroundcolor_); } deactivateaction_(); } else { if (selected_) { Console::ClearAt(x_, y_, selectedtext_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, selectedbackgroundcolor_); } else { Console::ClearAt(x_, y_, text_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, selectedbackgroundcolor_); } activateaction_(); } } void Button::Show(bool show) { show_ = show; if (show) { if (activated_) { Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, backgroundcolor_); } else if (selected_) { Console::WriteLineAt(x_, y_, selectedtext_, selectedtextcolor_, selectedbackgroundcolor_); } else { Console::WriteLineAt(x_, y_, text_, textcolor_, backgroundcolor_); } } else { if (activated_) { Console::ClearAt(x_, y_, activatedtext_.length()); } else if (selected_) { Console::ClearAt(x_, y_, selectedtext_.length()); } else { Console::ClearAt(x_, y_, text_.length()); } } } bool Button::Activated() const { return activated_; } bool Button::Selected() const { return selected_; } void Button::Move(int x, int y) { bool show = show_; if (show) Show(false); x_ = x; y_ = y; if (show) Show(true); }
24.734694
393
0.671617
18
711a1142d59343cc79012d7dee410650f9de72a6
369
cpp
C++
leetcode/338. Counting Bits/s1.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/338. Counting Bits/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/338. Counting Bits/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/counting-bits // Author: github.com/lzl124631x // Time: O(N) // Space: O(1) class Solution { public: vector<int> countBits(int num) { vector<int> ans(num + 1); for (int i = 1; i <= num; i *= 2) { ans[i] = 1; for (int j = 1; j < i && i + j <= num; ++j) ans[i + j] = ans[i] + ans[j]; } return ans; } };
24.6
79
0.520325
joycse06
711ac4d152e37cfec06cbed271607d3fe49f4d05
161
hpp
C++
osc-seq-cpp/src/filesystem/filesystem.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
osc-seq-cpp/src/filesystem/filesystem.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
osc-seq-cpp/src/filesystem/filesystem.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
#pragma once #include "../store/store.hpp" #include <string> void save_file(std::string path, Store& store); void open_file(std::string path, Store& store);
16.1
47
0.714286
Acaruso
7120d2b8ad8f6661da8a204eac1f2483f0a485c1
1,449
cpp
C++
primary/grmath.cpp
Wiladams/nd
9575e050c18225a138255a39de6c50954db2e731
[ "MIT" ]
11
2020-04-25T02:37:13.000Z
2021-08-08T13:08:36.000Z
primary/grmath.cpp
Wiladams/nd
9575e050c18225a138255a39de6c50954db2e731
[ "MIT" ]
null
null
null
primary/grmath.cpp
Wiladams/nd
9575e050c18225a138255a39de6c50954db2e731
[ "MIT" ]
null
null
null
#include "grmath.h" vec3 random_in_unit_disk() { while (true) { auto p = vec3(random_double_range(-1, 1), random_double_range(-1, 1), 0); if (p.lengthSquared() >= 1) continue; return p; } } vec3 random_unit_vector() { auto a = random_double_range(0, 2 * maths::Pi); auto z = random_double_range(-1, 1); auto r = sqrt(1 - z * z); return vec3(r * cos(a), r * sin(a), z); } vec3 random_in_unit_sphere() { while (true) { //auto p = vec3::random(-1, 1); auto p = random_vec3_range(-1, 1); if (p.lengthSquared() >= 1) continue; return p; } } vec3 random_in_hemisphere(const vec3& normal) { vec3 in_unit_sphere = random_in_unit_sphere(); if (dot(in_unit_sphere, normal) > 0.0) // In the same hemisphere as the normal return in_unit_sphere; else return -in_unit_sphere; } // These are here to be universal, but should probably // be in p5.cpp, or a specific app, like threed //template <> template <> vec<3, int> ::vec(const vec<3, float>& v) : x(int(v.x + .5f)), y(int(v.y + .5f)), z(int(v.z + .5f)) {} //template <> template <> vec<3, float>::vec(const vec<3, int>& v) : x((float)v.x), y((float)v.y), z((float)v.z) {} //template <> template <> vec<2, int> ::vec(const vec<2, float>& v) : x(int(v.x + .5f)), y(int(v.y + .5f)) {} //template <> template <> vec<2, float>::vec(const vec<2, int>& v) : x((float)v.x), y((float)v.y) {}
33.697674
129
0.585921
Wiladams
71255f887615f6b95557818672f14a96ac2dd586
5,904
hpp
C++
include/Simple-Utility/functional.hpp
DNKpp/Simple-Utility
db2d6cb1cc3849704f18272f8ce2d2bc05ad06a7
[ "BSL-1.0" ]
null
null
null
include/Simple-Utility/functional.hpp
DNKpp/Simple-Utility
db2d6cb1cc3849704f18272f8ce2d2bc05ad06a7
[ "BSL-1.0" ]
8
2021-12-30T22:07:39.000Z
2022-02-04T21:13:53.000Z
include/Simple-Utility/functional.hpp
DNKpp/Simple-Utility
db2d6cb1cc3849704f18272f8ce2d2bc05ad06a7
[ "BSL-1.0" ]
1
2020-08-19T13:02:58.000Z
2020-08-19T13:02:58.000Z
// Copyright Dominic Koepke 2019 - 2022. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #ifndef SL_UTILITY_FUNCTIONAL_HPP #define SL_UTILITY_FUNCTIONAL_HPP #pragma once #include <concepts> #include <functional> #include <type_traits> namespace sl::functional::detail { template <class TDerived> struct pipe; template <class TFunc1, class TFunc2> class composition_fn : public pipe<composition_fn<TFunc1, TFunc2>> { public: using function_type1 = TFunc1; using function_type2 = TFunc2; template <class TArg1, class TArg2> constexpr composition_fn ( TArg1&& arg1, TArg2&& arg2 ) noexcept(std::is_nothrow_constructible_v<TFunc1, TArg1> && std::is_nothrow_constructible_v<TFunc2, TArg2>) : m_Func1{ std::forward<TArg1>(arg1) }, m_Func2{ std::forward<TArg2>(arg2) } {} template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... v ) const noexcept(noexcept(std::invoke( std::declval<const TFunc2&>(), std::invoke(std::declval<const TFunc1&>(), std::forward<TArgs>(v)...) ))) { return std::invoke( m_Func2, std::invoke(m_Func1, std::forward<TArgs>(v)...) ); } template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... v ) noexcept(noexcept(std::invoke( std::declval<TFunc2&>(), std::invoke(std::declval<TFunc1&>(), std::forward<TArgs>(v)...) ))) { return std::invoke( m_Func2, std::invoke(m_Func1, std::forward<TArgs>(v)...) ); } private: [[no_unique_address]] TFunc1 m_Func1{}; [[no_unique_address]] TFunc2 m_Func2{}; }; template <class TFunc1, class TFunc2> composition_fn(TFunc1, TFunc2) -> composition_fn<std::remove_cvref_t<TFunc1>, std::remove_cvref_t<TFunc2>>; template <class TDerived> struct pipe { template <class TOther> constexpr auto operator | ( TOther&& other ) && noexcept(noexcept(composition_fn{ static_cast<TDerived&&>(*this), std::forward<TOther>(other) })) { return composition_fn{ static_cast<TDerived&&>(*this), std::forward<TOther>(other) }; } template <class TOther> constexpr auto operator | ( TOther&& other ) const & noexcept(noexcept(composition_fn{ static_cast<const TDerived&>(*this), std::forward<TOther>(other) })) { return composition_fn{ static_cast<const TDerived&>(*this), std::forward<TOther>(other) }; } template <class TLhs> friend constexpr auto operator | ( TLhs&& lhs, pipe&& rhs ) noexcept(noexcept(composition_fn{ std::forward<TLhs>(lhs), static_cast<TDerived&&>(rhs) })) requires (!requires { lhs.operator|(std::move(rhs)); }) { return composition_fn{ std::forward<TLhs>(lhs), static_cast<TDerived&&>(rhs) }; } template <class TLhs> friend constexpr auto operator | ( TLhs&& lhs, const pipe& rhs ) noexcept(noexcept(composition_fn{ std::forward<TLhs>(lhs), static_cast<const TDerived&>(rhs) })) requires (!requires { lhs.operator|(rhs); }) { return composition_fn{ std::forward<TLhs>(lhs), static_cast<const TDerived&>(rhs) }; } }; } namespace sl::functional { /** * \brief Helper type which accepts a functional type and enables pipe chaining. * \tparam TFunc The functional type. */ template <class TFunc> class transform_fn : public detail::pipe<transform_fn<TFunc>> { public: using function_type = TFunc; /** * \brief Forwards the constructor arguments to the internal functional object. * \tparam TArgs The constructor argument types. * \param args The constructor arguments. */ template <class... TArgs> requires std::constructible_from<TFunc, TArgs...> explicit constexpr transform_fn ( TArgs&&... args ) noexcept(std::is_nothrow_constructible_v<TFunc, TArgs...>) : m_Func{ std::forward<TArgs>(args)... } {} /** * \brief Invokes the internal functional with the given arguments. * \tparam TArgs The argument types. * \param args The arguments. * \return Returns as received by invocation. */ template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... args ) const noexcept(noexcept(std::invoke(std::declval<const TFunc&>(), args...))) { return std::invoke(m_Func, std::forward<TArgs>(args)...); } /** * \copydoc operator()() */ template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... args ) noexcept(noexcept(std::invoke(std::declval<TFunc&>(), args...))) { return std::invoke(m_Func, std::forward<TArgs>(args)...); } private: [[no_unique_address]] TFunc m_Func{}; }; /** * \brief Deduction guide. * \tparam TFunc Type of the given functional. */ template <class TFunc> transform_fn(TFunc) -> transform_fn<std::remove_cvref_t<TFunc>>; /** * \brief Functional object which static_cast the given argument to the target type on invocation. * \tparam TTarget The target type. */ template <class TTarget> inline constexpr transform_fn as{ []<class T>(T&& v) -> TTarget { return static_cast<TTarget>(std::forward<T>(v)); } }; /** * \brief Functional object which retrieves an object of a specific type from a tuple-like argument. * \tparam T The type to be retrieved. */ template <class T> inline constexpr transform_fn get{ []<class TTuple>(TTuple&& v) -> decltype(auto) { using std::get; return get<T>(std::forward<TTuple>(v)); } }; /** * \brief Functional object which retrieves an object at a specific index from a tuple-like argument. * \tparam VIndex The index of type to be retrieved. */ template <std::size_t VIndex> inline constexpr transform_fn get_at{ []<class TTuple>(TTuple&& v) -> decltype(auto) { using std::get; return get<VIndex>(std::forward<TTuple>(v)); } }; } #endif
23.902834
114
0.664634
DNKpp
712ba4926cb9a14eb7070608306e25d84e34ba23
1,708
cpp
C++
UI/TutorialHUD/Widget_KeyInput/Widget_KeyInputItem.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
UI/TutorialHUD/Widget_KeyInput/Widget_KeyInputItem.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
UI/TutorialHUD/Widget_KeyInput/Widget_KeyInputItem.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Widget_KeyInputItem.h" #include "Components/TextBlock.h" #include "Components/Image.h" void UWidget_KeyInputItem::NativeConstruct() { Super::NativeConstruct(); m_pKeyText = Cast<UTextBlock>(GetWidgetFromName(TEXT("KeyText"))); if (m_pKeyText == nullptr) { ULOG(TEXT("KeyText is nullptr")); return; } m_pKeyImg = Cast<UImage>(GetWidgetFromName(TEXT("KeyImg"))); if (m_pKeyImg == nullptr) { ULOG(TEXT("KeyImg is nullptr")); return; } } void UWidget_KeyInputItem::NativeDestruct() { Super::NativeDestruct(); if (m_pKeyText != nullptr) { if (m_pKeyText->IsValidLowLevel()) { m_pKeyText = nullptr; } } if (m_pKeyImg != nullptr) { if (m_pKeyImg->IsValidLowLevel()) { m_pKeyImg = nullptr; } } } void UWidget_KeyInputItem::NativeTick(const FGeometry& MyGeometry, float InDeltaTime) { Super::NativeTick(MyGeometry, InDeltaTime); } void UWidget_KeyInputItem::SetKeyText(const FText sKeyText, UTexture2D* pKeyImg) { if (m_pKeyText != nullptr) { m_sKeyState = sKeyText; if (pKeyImg == nullptr) { m_pKeyImg->SetBrushFromTexture(nullptr); m_pKeyImg->SetVisibility(ESlateVisibility::Hidden); m_pKeyText->SetVisibility(ESlateVisibility::SelfHitTestInvisible); m_pKeyText->SetText(sKeyText); } else { m_pKeyText->SetVisibility(ESlateVisibility::Hidden); m_pKeyImg->SetVisibility(ESlateVisibility::SelfHitTestInvisible); m_pKeyImg->SetBrushFromTexture(pKeyImg, true); } } } FText UWidget_KeyInputItem::GetKeyText() { if (m_pKeyText == nullptr) { ULOG(TEXT("KeyText is nullptr")); return FText::GetEmpty(); } return m_sKeyState; }
19.860465
85
0.719555
Bornsoul
7133ba40787d62c5e2c79058379ec01cab13c57b
8,259
cpp
C++
MEX/src/cpp/vision/features/feature_channels/hog_extractor.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
47
2016-07-25T00:48:59.000Z
2021-02-17T09:19:03.000Z
MEX/src/cpp/vision/features/feature_channels/hog_extractor.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
5
2016-09-17T19:40:46.000Z
2018-11-07T06:49:02.000Z
MEX/src/cpp/vision/features/feature_channels/hog_extractor.cpp
iqbalu/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
35
2016-07-21T09:13:15.000Z
2019-05-13T14:11:37.000Z
/* * hog_extractor.cpp * * Created on: Mar 22, 2012 * Author: Juergen Gall, mdantone */ #include <deque> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "hog_extractor.h" #include "cpp/vision/min_max_filter.hpp" using namespace std; using namespace cv; namespace vision { namespace features { namespace feature_channels { void HOGExtractor::extractFeatureChannels9(const cv::Mat& img, std::vector<cv::Mat>& Channels, bool use_max_filter) { // 9 feature channels // 3+9 channels: Lab + HOGlike features with 9 bins const int FEATURE_CHANNELS = 9; Channels.resize(FEATURE_CHANNELS); for (int c=0; c<FEATURE_CHANNELS; ++c) Channels[c].create(img.rows,img.cols, CV_8U); if( MIN(img.cols, img.rows) < 5 ){ cout <<"image is too small for HoG Extractor"<< endl; return; } Mat I_x; Mat I_y; // |I_x|, |I_y| Sobel(img,I_x,CV_16S,1,0,3); Sobel(img,I_y,CV_16S,0,1,3); //convertScaleAbs( I_x, Channels[3], 0.25); //convertScaleAbs( I_y, Channels[4], 0.25); int rows = I_x.rows; int cols = I_y.cols; Mat Iorient(img.rows,img.cols, CV_8UC1); Mat Imagn(img.rows,img.cols, CV_8UC1); if (I_x.isContinuous() && I_y.isContinuous() && Iorient.isContinuous() && Imagn.isContinuous()) { cols *= rows; rows = 1; } for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Iorient.ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { // Avoid division by zero float tx = (float)ptr_Ix[x] + (float)copysign(0.000001f, (float)ptr_Ix[x]); // Scaling [-pi/2 pi/2] -> [0 80*pi] ptr_out[x]=saturate_cast<uchar>( ( atan((float)ptr_Iy[x]/tx)+3.14159265f/2.0f ) * 80 ); } } // Magnitude of gradients for (int y = 0; y < rows; y++) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Imagn.ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { ptr_out[x] = saturate_cast<uchar>( sqrt((float)ptr_Ix[x]*(float)ptr_Ix[x] + (float)ptr_Iy[x]*(float)ptr_Iy[x])); } } // 9-bin HOG feature stored at vImg[7] - vImg[15] hog.extractOBin(Iorient, Imagn, Channels, 0); //max filter if( use_max_filter ) { for(int c=0; c<Channels.size(); ++c) ::vision::MinMaxFilter::maxfilt(Channels[c], 5); } } void HOGExtractor::extractFeatureChannels15(const cv::Mat& img, std::vector<cv::Mat>& Channels) { // 9 feature channels // 3+9 channels: Lab + HOGlike features with 9 bins const int FEATURE_CHANNELS = 15; Channels.resize(FEATURE_CHANNELS); for (int c=0; c<FEATURE_CHANNELS; ++c) Channels[c].create(img.rows,img.cols, CV_8U); if( MIN(img.cols, img.rows) < 5 ){ cout <<"image is too small for HoG Extractor"<< endl; return; } Mat I_x; Mat I_y; // Get intensity cvtColor( img, Channels[0], CV_RGB2GRAY ); // |I_x|, |I_y| Sobel(Channels[0],I_x,CV_16S,1,0,3); Sobel(Channels[0],I_y,CV_16S,0,1,3); //convertScaleAbs( I_x, Channels[3], 0.25); //convertScaleAbs( I_y, Channels[4], 0.25); int rows = I_x.rows; int cols = I_y.cols; if (I_x.isContinuous() && I_y.isContinuous() && Channels[1].isContinuous() && Channels[2].isContinuous()) { cols *= rows; rows = 1; } for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Channels[1].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { // Avoid division by zero float tx = (float)ptr_Ix[x] + (float)copysign(0.000001f, (float)ptr_Ix[x]); // Scaling [-pi/2 pi/2] -> [0 80*pi] ptr_out[x]=saturate_cast<uchar>( ( atan((float)ptr_Iy[x]/tx)+3.14159265f/2.0f ) * 80 ); } } // Magnitude of gradients for (int y = 0; y < rows; y++) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Channels[2].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { ptr_out[x] = saturate_cast<uchar>( sqrt((float)ptr_Ix[x]*(float)ptr_Ix[x] + (float)ptr_Iy[x]*(float)ptr_Iy[x])); } } // 9-bin HOG feature stored at vImg[7] - vImg[15] hog.extractOBin(Channels[1], Channels[2], Channels, 3); // |I_xx|, |I_yy| //Sobel(Channels[0],I_x,CV_16S, 2,0,3); //convertScaleAbs( I_x, Channels[5], 0.25); //Sobel(Channels[0],I_y,CV_16S, 0,2,3); //convertScaleAbs( I_y, Channels[6], 0.25); // L, a, b Mat imgRGB(img.size(), CV_8UC3); cvtColor( img, imgRGB, CV_RGB2Lab ); // Split color channels // overwriting the first 3 channels // Mat out[] = { Channels[0], Channels[1], Channels[2] }; // int from_to[] = { 0,0 , 1,1, 2,2 }; // mixChannels( &imgRGB, 1, out, 3, from_to, 3 ); split(imgRGB, &Channels[0]); // min filter for(int c=0; c<3; ++c) MinMaxFilter::minfilt(Channels[c], Channels[c+12], 5); //max filter for(int c=0; c<12; ++c) MinMaxFilter::maxfilt(Channels[c], 5); #if 0 // Debug namedWindow( "Show", CV_WINDOW_AUTOSIZE ); for(int i=0; i<FEATURE_CHANNELS; i++) { imshow( "Show", Channels[i] ); waitKey(0); } #endif } void HOGExtractor::extractFeatureChannels(const Mat& img, std::vector<cv::Mat>& channels) { // 32 feature channels // 7+9 channels: L, a, b, |I_x|, |I_y|, |I_xx|, |I_yy|, HOGlike features // with 9 bins (weighted orientations 5x5 neighborhood) // 16+16 channels: minfilter + MinMaxFilter::maxfilter on 5x5 neighborhood assert( img.channels() == 3); channels.resize(32); for(int c=0; c<32; ++c) channels[c].create(img.rows,img.cols, CV_8U); Mat I_x; Mat I_y; // Get intensity cvtColor( img, channels[0], CV_RGB2GRAY ); // |I_x|, |I_y| Sobel(channels[0],I_x,CV_16S,1,0,3); Sobel(channels[0],I_y,CV_16S,0,1,3); convertScaleAbs( I_x, channels[3], 0.25); convertScaleAbs( I_y, channels[4], 0.25); int rows = I_x.rows; int cols = I_y.cols; if (I_x.isContinuous() && I_y.isContinuous() && channels[1].isContinuous() && channels[2].isContinuous()) { cols *= rows; rows = 1; } for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = channels[1].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { // Avoid division by zero float tx = (float)ptr_Ix[x] + (float)copysign(0.000001f, (float)ptr_Ix[x]); // Scaling [-pi/2 pi/2] -> [0 80*pi] ptr_out[x]=saturate_cast<uchar>( (atan((float)ptr_Iy[x]/tx)+3.14159265f/2.0f) * 80); } } // Magnitude of gradients for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = channels[2].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { ptr_out[x] = saturate_cast<uchar>( sqrt((float)ptr_Ix[x]*(float)ptr_Ix[x] + (float)ptr_Iy[x]*(float)ptr_Iy[x])); } } // 9-bin HOG feature stored at vImg[7] - vImg[15] hog.extractOBin(channels[1], channels[2], channels, 7); // |I_xx|, |I_yy| Sobel(channels[0],I_x,CV_16S, 2,0,3); convertScaleAbs( I_x, channels[5], 0.25); Sobel(channels[0],I_y,CV_16S, 0,2,3); convertScaleAbs( I_y, channels[6], 0.25); // L, a, b Mat img_; cvtColor( img, img_, CV_RGB2Lab ); // Split color channels Mat out[] = { channels[0], channels[1], channels[2] }; int from_to[] = { 0,0 , 1,1, 2,2 }; mixChannels( &img_, 1, out, 3, from_to, 3 ); // int num_treads = boost::thread::hardware_concurrency(); { // boost::thread_pool::executor e(num_treads); // min filter for(int c=0; c<16; ++c){ // e.submit(boost::bind(&HOGExtractor::minfilt, // channels[old_size+c], channels[old_size+c+16], 5 )); MinMaxFilter::minfilt(channels[c], channels[c+16], 5); } // e.join_all(); } { // boost::thread_pool::executor e(num_treads); // max filter for(int c=0; c<16; ++c){ // e.submit(boost::bind(&HOGExtractor::MinMaxFilter::maxfilt, channels[old_size+c], 5 )); MinMaxFilter::maxfilt(channels[c], 5); } // e.join_all(); } #if 0 // Debug namedWindow( "Show", CV_WINDOW_AUTOSIZE ); for(int i=0; i<32; i++) { imshow( "Show", channels[old_size+i] ); waitKey(0); } #endif } } // namespace vision } // namespace features } // namespace feature_channels
26.053628
93
0.61097
umariqb
7136d585e28bc662454d5dffa282fa54b103b441
729
cpp
C++
tests/functionality/structures/matrices/dense/mathematical.cpp
szymonmaszke/numpp
9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9
[ "MIT" ]
10
2018-06-06T01:51:17.000Z
2021-01-02T15:17:00.000Z
tests/functionality/structures/matrices/dense/mathematical.cpp
vyzyv/numpp
9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9
[ "MIT" ]
2
2018-11-28T12:15:46.000Z
2018-12-16T00:03:38.000Z
tests/functionality/structures/matrices/dense/mathematical.cpp
szymonmaszke/numpp
9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9
[ "MIT" ]
2
2017-08-06T13:58:27.000Z
2018-04-06T06:45:22.000Z
#include "../../../../utilities/catch.hpp" #include "numpp/structures/matrices/dense.hpp" TEST_CASE( "dense matrix functions tests", "[mathemathical][matrix][dense][constexpr]" ){ constexpr numpp::matrix::dense<double, 4, 5> matrix{ 1.2, -4.5, 12412.3, 12512., 294.2352, 2, 5.35, -412.3, 12, 0, -34, 0, 0, 0, 4.5, 3, 1.3, 1.7, 0, 0.1 }; SECTION("log tests"){ constexpr auto matrix_log = std::log(matrix); REQUIRE(matrix_log(1,1) == std::log(matrix(1,1))); REQUIRE(matrix_log(2,3) == std::log(matrix(2,3))); } SECTION("pow tests"){ constexpr auto matrix_pow = std::pow(matrix, 2); REQUIRE(matrix_pow(1,1) == std::pow(matrix(1,1))); REQUIRE(matrix_pow(2,3) == std::pow(matrix(2,3))); } }
27
54
0.615912
szymonmaszke
713835ea7ab96a01ba37edae5b5b3ff5d5a60123
3,382
cpp
C++
cppLib/code/dep/G3D/source/Stopwatch.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
3
2019-05-14T07:19:59.000Z
2019-05-14T08:08:25.000Z
cppLib/code/dep/G3D/source/Stopwatch.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
null
null
null
cppLib/code/dep/G3D/source/Stopwatch.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
1
2018-08-08T07:39:16.000Z
2018-08-08T07:39:16.000Z
/** @file Stopwatch.cpp @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2005-10-05 @edited 2009-03-14 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #include "G3D/Stopwatch.h" #include "G3D/System.h" namespace G3D { Stopwatch::Stopwatch(const std::string& myName) : myName(myName), inBetween(false), lastTockTime(-1), lastDuration(0), lastCycleCount(0), m_fps(0), emwaFPS(0), m_smoothFPS(0), emwaDuration(0) { computeOverhead(); reset(); } void Stopwatch::computeOverhead() { cycleOverhead = 0; tick(); tock(); cycleOverhead = elapsedCycles(); } void Stopwatch::tick() { // This is 'alwaysAssert' instead of 'debugAssert' // since people rarely profile in debug mode. alwaysAssertM(! inBetween, "Stopwatch::tick() called twice in a row."); inBetween = true; // We read RDTSC twice here, but it is more abstract to implement this // way and at least we're reading the cycle count last. timeStart = System::time(); System::beginCycleCount(cycleStart); } void Stopwatch::tock() { System::endCycleCount(cycleStart); RealTime now = System::time(); lastDuration = now - timeStart; if (abs(emwaDuration - lastDuration) > max(emwaDuration, lastDuration) * 0.50) { // Off by more than 50% emwaDuration = lastDuration; } else { emwaDuration = lastDuration * 0.05 + emwaDuration * 0.95; } lastCycleCount = cycleStart - cycleOverhead; if (lastCycleCount < 0) { lastCycleCount = 0; } if (lastTockTime != -1.0) { m_fps = 1.0 / (now - lastTockTime); const double blend = 0.01; emwaFPS = m_fps * blend + emwaFPS * (1.0 - blend); double maxDiscrepancyPercentage = 0.25; if (abs(emwaFPS - m_fps) > max(emwaFPS, m_fps) * maxDiscrepancyPercentage) { // The difference between emwa and m_fps is way off, so // update emwa directly. emwaFPS = m_fps * 0.20 + emwaFPS * 0.80; } // Update m_smoothFPS only when the value varies significantly. // We round so as to not mislead the user as to the accuracy of // the number. if (m_smoothFPS == 0) { m_smoothFPS = m_fps; } else if (emwaFPS <= 20) { if (::fabs(m_smoothFPS - emwaFPS) > 0.75) { // Small number and display is off by more than 0.75; round to the nearest 0.1 m_smoothFPS = floor(emwaFPS * 10.0 + 0.5) / 10.0; } } else if (::fabs(m_smoothFPS - emwaFPS) > 1.25) { // Large number and display is off by more than 1.25; round to the nearest 1.0 m_smoothFPS = floor(emwaFPS + 0.5); } } lastTockTime = now; alwaysAssertM(inBetween, "Stopwatch::tock() called without matching tick."); inBetween = false; } void Stopwatch::reset() { prevTime = startTime = System::time(); prevMark = "start"; } void Stopwatch::after(const std::string& s) { RealTime now = System::time(); if (m_enabled) { debugPrintf("%s: %10s - %8fs since %s (%fs since start)\n", myName.c_str(), s.c_str(), now - prevTime, prevMark.c_str(), now - startTime); } prevTime = now; prevMark = s; } }
27.950413
94
0.591366
DrYaling
7142ada1847c6a703e24bcca79e470d6ff2ef011
15,222
cpp
C++
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-10-19T13:45:40.000Z
2020-12-10T20:21:03.000Z
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
expertisesolutions/dali-adaptor
810bf4dea833ea7dfbd2a0c82193bc0b3b155011
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/internal/text/text-abstraction/bidirectional-support-impl.h> // EXTERNAL INCLUDES #include <memory.h> #include <fribidi/fribidi.h> #include <dali/integration-api/debug.h> #include <dali/devel-api/common/singleton-service.h> namespace Dali { namespace TextAbstraction { namespace Internal { namespace { typedef unsigned char BidiDirection; // Internal charcter's direction. const BidiDirection LEFT_TO_RIGHT = 0u; const BidiDirection NEUTRAL = 1u; const BidiDirection RIGHT_TO_LEFT = 2u; /** * @param[in] paragraphDirection The FriBiDi paragraph's direction. * * @return Whether the paragraph is right to left. */ bool GetBidiParagraphDirection( FriBidiParType paragraphDirection ) { switch( paragraphDirection ) { case FRIBIDI_PAR_RTL: // Right-To-Left paragraph. case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph. { return true; } case FRIBIDI_PAR_LTR: // Left-To-Right paragraph. case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph. case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph. { return false; } } return false; } BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection ) { switch( characterDirection ) { case FRIBIDI_TYPE_LTR: // Left-To-Right letter. { return LEFT_TO_RIGHT; } case FRIBIDI_TYPE_AL: // Arabic Letter. case FRIBIDI_TYPE_RTL: // Right-To-Left letter. { return RIGHT_TO_LEFT; } case FRIBIDI_TYPE_AN: // Arabic Numeral. case FRIBIDI_TYPE_ES: // European number Separator. case FRIBIDI_TYPE_ET: // European number Terminator. case FRIBIDI_TYPE_EN: // European Numeral. default : { return NEUTRAL; } } } } struct BidirectionalSupport::Plugin { /** * Stores bidirectional info per paragraph. */ struct BidirectionalInfo { FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...) FriBidiLevel* embeddedLevels; ///< Embedded levels. FriBidiParType paragraphDirection; ///< The paragraph's direction. }; Plugin() : mParagraphBidirectionalInfo(), mFreeIndices() {} ~Plugin() { // free all resources. for( Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin(), endIt = mParagraphBidirectionalInfo.End(); it != endIt; ++it ) { BidirectionalInfo* info = *it; free( info->embeddedLevels ); free( info->characterTypes ); delete info; } } BidiInfoIndex CreateInfo( const Character* const paragraph, Length numberOfCharacters, bool matchSystemLanguageDirection, LayoutDirection::Type layoutDirection ) { // Reserve memory for the paragraph's bidirectional info. BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo(); bidirectionalInfo->characterTypes = reinterpret_cast<FriBidiCharType*>( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) ); if( !bidirectionalInfo->characterTypes ) { delete bidirectionalInfo; return 0; } bidirectionalInfo->embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) ); if( !bidirectionalInfo->embeddedLevels ) { free( bidirectionalInfo->characterTypes ); delete bidirectionalInfo; return 0; } // Retrieve the type of each character.. fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes ); // Retrieve the paragraph's direction. bidirectionalInfo->paragraphDirection = matchSystemLanguageDirection == true ? ( layoutDirection == LayoutDirection::RIGHT_TO_LEFT ? FRIBIDI_PAR_RTL : FRIBIDI_PAR_LTR ) : ( fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters ) ); // Retrieve the embedding levels. if (fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels ) == 0) { free( bidirectionalInfo->characterTypes ); delete bidirectionalInfo; return 0; } // Store the bidirectional info and return the index. BidiInfoIndex index = 0u; if( 0u != mFreeIndices.Count() ) { Vector<BidiInfoIndex>::Iterator it = mFreeIndices.End() - 1u; index = *it; mFreeIndices.Remove( it ); *( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo; } else { index = static_cast<BidiInfoIndex>( mParagraphBidirectionalInfo.Count() ); mParagraphBidirectionalInfo.PushBack( bidirectionalInfo ); } return index; } void DestroyInfo( BidiInfoIndex bidiInfoIndex ) { if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() ) { return; } // Retrieve the paragraph's bidirectional info. Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex; BidirectionalInfo* bidirectionalInfo = *it; if( NULL != bidirectionalInfo ) { // Free resources and destroy the container. free( bidirectionalInfo->embeddedLevels ); free( bidirectionalInfo->characterTypes ); delete bidirectionalInfo; *it = NULL; } // Add the index to the free indices vector. mFreeIndices.PushBack( bidiInfoIndex ); } void Reorder( BidiInfoIndex bidiInfoIndex, CharacterIndex firstCharacterIndex, Length numberOfCharacters, CharacterIndex* visualToLogicalMap ) { const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC; // Retrieve the paragraph's bidirectional info. const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); // Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table. for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) { visualToLogicalMap[ index ] = index; } // Copy embedded levels as fribidi_reorder_line() may change them. const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel ); FriBidiLevel* embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( embeddedLevelsSize ) ); if( embeddedLevels ) { memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize ); // Reorder the line. if (fribidi_reorder_line( flags, bidirectionalInfo->characterTypes + firstCharacterIndex, numberOfCharacters, 0u, bidirectionalInfo->paragraphDirection, embeddedLevels, NULL, reinterpret_cast<FriBidiStrIndex*>( visualToLogicalMap ) ) == 0) { DALI_LOG_ERROR("fribidi_reorder_line is failed\n"); } // Free resources. free( embeddedLevels ); } } bool GetMirroredText( Character* text, CharacterDirection* directions, Length numberOfCharacters ) const { bool updated = false; for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) { // Get a reference to the character inside the text. Character& character = *( text + index ); // Retrieve the mirrored character. FriBidiChar mirroredCharacter = character; bool mirrored = false; if( *( directions + index ) ) { mirrored = fribidi_get_mirror_char( character, &mirroredCharacter ); } updated = updated || mirrored; // Update the character inside the text. character = mirroredCharacter; } return updated; } bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const { // Retrieve the paragraph's bidirectional info. const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection ); } void GetCharactersDirection( BidiInfoIndex bidiInfoIndex, CharacterDirection* directions, Length numberOfCharacters ) { const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection ); CharacterDirection previousDirection = paragraphDirection; for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) { CharacterDirection& characterDirection = *( directions + index ); CharacterDirection nextDirection = false; characterDirection = false; // Get the bidi direction. const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) ); if( RIGHT_TO_LEFT == bidiDirection ) { characterDirection = true; nextDirection = true; } else if( NEUTRAL == bidiDirection ) { // For neutral characters it check's the next and previous directions. // If they are equals set that direction. If they are not, sets the paragraph's direction. // If there is no next, sets the paragraph's direction. nextDirection = paragraphDirection; // Look for the next non-neutral character. Length nextIndex = index + 1u; for( ; nextIndex < numberOfCharacters; ++nextIndex ) { BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) ); if( nextBidiDirection != NEUTRAL ) { nextDirection = RIGHT_TO_LEFT == nextBidiDirection; break; } } // Calculate the direction for all the neutral characters. characterDirection = previousDirection == nextDirection ? previousDirection : paragraphDirection; // Set the direction to all the neutral characters. // The indices from currentIndex + 1u to nextIndex - 1u are neutral characters. ++index; for( ; index < nextIndex; ++index ) { CharacterDirection& nextCharacterDirection = *( directions + index ); nextCharacterDirection = characterDirection; } // Set the direction of the next non-neutral character. if( nextIndex < numberOfCharacters ) { *( directions + nextIndex ) = nextDirection; } } previousDirection = nextDirection; } } Vector<BidirectionalInfo*> mParagraphBidirectionalInfo; ///< Stores the bidirectional info per paragraph. Vector<BidiInfoIndex> mFreeIndices; ///< Stores indices of free positions in the bidirectional info vector. }; BidirectionalSupport::BidirectionalSupport() : mPlugin( NULL ) { } BidirectionalSupport::~BidirectionalSupport() { delete mPlugin; } TextAbstraction::BidirectionalSupport BidirectionalSupport::Get() { TextAbstraction::BidirectionalSupport bidirectionalSupportHandle; SingletonService service( SingletonService::Get() ); if( service ) { // Check whether the singleton is already created BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) ); if(handle) { // If so, downcast the handle BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() ); bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl ); } else // create and register the object { bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport ); service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle ); } } return bidirectionalSupportHandle; } BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph, Length numberOfCharacters, bool matchSystemLanguageDirection, Dali::LayoutDirection::Type layoutDirection ) { CreatePlugin(); return mPlugin->CreateInfo( paragraph, numberOfCharacters, matchSystemLanguageDirection, layoutDirection ); } void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex ) { CreatePlugin(); mPlugin->DestroyInfo( bidiInfoIndex ); } void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex, CharacterIndex firstCharacterIndex, Length numberOfCharacters, CharacterIndex* visualToLogicalMap ) { CreatePlugin(); mPlugin->Reorder( bidiInfoIndex, firstCharacterIndex, numberOfCharacters, visualToLogicalMap ); } bool BidirectionalSupport::GetMirroredText( Character* text, CharacterDirection* directions, Length numberOfCharacters ) { CreatePlugin(); return mPlugin->GetMirroredText( text, directions, numberOfCharacters ); } bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const { if( !mPlugin ) { return false; } return mPlugin->GetParagraphDirection( bidiInfoIndex ); } void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex, CharacterDirection* directions, Length numberOfCharacters ) { CreatePlugin(); mPlugin->GetCharactersDirection( bidiInfoIndex, directions, numberOfCharacters ); } void BidirectionalSupport::CreatePlugin() { if( !mPlugin ) { mPlugin = new Plugin(); } } } // namespace Internal } // namespace TextAbstraction } // namespace Dali
32.25
178
0.6509
Coquinho
71440bf8a627282b7f74ca76ec1ae778b3dcbc9e
3,127
cpp
C++
src/bindings/c++/iccp-c++.cpp
Geof23/sail
d09e5abe212cbc7f40ff61713a5f75a254e52764
[ "BSD-3-Clause-Clear", "MIT" ]
null
null
null
src/bindings/c++/iccp-c++.cpp
Geof23/sail
d09e5abe212cbc7f40ff61713a5f75a254e52764
[ "BSD-3-Clause-Clear", "MIT" ]
null
null
null
src/bindings/c++/iccp-c++.cpp
Geof23/sail
d09e5abe212cbc7f40ff61713a5f75a254e52764
[ "BSD-3-Clause-Clear", "MIT" ]
null
null
null
/* This file is part of SAIL (https://github.com/smoked-herring/sail) Copyright (c) 2020 Dmitry Baryshev The MIT License 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 <cstdlib> #include <cstring> #include "sail-common.h" #include "sail.h" #include "sail-c++.h" namespace sail { class SAIL_HIDDEN iccp::pimpl { public: pimpl() : iccp{nullptr, 0} { } ~pimpl() { sail_free(iccp.data); } sail_iccp iccp; }; iccp::iccp() : d(new pimpl) { } iccp::iccp(const iccp &ic) : iccp() { *this = ic; } iccp& iccp::operator=(const iccp &ic) { with_data(ic.data(), ic.data_length()); return *this; } iccp::iccp(iccp &&ic) noexcept { d = ic.d; ic.d = nullptr; } iccp& iccp::operator=(iccp &&ic) { delete d; d = ic.d; ic.d = nullptr; return *this; } iccp::~iccp() { delete d; } bool iccp::is_valid() const { return d->iccp.data != nullptr && d->iccp.data_length > 0; } const void* iccp::data() const { return d->iccp.data; } unsigned iccp::data_length() const { return d->iccp.data_length; } iccp& iccp::with_data(const void *data, unsigned data_length) { sail_free(d->iccp.data); d->iccp.data = nullptr; d->iccp.data_length = 0; if (data == nullptr || data_length == 0) { return *this; } SAIL_TRY_OR_EXECUTE(sail_malloc(data_length, &d->iccp.data), /* on error */ return *this); d->iccp.data_length = data_length; memcpy(d->iccp.data, data, data_length); return *this; } iccp::iccp(const sail_iccp *ic) : iccp() { if (ic == nullptr) { SAIL_LOG_DEBUG("NULL pointer has been passed to sail::iccp(). The object is untouched"); return; } with_data(ic->data, ic->data_length); } sail_status_t iccp::to_sail_iccp(sail_iccp *ic) const { SAIL_CHECK_ICCP_PTR(ic); SAIL_TRY(sail_malloc(d->iccp.data_length, &ic->data)); memcpy(ic->data, d->iccp.data, d->iccp.data_length); ic->data_length = d->iccp.data_length; return SAIL_OK; } }
20.846667
96
0.653342
Geof23
7145f113cf2ab526df1efd2d7d5ed5574f7ca300
811
cpp
C++
c++/leetcode/0572-Subtree_of_Another_Tree-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0572-Subtree_of_Another_Tree-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0572-Subtree_of_Another_Tree-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 572 Subtree of Another Tree // https://leetcode.com/problems/subtree-of-another-tree // version: 1; create time: 2019-12-30 11:34:15; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSame(TreeNode* s, TreeNode* t) { if (!s && !t) return true; if (!s || !t) return false; return s->val == t->val && isSame(s->left, t->left) && isSame(s->right, t->right); } bool isSubtree(TreeNode* s, TreeNode* t) { if (!s && !t) return true; if (!s || !t) return false; if (isSame(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t)) return true; return false; } };
27.965517
90
0.556104
levendlee
7149ff58d8822b0bd35b5efa19c3277a1bf648c8
1,270
cpp
C++
memory/intrusive_ptr.cpp
xujungp02/boost_guide
328516455d334506f824402455a17afc606ca3bc
[ "Apache-2.0" ]
355
2015-03-06T12:03:51.000Z
2022-03-28T04:15:00.000Z
memory/intrusive_ptr.cpp
lak123456/boost_guide
1886ec8014838717222484f0fe872ecebc324e91
[ "Apache-2.0" ]
1
2017-10-04T18:14:17.000Z
2017-10-09T02:38:12.000Z
memory/intrusive_ptr.cpp
lak123456/boost_guide
1886ec8014838717222484f0fe872ecebc324e91
[ "Apache-2.0" ]
202
2015-03-23T16:16:45.000Z
2022-03-28T07:55:48.000Z
// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> using namespace std; #include <boost/smart_ptr.hpp> using namespace boost; ////////////////////////////////////////// struct counted_data { // ... int m_count = 0; ~counted_data() { cout << "dtor" << endl; } }; void intrusive_ptr_add_ref(counted_data* p) { ++p->m_count; } void intrusive_ptr_release(counted_data* p) { if(--p->m_count == 0) { delete p; } } ////////////////////////////////////////// #include <boost/smart_ptr/intrusive_ref_counter.hpp> struct counted_data2 : public intrusive_ref_counter<counted_data2> { ~counted_data2() { cout << "dtor2" << endl; } }; ////////////////////////////////////////// int main() { typedef intrusive_ptr<counted_data> counted_ptr; counted_ptr p(new counted_data); assert(p); assert(p->m_count == 1); counted_ptr p2(p); assert(p->m_count == 2); counted_ptr weak_p(p.get(), false); assert(weak_p->m_count == 2); p2.reset(); assert(!p2); assert(p->m_count == 1); { typedef intrusive_ptr<counted_data2> counted_ptr; counted_ptr p(new counted_data2); assert(p); assert(p->use_count() == 1); } }
17.162162
66
0.540945
xujungp02
7155d64874e7ce4b6e55b4aa18f88e7c4c6615dd
2,490
cpp
C++
Arrays/create.cpp
rajeshkumarblr/datastructures
ca5ebbb44d65272ead8e20cda5f9fee2c326c58a
[ "MIT" ]
null
null
null
Arrays/create.cpp
rajeshkumarblr/datastructures
ca5ebbb44d65272ead8e20cda5f9fee2c326c58a
[ "MIT" ]
null
null
null
Arrays/create.cpp
rajeshkumarblr/datastructures
ca5ebbb44d65272ead8e20cda5f9fee2c326c58a
[ "MIT" ]
null
null
null
#include <iostream> #include <time.h> #include <stdlib.h> #include "arrayops.h" #include "dsutils.h" using namespace std; void allocateArray(int size) { if (arr) { delete[] arr; } arr = new int[size]; n = size; } void createArray(int st, int end, int incr) { int size = (end - st) / incr + 1; allocateArray(size); int val = st; for (int i=0; i<size; i++) { arr[i]= val; val += incr; } } void createArrayValues() { int num; cout << "Create array with specific elements:" << endl; cout << "Enter the number of elements:"; cin >> num; allocateArray(num); for (int i=0; i< num; i++) { cout << "Enter the next element(" << i << ")"; cin >> arr[i]; } printArray("created Array:",arr,n); } void createArrayRandom(int num, int min, int max) { allocateArray(num); srandom(time(NULL)); double mul = ((max - min) / (double) RAND_MAX); for (int i=0; i< num; i++) { arr[i] = min + (rand() * mul); } } void createArrayRandomDriver() { int start, end, incr, num; cout << "Create array with random elements:" << endl; cout << "Enter the number of elements:"; cin >> num; cout << " Enter the range (start end):"; cin >> start >> end; cout << "Entered range is: (" << start << " - " << end << "). number of elements: " << num << endl; createArrayRandom(num, start, end); printArray("created Array:",arr,n); } void createArrayRange() { int start, end, incr; cout << "Create array by range:" << endl; cout << " Enter the range (start end):"; cin >> start >> end; cout << " Enter the increment by value:"; cin >> incr; cout << "Entered range is: (" << start << " - " << end << "). increment by: " << incr << endl; createArray(start, end,incr); printArray("created Array:",arr,n); } static vector<string> menuoptions = { "Return To Main Menu...", "Create array with range of numbers", "Create array with random values", "Create by entering values...", }; void createArrayDriver() { int choice; bool isCreated = false; cout << " Create Array Menu:\n"; do { printArrayDriver(); app->displayMenu(menuoptions); cout << "Enter your choice:"; cin >> choice; switch(choice) { case 0: return; case 1: createArrayRange(); break; case 2: createArrayRandomDriver(); break; case 3: createArrayValues(); break; default: continue; } isCreated = true; } while(!isCreated); }
23.271028
101
0.583936
rajeshkumarblr
71562197278abdecea7b48012d7d31c61d099bc2
228
cpp
C++
lib/libc/tests/ctype/isalpha.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
52
2015-11-27T13:56:00.000Z
2021-12-01T16:33:58.000Z
lib/libc/tests/ctype/isalpha.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
4
2017-06-26T17:59:51.000Z
2021-09-26T17:30:32.000Z
lib/libc/tests/ctype/isalpha.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
8
2016-08-26T09:42:27.000Z
2021-12-04T00:21:05.000Z
#include <gtest/gtest.h> #include <ctype.h> TEST(ctype, isalpha) { EXPECT_TRUE(isalpha('a')); EXPECT_TRUE(isalpha('z')); EXPECT_FALSE(isalpha(' ')); EXPECT_FALSE(isalpha('1')); EXPECT_FALSE(isalpha('@')); }
19
31
0.627193
otaviopace
7157aa8407ffc5d2453a56d06f3a30aa281ae1f5
6,608
cc
C++
src/kernel/arch/x86/architecture.cc
cmejj/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
16,500
2015-01-01T00:47:42.000Z
2022-03-31T17:12:02.000Z
src/kernel/arch/x86/architecture.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
66
2015-01-08T15:22:11.000Z
2021-12-16T09:04:37.000Z
src/kernel/arch/x86/architecture.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
3,814
2015-01-01T12:42:31.000Z
2022-03-31T14:26:50.000Z
#include <os.h> #include <x86.h> /* Stack pointer */ extern u32 * stack_ptr; /* Current cpu name */ static char cpu_name[512] = "x86-noname"; /* Detect the type of processor */ char* Architecture::detect(){ cpu_vendor_name(cpu_name); return cpu_name; } /* Start and initialize the architecture */ void Architecture::init(){ io.print("Architecture x86, cpu=%s \n", detect()); io.print("Loading GDT \n"); init_gdt(); asm(" movw $0x18, %%ax \n \ movw %%ax, %%ss \n \ movl %0, %%esp"::"i" (KERN_STACK)); io.print("Loading IDT \n"); init_idt(); io.print("Configure PIC \n"); init_pic(); io.print("Loading Task Register \n"); asm(" movw $0x38, %ax; ltr %ax"); } /* Initialise the list of processus */ void Architecture::initProc(){ firstProc= new Process("kernel"); firstProc->setState(ZOMBIE); firstProc->addFile(fsm.path("/dev/tty"),0); firstProc->addFile(fsm.path("/dev/tty"),0); firstProc->addFile(fsm.path("/dev/tty"),0); plist=firstProc; pcurrent=firstProc; pcurrent->setPNext(NULL); process_st* current=pcurrent->getPInfo(); current->regs.cr3 = (u32) pd0; } /* Reboot the computer */ void Architecture::reboot(){ u8 good = 0x02; while ((good & 0x02) != 0) good = io.inb(0x64); io.outb(0x64, 0xFE); } /* Shutdown the computer */ void Architecture::shutdown(){ // todo } /* Install a interruption handler */ void Architecture::install_irq(int_handler h){ // todo } /* Add a process to the scheduler */ void Architecture::addProcess(Process* p){ p->setPNext(plist); plist=p; } /* Fork a process */ int Architecture::fork(process_st* info,process_st* father){ memcpy((char*)info,(char*)father,sizeof(process_st)); info->pd = pd_copy(father->pd); } /* Initialise a new process */ int Architecture::createProc(process_st* info, char* file, int argc, char** argv){ page *kstack; process_st *previous; process_st *current; char **param, **uparam; u32 stackp; u32 e_entry; int pid; int i; pid = 1; info->pid = pid; if (argc) { param = (char**) kmalloc(sizeof(char*) * (argc+1)); for (i=0 ; i<argc ; i++) { param[i] = (char*) kmalloc(strlen(argv[i]) + 1); strcpy(param[i], argv[i]); } param[i] = 0; } info->pd = pd_create(); INIT_LIST_HEAD(&(info->pglist)); previous = arch.pcurrent->getPInfo(); current=info; asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"((info->pd)->base->p_addr)); e_entry = (u32) load_elf(file,info); if (e_entry == 0) { for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (current->regs.cr3)); pd_destroy(info->pd); return -1; } stackp = USER_STACK - 16; if (argc) { uparam = (char**) kmalloc(sizeof(char*) * argc); for (i=0 ; i<argc ; i++) { stackp -= (strlen(param[i]) + 1); strcpy((char*) stackp, param[i]); uparam[i] = (char*) stackp; } stackp &= 0xFFFFFFF0; // Creation des arguments de main() : argc, argv[]... stackp -= sizeof(char*); *((char**) stackp) = 0; for (i=argc-1 ; i>=0 ; i--) { stackp -= sizeof(char*); *((char**) stackp) = uparam[i]; } stackp -= sizeof(char*); *((char**) stackp) = (char*) (stackp + 4); stackp -= sizeof(char*); *((int*) stackp) = argc; stackp -= sizeof(char*); for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); kfree(uparam); } kstack = get_page_from_heap(); // Initialise le reste des registres et des attributs info->regs.ss = 0x33; info->regs.esp = stackp; info->regs.eflags = 0x0; info->regs.cs = 0x23; info->regs.eip = e_entry; info->regs.ds = 0x2B; info->regs.es = 0x2B; info->regs.fs = 0x2B; info->regs.gs = 0x2B; info->regs.cr3 = (u32) info->pd->base->p_addr; info->kstack.ss0 = 0x18; info->kstack.esp0 = (u32) kstack->v_addr + PAGESIZE - 16; info->regs.eax = 0; info->regs.ecx = 0; info->regs.edx = 0; info->regs.ebx = 0; info->regs.ebp = 0; info->regs.esi = 0; info->regs.edi = 0; info->b_heap = (char*) ((u32) info->e_bss & 0xFFFFF000) + PAGESIZE; info->e_heap = info->b_heap; info->signal = 0; for(i=0 ; i<32 ; i++) info->sigfn[i] = (char*) SIG_DFL; arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3":: "m"(current->regs.cr3)); return 1; } // Destroy a process void Architecture::destroy_process(Process* pp){ disable_interrupt(); u16 kss; u32 kesp; u32 accr3; list_head *p, *n; page *pg; process_st *proccurrent=(arch.pcurrent)->getPInfo(); process_st *pidproc=pp->getPInfo(); // Switch page to the process to destroy asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (pidproc->regs.cr3)); // Free process memory: // - pages used by the executable code // - user stack // - kernel stack // - pages directory // Free process memory list_for_each_safe(p, n, &pidproc->pglist) { pg = list_entry(p, struct page, list); release_page_frame(pg->p_addr); list_del(p); kfree(pg); } release_page_from_heap((char *) ((u32)pidproc->kstack.esp0 & 0xFFFFF000)); // Free pages directory asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"(pd0)); pd_destroy(pidproc->pd); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (proccurrent->regs.cr3)); // Remove from the list if (plist==pp){ plist=pp->getPNext(); } else{ Process* l=plist; Process*ol=plist; while (l!=NULL){ if (l==pp){ ol->setPNext(pp->getPNext()); } ol=l; l=l->getPNext(); } } enable_interrupt(); } void Architecture::change_process_father(Process* pe, Process* pere){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getPParent()==pe){ p->setPParent(pere); } p=pn; } } void Architecture::destroy_all_zombie(){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getState()==ZOMBIE && p->getPid()!=1){ destroy_process(p); delete p; } p=pn; } } /* Set the syscall arguments */ void Architecture::setParam(u32 ret, u32 ret1, u32 ret2, u32 ret3,u32 ret4){ ret_reg[0]=ret; ret_reg[1]=ret1; ret_reg[2]=ret2; ret_reg[3]=ret3; ret_reg[4]=ret4; } /* Enable the interruption */ void Architecture::enable_interrupt(){ asm ("sti"); } /* Disable the interruption */ void Architecture::disable_interrupt(){ asm ("cli"); } /* Get a syscall argument */ u32 Architecture::getArg(u32 n){ if (n<5) return ret_reg[n]; else return 0; } /* Set the return value of syscall */ void Architecture::setRet(u32 ret){ stack_ptr[14] = ret; }
19.550296
82
0.615466
cmejj
715d14a0dcd1f93c08d98a5dd3b4c9ee626e05f3
2,021
cpp
C++
3rdparty/openbw/bwapi/bwapi/TestAIModule/Source/InterceptorTest.cpp
ratiotile/StardustDevEnvironment
15c512b81579d8bd663db3fa8e0847d4c27f17e8
[ "MIT" ]
8
2020-09-29T17:11:15.000Z
2022-01-29T20:41:33.000Z
3rdparty/openbw/bwapi/bwapi/TestAIModule/Source/InterceptorTest.cpp
ratiotile/StardustDevEnvironment
15c512b81579d8bd663db3fa8e0847d4c27f17e8
[ "MIT" ]
1
2021-03-08T17:43:05.000Z
2021-03-09T06:35:04.000Z
3rdparty/openbw/bwapi/bwapi/TestAIModule/Source/InterceptorTest.cpp
ratiotile/StardustDevEnvironment
15c512b81579d8bd663db3fa8e0847d4c27f17e8
[ "MIT" ]
1
2021-03-01T04:31:30.000Z
2021-03-01T04:31:30.000Z
#include "InterceptorTest.h" using namespace std; using namespace BWAPI; void InterceptorTest::onStart() { BWAssert(Broodwar->isMultiplayer()==false); BWAssert(Broodwar->isReplay()==false); Broodwar->enableFlag(Flag::UserInput); Broodwar->sendText("show me the money"); int correctCarrierCount = 2; int correctInterceptorCount = 8; BWAssert(Broodwar->self()->completedUnitCount(UnitTypes::Protoss_Carrier)==correctCarrierCount); Broodwar->printf("interceptor count = %d",Broodwar->self()->completedUnitCount(UnitTypes::Protoss_Interceptor)); BWAssert(Broodwar->self()->completedUnitCount(UnitTypes::Protoss_Interceptor)==correctInterceptorCount); int carrierCount=0; int interceptorCount=0; for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Carrier) carrierCount++; if (u->getType()==UnitTypes::Protoss_Interceptor) interceptorCount++; } BWAssert(carrierCount==correctCarrierCount); BWAssert(interceptorCount==correctInterceptorCount);//fails because we cannot see interceptors until the first time they leave the carrier. for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Carrier) { BWAssert(u->getInterceptorCount()==4); } } } void InterceptorTest::onFrame() { for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Interceptor) Broodwar->drawTextMap(u->getPosition(),"isLoaded = %d",u->isLoaded()); } for (Unit u : Broodwar->self()->getUnits()) { if (!u->isLoaded()) Broodwar->drawTextMap(u->getPosition().x,u->getPosition().y-20,"loaded unit count = %d",u->getLoadedUnits().size()); } for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Carrier) { Unitset interceptors = u->getInterceptors(); for (Unit i : interceptors) { Unit c=i->getCarrier(); Broodwar->drawLineMap(i->getPosition(),c->getPosition(),Colors::White); } } } }
34.844828
141
0.682335
ratiotile
7160834b20fd537d7941549a1efb729d579636fc
6,444
cpp
C++
src/NetProtocol/Protocols/nCiosDiscovery.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Protocols/nCiosDiscovery.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Protocols/nCiosDiscovery.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
#include <netprotocol.h> N::CiosDiscovery:: CiosDiscovery (void) : UdpDiscovery ( ) , neighbors (NULL) { setParameter ( "Myself" , false ) ; } N::CiosDiscovery::~CiosDiscovery (void) { if ( NotNull(neighbors) ) { if ( neighbors->Used <= 0 ) { delete neighbors ; } else { neighbors->Used-- ; } ; neighbors = NULL ; } ; } bool N::CiosDiscovery::Interpret(int code,QByteArray & line) { QString m ; switch ( code ) { case 0 : if ( ! Parameters [ "Initialize" ] . toBool ( ) ) { if ( Parameters [ "Method" ] . toString ( ) == "Listen" ) { setParameter ( "Initialize" , true ) ; setParameter ( "Interval" , 30 ) ; } else if ( Parameters [ "Method" ] . toString ( ) == "Probe" ) { setParameter ( "Initialize" , true ) ; setParameter ( "Trying" , 15 ) ; PlaceAddress ( 100 ) ; } else if ( Parameters [ "Method" ] . toString ( ) == "Broadcast" ) { setParameter ( "Initialize" , true ) ; setParameter ( "Interval" , 100 ) ; PlaceAddress ( 300 ) ; } else { } ; } else { if ( Parameters [ "Method" ] . toString ( ) == "Probe" ) { int trying = Parameters["Trying"].toInt() ; if ( trying > 0 ) { setParameter ( "Trying" , trying - 1 ) ; PlaceAddress ( 100 ) ; } else { setParameter ( "Running" , false ) ; } ; } else if ( Parameters [ "Method" ] . toString ( ) == "Broadcast" ) { PlaceAddress ( 300 ) ; } else if ( Parameters [ "Method" ] . toString ( ) == "Listen" ) { neighbors -> Verify ( ) ; } ; } ; break ; case 100 : m = QString::fromUtf8(line) ; PlaceAddress ( 200 ) ; break ; case 200 : m = QString::fromUtf8(line) ; AcceptAddress ( m ) ; break ; case 300 : m = QString::fromUtf8(line) ; AcceptAddress ( m ) ; PlaceAddress ( 200 ) ; break ; default : break ; } ; return true ; } QString N::CiosDiscovery::LocalAddress(void) { return QString ( "%1:%2" ) . arg ( Parameters [ "Address" ] . toString( ) ) . arg ( Parameters [ "Port" ] . toInt ( ) ) ; } void N::CiosDiscovery::PlaceAddress (int code) { if ( Data ( Output ) . size ( ) > 0 ) return ; QStringList s ; QString m ; s << QString::number ( code ) ; s << LocalAddress ( ) ; s << Parameters [ "Hostname" ] . toString ( ) ; s << Parameters [ "Application" ] . toString ( ) ; if ( Parameters . contains ( "Addresses" ) ) { s << Parameters [ "Addresses" ] . toString ( ) ; } ; m = s . join ( " " ) ; Place ( m ) ; } void N::CiosDiscovery::AcceptAddress (QString address) { if ( address.length() <= 0 ) return ; QStringList s = address . split ( ' ' ) ; if ( s . count ( ) < 3 ) return ; if ( s [ 0 ] == LocalAddress ( ) ) { setParameter ( "Myself" , true ) ; neighbors -> Verify ( ) ; } else { QString addr = s[0] ; QString host = s[1] ; QString apps = s[2] ; if ( s . count ( ) > 3 ) { for (int i=0;i<3;i++) { s . takeFirst ( ) ; } ; neighbors -> Others ( host , s ) ; } ; neighbors -> Update ( addr,host,apps ) ; setParameter ( "Accept" , addr ) ; } ; }
51.552
78
0.257294
Vladimir-Lin
7163ce0e902b4bbefe1d7e45af385505e51aacab
852
cpp
C++
src/fig00-test.cpp
carlos-urena/figs-gen
d9161efedddb13a7e067e8efe56bccc904c8e065
[ "MIT" ]
null
null
null
src/fig00-test.cpp
carlos-urena/figs-gen
d9161efedddb13a7e067e8efe56bccc904c8e065
[ "MIT" ]
null
null
null
src/fig00-test.cpp
carlos-urena/figs-gen
d9161efedddb13a7e067e8efe56bccc904c8e065
[ "MIT" ]
null
null
null
#include <iostream> #include <vec_mat.h> int main( int argc, char *argv[] ) { using namespace std ; cout << "\\documentclass[border=1mm]{standalone}" << endl << "\\input{../src/header.tex}" << endl ; const char * tex = R"tex( \tikzisometrico \begin{tikzpicture}[scale=1.4,isometricXYZ] \ejesvi{0.8}{1.5} \casita %% \circulox{0.4}{1.2} \path (1.2,0.0,0.0) node [above=.7cm,right=.3cm]{$\trota{\alpha,\vx}$}; \circulox{0.4}{1.2} \path (1.2,0.0,0.0) node [above right=.3cm and .5cm]{$\trotax{\theta}$}; \circuloy{0.4}{1.2} \path (0.0,1.2,0.0) node [left=.6cm] {$\trotay{\theta}$} ; \circuloz{0.4}{1.2} \path (0.0,0.0,1.2) node [above left=.3cm and .5cm] {$\trotaz{\theta}$} ; \end{tikzpicture} )tex"; cout << tex << endl << "\\end{document}" << endl ; }
26.625
100
0.543427
carlos-urena
716900084d66edb7864f1780ed8737da398ed885
34,154
cpp
C++
src/mechanisms.cpp
opendnssec/pkcs11-testing
cac56d02daadf333485c2376058db912dc37053a
[ "BSD-1-Clause" ]
14
2015-10-19T01:35:58.000Z
2020-10-09T09:49:04.000Z
src/mechanisms.cpp
opendnssec/pkcs11-testing
cac56d02daadf333485c2376058db912dc37053a
[ "BSD-1-Clause" ]
null
null
null
src/mechanisms.cpp
opendnssec/pkcs11-testing
cac56d02daadf333485c2376058db912dc37053a
[ "BSD-1-Clause" ]
3
2016-01-17T17:26:30.000Z
2022-02-08T09:46:11.000Z
/* $Id$ */ /* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /***************************************************************************** mechanisms.cpp Functions for mechanism tests *****************************************************************************/ #include "mechanisms.h" #include "error.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <unistd.h> extern CK_FUNCTION_LIST_PTR p11; int showMechs(char *slot) { CK_MECHANISM_TYPE_PTR pMechanismList; CK_SLOT_ID slotID; CK_RV rv; CK_ULONG ulMechCount; if (slot == NULL) { fprintf(stderr, "ERROR: A slot number must be supplied. " "Use --slot <number>\n"); return 1; } slotID = atoi(slot); // Get the size of the buffer rv = p11->C_GetMechanismList(slotID, NULL_PTR, &ulMechCount); if (rv == CKR_SLOT_ID_INVALID) { fprintf(stderr, "ERROR: The slot does not exist.\n"); return 1; } if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the number of mechanisms. rv=%s\n", rv2string(rv)); return 1; } pMechanismList = (CK_MECHANISM_TYPE_PTR)malloc(ulMechCount * sizeof(CK_MECHANISM_TYPE_PTR)); // Get the mechanism list rv = p11->C_GetMechanismList(slotID, pMechanismList, &ulMechCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the list of mechanisms. rv=%s\n", rv2string(rv)); free(pMechanismList); return 1; } printf("The following mechanisms are supported:\n"); printf("(key size is in bits or bytes depending on mechanism)\n\n"); for (int i = 0; i < ulMechCount; i++) { printMechInfo(slotID, pMechanismList[i]); } free(pMechanismList); return 0; } int testDNSSEC(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; int retVal = 0; printf("\n************************************************\n"); printf("* Testing what DNSSEC algorithms are available *\n"); printf("************************************************\n"); printf("\n(Cannot test GOST since it is not available in PKCS#11 v2.20)\n"); if (testDNSSEC_digest(slotID, hSession)) retVal = 1; if (testDNSSEC_rsa_keygen(slotID, hSession)) retVal = 1; if (testDNSSEC_rsa_sign(slotID, hSession)) retVal = 1; if (testDNSSEC_dsa_keygen(slotID, hSession)) retVal = 1; if (testDNSSEC_dsa_sign(slotID, hSession)) retVal = 1; return retVal; } int testSuiteB(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; int retVal = 0; printf("\n***************************************************\n"); printf("* Testing if NSA Suite B algorithms are available *\n"); printf("***************************************************\n"); if (testSuiteB_AES(slotID, hSession)) retVal = 1; if (testSuiteB_ECDSA(slotID, hSession)) retVal = 1; if (testSuiteB_ECDH(slotID, hSession)) retVal = 1; if (testSuiteB_SHA(slotID, hSession)) retVal = 1; return retVal; } int testSuiteB_AES(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_AES_KEY_GEN, CKM_AES_CBC, CKM_AES_CTR }; printf("\nTesting symmetric encryption\n"); printf("****************************\n"); printf(" (Not testing functionality)\n"); printf(" Should support between 128 and 256 bits.\n\n"); for (int i = 0; i < 3; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } if (info.ulMinKeySize > 16 || info.ulMaxKeySize < 32) { printf("OK, but only support %i-%i bits.\n", info.ulMinKeySize * 8, info.ulMaxKeySize * 8); } else { printf("OK\n"); } } return retVal; } int testSuiteB_ECDSA(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_EC_KEY_PAIR_GEN, CKM_ECDSA }; printf("\nTesting signatures\n"); printf("*********************\n"); printf(" (Not testing functionality)\n"); printf(" Should support between 256 and 384 bits.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } if (info.ulMinKeySize > 256 || info.ulMaxKeySize < 384) { printf("OK, but only support %i-%i bits\n", info.ulMinKeySize, info.ulMaxKeySize); } else { printf("OK\n"); } } return retVal; } int testSuiteB_ECDH(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE }; printf("\nTesting key agreement\n"); printf("*********************\n"); printf(" (Not testing functionality)\n"); printf(" Should support between 256 and 384 bits.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } if (info.ulMinKeySize > 256 || info.ulMaxKeySize < 384) { printf("OK, but only support %i-%i bits\n", info.ulMinKeySize, info.ulMaxKeySize); } else { printf("OK\n"); } } return retVal; } int testSuiteB_SHA(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_SHA256, CKM_SHA384 }; printf("\nTesting digesting\n"); printf("*****************\n"); printf(" (Not testing functionality)\n"); printf(" Will test if the digesting mechanisms are supported.\n"); printf(" If the digesting algorithms are not available, \n"); printf(" then digesting has to be done in the host application.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } return retVal; } int testDNSSEC_digest(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_BYTE_PTR digest; CK_ULONG digestLen; CK_BYTE data[] = {"Text to digest"}; CK_MECHANISM mechanism = { CKM_VENDOR_DEFINED, NULL_PTR, 0 }; CK_MECHANISM_TYPE types[] = { CKM_MD5, CKM_SHA_1, CKM_SHA256, CKM_SHA512 }; printf("\nTesting digesting\n"); printf("*****************\n"); printf(" Will test the digesting mechanisms.\n"); printf(" If the algorithm is not available, then digesting has to be done\n"); printf(" in the host application. (MD5 is not recommended to use)\n\n"); for (int i = 0; i < 4; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } mechanism.mechanism = types[i]; rv = p11->C_DigestInit(hSession, &mechanism); if (rv != CKR_OK) { printf("Available, but could not initialize digesting. rv=%s\n", rv2string(rv)); retVal = 1; continue; } rv = p11->C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, &digestLen); if (rv != CKR_OK) { printf("Available, but could not check the size of the digest. rv=%s\n", rv2string(rv)); retVal = 1; continue; } digest = (CK_BYTE_PTR)malloc(digestLen); rv = p11->C_Digest(hSession, data, sizeof(data)-1, digest, &digestLen); free(digest); if (rv != CKR_OK) { printf("Available, but could not digest the data. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } return retVal; } int testDNSSEC_rsa_keygen(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_OBJECT_HANDLE hPublicKey, hPrivateKey; CK_BBOOL ckTrue = CK_TRUE; CK_MECHANISM keyGenMechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0}; CK_BYTE publicExponent[] = { 1, 0, 1 }; CK_ATTRIBUTE publicKeyTemplate[] = { { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_WRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_MODULUS_BITS, NULL_PTR, 0 }, { CKA_PUBLIC_EXPONENT, &publicExponent, sizeof(publicExponent) } }; CK_ATTRIBUTE privateKeyTemplate[] = { { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_UNWRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) } }; CK_ULONG keySizes[] = { 512, 768, 1024, 1536, 2048, 3072, 4096 }; printf("\nTesting RSA key generation\n"); printf("**************************\n"); printf(" Will test if RSA key generation is supported.\n"); printf(" DNSSEC support keys up to 4096 bits.\n\n"); printf(" %s: ", getMechName(CKM_RSA_PKCS_KEY_PAIR_GEN)); rv = p11->C_GetMechanismInfo(slotID, CKM_RSA_PKCS_KEY_PAIR_GEN, &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); return 1; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); return 1; } if (info.ulMaxKeySize < 4096) { printf("OK, but support maximum %i bits\n", info.ulMaxKeySize); } else { printf("OK\n"); } for (int i = 0; i < 7; i++) { printf(" %i bits: ", keySizes[i]); CK_ULONG keySize = keySizes[i]; publicKeyTemplate[4].pValue = &keySize; publicKeyTemplate[4].ulValueLen = sizeof(keySize); rv = p11->C_GenerateKeyPair(hSession, &keyGenMechanism, publicKeyTemplate, 6, privateKeyTemplate, 6, &hPublicKey, &hPrivateKey); if (rv != CKR_OK) { printf("Failed. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); p11->C_DestroyObject(hSession, hPublicKey); p11->C_DestroyObject(hSession, hPrivateKey); } return retVal; } int testDNSSEC_rsa_sign(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_OBJECT_HANDLE hPublicKey, hPrivateKey; CK_BBOOL ckTrue = CK_TRUE; CK_MECHANISM keyGenMechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0}; CK_BYTE publicExponent[] = { 1, 0, 1 }; CK_ULONG modulusBits = 1024; CK_MECHANISM mechanism = { CKM_VENDOR_DEFINED, NULL_PTR, 0 }; CK_ULONG length; CK_BYTE_PTR pSignature; CK_BYTE data[] = {"Text"}; CK_ATTRIBUTE publicKeyTemplate[] = { { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_WRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_MODULUS_BITS, &modulusBits, sizeof(modulusBits) }, { CKA_PUBLIC_EXPONENT, &publicExponent, sizeof(publicExponent) } }; CK_ATTRIBUTE privateKeyTemplate[] = { { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_UNWRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) } }; CK_MECHANISM_TYPE types[] = { CKM_RSA_PKCS, CKM_RSA_X_509, CKM_MD5_RSA_PKCS, CKM_SHA1_RSA_PKCS, CKM_SHA256_RSA_PKCS, CKM_SHA512_RSA_PKCS }; printf("\nTesting RSA signing\n"); printf("*******************\n"); printf(" Will test if RSA signing is supported.\n"); printf(" Doing RAW RSA signing is not recommended (CKM_RSA_X_509)\n"); printf(" If the digesting algorithms are not available, \n"); printf(" then digesting has to be done in the host application.\n"); printf(" Then use the RSA only mechanisms.\n\n"); rv = p11->C_GenerateKeyPair(hSession, &keyGenMechanism, publicKeyTemplate, 6, privateKeyTemplate, 6, &hPublicKey, &hPrivateKey); if (rv != CKR_OK) { printf("Failed to generate a keypair. rv=%s\n", rv2string(rv)); printf("RSA is probably not supported\n"); return 1; } for (int i = 0; i < 6; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } mechanism.mechanism = types[i]; rv = p11->C_SignInit(hSession, &mechanism, hPrivateKey); if (rv != CKR_OK) { printf("Available, but could not initialize signing. rv=%s\n", rv2string(rv)); retVal = 1; continue; } rv = p11->C_Sign(hSession, data, sizeof(data)-1, NULL_PTR, &length); if (rv != CKR_OK) { printf("Available, but could not check the size of the signature. rv=%s\n", rv2string(rv)); retVal = 1; continue; } pSignature = (CK_BYTE_PTR)malloc(length); rv = p11->C_Sign(hSession, data, sizeof(data)-1, pSignature, &length); free(pSignature); if (rv != CKR_OK) { printf("Available, but could not sign the data. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } p11->C_DestroyObject(hSession, hPublicKey); p11->C_DestroyObject(hSession, hPrivateKey); return retVal; } int testDNSSEC_dsa_keygen(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_ULONG keySizes[] = { 512, 640, 768, 896, 1024 }; printf("\nTesting DSA key generation\n"); printf("**************************\n"); printf(" (Not testing functionality)\n"); printf(" Will test if DSA key generation is supported.\n"); printf(" DNSSEC support keys up to 1024 bits.\n\n"); printf(" %s: ", getMechName(CKM_DSA_PARAMETER_GEN)); rv = p11->C_GetMechanismInfo(slotID, CKM_DSA_PARAMETER_GEN, &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; } else if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; } else { if (info.ulMaxKeySize < 1024) { printf("OK, but support maximum %i bits\n", info.ulMaxKeySize); } else { printf("OK\n"); } } printf(" %s: ", getMechName(CKM_DSA_KEY_PAIR_GEN)); rv = p11->C_GetMechanismInfo(slotID, CKM_DSA_KEY_PAIR_GEN, &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; } else if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; } else { if (info.ulMaxKeySize < 1024) { printf("OK, but support maximum %i bits\n", info.ulMaxKeySize); } else { printf("OK\n"); } } // for (int i = 0; i < 5; i++) // { // } return retVal; } int testDNSSEC_dsa_sign(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_DSA, CKM_DSA_SHA1 }; printf("\nTesting DSA signing\n"); printf("*******************\n"); printf(" (Not testing functionality)\n"); printf(" Will test if DSA signing is supported.\n"); printf(" If the digesting algorithm is not available, \n"); printf(" then digesting has to be done in the host application.\n"); printf(" Then use the DSA only mechanism.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } return retVal; } void printMechInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE mechType) { CK_MECHANISM_INFO info; CK_RV rv; info.ulMinKeySize = 0; info.ulMaxKeySize = 0; printf("%-36s", getMechName(mechType)); rv = p11->C_GetMechanismInfo(slotID, mechType, &info); if (rv != CKR_OK) { printf(" Could not get info about the mechanism. rv=%s\n", rv2string(rv)); return; } printMechKeySize(info.ulMinKeySize, info.ulMaxKeySize); printMechFlags(info.flags); } void printMechKeySize(CK_ULONG ulMinKeySize, CK_ULONG ulMaxKeySize) { char buffer[512]; buffer[0] = '\0'; if (ulMinKeySize) { if (ulMaxKeySize > ulMinKeySize) { sprintf(buffer, "%i - %i", ulMinKeySize, ulMaxKeySize); } else { sprintf(buffer, "%i", ulMinKeySize); } } printf("%-14s", buffer); } void printMechFlags(CK_FLAGS flags) { std::string stringFlags = ""; if (flags & CKF_HW) { stringFlags += "HW "; flags ^= CKF_HW; } else { stringFlags += "No-HW "; } if (flags & CKF_ENCRYPT) { stringFlags += "encrypt "; flags ^= CKF_ENCRYPT; } if (flags & CKF_DECRYPT) { stringFlags += "decrypt "; flags ^= CKF_DECRYPT; } if (flags & CKF_DIGEST) { stringFlags += "digest "; flags ^= CKF_DIGEST; } if (flags & CKF_SIGN) { stringFlags += "sign "; flags ^= CKF_SIGN; } if (flags & CKF_SIGN_RECOVER) { stringFlags += "sign-recover "; flags ^= CKF_SIGN_RECOVER; } if (flags & CKF_VERIFY) { stringFlags += "verify "; flags ^= CKF_VERIFY; } if (flags & CKF_VERIFY_RECOVER) { stringFlags += "verify-recover "; flags ^= CKF_VERIFY_RECOVER; } if (flags & CKF_GENERATE) { stringFlags += "generate "; flags ^= CKF_GENERATE; } if (flags & CKF_GENERATE_KEY_PAIR) { stringFlags += "generate-key-pair "; flags ^= CKF_GENERATE_KEY_PAIR; } if (flags & CKF_WRAP) { stringFlags += "wrap "; flags ^= CKF_WRAP; } if (flags & CKF_UNWRAP) { stringFlags += "unwrap "; flags ^= CKF_UNWRAP; } if (flags & CKF_DERIVE) { stringFlags += "derive "; flags ^= CKF_DERIVE; } printf("%s\n", stringFlags.c_str()); } const char* getMechName(CK_MECHANISM_TYPE mechType) { static char buffer[20]; switch (mechType) { case CKM_RSA_PKCS_KEY_PAIR_GEN: return "CKM_RSA_PKCS_KEY_PAIR_GEN"; case CKM_RSA_PKCS: return "CKM_RSA_PKCS"; case CKM_RSA_9796: return "CKM_RSA_9796"; case CKM_RSA_X_509: return "CKM_RSA_X_509"; case CKM_MD2_RSA_PKCS: return "CKM_MD2_RSA_PKCS"; case CKM_MD5_RSA_PKCS: return "CKM_MD5_RSA_PKCS"; case CKM_SHA1_RSA_PKCS: return "CKM_SHA1_RSA_PKCS"; case CKM_RIPEMD128_RSA_PKCS: return "CKM_RIPEMD128_RSA_PKCS"; case CKM_RIPEMD160_RSA_PKCS: return "CKM_RIPEMD160_RSA_PKCS"; case CKM_RSA_PKCS_OAEP: return "CKM_RSA_PKCS_OAEP"; case CKM_RSA_X9_31_KEY_PAIR_GEN: return "CKM_RSA_X9_31_KEY_PAIR_GEN"; case CKM_RSA_X9_31: return "CKM_RSA_X9_31"; case CKM_SHA1_RSA_X9_31: return "CKM_SHA1_RSA_X9_31"; case CKM_RSA_PKCS_PSS: return "CKM_RSA_PKCS_PSS"; case CKM_SHA1_RSA_PKCS_PSS: return "CKM_SHA1_RSA_PKCS_PSS"; case CKM_DSA_KEY_PAIR_GEN: return "CKM_DSA_KEY_PAIR_GEN"; case CKM_DSA: return "CKM_DSA"; case CKM_DSA_SHA1: return "CKM_DSA_SHA1"; case CKM_DH_PKCS_KEY_PAIR_GEN: return "CKM_DH_PKCS_KEY_PAIR_GEN"; case CKM_DH_PKCS_DERIVE: return "CKM_DH_PKCS_DERIVE"; case CKM_X9_42_DH_KEY_PAIR_GEN: return "CKM_X9_42_DH_KEY_PAIR_GEN"; case CKM_X9_42_DH_DERIVE: return "CKM_X9_42_DH_DERIVE"; case CKM_X9_42_DH_HYBRID_DERIVE: return "CKM_X9_42_DH_HYBRID_DERIVE"; case CKM_X9_42_MQV_DERIVE: return "CKM_X9_42_MQV_DERIVE"; case CKM_SHA256_RSA_PKCS: return "CKM_SHA256_RSA_PKCS"; case CKM_SHA384_RSA_PKCS: return "CKM_SHA384_RSA_PKCS"; case CKM_SHA512_RSA_PKCS: return "CKM_SHA512_RSA_PKCS"; case CKM_SHA256_RSA_PKCS_PSS: return "CKM_SHA256_RSA_PKCS_PSS"; case CKM_SHA384_RSA_PKCS_PSS: return "CKM_SHA384_RSA_PKCS_PSS"; case CKM_SHA512_RSA_PKCS_PSS: return "CKM_SHA512_RSA_PKCS_PSS"; case CKM_SHA224_RSA_PKCS: return "CKM_SHA224_RSA_PKCS"; case CKM_SHA224_RSA_PKCS_PSS: return "CKM_SHA224_RSA_PKCS_PSS"; case CKM_RC2_KEY_GEN: return "CKM_RC2_KEY_GEN"; case CKM_RC2_ECB: return "CKM_RC2_ECB"; case CKM_RC2_CBC: return "CKM_RC2_CBC"; case CKM_RC2_MAC: return "CKM_RC2_MAC"; case CKM_RC2_MAC_GENERAL: return "CKM_RC2_MAC_GENERAL"; case CKM_RC2_CBC_PAD: return "CKM_RC2_CBC_PAD"; case CKM_RC4_KEY_GEN: return "CKM_RC4_KEY_GEN"; case CKM_RC4: return "CKM_RC4"; case CKM_DES_KEY_GEN: return "CKM_DES_KEY_GEN"; case CKM_DES_ECB: return "CKM_DES_ECB"; case CKM_DES_CBC: return "CKM_DES_CBC"; case CKM_DES_MAC: return "CKM_DES_MAC"; case CKM_DES_MAC_GENERAL: return "CKM_DES_MAC_GENERAL"; case CKM_DES_CBC_PAD: return "CKM_DES_CBC_PAD"; case CKM_DES2_KEY_GEN: return "CKM_DES2_KEY_GEN"; case CKM_DES3_KEY_GEN: return "CKM_DES3_KEY_GEN"; case CKM_DES3_ECB: return "CKM_DES3_ECB"; case CKM_DES3_CBC: return "CKM_DES3_CBC"; case CKM_DES3_MAC: return "CKM_DES3_MAC"; case CKM_DES3_MAC_GENERAL: return "CKM_DES3_MAC_GENERAL"; case CKM_DES3_CBC_PAD: return "CKM_DES3_CBC_PAD"; case CKM_CDMF_KEY_GEN: return "CKM_CDMF_KEY_GEN"; case CKM_CDMF_ECB: return "CKM_CDMF_ECB"; case CKM_CDMF_CBC: return "CKM_CDMF_CBC"; case CKM_CDMF_MAC: return "CKM_CDMF_MAC"; case CKM_CDMF_MAC_GENERAL: return "CKM_CDMF_MAC_GENERAL"; case CKM_CDMF_CBC_PAD: return "CKM_CDMF_CBC_PAD"; case CKM_DES_OFB64: return "CKM_DES_OFB64"; case CKM_DES_OFB8: return "CKM_DES_OFB8"; case CKM_DES_CFB64: return "CKM_DES_CFB64"; case CKM_DES_CFB8: return "CKM_DES_CFB8"; case CKM_MD2: return "CKM_MD2"; case CKM_MD2_HMAC: return "CKM_MD2_HMAC"; case CKM_MD2_HMAC_GENERAL: return "CKM_MD2_HMAC_GENERAL"; case CKM_MD5: return "CKM_MD5"; case CKM_MD5_HMAC: return "CKM_MD5_HMAC"; case CKM_MD5_HMAC_GENERAL: return "CKM_MD5_HMAC_GENERAL"; case CKM_SHA_1: return "CKM_SHA_1"; case CKM_SHA_1_HMAC: return "CKM_SHA_1_HMAC"; case CKM_SHA_1_HMAC_GENERAL: return "CKM_SHA_1_HMAC_GENERAL"; case CKM_RIPEMD128: return "CKM_RIPEMD128"; case CKM_RIPEMD128_HMAC: return "CKM_RIPEMD128_HMAC"; case CKM_RIPEMD128_HMAC_GENERAL: return "CKM_RIPEMD128_HMAC_GENERAL"; case CKM_RIPEMD160: return "CKM_RIPEMD160"; case CKM_RIPEMD160_HMAC: return "CKM_RIPEMD160_HMAC"; case CKM_RIPEMD160_HMAC_GENERAL: return "CKM_RIPEMD160_HMAC_GENERAL"; case CKM_SHA256: return "CKM_SHA256"; case CKM_SHA256_HMAC: return "CKM_SHA256_HMAC"; case CKM_SHA256_HMAC_GENERAL: return "CKM_SHA256_HMAC_GENERAL"; case CKM_SHA224: return "CKM_SHA224"; case CKM_SHA224_HMAC: return "CKM_SHA224_HMAC"; case CKM_SHA224_HMAC_GENERAL: return "CKM_SHA224_HMAC_GENERAL"; case CKM_SHA384: return "CKM_SHA384"; case CKM_SHA384_HMAC: return "CKM_SHA384_HMAC"; case CKM_SHA384_HMAC_GENERAL: return "CKM_SHA384_HMAC_GENERAL"; case CKM_SHA512: return "CKM_SHA512"; case CKM_SHA512_HMAC: return "CKM_SHA512_HMAC"; case CKM_SHA512_HMAC_GENERAL: return "CKM_SHA512_HMAC_GENERAL"; case CKM_SECURID_KEY_GEN: return "CKM_SECURID_KEY_GEN"; case CKM_SECURID: return "CKM_SECURID"; case CKM_HOTP_KEY_GEN: return "CKM_HOTP_KEY_GEN"; case CKM_HOTP: return "CKM_HOTP"; case CKM_ACTI: return "CKM_ACTI"; case CKM_ACTI_KEY_GEN: return "CKM_ACTI_KEY_GEN"; case CKM_CAST_KEY_GEN: return "CKM_CAST_KEY_GEN"; case CKM_CAST_ECB: return "CKM_CAST_ECB"; case CKM_CAST_CBC: return "CKM_CAST_CBC"; case CKM_CAST_MAC: return "CKM_CAST_MAC"; case CKM_CAST_MAC_GENERAL: return "CKM_CAST_MAC_GENERAL"; case CKM_CAST_CBC_PAD: return "CKM_CAST_CBC_PAD"; case CKM_CAST3_KEY_GEN: return "CKM_CAST3_KEY_GEN"; case CKM_CAST3_ECB: return "CKM_CAST3_ECB"; case CKM_CAST3_CBC: return "CKM_CAST3_CBC"; case CKM_CAST3_MAC: return "CKM_CAST3_MAC"; case CKM_CAST3_MAC_GENERAL: return "CKM_CAST3_MAC_GENERAL"; case CKM_CAST3_CBC_PAD: return "CKM_CAST3_CBC_PAD"; case CKM_CAST128_KEY_GEN: return "CKM_CAST128_KEY_GEN"; case CKM_CAST128_ECB: return "CKM_CAST128_ECB"; case CKM_CAST128_CBC: return "CKM_CAST128_CBC"; case CKM_CAST128_MAC: return "CKM_CAST128_MAC"; case CKM_CAST128_MAC_GENERAL: return "CKM_CAST128_MAC_GENERAL"; case CKM_CAST128_CBC_PAD: return "CKM_CAST128_CBC_PAD"; case CKM_RC5_KEY_GEN: return "CKM_RC5_KEY_GEN"; case CKM_RC5_ECB: return "CKM_RC5_ECB"; case CKM_RC5_CBC: return "CKM_RC5_CBC"; case CKM_RC5_MAC: return "CKM_RC5_MAC"; case CKM_RC5_MAC_GENERAL: return "CKM_RC5_MAC_GENERAL"; case CKM_RC5_CBC_PAD: return "CKM_RC5_CBC_PAD"; case CKM_IDEA_KEY_GEN: return "CKM_IDEA_KEY_GEN"; case CKM_IDEA_ECB: return "CKM_IDEA_ECB"; case CKM_IDEA_CBC: return "CKM_IDEA_CBC"; case CKM_IDEA_MAC: return "CKM_IDEA_MAC"; case CKM_IDEA_MAC_GENERAL: return "CKM_IDEA_MAC_GENERAL"; case CKM_IDEA_CBC_PAD: return "CKM_IDEA_CBC_PAD"; case CKM_GENERIC_SECRET_KEY_GEN: return "CKM_GENERIC_SECRET_KEY_GEN"; case CKM_CONCATENATE_BASE_AND_KEY: return "CKM_CONCATENATE_BASE_AND_KEY"; case CKM_CONCATENATE_BASE_AND_DATA: return "CKM_CONCATENATE_BASE_AND_DATA"; case CKM_CONCATENATE_DATA_AND_BASE: return "CKM_CONCATENATE_DATA_AND_BASE"; case CKM_XOR_BASE_AND_DATA: return "CKM_XOR_BASE_AND_DATA"; case CKM_EXTRACT_KEY_FROM_KEY: return "CKM_EXTRACT_KEY_FROM_KEY"; case CKM_SSL3_PRE_MASTER_KEY_GEN: return "CKM_SSL3_PRE_MASTER_KEY_GEN"; case CKM_SSL3_MASTER_KEY_DERIVE: return "CKM_SSL3_MASTER_KEY_DERIVE"; case CKM_SSL3_KEY_AND_MAC_DERIVE: return "CKM_SSL3_KEY_AND_MAC_DERIVE"; case CKM_SSL3_MASTER_KEY_DERIVE_DH: return "CKM_SSL3_MASTER_KEY_DERIVE_DH"; case CKM_TLS_PRE_MASTER_KEY_GEN: return "CKM_TLS_PRE_MASTER_KEY_GEN"; case CKM_TLS_MASTER_KEY_DERIVE: return "CKM_TLS_MASTER_KEY_DERIVE"; case CKM_TLS_KEY_AND_MAC_DERIVE: return "CKM_TLS_KEY_AND_MAC_DERIVE"; case CKM_TLS_MASTER_KEY_DERIVE_DH: return "CKM_TLS_MASTER_KEY_DERIVE_DH"; case CKM_TLS_PRF: return "CKM_TLS_PRF"; case CKM_SSL3_MD5_MAC: return "CKM_SSL3_MD5_MAC"; case CKM_SSL3_SHA1_MAC: return "CKM_SSL3_SHA1_MAC"; case CKM_MD5_KEY_DERIVATION: return "CKM_MD5_KEY_DERIVATION"; case CKM_MD2_KEY_DERIVATION: return "CKM_MD2_KEY_DERIVATION"; case CKM_SHA1_KEY_DERIVATION: return "CKM_SHA1_KEY_DERIVATION"; case CKM_SHA256_KEY_DERIVATION: return "CKM_SHA256_KEY_DERIVATION"; case CKM_SHA384_KEY_DERIVATION: return "CKM_SHA384_KEY_DERIVATION"; case CKM_SHA512_KEY_DERIVATION: return "CKM_SHA512_KEY_DERIVATION"; case CKM_SHA224_KEY_DERIVATION: return "CKM_SHA224_KEY_DERIVATION"; case CKM_PBE_MD2_DES_CBC: return "CKM_PBE_MD2_DES_CBC"; case CKM_PBE_MD5_DES_CBC: return "CKM_PBE_MD5_DES_CBC"; case CKM_PBE_MD5_CAST_CBC: return "CKM_PBE_MD5_CAST_CBC"; case CKM_PBE_MD5_CAST3_CBC: return "CKM_PBE_MD5_CAST3_CBC"; case CKM_PBE_MD5_CAST128_CBC: return "CKM_PBE_MD5_CAST128_CBC"; case CKM_PBE_SHA1_CAST128_CBC: return "CKM_PBE_SHA1_CAST128_CBC"; case CKM_PBE_SHA1_RC4_128: return "CKM_PBE_SHA1_RC4_128"; case CKM_PBE_SHA1_RC4_40: return "CKM_PBE_SHA1_RC4_40"; case CKM_PBE_SHA1_DES3_EDE_CBC: return "CKM_PBE_SHA1_DES3_EDE_CBC"; case CKM_PBE_SHA1_DES2_EDE_CBC: return "CKM_PBE_SHA1_DES2_EDE_CBC"; case CKM_PBE_SHA1_RC2_128_CBC: return "CKM_PBE_SHA1_RC2_128_CBC"; case CKM_PBE_SHA1_RC2_40_CBC: return "CKM_PBE_SHA1_RC2_40_CBC"; case CKM_PKCS5_PBKD2: return "CKM_PKCS5_PBKD2"; case CKM_PBA_SHA1_WITH_SHA1_HMAC: return "CKM_PBA_SHA1_WITH_SHA1_HMAC"; case CKM_WTLS_PRE_MASTER_KEY_GEN: return "CKM_WTLS_PRE_MASTER_KEY_GEN"; case CKM_WTLS_MASTER_KEY_DERIVE: return "CKM_WTLS_MASTER_KEY_DERIVE"; case CKM_WTLS_MASTER_KEY_DERVIE_DH_ECC: return "CKM_WTLS_MASTER_KEY_DERVIE_DH_ECC"; case CKM_WTLS_PRF: return "CKM_WTLS_PRF"; case CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: return "CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE"; case CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: return "CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE"; case CKM_KEY_WRAP_LYNKS: return "CKM_KEY_WRAP_LYNKS"; case CKM_KEY_WRAP_SET_OAEP: return "CKM_KEY_WRAP_SET_OAEP"; case CKM_CMS_SIG: return "CKM_CMS_SIG"; case CKM_KIP_DERIVE: return "CKM_KIP_DERIVE"; case CKM_KIP_WRAP: return "CKM_KIP_WRAP"; case CKM_KIP_MAC: return "CKM_KIP_MAC"; case CKM_CAMELLIA_KEY_GEN: return "CKM_CAMELLIA_KEY_GEN"; case CKM_CAMELLIA_ECB: return "CKM_CAMELLIA_ECB"; case CKM_CAMELLIA_CBC: return "CKM_CAMELLIA_CBC"; case CKM_CAMELLIA_MAC: return "CKM_CAMELLIA_MAC"; case CKM_CAMELLIA_MAC_GENERAL: return "CKM_CAMELLIA_MAC_GENERAL"; case CKM_CAMELLIA_CBC_PAD: return "CKM_CAMELLIA_CBC_PAD"; case CKM_CAMELLIA_ECB_ENCRYPT_DATA: return "CKM_CAMELLIA_ECB_ENCRYPT_DATA"; case CKM_CAMELLIA_CBC_ENCRYPT_DATA: return "CKM_CAMELLIA_CBC_ENCRYPT_DATA"; case CKM_CAMELLIA_CTR: return "CKM_CAMELLIA_CTR"; case CKM_ARIA_KEY_GEN: return "CKM_ARIA_KEY_GEN"; case CKM_ARIA_ECB: return "CKM_ARIA_ECB"; case CKM_ARIA_CBC: return "CKM_ARIA_CBC"; case CKM_ARIA_MAC: return "CKM_ARIA_MAC"; case CKM_ARIA_MAC_GENERAL: return "CKM_ARIA_MAC_GENERAL"; case CKM_ARIA_CBC_PAD: return "CKM_ARIA_CBC_PAD"; case CKM_ARIA_ECB_ENCRYPT_DATA: return "CKM_ARIA_ECB_ENCRYPT_DATA"; case CKM_ARIA_CBC_ENCRYPT_DATA: return "CKM_ARIA_CBC_ENCRYPT_DATA"; case CKM_SKIPJACK_KEY_GEN: return "CKM_SKIPJACK_KEY_GEN"; case CKM_SKIPJACK_ECB64: return "CKM_SKIPJACK_ECB64"; case CKM_SKIPJACK_CBC64: return "CKM_SKIPJACK_CBC64"; case CKM_SKIPJACK_OFB64: return "CKM_SKIPJACK_OFB64"; case CKM_SKIPJACK_CFB64: return "CKM_SKIPJACK_CFB64"; case CKM_SKIPJACK_CFB32: return "CKM_SKIPJACK_CFB32"; case CKM_SKIPJACK_CFB16: return "CKM_SKIPJACK_CFB16"; case CKM_SKIPJACK_CFB8: return "CKM_SKIPJACK_CFB8"; case CKM_SKIPJACK_WRAP: return "CKM_SKIPJACK_WRAP"; case CKM_SKIPJACK_PRIVATE_WRAP: return "CKM_SKIPJACK_PRIVATE_WRAP"; case CKM_SKIPJACK_RELAYX: return "CKM_SKIPJACK_RELAYX"; case CKM_KEA_KEY_PAIR_GEN: return "CKM_KEA_KEY_PAIR_GEN"; case CKM_KEA_KEY_DERIVE: return "CKM_KEA_KEY_DERIVE"; case CKM_FORTEZZA_TIMESTAMP: return "CKM_FORTEZZA_TIMESTAMP"; case CKM_BATON_KEY_GEN: return "CKM_BATON_KEY_GEN"; case CKM_BATON_ECB128: return "CKM_BATON_ECB128"; case CKM_BATON_ECB96: return "CKM_BATON_ECB96"; case CKM_BATON_CBC128: return "CKM_BATON_CBC128"; case CKM_BATON_COUNTER: return "CKM_BATON_COUNTER"; case CKM_BATON_SHUFFLE: return "CKM_BATON_SHUFFLE"; case CKM_BATON_WRAP: return "CKM_BATON_WRAP"; case CKM_EC_KEY_PAIR_GEN: return "CKM_EC_KEY_PAIR_GEN"; case CKM_ECDSA: return "CKM_ECDSA"; case CKM_ECDSA_SHA1: return "CKM_ECDSA_SHA1"; case CKM_ECDH1_DERIVE: return "CKM_ECDH1_DERIVE"; case CKM_ECDH1_COFACTOR_DERIVE: return "CKM_ECDH1_COFACTOR_DERIVE"; case CKM_ECMQV_DERIVE: return "CKM_ECMQV_DERIVE"; case CKM_JUNIPER_KEY_GEN: return "CKM_JUNIPER_KEY_GEN"; case CKM_JUNIPER_ECB128: return "CKM_JUNIPER_ECB128"; case CKM_JUNIPER_CBC128: return "CKM_JUNIPER_CBC128"; case CKM_JUNIPER_COUNTER: return "CKM_JUNIPER_COUNTER"; case CKM_JUNIPER_SHUFFLE: return "CKM_JUNIPER_SHUFFLE"; case CKM_JUNIPER_WRAP: return "CKM_JUNIPER_WRAP"; case CKM_FASTHASH: return "CKM_FASTHASH"; case CKM_AES_KEY_GEN: return "CKM_AES_KEY_GEN"; case CKM_AES_ECB: return "CKM_AES_ECB"; case CKM_AES_CBC: return "CKM_AES_CBC"; case CKM_AES_MAC: return "CKM_AES_MAC"; case CKM_AES_MAC_GENERAL: return "CKM_AES_MAC_GENERAL"; case CKM_AES_CBC_PAD: return "CKM_AES_CBC_PAD"; case CKM_AES_CTR: return "CKM_AES_CTR"; case CKM_BLOWFISH_KEY_GEN: return "CKM_BLOWFISH_KEY_GEN"; case CKM_BLOWFISH_CBC: return "CKM_BLOWFISH_CBC"; case CKM_TWOFISH_KEY_GEN: return "CKM_TWOFISH_KEY_GEN"; case CKM_TWOFISH_CBC: return "CKM_TWOFISH_CBC"; case CKM_DES_ECB_ENCRYPT_DATA: return "CKM_DES_ECB_ENCRYPT_DATA"; case CKM_DES_CBC_ENCRYPT_DATA: return "CKM_DES_CBC_ENCRYPT_DATA"; case CKM_DES3_ECB_ENCRYPT_DATA: return "CKM_DES3_ECB_ENCRYPT_DATA"; case CKM_DES3_CBC_ENCRYPT_DATA: return "CKM_DES3_CBC_ENCRYPT_DATA"; case CKM_AES_ECB_ENCRYPT_DATA: return "CKM_AES_ECB_ENCRYPT_DATA"; case CKM_AES_CBC_ENCRYPT_DATA: return "CKM_AES_CBC_ENCRYPT_DATA"; case CKM_DSA_PARAMETER_GEN: return "CKM_DSA_PARAMETER_GEN"; case CKM_DH_PKCS_PARAMETER_GEN: return "CKM_DH_PKCS_PARAMETER_GEN"; case CKM_X9_42_DH_PARAMETER_GEN: return "CKM_X9_42_DH_PARAMETER_GEN"; case CKM_VENDOR_DEFINED: return "CKM_VENDOR_DEFINED"; defult: break; } sprintf(buffer, "0x%08X", mechType); return buffer; }
25.583521
130
0.703988
opendnssec
716c8ceaca06b28f5179b8b5441c557e982f619f
2,213
cpp
C++
Windows/src/Code_highlighting.cpp
SongZihui-sudo/easyhtmleditor
6ac122e0f6cff16da98adb74da2e3a2dba153748
[ "MIT" ]
1
2022-01-23T14:49:51.000Z
2022-01-23T14:49:51.000Z
Windows/src/Code_highlighting.cpp
SongZihui-sudo/easyhtmleditor
6ac122e0f6cff16da98adb74da2e3a2dba153748
[ "MIT" ]
9
2022-02-11T13:09:29.000Z
2022-03-14T12:13:39.000Z
Windows/src/Code_highlighting.cpp
SongZihui-sudo/easyhtmleditor
6ac122e0f6cff16da98adb74da2e3a2dba153748
[ "MIT" ]
null
null
null
#include "../include/Code_highlighting.h" #include "../include/EasyCodingEditor.h" using namespace cht; using namespace edt; edt::easyhtmleditor e1; //设置颜色 void Code_highlighting::Set_color(int wr,int wg,int wb,int br,int bg,int bb){ printf("\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm",wr,wg,wb,br,bg,bb); //\033[38表示前景,\033[48表示背景,三个%d表示混合的数 } //rgb初始化 void Code_highlighting::rgb_init(){ HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); //输入句柄 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //输出句柄 DWORD dwInMode, dwOutMode; GetConsoleMode(hIn, &dwInMode); //获取控制台输入模式 GetConsoleMode(hOut, &dwOutMode); //获取控制台输出模式 dwInMode |= 0x0200; //更改 dwOutMode |= 0x0004; SetConsoleMode(hIn, dwInMode); //设置控制台输入模式 SetConsoleMode(hOut, dwOutMode); //设置控制台输出模式 } //词法分析 bool Code_highlighting::Lexical_analysis(deque <string> ready_highlight){ vector <int> state; vector <cht::pos> postion; for (int i = 0; i < ready_highlight.size(); i++){ int bit_num = 0; int bit_y = 0; int bit_x = 0; int bit = 0; for (int j = 0; j < key_words.size(); j++){ int k = 0; int n = 0; int y = 0; while(ready_highlight[i][k]!='\0'&&key_words[j][n]!='\0'){ if(ready_highlight[i][k]==key_words[j][n]){ k++; n++; } else{ k=k-n+1; n=0; } } if(key_words[j][n]=='\0'){ state.push_back(j); cht::pos p1; p1.y = i; p1.x = k - n; postion.push_back(p1); } //(k-n); //主串中存在该模式返回下标号 else; //主串中不存在该模式 } } for (int i = 0; i < state.size(); i++){ if (state[i]){ e1.SetPos(postion[i].x,postion[i].y); Set_color(1,186,200,0,0,0); cout<<key_words[state[i]]; Set_color(255,255,255,0,0,0); } else; } postion.clear(); state.clear(); ready_highlight.clear(); return false; } //读取文件 bool Code_highlighting::read_setting_files(string language){ if (language == "c" || language == "cpp"){ fstream out_setting; out_setting.open("../Code_highlighting/c_setting.txt"); string out_str; if (out_setting){ while (getline(out_setting,out_str)){ key_words.push_back(out_str); } } else{ cerr<<"can not open the files!!!"<<endl; return false; } } else; return true; }
24.318681
77
0.621329
SongZihui-sudo
7175c2c3c49bf787331bffc1580fe566c969736d
340
cpp
C++
Linked List/Circular Linked List/Implementation.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
8
2021-02-14T13:13:27.000Z
2022-01-08T23:58:32.000Z
Linked List/Circular Linked List/Implementation.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
Linked List/Circular Linked List/Implementation.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
15
2021-03-01T03:54:29.000Z
2021-10-19T18:29:00.000Z
#include <bits/stdc++.h> using namespace std; struct Node{ int data; Node* next; Node(int d){ data=d; next=NULL; } }; int main() { Node *head=new Node(10); head->next=new Node(5); head->next->next=new Node(20); head->next->next->next=new Node(15); head->next->next->next->next=head; return 0; }
15.454545
37
0.576471
shouryagupta21
71820553d922ccffc2c5735d4282b3e3c8facc08
1,560
cpp
C++
tests/core/gui/widgets/PanelTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
null
null
null
tests/core/gui/widgets/PanelTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
29
2020-10-21T07:34:55.000Z
2021-01-12T15:15:53.000Z
tests/core/gui/widgets/PanelTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
1
2020-10-19T19:30:40.000Z
2020-10-19T19:30:40.000Z
#include <catch2/catch.hpp> #include "core/gui/widgets/Panel.h" #include "core/gui/widgets/VerticalLayout.h" #include "core/gui/widgets/Button.h" #include "TestsUtils.h" TEST_CASE("[Panel]") { auto vLayout = ire::core::gui::VerticalLayout::create({ 200, 200 }); auto button = ire::core::gui::Button::create(); vLayout->add(std::move(button), "Button"); auto button1 = ire::core::gui::Button::create(); vLayout->add(std::move(button1), "Button1"); auto panel = ire::core::gui::Panel::create({300, 300}, std::move(vLayout), "VerticalLayout"); SECTION("WidgetType") { REQUIRE(panel->getType().getName() == "Panel"); } SECTION("Background color and Outline ") { panel->setBackgroundColor(sf::Color::Magenta); REQUIRE(panel->getBackgroundColor() == sf::Color::Magenta); panel->setOutlineColor(sf::Color::Red); REQUIRE(panel->getOutlineColor() == sf::Color::Red); panel->setOutlineThickness(15); REQUIRE(panel->getOutlineThickness() == 15); } SECTION("Position and Size") { panel->setPosition({ 25, 50 }); REQUIRE(areAlmostEqual(panel->getPosition(), sf::Vector2f({ 25, 50 }))); REQUIRE(areAlmostEqual(panel->getLayout()->getPosition(), sf::Vector2f({ 25, 50 }))); REQUIRE(areAlmostEqual(panel->getSize(), sf::Vector2f({ 300, 300 }))); REQUIRE(areAlmostEqual(panel->getLayout()->getSize(), sf::Vector2f({ 300, 300 }))); panel->setSize({ 250, 500 }); REQUIRE(areAlmostEqual(panel->getSize(), sf::Vector2f({ 250, 500 }))); REQUIRE(areAlmostEqual(panel->getLayout()->getSize(), sf::Vector2f({ 250, 500 }))); } }
31.2
94
0.674359
Kubaaa96
7183a7bcc789f718336e25d0388a553c39091d42
3,417
cpp
C++
src/simple-2d-polydar.cpp
mdsumner/polydar
44009e76fdbf36cb71d97253427e8b4000f53ec5
[ "MIT" ]
2
2020-05-05T07:07:27.000Z
2020-05-05T07:19:17.000Z
src/simple-2d-polydar.cpp
mdsumner/polydar
44009e76fdbf36cb71d97253427e8b4000f53ec5
[ "MIT" ]
null
null
null
src/simple-2d-polydar.cpp
mdsumner/polydar
44009e76fdbf36cb71d97253427e8b4000f53ec5
[ "MIT" ]
null
null
null
/** simple.cpp Purpose: Example of using polylidar in C++ @author Jeremy Castagno @version 05/20/19 */ #include <Rcpp.h> using namespace Rcpp; #include <iostream> #include <sstream> // std::istringstream #include <vector> #include <string> #include <fstream> #include <iomanip> #include "include/polylidar/polylidar.hpp" // Print arrays template <typename TElem> std::ostream& operator<<(std::ostream& os, const std::vector<TElem>& vec) { auto iter_begin = vec.begin(); auto iter_end = vec.end(); os << "["; for (auto iter = iter_begin; iter != iter_end; ++iter) { std::cout << ((iter != iter_begin) ? "," : "") << *iter; } os << "]"; return os; } // [[Rcpp::export]] Rcpp::List rcpp_polydar(NumericVector x, IntegerVector dim, NumericVector xyThresh, NumericVector alpha, NumericVector lmax, IntegerVector minTriangles, IntegerVector MAX_ITER) { //int argc; //char *argv[]; // std::cout << "Simple C++ Example of Polylidar" << std::endl; std::vector<double> points = as<std::vector<double> >(x); // std::vector<double> points = { // 0.0, 0.0, // 0.0, 1.0, // 1.0, 1.0, // 1.0, 0.0, // 5.0, 0.1, // }; // 5 X 2 matrix as one contigious array // Convert to multidimensional array std::vector<std::size_t> shape = { points.size() / 2, 2 }; polylidar::Matrix<double> points_(points.data(), shape[0], shape[1]); // Set configuration parameters polylidar::Config config; config.dim = dim[0]; config.xyThresh = xyThresh[0]; config.alpha = alpha[0]; config.lmax = lmax[0]; config.minTriangles = minTriangles[0]; // Extract polygon std::vector<float> timings; auto before = std::chrono::high_resolution_clock::now(); auto polygons = polylidar::ExtractPolygonsAndTimings(points_, config, timings); for (int i = 0; i < MAX_ITER[0]; i++) { polygons = polylidar::ExtractPolygonsAndTimings(points_, config, timings); } // FIXME: I have no idea how to get this stuff out // c++ fu is -- // for(auto const& polygon: polygons) { // polygon.shell; // what do we do? see std::cout below // } auto after = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(after - before); // std::cout << "Polylidar took " << elapsed.count() << " milliseconds processing a " << shape[0] << " point cloud" << std::endl; // std::cout << "Point indices of Polygon Shell: "; Rcpp::List out(polygons.capacity()); int jj = 0; for(auto const& polygon: polygons) { // std::cout << polygon.shell << std::endl; IntegerVector idx(polygon.shell.capacity()); for (int ii = 0; ii < idx.length(); ii ++) { idx[ii] = (int)polygon.shell[ii]; } out[jj] = Rcpp::wrap(idx); jj = jj + 1; } // std::cout << polygons.capacity() << std::endl; // out[0] = Rcpp::wrap(idx); // std::cout << std::endl; // std::cout << "Detailed timings in milliseconds:" << std::endl; // std::cout << std::fixed << std::setprecision(2) << "Delaunay Triangulation: " << timings[0] << "; Mesh Extraction: " << timings[1] << "; Polygon Extraction: " << timings[2] <<std::endl; return out; }
30.508929
190
0.580334
mdsumner
71845503f276eb0333c946c1edf10ba8fc60df38
1,016
cpp
C++
src/NGFX/Private/Vulkan/vk_pipeline.cpp
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/NGFX/Private/Vulkan/vk_pipeline.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/NGFX/Private/Vulkan/vk_pipeline.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include "vk_common.h" namespace vulkan { GpuRenderPipeline::GpuRenderPipeline(GpuDevice* device, ngfx::RenderPipelineDesc const& desc) : GpuPipelineBase(device) { create_info_.stageCount; create_info_.pStages; create_info_.pVertexInputState; create_info_.pInputAssemblyState; create_info_.pTessellationState; create_info_.pViewportState; create_info_.pRasterizationState; create_info_.pMultisampleState; create_info_.pDepthStencilState; create_info_.pColorBlendState; create_info_.pDynamicState; create_info_.layout; create_info_.renderPass; create_info_.subpass; create_info_.basePipelineHandle; create_info_.basePipelineIndex; } GpuRenderPipeline::~GpuRenderPipeline() { } GpuComputePipeline::GpuComputePipeline(GpuDevice* device, ngfx::ComputePipelineDesc const& desc) : GpuPipelineBase(device) { create_info_.stage; create_info_.layout; create_info_.basePipelineIndex; create_info_.basePipelineHandle; } GpuComputePipeline::~GpuComputePipeline() { } }
24.190476
97
0.806102
PixPh
71898089850d4aaee8c18f2f9f3e84cddecb0816
460
cpp
C++
HandAugementedReality/HandAugementedReality/Finger.cpp
nemcek/hand-augmented-reality
6f4c1f23e1d18d35b3cc65bcc109ca06a8023ea6
[ "MIT" ]
null
null
null
HandAugementedReality/HandAugementedReality/Finger.cpp
nemcek/hand-augmented-reality
6f4c1f23e1d18d35b3cc65bcc109ca06a8023ea6
[ "MIT" ]
null
null
null
HandAugementedReality/HandAugementedReality/Finger.cpp
nemcek/hand-augmented-reality
6f4c1f23e1d18d35b3cc65bcc109ca06a8023ea6
[ "MIT" ]
1
2021-12-16T03:26:28.000Z
2021-12-16T03:26:28.000Z
#include "Finger.h" Finger::Finger() { } Finger::Finger(const Point& finger_tip_point, FingerType type) { this->location = Location(finger_tip_point); this->roi = Rect(Point(location.get().x - width / 2, location.get().y - height / 4), Size(width, height)); this->type = type; } /// Extracts finger from image by defined finger's region of interest void Finger::extract(const Mat & frame) { this->roi_data = frame(this->roi); } Finger::~Finger() { }
18.4
107
0.684783
nemcek
718aad9333fdba92b3c5e4fc7de25fdc1906a5cd
8,951
hpp
C++
hwlib/doxyfiles/texts/hwlib-doxygen-#0070-graphics.hpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
46
2017-02-15T14:24:14.000Z
2021-10-01T14:25:57.000Z
hwlib/doxyfiles/texts/hwlib-doxygen-#0070-graphics.hpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
27
2017-02-15T15:13:42.000Z
2021-08-28T15:29:01.000Z
hwlib/doxyfiles/texts/hwlib-doxygen-#0070-graphics.hpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
39
2017-05-18T11:51:03.000Z
2021-09-14T09:07:01.000Z
// ========================================================================== // // File : hwlib-doxygen-char-io.hpp // Part of : C++ hwlib library for close-to-the-hardware OO programming // Copyright : [email protected] 2017-2019 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // ========================================================================== // this file contains Doxygen lines (of course, that is its only purpose) /// @file /// \page graphics Graphics /// /// The (abstract) types /// \ref hwlib::istream istream and \ref hwlib::ostream ostream /// are used to read and write characters. /// /// <BR> /// /// ========================================================================= /// /// \section xy xy /// /// An \ref hwlib::xy "xy" is a value type that stores two int__fst16_t /// values x and y. xy values can be added and subtracted, and can be /// multiplied and divided by an integer value. /// An xy can also be printed /// to an \ref hwlib::ostream "ostream" using operator<<. /// /// attributes and operations | meaning or effect /// -------------------------------- | ------------------------------------------ /// \ref hwlib::xy::x "x" | x value /// \ref hwlib::xy::y "y" | y value /// \ref hwlib::xy::operator+ "+" | adds two xy values /// \ref hwlib::xy::operator+ "-" | subtracts to xy values /// \ref hwlib::xy::operator+ "*" | multiplies the x and y value by an integer /// \ref hwlib::xy::operator/ "/" | divides the x and y values by an integer /// \ref hwlib::xy::operator<< "<<" | prints an xy to an \ref hwlib::ostream "ostream" /// /// The overloaded all() function can be used to iterate over all (x,y) values /// within the (0 .. x-1, 0 .. y-1) range (in some unspecified order). /// /// <BR> /// /// ========================================================================= /// /// \section color color /// /// A \ref hwlib::color "color" is a value type that stores a color as /// three 8-bit red, green and blue values, plus a 'is_transparent' flag. /// When the transparent flag is not set, the color values determine the /// color. When it is set, the color values have no meaning. /// An color can also be printed /// to an \ref hwlib::ostream "ostream" using operator<<. /// /// Colors can be constructed, negated, /// and compared for equality or inequality. /// /// attributes and operations | meaning or effect /// --------------------------------------------------- | ------------------------------------------ /// \ref hwlib::color::is_transparent "is_transparent" | transparency flag /// \ref hwlib::color::red "rad" | red intensity /// \ref hwlib::color::green "green" | green intensity /// \ref hwlib::color::blue "blue" | blue intensity /// \ref hwlib::color::color(uint_fast32_t red,uint_fast32_t green,uint_fast32_t blue,bool transparent) "color(r,g,b)" | construct a color from its components /// \ref hwlib::color::color(uint_fast32_t) "color(v)" | construct a color from its 24-bit RGB value /// \ref hwlib::color::operator- "-" | yields the inverse of a color /// \ref hwlib::color::operator== "==" | tests for equality /// \ref hwlib::color::operator!= "!=" | tests for inequality /// \ref hwlib::color::operator<< "<<" | prints an xy to an \ref hwlib::ostream "ostream" /// /// The following color constants are available: /// - \ref hwlib::black "black" /// - \ref hwlib::white "white" /// - \ref hwlib::red "red" /// - \ref hwlib::green "green" /// - \ref hwlib::blue "blue" /// - \ref hwlib::gray "gray" /// - \ref hwlib::yellow "yellow" /// - \ref hwlib::cyan "cyan" /// - \ref hwlib::magenta "magenta" /// - \ref hwlib::transparent "transparent" /// - \ref hwlib::violet "violet" /// - \ref hwlib::sienna "sienna" /// - \ref hwlib::purple "purple" /// - \ref hwlib::pink "pink" /// - \ref hwlib::silver "silver" /// - \ref hwlib::brown "brown" /// - \ref hwlib::salmon "salmon" /// /// <BR> /// /// ========================================================================= /// /// \section image image /// /// An \ref hwlib::image image is an abstract class that defines /// an interface to a picture, that is: a rectangle of read-only pixels. /// An image is used to embed a picture in the application. /// /// attributes and operations | meaning or effect /// ------------------------------------------ | ------------------------------------------ /// \ref hwlib::image::size "size" | size in pixels in x and y direction /// \ref hwlib::image::operator[] operator [] | the color of the pixel at location loc /// /// <BR> /// /// ========================================================================= /// /// \section font font /// /// An \ref hwlib::font font is an abstract class that defines /// an interface to a set of pictures that show characters as a graphic /// images. /// A font is used to implement a character /// \ref hwlib::terminal "terminal" on a graphic /// \ref hwlib::window window. /// /// attributes and operations | meaning or effect /// ----------------------------------------------- | ------------------------------------------ /// \ref hwlib::image::operator[] "operator[ c ]" | returns the image for char c /// /// Two concrete built-in font classes are available: /// - \ref hwlib::font_default_8x8 font_default_8x8 /// - \ref hwlib::font_default_16x16 font_default_16x16 /// /// The font_default_16x16 is not available on AVR8 targets because /// the AVR compiler can't handle it. /// /// <BR> /// /// ========================================================================= /// /// \section window window /// /// An \ref hwlib::window window is an abstract class that defines /// an interface to a graphics display. The display can be cleared, /// and a pixel can be set to a color. /// /// Window operations are (potentially) buffered: a subsequent /// \ref hwlib::window::flush "flush()" call is required in order /// for the previous operations to take effect. /// /// attributes and operations | meaning or effect /// ----------------------------------------------- | ------------------------------------------ /// \ref hwlib::window::size "size" | size of the display, in pixels in a x any direction /// \ref hwlib::window::background "background" | the background color /// \ref hwlib::window::foreground "foreground" | the foreground color /// \ref hwlib::window::clear "clear()" | write the background color to all pixels /// \ref hwlib::window::clear "clear(col)" | write color col to tall pixels /// \ref hwlib::window::write "write(loc, col)" | write color col to the pixel at loc /// \ref hwlib::window::write "write(loc, img)" | write image img to the location loc /// \ref hwlib::window::flush "flush()" | flush all pending changes to the window /// /// The \ref hwlib::window_part "window_part" decorator creates a /// window in a rectangular part of another window. /// /// The \ref hwlib::window_invert "window_invert" decorator creates a /// window that writes inverted (the color of each pixel negated) to the /// underlying window. /// /// <BR> /// /// ========================================================================= /// /// \section drawables drawables /// /// A \ref hwlib::drawable drawable is an abstract class that defines /// an interface for something that cab be drawn /// on a \ref hwlib::window window. /// /// attributes and operations | meaning or effect /// ----------------------------------------------- | ------------------------------------------ /// \ref hwlib::drawable::start "start" | origin (top left corner) of where the drawable is to be drawn /// \ref hwlib::drawable::draw "draw(w)" | draw the drawable on window w /// /// A \ref hwlib::line "line" is a drawable. /// It is created by specifying its origin and its endpoint. /// A color can be specified. /// If none is, the foreground color of the window is used. /// /// A \ref hwlib::circle "circle" is a drawable. /// It is created by specifying its midpoint and its radius /// A color can be specified. /// If none is, the foreground color of the window is used. /// /// <BR> /// /// ========================================================================= /// /// \section terminal_from terminal_from /// /// A \ref hwlib::terminal_from "terminal_from" creates a /// character \ref hwlib::terminal "terminal" from a window and /// a character \ref hwlib::font "font". /// /// /// <BR> ///
43.451456
163
0.537594
TheBlindMick
718affb17c3349b1fbdd5e5ef593df60654db8a3
1,755
cpp
C++
901-1000/928. Minimize Malware Spread II.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
901-1000/928. Minimize Malware Spread II.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
901-1000/928. Minimize Malware Spread II.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
class Solution { public: int minMalwareSpread(vector<vector<int>> &graph, vector<int> &initial) { int N = graph.size(); vector<bool> flag(N, false); vector<vector<int>> connected(N, vector<int>()); vector<vector<int>> edges(N, vector<int>()); for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { if (graph[i][j]) { edges[i].push_back(j); edges[j].push_back(i); } } } for (auto &i : initial) { flag[i] = true; } for (auto &n : initial) { unordered_set<int> s; queue<int> q; q.push(n); while (!q.empty()) { auto cur = q.front(); q.pop(); for (auto i : edges[cur]) { if (!flag[i] && s.find(i) == s.end()) { s.insert(i); q.push(i); } } } for (auto &idx : s) { connected[idx].push_back(n); } } vector<int> counter(N, 0); for (int i = 0; i < N; ++i) { if (!flag[i] && connected[i].size() == 1) { counter[connected[i][0]]++; } } int idx = -1, best = INT_MIN; for (auto &n : initial) { if (counter[n] > best || (counter[n] == best && n < idx)) { idx = n; best = counter[n]; } } return idx; } };
26.19403
74
0.325356
erichuang1994
718c201296b2b15165e073a60cdff475dc75aad9
7,348
cpp
C++
mwidgets/src/mediawidget/downloaddialog.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
mwidgets/src/mediawidget/downloaddialog.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
mwidgets/src/mediawidget/downloaddialog.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
#include "downloaddialog.h" DownloadDialog::DownloadDialog(QWidget * parent) : QDialog(parent) { dialogText = QString("Downloading file:\n%1\n\nTarget directory:\n%2\n"); pixmap = QIcon::fromTheme("download").pixmap(QSize(48, 48)); } DownloadDialog::~DownloadDialog() { destroy(); } // TODO prompt for directory if not known.... give a chance to change if known void DownloadDialog::download(const QString &url, const QString &directory) { if (checkTargetExists(url, directory)) { close(); return; } imageLabel = new QLabel; imageLabel->setPixmap(pixmap); QFileInfo urlInfo(url); textLabel = new QLabel(dialogText.arg(urlInfo.fileName()).arg(directory)); buttonAbort = new QPushButton(QIcon::fromTheme("dialog-cancel"), tr("Abort")); connect(buttonAbort, SIGNAL(clicked()), this, SLOT(cancel())); buttonBox = new QDialogButtonBox(Qt::Horizontal); buttonBox->addButton(buttonAbort, QDialogButtonBox::RejectRole); progressBar = new QProgressBar; progressBar->setValue(0); progressBar->setFormat("%v / %m KB (%p%)"); QHBoxLayout * iconAndTextLayout = new QHBoxLayout; iconAndTextLayout->setSpacing(22); iconAndTextLayout->setContentsMargins(11, 11, 11, 11); iconAndTextLayout->addWidget(imageLabel); iconAndTextLayout->addWidget(textLabel); QHBoxLayout * abortButtonLayout = new QHBoxLayout; abortButtonLayout->addStretch(); abortButtonLayout->addWidget(buttonBox); QVBoxLayout * completeLayout = new QVBoxLayout; completeLayout->addLayout(iconAndTextLayout); completeLayout->addWidget(progressBar); completeLayout->addLayout(abortButtonLayout); QGridLayout * mainLayout = new QGridLayout; mainLayout->addLayout(completeLayout, 0, 0); setLayout(mainLayout); setMaximumSize(width(), height()); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setWindowTitle(QString(tr("%1 - downloading")).arg(file)); show(); targetFile.open(QFile::WriteOnly); downloader = new QHttpDownload; connect(downloader, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateProgressBar(qint64,qint64))); connect(downloader, SIGNAL(chunk(QByteArray)), this, SLOT(saveChunk(QByteArray))); connect(downloader, SIGNAL(clear()), this, SLOT(reset())); connect(downloader, SIGNAL(complete(QByteArray)), this, SLOT(complete())); sourceUrl = url; downloader->download(url); } void DownloadDialog::downloadToFile(const QString &remoteFile, const QString &localFile) { sourceUrl = remoteFile; targetFile.setFileName(localFile); dir = QFileInfo(targetFile).dir().canonicalPath(); file = QFileInfo(targetFile).fileName(); imageLabel = new QLabel; imageLabel->setPixmap(pixmap); QFileInfo urlInfo(remoteFile); textLabel = new QLabel(dialogText.arg(urlInfo.fileName()).arg(targetFile.fileName())); buttonAbort = new QPushButton(QIcon::fromTheme("dialog-cancel"), tr("Abort")); connect(buttonAbort, SIGNAL(clicked()), this, SLOT(cancel())); buttonBox = new QDialogButtonBox(Qt::Horizontal); buttonBox->addButton(buttonAbort, QDialogButtonBox::RejectRole); progressBar = new QProgressBar; progressBar->setValue(0); progressBar->setFormat("%v / %m KB (%p%)"); QHBoxLayout * iconAndTextLayout = new QHBoxLayout; iconAndTextLayout->setSpacing(22); iconAndTextLayout->setContentsMargins(11, 11, 11, 11); iconAndTextLayout->addWidget(imageLabel); iconAndTextLayout->addWidget(textLabel); QHBoxLayout * abortButtonLayout = new QHBoxLayout; abortButtonLayout->addStretch(); abortButtonLayout->addWidget(buttonBox); QVBoxLayout * completeLayout = new QVBoxLayout; completeLayout->addLayout(iconAndTextLayout); completeLayout->addWidget(progressBar); completeLayout->addLayout(abortButtonLayout); QGridLayout * mainLayout = new QGridLayout; mainLayout->addLayout(completeLayout, 0, 0); setLayout(mainLayout); setMaximumSize(width(), height()); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setWindowTitle(QString(tr("%1 - downloading")).arg(file)); show(); bool ioResult = targetFile.open(QFile::WriteOnly); if (! ioResult) { qDebug() << "Could not open target file"; cleanup(); return; } downloader = new QHttpDownload; connect(downloader, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateProgressBar(qint64,qint64))); connect(downloader, SIGNAL(chunk(QByteArray)), this, SLOT(saveChunk(QByteArray))); connect(downloader, SIGNAL(clear()), this, SLOT(reset())); connect(downloader, SIGNAL(complete(QByteArray)), this, SLOT(complete())); downloader->download(remoteFile); } void DownloadDialog::cancel() { downloader->blockSignals(true); downloader->disconnect(); targetFile.remove(); cleanup(); } void DownloadDialog::updateProgressBar(qint64 val, qint64 max) { progressBar->setValue(qRound((qreal)val/1024)); progressBar->setMaximum(qRound((qreal)max/1024)); } void DownloadDialog::complete() { targetFile.flush(); targetFile.close(); emit downloadCompleted(sourceUrl); emit downloadCompleted(this); emit downloadCompleted(this, sourceUrl); } void DownloadDialog::saveChunk(QByteArray chunk) { targetFile.write(chunk); } QString DownloadDialog::getSourceUrl() const { return sourceUrl; } QString DownloadDialog::getTargetFile() const { return QFile::decodeName(targetFile.fileName().toLocal8Bit()); } void DownloadDialog::reset() { targetFile.flush(); targetFile.resize(0); } void DownloadDialog::cleanup() { downloader->deleteLater(); downloader = 0; close(); } bool DownloadDialog::checkTargetExists(const QString &url, const QString &directory) { QFileInfo info(url); file = info.fileName(); if (file.isEmpty()) { file = QString("download_%1").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")); } dir = directory; QString filename = QString("%1/%2").arg(dir).arg(file); QString message = QString(tr("File with name %1 already exists in directory %2\n" "You can click \"Yes\" to continue download, overwriting it,\n" "\"No\" to abort or \"Ignore\" to download file\n" "with randomly picked new name.\n\n" "Do you wish to proceed?")).arg(file).arg(dir); if (QFile::exists(filename)) { int result = QMessageBox::question( this, tr("File exists"), message, QMessageBox::Yes | QMessageBox::No | QMessageBox::Ignore, QMessageBox::No); if (result == QMessageBox::No) { return true; } if (result == QMessageBox::Ignore) { file.prepend(QCryptographicHash::hash(QDateTime::currentDateTime().toString().toLocal8Bit(), QCryptographicHash::Md5).toHex()); filename = QString("%1/%2").arg(dir).arg(file); } } targetFile.setFileName(filename); return false; }
30.238683
104
0.662221
quntax
718f148237aa142c37818bef9b5a428a39a9e747
4,292
cpp
C++
Editor/src/ImGuiWidgets/Viewport.cpp
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
Editor/src/ImGuiWidgets/Viewport.cpp
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
Editor/src/ImGuiWidgets/Viewport.cpp
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
#include "Viewport.h" #include <Hildur.h> #include <ImGui/imgui.h> #define BIND_EVENT_FN(x) std::bind(&Viewport::x, this, std::placeholders::_1) namespace Editor { Viewport::Viewport() { } Viewport::~Viewport() { } void Viewport::Init(uint32_t width, uint32_t height) { m_ObjectIDFrameBuffer = Hildur::FrameBuffer::Create(width, height); m_ObjectIDFrameBuffer->AddTextureAttachment("ID"); m_ObjectIDFrameBuffer->AddDepthBufferAttachment(); m_ObjectIDFrameBuffer->Ready(); } void Viewport::Render(Hildur::Ref<Hildur::FrameBuffer> framebuffer, const Hildur::Window& window) { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0.0f, 0.0f }); ImGui::Begin("Viewport"); if (m_ViewportWidth != ImGui::GetWindowContentRegionMax().x || m_ViewportHeight != ImGui::GetWindowContentRegionMax().y) { m_ViewportWidth = ImGui::GetWindowContentRegionMax().x; m_ViewportHeight = ImGui::GetWindowContentRegionMax().y; m_Rezised = true; } m_ViewportPosX = ImGui::GetWindowContentRegionMin().x + ImGui::GetWindowPos().x; m_ViewportPosY = ImGui::GetWindowContentRegionMin().y + ImGui::GetWindowPos().y; m_IsInViewport = ImGui::IsWindowHovered(); if (m_Rezised) { m_ObjectIDFrameBuffer->Resize(m_ViewportWidth, m_ViewportHeight); framebuffer->Resize(m_ViewportWidth, m_ViewportHeight); if (Hildur::Camera::GetMainCamera() != nullptr) Hildur::Camera::GetMainCamera()->UpdateAspect((float)m_ViewportWidth / (float)m_ViewportHeight); m_Rezised = false; } if (m_IsInViewport) { m_MouseViewportPosX = (float)((float)(Hildur::Input::GetMouseX() + window.GetPositionX() - m_ViewportPosX) / (float)m_ViewportWidth) - 0.5f; m_MouseViewportPosY = (float)((float)(Hildur::Input::GetMouseY() + window.GetPositionY() - m_ViewportPosY) / (float)m_ViewportHeight) - 0.5f; } ImGui::GetWindowDrawList()->AddImage( (void*)(intptr_t)framebuffer->GetAttachment("color")->rendererID, ImVec2(ImGui::GetCursorScreenPos()), ImVec2(ImGui::GetCursorScreenPos().x + m_ViewportWidth, ImGui::GetCursorScreenPos().y + m_ViewportHeight)); Hildur::Renderer::OnWindowResize(m_ViewportWidth, m_ViewportHeight); ImGui::End(); ImGui::PopStyleVar(); //Test ImGui::Begin("ID Buffer"); uint32_t imageWidth = ImGui::GetWindowContentRegionMax().x; uint32_t imageHeight = ImGui::GetWindowContentRegionMax().y; ImGui::GetWindowDrawList()->AddImage( (void*)(intptr_t)m_ObjectIDFrameBuffer->GetAttachment("ID")->rendererID, ImVec2(ImGui::GetCursorScreenPos()), ImVec2(ImGui::GetCursorScreenPos().x + imageWidth, ImGui::GetCursorScreenPos().y + imageHeight)); ImGui::End(); } void Viewport::OnEvent(Hildur::Event& e) { Hildur::EventDispatcher distpatcher(e); distpatcher.Dispatch<Hildur::WindowResizeEvent>(BIND_EVENT_FN(OnWindowResize)); distpatcher.Dispatch<Hildur::WindowMoveEvent>(BIND_EVENT_FN(OnWindowMove)); distpatcher.Dispatch<Hildur::WindowCloseEvent>(BIND_EVENT_FN(OnWindowClose)); distpatcher.Dispatch<Hildur::MouseButtonPressedEvent>(BIND_EVENT_FN(OnMouseClick)); distpatcher.Dispatch<Hildur::MouseScrolledEvent>(BIND_EVENT_FN(OnMouseScrolled)); } bool Viewport::OnWindowResize(Hildur::WindowResizeEvent& e) { m_Rezised = true; return false; } bool Viewport::OnWindowMove(Hildur::WindowMoveEvent& e) { return false; } bool Viewport::OnWindowClose(Hildur::WindowCloseEvent& e) { return false; } bool Viewport::OnMouseClick(Hildur::MouseButtonPressedEvent& e) { if (IsMouseInViewport() && e.GetMouseButton() == 0) { glm::vec3 objectID = ReadPixel(GetMouseViewportPos().x, GetMouseViewportPos().y); m_SelectedEntity = Hildur::Renderer::GetEntityFromID((uint32_t)(objectID.x * 255)); std::string name = m_SelectedEntity != nullptr ? m_SelectedEntity->m_Name : "The void!"; HR_CORE_WARN("Click in viewport! (this is supposed to happen), coords: ({0}, {1}), Object ID: {2}, Object name: {3}", GetMouseViewportPosNorm().x, GetMouseViewportPosNorm().y, objectID.x, name.c_str()); } return false; } bool Viewport::OnMouseScrolled(Hildur::MouseScrolledEvent& e) { return false; } void Viewport::UpdateSize() { } glm::vec3 Viewport::ReadPixel(uint32_t x, uint32_t y) { return m_ObjectIDFrameBuffer->ReadPixel("ID", x, y); } }
30.657143
206
0.731827
FelipeCalin
7190cdfec8b8840ab8a822b73e34a51a587241eb
5,883
cpp
C++
samples/flocking.cpp
jdduke/fpcpp
d9dba8aed135c85383a733fba3537d6afca5ddd7
[ "MIT" ]
16
2015-08-05T09:31:55.000Z
2021-04-18T02:23:46.000Z
samples/flocking.cpp
jdduke/fpcpp
d9dba8aed135c85383a733fba3537d6afca5ddd7
[ "MIT" ]
null
null
null
samples/flocking.cpp
jdduke/fpcpp
d9dba8aed135c85383a733fba3537d6afca5ddd7
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012, Jared Duke. // This code is released under the MIT License. // www.opensource.org/licenses/mit-license.php ///////////////////////////////////////////////////////////////////////////// #include <fpcpp.h> #include <iostream> #include <time.h> #define _USE_MATH_DEFINES #include <math.h> #include <array> #if WIN32 #include <Windows.h> inline void idle(DWORD milliseconds) { Sleep(milliseconds); } #else #include <unistd.h> inline void idle(size_t microseconds) { usleep(microseconds*1000); } #endif /////////////////////////////////////////////////////////////////////////// enum { BOIDS = 25, X = 80, Y = 30, NEIGHBORHOOD = 15, AVOIDANCE = 5, }; /////////////////////////////////////////////////////////////////////////// using fp::fst; using fp::snd; using fp::index; using fp::types; typedef types<float,float>::pair P; typedef types<float,float>::pair D; typedef types<P, D>::pair Boid; typedef types<Boid>::list Boids; P pos(const Boid& b) { return fst(b); } D dir(const Boid& b) { return snd(b); } namespace std { template< typename T > std::pair<T,T> operator+(const std::pair<T,T>& a, const std::pair<T,T>& b) { return std::make_pair( fst(a) + fst(b), snd(b) + snd(b) ); } template< typename T > std::pair<T,T> operator-(const std::pair<T,T>& a, const std::pair<T,T>& b) { return std::make_pair( fst(a) - fst(b), snd(b) - snd(b) ); } template< typename T > std::pair<T,T> operator*(const std::pair<T,T>& a, T b) { return std::make_pair( fst(a) * b, snd(a) * b ); } template< typename T > std::pair<T,T> operator/(const std::pair<T,T>& a, T b) { return std::make_pair( fst(a) / b, snd(a) / b ); } } using namespace std; template <typename T> inline float length( const T& t ) { const let x = fst(t); const let y = snd(t); return sqrtf( (float)x*x + (float)y*y ); } template <typename T> inline T normalize( const T& t ) { const let tLength = length( t ); return tLength > 0.f ? t / tLength : t; } template <typename T> inline float dist( const T& a, const T& b) { return length( a - b ); } template <typename T, typename U, typename V> inline T clamp(const T& value, const U& low, const V& high) { return value < low ? low : (value > high ? high : value); } template <typename T> inline T fmod_(T t, T modulus) { return t >= (T)0 ? fmod(t, modulus) : modulus - fmod(-t, modulus); } template <typename T, typename U> inline T pmod( const T& t, U fstMod, U sndMod ) { return T( fmod_( fst(t), fstMod ), fmod_( snd(t), sndMod ) ); } /////////////////////////////////////////////////////////////////////////// D avoidance( const Boid& boid, const Boids& neighbors ) { return fp::sum( fp::map( [&](const Boid& otherBoid) -> D { const let avoidanceWeight = 1.f - (dist( pos(boid), pos(otherBoid) ) / NEIGHBORHOOD); return normalize( pos(boid) - pos(otherBoid) ) * avoidanceWeight + dir( boid ) * (1.f - avoidanceWeight); }, neighbors) ) / (float)neighbors.size(); } D alignment( const Boid& boid, const Boids& neighbors ) { const let avgDir = fp::sum( fp::map( &dir, neighbors )) / (float)neighbors.size(); return (avgDir + dir( boid )) *.5f; } D cohesion( const Boid& boid, const Boids& neighbors ) { const let avgPos = fp::sum( fp::map( &pos, neighbors) ) / (float)neighbors.size(); return (normalize( avgPos - pos( boid ) ) + dir( boid )) *.5f; } Boid evolve( const Boid& boid, const Boids& neighbors ) { let newDir = dir( boid ); if ( fp::length(neighbors) != 0) { std::array<float, 3> weights = { .5f, .2f, .3f }; newDir = normalize( avoidance( boid, neighbors ) * weights[0] + alignment( boid, neighbors ) * weights[1] + cohesion( boid, neighbors ) * weights[2] ); } let newPos = pmod( pos( boid ) + newDir, (float)X, (float)Y); return Boid( newPos, newDir ); } /////////////////////////////////////////////////////////////////////////// Boids evolve( const Boids& boids, size_t x, size_t y ) { return fp::map( [=,&boids]( const Boid& boid ) -> Boid { let neighbors = fp::filter( [=,&boid]( const Boid& otherBoid ) { return ( boid != otherBoid ) && ( dist( pos(boid), pos(otherBoid) ) < NEIGHBORHOOD ); }, boids ); return evolve( boid, neighbors ); }, boids); } #ifndef M_PI #define M_PI 3.14159265358979323846 #endif int main(int argc, char **argv) { srand((unsigned)time((time_t*)NULL)); std::array<char, 8> cardinalToChar = { '-', '/', '|', '\\', '-', '/', '|', '\\' }; let showCell = [&]( const D& v ) -> char { if (length(v) < .25) return ' '; let theta = atan2f( snd(v), fst(v) ); theta = theta < 0.f ? theta + 2.f*(float)M_PI : theta; let const index = (int)(theta * (4.f/M_PI)) % cardinalToChar.size(); return cardinalToChar[index]; }; let boids = fp::zip(fp::zip(fp::uniformN(BOIDS, 0.f, (float)X), fp::uniformN(BOIDS, 0.f, (float)Y)), fp::zip(fp::uniformN(BOIDS, -1.f,1.f), fp::uniformN(BOIDS, -1.f,1.f))); typedef std::array< D, X > Row; typedef std::array< Row, Y > Grid; while (true) { boids = evolve(boids, X, Y); Grid grid; for (size_t i = 0; i < fp::length(boids); ++i) { let x = (int)fst( pos(index(i,boids)) ) % X; let y = (int)snd( pos(index(i,boids)) ) % Y; grid[y][x] = grid[y][x] + dir( index(i,boids) ); } let showRow = [=](const Row& r) -> std::string { return fp::show(fp::map( showCell, r) ); }; std::cout << std::endl << fp::foldl1( [](const std::string& a, const std::string& b) { return a + "\n" + b; }, fp::map( showRow, grid )) << std::endl << std::endl; } return 0; }
29.712121
97
0.536291
jdduke
7193bd769bf53d713ca1f480c94054ab7e371e06
683
cpp
C++
tools/ifaceed/ifaceed/scripting/querytable.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
tools/ifaceed/ifaceed/scripting/querytable.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
tools/ifaceed/ifaceed/scripting/querytable.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include "querytable.h" #include <QVector> #include <renderer.h> #include <db/dbdatabase.h> #include <db/dbtable.h> QVector<unsigned long long> scripting::query_table( const sad::String& table, const sad::String& type_of_objects ) { sad::db::Database* db = sad::Renderer::ref()->database(""); sad::Vector<sad::db::Object*> objects; db->table(table)->objects(objects); QVector<unsigned long long> result; for(size_t i = 0; i < objects.size(); i++) { if (objects[i]->Active && objects[i]->isInstanceOf(type_of_objects)) { result << objects[i]->MajorId; } } return result; }
22.766667
77
0.590044
mamontov-cpp
7195d91b67b3890eda661e549e9f0936879e9562
1,105
cpp
C++
thread/example3.cpp
TedLyngmo/lyn_threads
576230ded5d5f8f0b17aabec870a7201f4f9108e
[ "Unlicense" ]
null
null
null
thread/example3.cpp
TedLyngmo/lyn_threads
576230ded5d5f8f0b17aabec870a7201f4f9108e
[ "Unlicense" ]
null
null
null
thread/example3.cpp
TedLyngmo/lyn_threads
576230ded5d5f8f0b17aabec870a7201f4f9108e
[ "Unlicense" ]
null
null
null
#include "lyn/thread.hpp" #include <chrono> #include <iostream> #include <thread> // event example lyn::thread::event<true> ev; // true = auto reset int state = 0; void a_thread() { // waits for ev to be signaled // runs the lambda // sets ev to non-signaled bool executed = ev.wait_for(std::chrono::milliseconds(5), []{ ++state; std::cout << "second TRUE\n"; }); if(not executed) { ev.wait([]{ std::cout << "second FALSE\n"; }); } ev.wait([]{ std::cout << "fourth: " << ++state << '\n'; }); // unguarded work } int main() { for(int i=0; i < 1000; ++i) { auto th = std::thread(a_thread); // runs the lambda // sets ev to signaled std::this_thread::sleep_for(std::chrono::milliseconds(5)); ev.set([]{ std::cout << "first " << ++state << '\n'; }); ev.wait_for_reset([]{ std::cout << "reset\n"; }); ev.set([]{ std::cout << "third " << ++state << '\n'; }); th.join(); } }
19.385965
66
0.472398
TedLyngmo
71969823bed10163f644eff544d814836e58e2da
52,395
cc
C++
Modules/Registration/src/irtkRegisteredImage.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
3
2018-10-04T19:32:36.000Z
2021-09-02T07:37:30.000Z
Modules/Registration/src/irtkRegisteredImage.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
null
null
null
Modules/Registration/src/irtkRegisteredImage.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
4
2016-03-17T02:55:00.000Z
2018-02-03T05:40:05.000Z
/* The Image Registration Toolkit (IRTK) * * Copyright 2008-2015 Imperial College London * * 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 <irtkRegisteredImage.h> #include <irtkGaussianBlurring.h> #include <irtkGradientImageFilter.h> #include <irtkHessianImageFilter.h> #include <irtkVoxelFunction.h> #include <irtkImageGradientFunction.h> #include <irtkLinearInterpolateImageFunction.hxx> // incl. inline definitions #include <irtkFastLinearImageGradientFunction.hxx> // incl. inline definitions // ----------------------------------------------------------------------------- irtkRegisteredImage::irtkRegisteredImage() : _InputImage (NULL), _InputGradient (NULL), _InputHessian (NULL), _Transformation (NULL), _InterpolationMode (Interpolation_FastLinear), _ExtrapolationMode (Extrapolation_Default), _WorldCoordinates (NULL), _ImageToWorld (NULL), _ExternalDisplacement (NULL), _FixedDisplacement (NULL), _Displacement (NULL), _CacheWorldCoordinates (true), // FIXME: MUST be true to also cache anything else... _CacheFixedDisplacement(false), // by default, only if required by transformation _CacheDisplacement (false), // (c.f. irtkTransformation::RequiresCachingOfDisplacements) _SelfUpdate (true), _MinIntensity (numeric_limits<double>::quiet_NaN()), _MaxIntensity (numeric_limits<double>::quiet_NaN()), _GradientSigma (.0), _HessianSigma (.0), _PrecomputeDerivatives (false), _NumberOfActiveLevels (0), _NumberOfPassiveLevels (0) { for (int i = 0; i < 13; ++i) _Offset[i] = -1; } // ----------------------------------------------------------------------------- irtkRegisteredImage::irtkRegisteredImage(const irtkRegisteredImage &other) : irtkGenericImage<double>(other), _InputImage (other._InputImage), _InputGradient (other._InputGradient ? new GradientImageType(*other._InputGradient) : NULL), _InputHessian (other._InputHessian ? new GradientImageType(*other._InputHessian) : NULL), _Transformation (other._Transformation), _InterpolationMode (other._InterpolationMode), _ExtrapolationMode (other._ExtrapolationMode), _WorldCoordinates (other._WorldCoordinates), _ImageToWorld (other._ImageToWorld ? new irtkWorldCoordsImage (*other._ImageToWorld) : NULL), _ExternalDisplacement (other._ExternalDisplacement), _FixedDisplacement (other._FixedDisplacement ? new DisplacementImageType(*other._FixedDisplacement) : NULL), _Displacement (other._Displacement ? new DisplacementImageType(*other._Displacement) : NULL), _CacheWorldCoordinates (other._CacheWorldCoordinates), _CacheFixedDisplacement(other._CacheFixedDisplacement), _CacheDisplacement (other._CacheDisplacement), _SelfUpdate (other._SelfUpdate), _MinIntensity (other._MinIntensity), _MaxIntensity (other._MaxIntensity), _GradientSigma (other._GradientSigma), _HessianSigma (other._HessianSigma), _PrecomputeDerivatives (other._PrecomputeDerivatives), _NumberOfActiveLevels (other._NumberOfActiveLevels), _NumberOfPassiveLevels (other._NumberOfPassiveLevels) { memcpy(_Offset, other._Offset, 13 * sizeof(int)); } // ----------------------------------------------------------------------------- irtkRegisteredImage &irtkRegisteredImage::operator =(const irtkRegisteredImage &other) { irtkGenericImage<double>::operator =(other); _InputImage = other._InputImage; _InputGradient = other._InputGradient ? new GradientImageType(*other._InputGradient) : NULL; _InputHessian = other._InputHessian ? new GradientImageType(*other._InputHessian) : NULL; _Transformation = other._Transformation; _InterpolationMode = other._InterpolationMode; _ExtrapolationMode = other._ExtrapolationMode; _WorldCoordinates = other._WorldCoordinates; _ImageToWorld = other._ImageToWorld ? new irtkWorldCoordsImage (*other._ImageToWorld) : NULL; _ExternalDisplacement = other._ExternalDisplacement; _FixedDisplacement = other._FixedDisplacement ? new DisplacementImageType(*other._FixedDisplacement) : NULL; _Displacement = other._Displacement ? new DisplacementImageType(*other._Displacement) : NULL; _CacheWorldCoordinates = other._CacheWorldCoordinates; _CacheFixedDisplacement = other._CacheFixedDisplacement; _CacheDisplacement = other._CacheDisplacement; _SelfUpdate = other._SelfUpdate; _MinIntensity = other._MinIntensity; _MaxIntensity = other._MaxIntensity; _GradientSigma = other._GradientSigma; _HessianSigma = other._HessianSigma; _PrecomputeDerivatives = other._PrecomputeDerivatives; _NumberOfActiveLevels = other._NumberOfActiveLevels; _NumberOfPassiveLevels = other._NumberOfPassiveLevels; memcpy(_Offset, other._Offset, 13 * sizeof(int)); return *this; } // ----------------------------------------------------------------------------- irtkRegisteredImage::~irtkRegisteredImage() { if (_ImageToWorld != _WorldCoordinates) delete _ImageToWorld; delete _FixedDisplacement; delete _Displacement; if (_InputGradient != _InputImage) delete _InputGradient; delete _InputHessian; } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Initialize(const irtkImageAttributes &attr, int t) { IRTK_START_TIMING(); // Clear possibly previously allocated displacement cache if (!_Transformation) Delete(_Displacement); // Check if input image is set if (!_InputImage) { cerr << "irtkRegisteredImage::Initialize: Missing input image" << endl; exit(1); } // Initialize base class if (attr._t > 1) { cerr << "irtkRegisteredImage::Initialize: Split multi-channel image/temporal sequence up into separate 2D/3D images" << endl; exit(1); } if (t == 0) t = 1; if (t != 1 && t != 4 && t != 10 && t != 13) { cerr << "irtkRegisteredImage::Initialize: Number of registered image channels must be either 1, 4, 10 or 13" << endl; exit(1); } irtkGenericImage<double>::Initialize(attr, t); // Set background value/foreground mask if (_InputImage->HasBackgroundValue()) { this->PutBackgroundValueAsDouble(_InputImage->GetBackgroundValueAsDouble()); } else { this->PutBackgroundValueAsDouble(MIN_GREY); } // Pre-compute world coordinates if (_WorldCoordinates) { if (_ImageToWorld != _WorldCoordinates) { delete _ImageToWorld; _ImageToWorld = _WorldCoordinates; } } else if (_CacheWorldCoordinates) { if (!_ImageToWorld) _ImageToWorld = new irtkWorldCoordsImage(); this->ImageToWorld(*_ImageToWorld, true /* i.e., always 3D vectors */); } else { Delete(_ImageToWorld); } // Determine number of active (changing) and passive (fixed) levels bool cache_fixed = !_ExternalDisplacement && _CacheFixedDisplacement; const irtkMultiLevelTransformation *mffd = NULL; if ((mffd = dynamic_cast<const irtkMultiLevelTransformation *>(_Transformation))) { _NumberOfPassiveLevels = 0; for (int l = 0; l < mffd->NumberOfLevels(); ++l) { if (mffd->LocalTransformationIsActive(l)) break; if (mffd->GetLocalTransformation(l)->RequiresCachingOfDisplacements()) cache_fixed = true; ++_NumberOfPassiveLevels; } _NumberOfActiveLevels = mffd->NumberOfLevels() - _NumberOfPassiveLevels; if (_NumberOfPassiveLevels == 0 && mffd->GetGlobalTransformation()->IsIdentity()) { _NumberOfPassiveLevels = -1; } } else if (_Transformation) { _NumberOfActiveLevels = 1; _NumberOfPassiveLevels = -1; } else { _NumberOfActiveLevels = 0; _NumberOfPassiveLevels = -1; } // Pre-compute fixed displacements if (cache_fixed && _NumberOfPassiveLevels >= 0) { if (!_FixedDisplacement) _FixedDisplacement = new DisplacementImageType(); _FixedDisplacement->Initialize(attr, 3); mffd->Displacement(-1, _NumberOfPassiveLevels, *_FixedDisplacement, _InputImage->GetTOrigin(), _ImageToWorld); } else { Delete(_FixedDisplacement); } // Pre-compute input derivatives if (t > 1) ComputeInputGradient(_GradientSigma); if (t > 4) ComputeInputHessian (_HessianSigma ); // Initialize offsets of registered image channels _Offset[0] = 0; _Offset[1] = this->NumberOfVoxels(); for (int c = 2; c < 13; ++c) _Offset[c] = _Offset[c-1] + _Offset[1]; // Attention: Initialization of actual image content must be forced upon first // Update call. This is initiated by the irtkImageSimilarity::Update // function which in turn is called before the first energy gradient // evaluation (see irtkGradientDescent::Gradient). IRTK_DEBUG_TIMING(4, "initialization of " << (_Transformation ? "moving" : "fixed") << " image"); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::ComputeInputGradient(double sigma) { IRTK_START_TIMING(); // Smooth input image InputImageType *blurred_image = _InputImage; if (sigma > .0) { blurred_image = new InputImageType; if (this->HasBackgroundValue()) { blurred_image->PutBackgroundValueAsDouble(this->GetBackgroundValueAsDouble()); irtkGaussianBlurringWithPadding<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize(), this->GetBackgroundValueAsDouble()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } else { irtkGaussianBlurring<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } } if (_PrecomputeDerivatives) { // Compute image gradient using finite differences typedef irtkGradientImageFilter<GradientImageType::VoxelType> FilterType; FilterType filter(FilterType::GRADIENT_VECTOR); filter.SetInput (blurred_image); filter.SetOutput(_InputGradient ? _InputGradient : new GradientImageType); // Note that even though the original nreg2 implementation did divide // the image gradient initially by the voxel size, the similarity gradient // was reoriented then by irtkImageRegistration2::EvaluateGradient using the // upper 3x3 image to world matrix. This effectively multiplied by the voxel // size again which is equivalent to only reorienting the image gradient // computed w.r.t. the voxel coordinates, i.e., leaving the magnitude of the // gradient in voxel units rather than world units (i.e., mm's). filter.UseVoxelSize (version.Major() >= 3); filter.UseOrientation(true); if (this->HasBackgroundValue()) { filter.SetPadding(this->GetBackgroundValueAsDouble()); } filter.Run(); _InputGradient = filter.GetOutput(); _InputGradient->PutTSize(.0); _InputGradient->PutBackgroundValueAsDouble(.0); if (blurred_image != _InputImage) delete blurred_image; IRTK_DEBUG_TIMING(5, "computation of 1st order image derivatives"); } else { delete _InputGradient; _InputGradient = blurred_image; IRTK_DEBUG_TIMING(5, "low-pass filtering of image for 1st order derivatives"); } } // ----------------------------------------------------------------------------- void irtkRegisteredImage::ComputeInputHessian(double sigma) { IRTK_START_TIMING(); // Smooth input image InputImageType *blurred_image = _InputImage; if (sigma > .0) { blurred_image = new InputImageType; if (this->HasBackgroundValue()) { blurred_image->PutBackgroundValueAsDouble(this->GetBackgroundValueAsDouble()); irtkGaussianBlurringWithPadding<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize(), this->GetBackgroundValueAsDouble()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } else { irtkGaussianBlurring<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } } // Compute 2nd order image derivatives using finite differences typedef irtkHessianImageFilter<HessianImageType::VoxelType> FilterType; FilterType filter(FilterType::HESSIAN_MATRIX); filter.SetInput (blurred_image); filter.SetOutput (_InputHessian ? _InputHessian : new HessianImageType); filter.UseVoxelSize (true); filter.UseOrientation(true); if (this->HasBackgroundValue()) { filter.SetPadding(this->GetBackgroundValueAsDouble()); } filter.Run(); _InputHessian = filter.GetOutput(); _InputHessian->PutTSize(.0); _InputHessian->PutBackgroundValueAsDouble(.0); if (blurred_image != _InputImage) delete blurred_image; IRTK_DEBUG_TIMING(5, "computation of 2nd order image derivatives"); } // ============================================================================= // Update // ============================================================================= // ----------------------------------------------------------------------------- // Base class of voxel transformation functors struct Transformer { typedef irtkWorldCoordsImage::VoxelType CoordType; /// Constructor Transformer() : _Input (NULL), _Transformation(NULL), _Output (NULL), _y(0), _z(0) {} /// Initialize data members void Initialize(irtkRegisteredImage *o, const irtkBaseImage *i, const irtkTransformation *t) { _Input = i; _t = i->GetTOrigin(); _t0 = o->GetTOrigin(); _Transformation = t; _Output = o; _y = o->GetX() * o->GetY() * o->GetZ(); _z = 2 * _y; } /// Transform output voxel void operator ()(double &x, double &y, double &z) { _Output->ImageToWorld(x, y, z); _Transformation->Transform(x, y, z, _t, _t0); _Input->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates void operator ()(double &x, double &y, double &z, const CoordType *wc) { x = wc[_x], y = wc[_y], z = wc[_z]; _Transformation->Transform(x, y, z, _t, _t0); _Input->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates and displacements void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *dx) { x = wc[_x] + dx[_x]; y = wc[_y] + dx[_y]; z = wc[_z] + dx[_z]; _Input->WorldToImage(x, y, z); } protected: const irtkBaseImage *_Input; const irtkTransformation *_Transformation; irtkRegisteredImage *_Output; static const int _x = 0; ///< Offset of x component int _y; ///< Offset of y component int _z; ///< Offset of z component double _t; ///< Time point double _t0; ///< Time point of target }; // ----------------------------------------------------------------------------- // Transformer used when no fixed transformation is cached struct DefaultTransformer : public Transformer { using Transformer::operator(); /// As this transformer is only used when no fixed transformation is cached, /// this overloaded operator should never be invoked void operator ()(double &, double &, double &, const CoordType *, const double *, const double *) { cerr << "irtkRegisteredImage::DefaultTransformer used even though _FixedDisplacement assumed to be NULL ?!?" << endl; exit(1); } }; // ----------------------------------------------------------------------------- // Transform output voxel using additive composition of displacements struct AdditiveTransformer : public Transformer { using Transformer::operator(); /// Transform output voxel using pre-computed world coordinates and displacements void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *d1, const double *d2) { x = wc[_x] + d1[_x] + d2[_x]; y = wc[_y] + d1[_y] + d2[_y]; z = wc[_z] + d1[_z] + d2[_z]; _Input->WorldToImage(x, y, z); } }; // ----------------------------------------------------------------------------- // Transform output voxel using fluid composition of displacements struct FluidTransformer : public Transformer { using Transformer::operator(); /// Transform output voxel using pre-computed world coordinates and displacements /// /// Because fluid composition of displacement fields would require interpolation, /// let irtkTransformation::Displacement handle the fluid composition already when /// computing the second displacement field. void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *, const double *dx) { x = wc[_x] + dx[_x]; y = wc[_y] + dx[_y]; z = wc[_z] + dx[_z]; _Input->WorldToImage(x, y, z); } }; // ----------------------------------------------------------------------------- // Transformer used when no transformation is set or custom displacement field given struct FixedTransformer : public Transformer { // Visual Studio 2013 has troubles resolving // void operator()(double&, double&, double&) // if a using Transformer::operator() statement is used because it is also // defined by this subclass. Instead, just re-implement the only other // overloaded version as well. /// Transform output voxel void operator ()(double &x, double &y, double &z) { _Output->ImageToWorld(x, y, z); _Input ->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates void operator ()(double &x, double &y, double &z, const CoordType *wc) { x = wc[_x], y = wc[_y], z = wc[_z]; _Input->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates and displacements void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *dx) { Transformer::operator()(x, y, z, wc, dx); } /// As this transformer is only used when no transformation is set, /// this overloaded operator should never be invoked void operator ()(double &, double &, double &, const CoordType *, const double *, const double *) { cerr << "irtkRegisteredImage::FixedTransformer(..., d1, d2) used even though _Transformation assumed to be NULL ?!?" << endl; exit(1); } }; // ----------------------------------------------------------------------------- // Auxiliary function to allocate and initialize image interpolate function template <class ImageFunction> void New( ImageFunction *&f, const irtkBaseImage *image, #ifndef NDEBUG irtkInterpolationMode interp, #else irtkInterpolationMode, #endif irtkExtrapolationMode extrap, double padding, double default_value) { if (image) { f = new ImageFunction(); #ifndef NDEBUG interp = InterpolationWithoutPadding(interp); if (interp == Interpolation_FastLinear) interp = Interpolation_Linear; irtkInterpolationMode mode = f->InterpolationMode(); if (mode == Interpolation_FastLinear) mode = Interpolation_Linear; if (mode != interp) { cout << endl; cerr << __FILE__ << ":" << __LINE__ << ": Mismatch of interpolation mode: expected \"" << ToString(interp) << "\", but got \"" << ToString(mode) << "\"" << endl; exit(1); } #endif irtkImageGradientFunction *g = dynamic_cast<irtkImageGradientFunction *>(f); if (g) g->WrtWorld(true); f->Input(const_cast<irtkBaseImage *>(image)); if (extrap != Extrapolation_Default) { f->Extrapolator(f->New(extrap, image), true); } f->DefaultValue(default_value); f->Initialize(); if (f->Extrapolator()) f->Extrapolator()->DefaultValue(padding); } } template <> void New(irtkInterpolateImageFunction *&f, const irtkBaseImage *image, irtkInterpolationMode interp, irtkExtrapolationMode extrap, double padding, double default_value) { if (image) { f = irtkInterpolateImageFunction::New(interp, const_cast<irtkBaseImage *>(image)); f->Input(const_cast<irtkBaseImage *>(image)); if (extrap != Extrapolation_Default) { f->Extrapolator(f->New(extrap, image), true); } f->DefaultValue(default_value); f->Initialize(); if (f->Extrapolator()) f->Extrapolator()->DefaultValue(padding); } } template <> void New(irtkImageGradientFunction *&f, const irtkBaseImage *image, irtkInterpolationMode interp, irtkExtrapolationMode extrap, double padding, double default_value) { if (image) { f = irtkImageGradientFunction::New(interp, const_cast<irtkBaseImage *>(image)); f->WrtWorld(true); f->Input(const_cast<irtkBaseImage *>(image)); if (extrap != Extrapolation_Default) { f->Extrapolator(f->New(extrap, image), true); } f->DefaultValue(default_value); f->Initialize(); if (f->Extrapolator()) f->Extrapolator()->DefaultValue(padding); } } // TODO: Add template specialization for irtkImageHessianFunction // ----------------------------------------------------------------------------- // Base class of voxel interpolation functions template <class IntensityFunction, class GradientFunction, class HessianFunction> class Interpolator { protected: IntensityFunction *_IntensityFunction; GradientFunction *_GradientFunction; HessianFunction *_HessianFunction; bool _InterpolateWithPadding; double _PaddingValue; double _MinIntensity; double _MaxIntensity; double _RescaleSlope; double _RescaleIntercept; int _NumberOfVoxels; int _NumberOfChannels; irtkVector3D<int> _InputSize; public: /// Constructor Interpolator() : _IntensityFunction (NULL), _GradientFunction (NULL), _HessianFunction (NULL), _InterpolateWithPadding(false), _PaddingValue (-1), _MinIntensity (numeric_limits<double>::quiet_NaN()), _MaxIntensity (numeric_limits<double>::quiet_NaN()), _RescaleSlope (1.0), _RescaleIntercept (.0), _NumberOfVoxels (0), _NumberOfChannels (0) {} /// Copy constructor Interpolator(const Interpolator &other) : _IntensityFunction (NULL), _GradientFunction (NULL), _HessianFunction (NULL), _InterpolateWithPadding(other._InterpolateWithPadding), _PaddingValue (other._PaddingValue), _MinIntensity (other._MinIntensity), _MaxIntensity (other._MaxIntensity), _RescaleSlope (other._RescaleSlope), _RescaleIntercept (other._RescaleIntercept), _NumberOfVoxels (other._NumberOfVoxels), _NumberOfChannels (other._NumberOfChannels), _InputSize (other._InputSize) { if (other._IntensityFunction) { const irtkBaseImage *f = other._IntensityFunction->Input(); const double f_bg = (f->HasBackgroundValue() ? f->GetBackgroundValueAsDouble() : MIN_GREY); New<IntensityFunction>(_IntensityFunction, f, other._IntensityFunction->InterpolationMode(), other._IntensityFunction->ExtrapolationMode(), f_bg, f_bg); } if (other._GradientFunction) { const irtkBaseImage *g = other._GradientFunction->Input(); const double g_bg = (g->HasBackgroundValue() ? g->GetBackgroundValueAsDouble() : .0); New<GradientFunction>(_GradientFunction, g, other._GradientFunction->InterpolationMode(), other._GradientFunction->ExtrapolationMode(), g_bg, .0); } if (other._HessianFunction) { const irtkBaseImage *h = other._HessianFunction->Input(); const double h_bg = (h->HasBackgroundValue() ? h->GetBackgroundValueAsDouble() : .0); New<HessianFunction>(_HessianFunction, h, other._HessianFunction->InterpolationMode(), other._HessianFunction->ExtrapolationMode(), h_bg, .0); } } /// Destructor ~Interpolator() { Delete(_IntensityFunction); Delete(_GradientFunction); Delete(_HessianFunction); } /// Initialize data members void Initialize(irtkRegisteredImage *o, const irtkBaseImage *f, const irtkBaseImage *g, const irtkBaseImage *h, double omin = numeric_limits<double>::quiet_NaN(), double omax = numeric_limits<double>::quiet_NaN()) { _InterpolateWithPadding = (ToString(o->InterpolationMode()).find("with padding") != string::npos); if (o->HasBackgroundValue()) _PaddingValue = o->GetBackgroundValueAsDouble(); _NumberOfVoxels = o->GetX() * o->GetY() * o->GetZ(); _NumberOfChannels = o->GetT(); const double f_bg = (f->HasBackgroundValue() ? f->GetBackgroundValueAsDouble() : MIN_GREY); const double g_bg = (g && g->HasBackgroundValue() ? g->GetBackgroundValueAsDouble() : .0); const double h_bg = (h && h->HasBackgroundValue() ? h->GetBackgroundValueAsDouble() : .0); New<IntensityFunction>(_IntensityFunction, f, o->InterpolationMode(), o->ExtrapolationMode(), f_bg, f_bg); New<GradientFunction >(_GradientFunction, g, o->InterpolationMode(), Extrapolation_Default, g_bg, .0); New<HessianFunction >(_HessianFunction, h, o->InterpolationMode(), Extrapolation_Default, h_bg, .0); _MinIntensity = omin; _MaxIntensity = omax; if (!IsNaN(omin) || !IsNaN(omax)) { double imin, imax; f->GetMinMaxAsDouble(imin, imax); if (IsNaN(omin)) omin = imin; if (IsNaN(omax)) omax = imax; _RescaleSlope = (omax - omin) / (imax - imin); _RescaleIntercept = omin - _RescaleSlope * imin; } else { _RescaleSlope = 1.0; _RescaleIntercept = 0.0; } _InputSize = irtkVector3D<int>(f->X(), f->Y(), f->Z()); } /// Determine interpolation mode at given location /// /// \retval 1 Output channels should be interpolated without boundary checks. /// \retval 0 Output channels should be interpolated at boundary. /// \retval -1 Output channels should be padded. /// /// \note The return value 0 was used in a previous implementation but is /// currently unused. The mode is either 1 (inside) or -1 (outside). int InterpolationMode(double x, double y, double z, bool check_value = true) const { // Use bounds suitable also for _GradientFunction and _HessianFunction. // The linear image gradient function requires more strict bounds than // the linear image intensity interpolation function. bool inside = (.5 < x && x < _InputSize._x - 1.5 && .5 < y && y < _InputSize._y - 1.5); if (inside) { if (_InputSize._z == 1) inside = fequal(z, .0, 1e-3); else inside = (.5 < z && z < _InputSize._z - 1.5); if (inside && check_value) { if (_InterpolateWithPadding) { double value = _IntensityFunction->EvaluateWithPadding(x, y, z); if (value == _IntensityFunction->DefaultValue()) return -1; } } return inside ? 1 : -1; } return -1; } /// Interpolate input intensity function /// /// \return The interpolation mode, i.e., result of inside/outside domain check. int InterpolateIntensity(double x, double y, double z, double *o) { // Check if location is inside image domain int mode = InterpolationMode(x, y, z, false); if (mode == 1) { // Either interpolate using the input padding value to exclude background if (_InterpolateWithPadding) { *o = _IntensityFunction->EvaluateWithPaddingInside(x, y, z); // or simply ignore the input background value as done by nreg2 } else { *o = _IntensityFunction->EvaluateInside(x, y, z); } // Set background to output padding value if (*o == _IntensityFunction->DefaultValue()) { *o = _PaddingValue; if (_InterpolateWithPadding) return -1; // Rescale foreground to desired [min, max] range } else if (_RescaleSlope != 1.0 || _RescaleIntercept != .0) { *o = (*o) * _RescaleSlope + _RescaleIntercept; if (*o < _MinIntensity) *o = _MinIntensity; else if (*o > _MaxIntensity) *o = _MaxIntensity; } // Otherwise, set output intensity to outside value } else { *o = _PaddingValue; } // Pass inside/outside check result on to derivative interpolation // functions such that these boundary checks are only done once. // This requires the same interpolation mode for all channels. return mode; } /// Interpolate 1st order derivatives of input intensity function void InterpolateGradient(double x, double y, double z, double *o, int mode = 0) { o += _NumberOfVoxels; switch (mode) { // Inside case 1: if (_InterpolateWithPadding) { _GradientFunction->EvaluateWithPaddingInside(o, x, y, z, _NumberOfVoxels); } else { _GradientFunction->EvaluateInside(o, x, y, z, _NumberOfVoxels); } break; // Outside/Boundary default: for (int c = 1; c <= 3; ++c, o += _NumberOfVoxels) *o = .0; } } /// Interpolate 2nd order derivatives of input intensity function void InterpolateHessian(double x, double y, double z, double *o, int mode = 0) { o += 4 * _NumberOfVoxels; switch (mode) { // Inside case 1: if (_InterpolateWithPadding) { _HessianFunction->EvaluateWithPaddingInside(o, x, y, z, _NumberOfVoxels); } else { _HessianFunction->EvaluateInside(o, x, y, z, _NumberOfVoxels); } break; // Outside/Boundary default: for (int c = 4; c < _NumberOfChannels; ++c, o += _NumberOfVoxels) *o = .0; } } }; // ----------------------------------------------------------------------------- // Interpolates intensity template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { this->InterpolateIntensity(x, y, z, o); } }; // ----------------------------------------------------------------------------- // Interpolates 1st order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct GradientInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolationMode (x, y, z); this ->InterpolateGradient(x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct HessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolationMode (x, y, z); this ->InterpolateHessian(x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates intensity and 1st order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityAndGradientInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolateIntensity(x, y, z, o); this ->InterpolateGradient (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates intensity and 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityAndHessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolateIntensity(x, y, z, o); this ->InterpolateHessian (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates 1st and 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct GradientAndHessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolationMode (x, y, z); this ->InterpolateGradient(x, y, z, o, mode); this ->InterpolateHessian (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates intensity, 1st and 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityAndGradientAndHessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolateIntensity(x, y, z, o); this ->InterpolateGradient (x, y, z, o, mode); this ->InterpolateHessian (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Voxel update function template <class Transformer, class Interpolator> struct UpdateFunction : public irtkVoxelFunction { private: typedef typename Transformer::CoordType CoordType; Transformer _Transform; Interpolator _Interpolate; public: /// Constructor UpdateFunction(const irtkBaseImage *f, const irtkBaseImage *g, const irtkBaseImage *h, const irtkTransformation *t, irtkRegisteredImage *o, double omin = numeric_limits<double>::quiet_NaN(), double omax = numeric_limits<double>::quiet_NaN()) { _Transform .Initialize(o, f, t); _Interpolate.Initialize(o, f, g, h, omin, omax); } /// Resample input without pre-computed maps void operator ()(int i, int j, int k, int, double *o) { double x = i, y = j, z = k; _Transform (x, y, z); _Interpolate(x, y, z, o); } /// Resample input using pre-computed world coordinates void operator ()(int i, int j, int k, int, const CoordType *wc, double *o) { double x = i, y = j, z = k; _Transform (x, y, z, wc); _Interpolate(x, y, z, o); } /// Resample input using pre-computed world coordinates and displacements void operator ()(int i, int j, int k, int, const CoordType *wc, const double *dx, double *o) { double x = i, y = j, z = k; _Transform (x, y, z, wc, dx); _Interpolate(x, y, z, o); } /// Resample input using pre-computed world coordinates and additive displacements void operator ()(int i, int j, int k, int, const CoordType *wc, const double *d1, const double *d2, double *o) { double x = i, y = j, z = k; _Transform (x, y, z, wc, d1, d2); _Interpolate(x, y, z, o); } }; // ----------------------------------------------------------------------------- template <class Transformer, class Interpolator> void irtkRegisteredImage::Update3(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian) { typedef UpdateFunction<Transformer, Interpolator> Function; Function f(intensity ? _InputImage : NULL, gradient ? _InputGradient : NULL, hessian ? _InputHessian : NULL, _Transformation, this, _MinIntensity, _MaxIntensity); if (_ImageToWorld) { if (_ExternalDisplacement) { ParallelForEachVoxel(region, _ImageToWorld, _ExternalDisplacement, this, f); } else if (_Displacement) { if (_FixedDisplacement) { ParallelForEachVoxel(region, _ImageToWorld, _FixedDisplacement, _Displacement, this, f); } else { ParallelForEachVoxel(region, _ImageToWorld, _Displacement, this, f); } } else { ParallelForEachVoxel(region, _ImageToWorld, this, f); } } else { ParallelForEachVoxel(region, this, f); } } // ----------------------------------------------------------------------------- template <class Transformer, class IntensityFunction, class GradientFunction, class HessianFunction> void irtkRegisteredImage::Update2(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian) { // Auxiliary macro -- undefined again at the end of this body #define _update_using(Interpolator) \ Update3< \ Transformer, \ Interpolator<IntensityFunction, GradientFunction, HessianFunction> \ >(region, intensity, gradient, hessian) if (intensity) { if (gradient) { if (hessian) { _update_using(IntensityAndGradientAndHessianInterpolator); } else { _update_using(IntensityAndGradientInterpolator); } } else { if (hessian) { _update_using(IntensityAndHessianInterpolator); } else { _update_using(IntensityInterpolator); } } } else { if (gradient) { if (hessian) { _update_using(GradientAndHessianInterpolator); } else { _update_using(GradientInterpolator); } } else { if (hessian) { _update_using(HessianInterpolator); } else { cerr << "irtkRegisteredImage::Update: At least one output channel should be updated" << endl; exit(1); } } } #undef _update_using } // ----------------------------------------------------------------------------- template <class Transformer> void irtkRegisteredImage::Update1(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian) { irtkInterpolationMode interpolation = InterpolationWithoutPadding(_InterpolationMode); if (_PrecomputeDerivatives) { // Instantiate image functions for commonly used interpolation methods // to allow the compiler to generate optimized code for these if (interpolation == Interpolation_Linear || interpolation == Interpolation_FastLinear) { // Auxiliary macro -- undefined again at the end of this body #define _update_using(InterpolatorType) \ Update2<Transformer, InterpolatorType<InputImageType>, \ InterpolatorType<GradientImageType>, \ InterpolatorType<HessianImageType> > \ (region, intensity, gradient, hessian) if (this->GetZ() == 1) { _update_using(irtkGenericLinearInterpolateImageFunction2D); } else { _update_using(irtkGenericLinearInterpolateImageFunction3D); } #undef _update_using // Otherwise use generic interpolate image function interface } else { Update2<Transformer, irtkInterpolateImageFunction, irtkInterpolateImageFunction, irtkInterpolateImageFunction> (region, intensity, gradient, hessian); } } else { // Auxiliary macro -- undefined again at the end of this body // TODO: Use also some HessianInterpolatorType #define _update_using(InterpolatorType, GradientInterpolatorType) \ Update2<Transformer, InterpolatorType<InputImageType>, \ GradientInterpolatorType<InputImageType>, \ InterpolatorType<HessianImageType> > \ (region, intensity, gradient, hessian) // Instantiate image functions for commonly used interpolation methods // to allow the compiler to generate optimized code for these if (interpolation == Interpolation_Linear) { if (this->GetZ() == 1) { _update_using(irtkGenericLinearInterpolateImageFunction2D, irtkGenericLinearImageGradientFunction2D); } else { _update_using(irtkGenericLinearInterpolateImageFunction3D, irtkGenericLinearImageGradientFunction3D); } } else if (interpolation == Interpolation_FastLinear) { if (this->GetZ() == 1) { _update_using(irtkGenericLinearInterpolateImageFunction2D, irtkGenericFastLinearImageGradientFunction2D); } else { _update_using(irtkGenericLinearInterpolateImageFunction3D, irtkGenericFastLinearImageGradientFunction3D); } // Otherwise use generic interpolate image function interface // TODO: Implement and use irtkImageHessianFunction } else { Update2<Transformer, irtkInterpolateImageFunction, irtkImageGradientFunction, irtkInterpolateImageFunction> (region, intensity, gradient, hessian); } #undef _update_using } } // ----------------------------------------------------------------------------- template <class TOut, class TIn> inline void CopyChannels(irtkGenericImage<TOut> *tgt, int l, const irtkGenericImage<TIn> *src) { assert(tgt->GetX() == src->GetX()); assert(tgt->GetY() == src->GetY()); assert(tgt->GetZ() == src->GetZ()); assert(tgt->GetT() >= l + src->GetT()); TOut *out = tgt->GetPointerToVoxels(0, 0, 0, l); const TIn *in = src->GetPointerToVoxels(); const int nvox = src->GetNumberOfVoxels(); for (int idx = 0; idx < nvox; ++idx) { (*out++) = static_cast<TOut>(*in++); } } // ----------------------------------------------------------------------------- template <> inline void CopyChannels(irtkGenericImage<irtkRegisteredImage::VoxelType> *tgt, int l, const irtkGenericImage<irtkRegisteredImage::VoxelType> *src) { assert(tgt->GetX() == src->GetX()); assert(tgt->GetY() == src->GetY()); assert(tgt->GetZ() == src->GetZ()); assert(tgt->GetT() >= l + src->GetT()); memcpy(tgt->GetPointerToVoxels(0, 0, 0, l), src->GetPointerToVoxels(), src->GetNumberOfVoxels() * sizeof(irtkRegisteredImage::VoxelType)); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Update(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian, bool force) { // Update only channels that were initialized even if requested gradient = gradient && this->T() >= 4; hessian = hessian && this->T() >= 10; // Do nothing if no output should be updated if (!intensity && !gradient && !hessian) return; // Do nothing if no transformation is set or self-update is disabled // (i.e., external process is responsible for update of registered image) if (!force && (!_Transformation || !_SelfUpdate)) return; IRTK_START_TIMING(); if (_ExternalDisplacement && region.cols ().begin() == 0 && region.cols ().end() == _ExternalDisplacement->X() && region.rows ().begin() == 0 && region.rows ().end() == _ExternalDisplacement->Y() && region.pages().begin() == 0 && region.pages().end() == _ExternalDisplacement->Z()) { // Always use provided externally updated displacement field if given Update1<DefaultTransformer>(region, intensity, gradient, hessian); } else { // End time point of deformation and initial time for velocity-based // transformations, i.e., time point of initial condition of ODE const double t = _InputImage->GetTOrigin(); const double t0 = this ->GetTOrigin(); // ------------------------------------------------------------------------- // Update moving image (i.e., constantly changing transformation is set) if (_Transformation && _NumberOfActiveLevels > 0) { // For some transformations, it is faster to compute the displacements // all at once such as those which are represented by velocity fields. const bool cache = _CacheDisplacement || _Transformation->RequiresCachingOfDisplacements(); if (cache && !_Displacement) _Displacement = new DisplacementImageType(); // If we pre-computed the fixed displacement of the passive MFFD levels const irtkMultiLevelTransformation *mffd; if (_FixedDisplacement && (mffd = dynamic_cast<const irtkMultiLevelTransformation *>(_Transformation))) { if (dynamic_cast<const irtkFluidFreeFormTransformation *>(mffd)) { if (_Displacement) { *_Displacement = *_FixedDisplacement; mffd->Displacement(_NumberOfPassiveLevels, -1, *_Displacement, t, t0, _ImageToWorld); } Update1<FluidTransformer>(region, intensity, gradient, hessian); } else { if (_Displacement) { _Displacement->Initialize(_attr, 3); mffd->Displacement(_NumberOfPassiveLevels, -1, *_Displacement, t, t0, _ImageToWorld); } Update1<AdditiveTransformer>(region, intensity, gradient, hessian); } // Otherwise, simply let the (non-)MFFD compute the total transformation } else { if (_Displacement) { _Displacement->Initialize(_attr, 3); _Transformation->Displacement(*_Displacement, t, t0, _ImageToWorld); } Update1<DefaultTransformer>(region, intensity, gradient, hessian); } // ------------------------------------------------------------------------- // Update fixed image } else { // Copy input images if no transformation is set and the image attributes // of the input images are identical to those of the output images if (!_Transformation && this->HasSpatialAttributesOf(_InputImage)) { // Copy intensities if (intensity) { // Rescale foreground intensities to [_MinIntensity, _MaxIntensity] if (!IsNaN(_MinIntensity) || !IsNaN(_MaxIntensity)) { const int nvox = NumberOfVoxels(); if (nvox > 0) { InputImageType::VoxelType *iptr = _InputImage->Data(); InputImageType::VoxelType imin; InputImageType::VoxelType imax; imin = voxel_limits<InputImageType::VoxelType>::max(); imax = voxel_limits<InputImageType::VoxelType>::min(); for (int idx = 0; idx < nvox; ++idx, ++iptr) { if (_InputImage->IsForeground(idx)) { if (*iptr < imin) imin = *iptr; if (*iptr > imax) imax = *iptr; } } if (imin <= imax) { double omin = _MinIntensity; double omax = _MaxIntensity; if (IsNaN(omin)) omin = imin; if (IsNaN(omax)) omax = imax; const double slope = (omax - omin) / static_cast<double>(imax - imin); const double inter = omin - slope * static_cast<double>(imin); iptr = _InputImage->Data(); VoxelType *optr = this->Data(); const VoxelType bg = voxel_cast<VoxelType>(this->_bg); for (int idx = 0; idx < nvox; ++idx, ++iptr, ++optr) { if (_InputImage->IsForeground(idx)) { *optr = voxel_cast<VoxelType>(inter + slope * static_cast<double>(*iptr)); if (*optr < _MinIntensity) *optr = _MinIntensity; else if (*optr > _MaxIntensity) *optr = _MaxIntensity; } else { *optr = bg; } } } } } else { CopyChannels(this, 0, _InputImage); } } // Copy derivatives if (gradient) CopyChannels(this, 1, _InputGradient); if (hessian) CopyChannels(this, 4, _InputHessian); // Copy background mask (if set) this->PutMask(_InputImage->GetMask()); // Resample input images on (transformed) output image grid otherwise } else { Delete(_Displacement); _Displacement = _FixedDisplacement; _FixedDisplacement = NULL; if (_Transformation) { const bool cache = _CacheDisplacement || _Transformation->RequiresCachingOfDisplacements(); if (cache && !_Displacement) { _Displacement = new DisplacementImageType(); _Transformation->Displacement(*_Displacement, t, t0, _ImageToWorld); } } Update1<FixedTransformer>(region, intensity, gradient, hessian); Delete(_Displacement); // image usually only transformed once } } } IRTK_DEBUG_TIMING(4, "update of " << (_Transformation ? "moving" : "fixed") << " image" << " (intensity=" << (intensity ? "yes" : "no") << ", gradient=" << (gradient ? "yes" : "no") << ", hessian=" << (hessian ? "yes" : "no") << ")"); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Update(bool intensity, bool gradient, bool hessian, bool force) { blocked_range3d<int> region(0, Z(), 0, Y(), 0, X()); this->Update(region, intensity, gradient, hessian, force); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Update(const blocked_range3d<int> &region, const DisplacementImageType *disp, bool intensity, bool gradient, bool hessian) { // Update only channels that were initialized even if requested gradient = gradient && this->T() >= 4; hessian = hessian && this->T() >= 10; // Do nothing if no output should be updated if (!intensity && !gradient && !hessian) return; // Image to world map required by Update3 if (!_ImageToWorld) { _ImageToWorld = new irtkWorldCoordsImage(); this->ImageToWorld(*_ImageToWorld, true /* i.e., always 3D vectors */); } // Keep pointers to own displacement fields DisplacementImageType * const _disp = _Displacement; DisplacementImageType * const _fixed = _FixedDisplacement; // Replace displacement fields by user arguments _Displacement = const_cast<DisplacementImageType *>(disp); _FixedDisplacement = NULL; // Interpolate within specified region using fixed transfomer Update1<FixedTransformer>(region, intensity, gradient, hessian); // Reset pointers to own displacement fields _Displacement = _disp; _FixedDisplacement = _fixed; }
40.334873
129
0.616776
kevin-keraudren
719808bb3bebe7d1d308ff050376afa792945677
448
cc
C++
phastaIO/phiotimer_empty/phiotimer_empty.cc
polmes/phasta
38a361e8033072fa0b5376e424dddd3efa5a65d5
[ "BSD-3-Clause" ]
49
2015-04-16T13:45:34.000Z
2022-02-07T01:02:49.000Z
phastaIO/phiotimer_empty/phiotimer_empty.cc
polmes/phasta
38a361e8033072fa0b5376e424dddd3efa5a65d5
[ "BSD-3-Clause" ]
21
2015-10-06T19:50:43.000Z
2017-12-17T03:47:51.000Z
phastaIO/phiotimer_empty/phiotimer_empty.cc
polmes/phasta
38a361e8033072fa0b5376e424dddd3efa5a65d5
[ "BSD-3-Clause" ]
38
2015-04-21T12:13:40.000Z
2021-11-12T19:38:00.000Z
#include <phiotimer.h> void phastaio_time(phastaioTime*) {} size_t phastaio_time_diff(phastaioTime*, phastaioTime*) { return 1; } void phastaio_addReadBytes(size_t) {} void phastaio_addWriteBytes(size_t) {} void phastaio_addReadTime(size_t) {} void phastaio_addWriteTime(size_t) {} void phastaio_setfile(int) {} void phastaio_addOpenTime(size_t) {} void phastaio_addCloseTime(size_t) {} void phastaio_printStats() {} void phastaio_initStats() {}
29.866667
57
0.790179
polmes
71a4545a18af8f66eda7bfb88777af13752a4729
16,127
cpp
C++
tests/tst_seasidefilteredmodel/seasidecache.cpp
LaakkonenJussi/nemo-qml-plugin-contacts
e94e468786000d4c4d403fea1bec8e49e37a471e
[ "BSD-3-Clause" ]
null
null
null
tests/tst_seasidefilteredmodel/seasidecache.cpp
LaakkonenJussi/nemo-qml-plugin-contacts
e94e468786000d4c4d403fea1bec8e49e37a471e
[ "BSD-3-Clause" ]
3
2021-09-29T07:13:48.000Z
2022-03-31T11:03:07.000Z
tests/tst_seasidefilteredmodel/seasidecache.cpp
LaakkonenJussi/nemo-qml-plugin-contacts
e94e468786000d4c4d403fea1bec8e49e37a471e
[ "BSD-3-Clause" ]
1
2022-03-25T15:33:41.000Z
2022-03-25T15:33:41.000Z
/* * Copyright (C) 2013 Jolla Mobile <[email protected]> * * You may use this file under the terms of the BSD license as follows: * * "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 Nemo Mobile nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." */ #include "seasidecache.h" #include <qcontactstatusflags_impl.h> #include <QContactName> #include <QContactAvatar> #include <QContactEmailAddress> #include <QContactPhoneNumber> #include <QtDebug> struct Contact { const char *firstName; const char *middleName; const char *lastName; const bool isFavorite; const bool isOnline; const char *email; const char *phoneNumber; const char *avatar; }; static const Contact contactsData[] = { /*1*/ { "Aaron", u8"Elvis", "Aaronson", false, false, "[email protected]", "1234567", 0 }, /*2*/ { "Aaron", u8"elvis", "Arthur", false, true, "[email protected]", 0, 0 }, /*3*/ { "Aaron", u8"\u00CBlvis", "Johns", true, false, "[email protected]", 0, 0 }, // 'Ëlvis' /*4*/ { "Arthur", u8"Elvi\u00DF", "Johns", false, true, "[email protected]", "2345678", 0 }, // 'Elviß' /*5*/ { "Jason", u8"\u00C6lvis", "Aaronson", false, false, "[email protected]", "3456789", 0 }, // 'Ælvis' /*6*/ { "Joe", u8"\u00D8lvis", "Johns", true, true, "[email protected]", 0, "file:///cache/joe.jpg" }, // 'Ølvis' /*7*/ { "Robin", u8"\u00D8lvi\u00DF", "Burchell", true, false, 0, "9876543", 0 } // 'Ølviß' }; static QStringList getAllContactDisplayLabelGroups() { QStringList groups; for (char c = 'A'; c <= 'Z'; ++c) { groups.append(QString(QChar::fromLatin1(c))); } groups.append(QString::fromLatin1("#")); return groups; } static QString determineDisplayLabelGroup(const SeasideCache::CacheItem *cacheItem, const QString &preferredProperty) { if (!cacheItem) return QString(); const QContactName nameDetail = cacheItem->contact.detail<QContactName>(); QString group = cacheItem->contact.detail<QContactDisplayLabel>().value(QContactDisplayLabel__FieldLabelGroup).toString(); const QString sort(preferredProperty == QString::fromLatin1("firstName") ? nameDetail.firstName() : nameDetail.lastName()); if (group.isEmpty() && !sort.isEmpty()) { group = QString(sort[0].toUpper()); } else if (group.isEmpty() && !cacheItem->displayLabel.isEmpty()) { group = QString(cacheItem->displayLabel[0].toUpper()); } if (group.isNull() || !SeasideCache::allContactDisplayLabelGroups.contains(group)) { group = QString::fromLatin1("#"); // 'other' group } return group; } QStringList SeasideCache::allContactDisplayLabelGroups = getAllContactDisplayLabelGroups(); SeasideCache *SeasideCache::instancePtr = 0; SeasideCache *SeasideCache::instance() { return instancePtr; } QContactManager *SeasideCache::manager() { static QContactManager *mgr = new QContactManager; return mgr; } QContactId SeasideCache::apiId(const QContact &contact) { return contact.id(); } QContactId SeasideCache::apiId(quint32 iid) { return QtContactsSqliteExtensions::apiContactId(iid, manager()->managerUri()); } bool SeasideCache::validId(const QContactId &id) { return !id.isNull(); } quint32 SeasideCache::internalId(const QContact &contact) { return internalId(contact.id()); } quint32 SeasideCache::internalId(const QContactId &id) { return QtContactsSqliteExtensions::internalContactId(id); } SeasideCache::SeasideCache() { instancePtr = this; for (int i = 0; i < FilterTypesCount; ++i) { m_models[i] = 0; m_populated[i] = false; } } void SeasideCache::reset() { for (int i = 0; i < FilterTypesCount; ++i) { m_contacts[i].clear(); m_populated[i] = false; m_models[i] = 0; } m_cache.clear(); m_cacheIndices.clear(); for (uint i = 0; i < sizeof(contactsData) / sizeof(Contact); ++i) { QContact contact; // This is specific to the qtcontacts-sqlite backend: contact.setId(apiId(i + 1)); QContactName name; name.setFirstName(QString::fromLatin1(contactsData[i].firstName)); name.setMiddleName(QString::fromUtf8(contactsData[i].middleName)); name.setLastName(QString::fromLatin1(contactsData[i].lastName)); contact.saveDetail(&name); if (contactsData[i].avatar) { QContactAvatar avatar; avatar.setImageUrl(QUrl(QLatin1String(contactsData[i].avatar))); contact.saveDetail(&avatar); } QContactStatusFlags statusFlags; if (contactsData[i].email) { QContactEmailAddress email; email.setEmailAddress(QLatin1String(contactsData[i].email)); contact.saveDetail(&email); statusFlags.setFlag(QContactStatusFlags::HasEmailAddress, true); } if (contactsData[i].phoneNumber) { QContactPhoneNumber phoneNumber; phoneNumber.setNumber(QLatin1String(contactsData[i].phoneNumber)); contact.saveDetail(&phoneNumber); statusFlags.setFlag(QContactStatusFlags::HasPhoneNumber, true); } contact.saveDetail(&statusFlags); m_cacheIndices.insert(internalId(contact), m_cache.count()); m_cache.append(CacheItem(contact)); QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName(); CacheItem &cacheItem = m_cache.last(); cacheItem.displayLabelGroup = determineDisplayLabelGroup(&cacheItem, sortProperty()); cacheItem.displayLabel = fullName; } insert(FilterAll, 0, getContactsForFilterType(FilterAll)); insert(FilterFavorites, 0, getContactsForFilterType(FilterFavorites)); } QList<quint32> SeasideCache::getContactsForFilterType(FilterType filterType) { QList<quint32> ids; for (uint i = 0; i < sizeof(contactsData) / sizeof(Contact); ++i) { if ((filterType == FilterAll) || (filterType == FilterFavorites && contactsData[i].isFavorite)) { ids.append(internalId(instancePtr->m_cache[i].contact.id())); } } return ids; } SeasideCache::~SeasideCache() { instancePtr = 0; } void SeasideCache::registerModel(ListModel *model, FilterType type, FetchDataType, FetchDataType) { for (int i = 0; i < FilterTypesCount; ++i) instancePtr->m_models[i] = 0; instancePtr->m_models[type] = model; } void SeasideCache::unregisterModel(ListModel *) { for (int i = 0; i < FilterTypesCount; ++i) instancePtr->m_models[i] = 0; } void SeasideCache::registerUser(QObject *) { } void SeasideCache::unregisterUser(QObject *) { } void SeasideCache::registerChangeListener(ChangeListener *) { } void SeasideCache::unregisterChangeListener(ChangeListener *) { } void SeasideCache::unregisterResolveListener(ResolveListener *) { } int SeasideCache::contactId(const QContact &contact) { quint32 internal = internalId(contact); return static_cast<int>(internal); } SeasideCache::CacheItem *SeasideCache::existingItem(const QContactId &id) { quint32 iid(internalId(id)); if (instancePtr->m_cacheIndices.contains(iid)) { return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]]; } return 0; } SeasideCache::CacheItem *SeasideCache::existingItem(quint32 iid) { if (instancePtr->m_cacheIndices.contains(iid)) { return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]]; } return 0; } SeasideCache::CacheItem *SeasideCache::itemById(const QContactId &id, bool) { quint32 iid(internalId(id)); if (instancePtr->m_cacheIndices.contains(iid)) { return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]]; } return 0; } SeasideCache::CacheItem *SeasideCache::itemById(int id, bool) { if (id == 0) return 0; // Construct a valid id from this value QContactId contactId = apiId(id); if (contactId.isNull()) { qWarning() << "Unable to formulate valid ID from:" << id; return 0; } return itemById(contactId); } QContact SeasideCache::contactById(const QContactId &id) { quint32 iid(internalId(id)); return instancePtr->m_cache[instancePtr->m_cacheIndices[iid]].contact; } QString SeasideCache::displayLabelGroup(const CacheItem *cacheItem) { if (!cacheItem) return QString(); return cacheItem->displayLabelGroup; } QStringList SeasideCache::allDisplayLabelGroups() { return allContactDisplayLabelGroups; } void SeasideCache::ensureCompletion(CacheItem *) { } void SeasideCache::refreshContact(CacheItem *) { } SeasideCache::CacheItem *SeasideCache::itemByPhoneNumber(const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::itemByEmailAddress(const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::itemByOnlineAccount(const QString &, const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::resolvePhoneNumber(ResolveListener *, const QString &, bool) { // TODO: implement and test these functions return 0; } SeasideCache::CacheItem *SeasideCache::resolveEmailAddress(ResolveListener *, const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::resolveOnlineAccount(ResolveListener *, const QString &, const QString &, bool) { return 0; } QContactId SeasideCache::selfContactId() { return QContactId(); } bool SeasideCache::saveContact(const QContact &) { return false; } bool SeasideCache::saveContacts(const QList<QContact> &) { return false; } void SeasideCache::removeContact(const QContact &) { } void SeasideCache::removeContacts(const QList<QContact> &) { } void SeasideCache::aggregateContacts(const QContact &, const QContact &) { } void SeasideCache::disaggregateContacts(const QContact &, const QContact &) { } void SeasideCache::fetchConstituents(const QContact &contact) { if (SeasideCache::CacheItem *item = itemById(SeasideCache::apiId(contact))) { if (item->itemData) { item->itemData->constituentsFetched(QList<int>()); } } } void SeasideCache::fetchMergeCandidates(const QContact &contact) { if (SeasideCache::CacheItem *item = itemById(SeasideCache::apiId(contact))) { if (item->itemData) { item->itemData->mergeCandidatesFetched(QList<int>()); } } } const QList<quint32> *SeasideCache::contacts(FilterType filterType) { return &instancePtr->m_contacts[filterType]; } bool SeasideCache::isPopulated(FilterType filterType) { return instancePtr->m_populated[filterType]; } QString SeasideCache::getPrimaryName(const QContact &) { return QString(); } QString SeasideCache::getSecondaryName(const QContact &) { return QString(); } QString SeasideCache::primaryName(const QString &, const QString &) { return QString(); } QString SeasideCache::secondaryName(const QString &, const QString &) { return QString(); } QString SeasideCache::placeholderDisplayLabel() { return QString(); } void SeasideCache::decomposeDisplayLabel(const QString &, QContactName *) { } QString SeasideCache::generateDisplayLabel(const QContact &, DisplayLabelOrder) { return QString(); } QString SeasideCache::generateDisplayLabelFromNonNameDetails(const QContact &) { return QString(); } QUrl SeasideCache::filteredAvatarUrl(const QContact &contact, const QStringList &) { foreach (const QContactAvatar &av, contact.details<QContactAvatar>()) { return av.imageUrl(); } return QUrl(); } bool SeasideCache::removeLocalAvatarFile(const QContact &, const QContactAvatar &) { return false; } QString SeasideCache::normalizePhoneNumber(const QString &input, bool) { return input; } QString SeasideCache::minimizePhoneNumber(const QString &input, bool) { return input; } QContactCollectionId SeasideCache::aggregateCollectionId() { return QContactCollectionId(); } QContactCollectionId SeasideCache::localCollectionId() { return QContactCollectionId(); } SeasideCache::DisplayLabelOrder SeasideCache::displayLabelOrder() { return FirstNameFirst; } QString SeasideCache::sortProperty() { return QString::fromLatin1("firstName"); } QString SeasideCache::groupProperty() { return QString::fromLatin1("firstName"); } void SeasideCache::populate(FilterType filterType) { m_populated[filterType] = true; if (m_models[filterType]) m_models[filterType]->makePopulated(); } void SeasideCache::insert(FilterType filterType, int index, const QList<quint32> &ids) { if (m_models[filterType]) m_models[filterType]->sourceAboutToInsertItems(index, index + ids.count() - 1); for (int i = 0; i < ids.count(); ++i) m_contacts[filterType].insert(index + i, ids.at(i)); if (m_models[filterType]) { m_models[filterType]->sourceItemsInserted(index, index + ids.count() - 1); m_models[filterType]->sourceItemsChanged(); } } void SeasideCache::remove(FilterType filterType, int index, int count) { if (m_models[filterType]) m_models[filterType]->sourceAboutToRemoveItems(index, index + count - 1); QList<quint32>::iterator it = m_contacts[filterType].begin() + index; m_contacts[filterType].erase(it, it + count); if (m_models[filterType]) { m_models[filterType]->sourceItemsRemoved(); m_models[filterType]->sourceItemsChanged(); } } int SeasideCache::importContacts(const QString &) { return 0; } QString SeasideCache::exportContacts() { return QString(); } void SeasideCache::setFirstName(FilterType filterType, int index, const QString &firstName) { CacheItem &cacheItem = m_cache[m_cacheIndices[m_contacts[filterType].at(index)]]; QContactName name = cacheItem.contact.detail<QContactName>(); name.setFirstName(firstName); cacheItem.contact.saveDetail(&name); QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName(); cacheItem.displayLabelGroup = determineDisplayLabelGroup(&cacheItem, sortProperty()); cacheItem.displayLabel = fullName; ItemListener *listener(cacheItem.listeners); while (listener) { listener->itemUpdated(&cacheItem); listener = listener->next; } if (m_models[filterType]) m_models[filterType]->sourceDataChanged(index, index); } quint32 SeasideCache::idAt(int index) const { return internalId(m_cache[index].contact.id()); }
27.805172
151
0.688163
LaakkonenJussi
71a5684041c3b8c47eb09591a384c59fd46ce891
3,297
cpp
C++
Src/Legacy/Math/matrix4.cpp
visualizersdotnl/tpb-06-final
7bd0b0e3fb954381466b2eb89d5edebef9f39ea7
[ "MIT" ]
4
2015-12-15T23:04:27.000Z
2018-01-17T23:09:10.000Z
Src/Legacy/Math/matrix4.cpp
visualizersdotnl/tpb-06-final
7bd0b0e3fb954381466b2eb89d5edebef9f39ea7
[ "MIT" ]
null
null
null
Src/Legacy/Math/matrix4.cpp
visualizersdotnl/tpb-06-final
7bd0b0e3fb954381466b2eb89d5edebef9f39ea7
[ "MIT" ]
null
null
null
#include <Shared/assert.h> #include "matrix4.h" #include "vector4.h" #include "misc.h" Matrix4 Matrix4::IDENTITY; void Matrix4::Init() { IDENTITY.SetIdentity(); } void Matrix4::SetIdentity() { _11 = 1.0f; _12 = 0.0f; _13 = 0.0f; _14 = 0.0f; _21 = 0.0f; _22 = 1.0f; _23 = 0.0f; _24 = 0.0f; _31 = 0.0f; _32 = 0.0f; _33 = 1.0f; _34 = 0.0f; _41 = 0.0f; _42 = 0.0f; _43 = 0.0f; _44 = 1.0f; } // Inspired by Wine's implementation of D3DXMatrixInverse // http://source.winehq.org/source/dlls/d3dx9_36/math.c#L227 Matrix4 Matrix4::Inversed() const { Matrix4 result; Vector4 vec[3]; float det = Determinant(); ASSERT( !FloatsEqual(det, 0.0f, 0.0000001f) ); static const float factor[4] = { 1, -1, 1, -1 }; for (int i=0; i<4; i++) { for (int j=0; j<4; j++) { if (j != i) { int a = j; if (j > i) a -= 1; vec[a].x = m[j][0]; vec[a].y = m[j][1]; vec[a].z = m[j][2]; vec[a].w = m[j][3]; } } Vector4 v = vec[0].Cross(vec[1], vec[2]); result.m[0][i] = factor[i] * v.x / det; result.m[1][i] = factor[i] * v.y / det; result.m[2][i] = factor[i] * v.z / det; result.m[3][i] = factor[i] * v.w / det; } return result; } // Inspired by Wine's implementation of D3DXMatrixDeterminant // http://source.winehq.org/source/dlls/d3dx9_36/math.c#L214 float Matrix4::Determinant() const { Vector4 v1, v2, v3; v1.x = m[0][0]; v1.y = m[1][0]; v1.z = m[2][0]; v1.w = m[3][0]; v2.x = m[0][1]; v2.y = m[1][1]; v2.z = m[2][1]; v2.w = m[3][1]; v3.x = m[0][2]; v3.y = m[1][2]; v3.z = m[2][2]; v3.w = m[3][2]; Vector4 minor = v1.Cross(v2, v3); return - (m[0][3] * minor.x + m[1][3] * minor.y + m[2][3] * minor.z + m[3][3] * minor.w); } //// Polar decomposition, based on: //// http://callumhay.blogspot.nl/2010/10/decomposing-affine-transforms.html //void Matrix4::PolarDecompose(Vector3* outTranslation, Matrix4* outRotation, Vector3* outScale) //{ // *outTranslation = Vector3(m[3][0], m[3][1], m[3][2]); // // Matrix4 m = *this; // m.m[3][0] = 0; // m.m[3][1] = 0; // m.m[3][2] = 0; // // // Extract the rotation component - this is done using polar decompostion, where // // we successively average the matrix with its inverse transpose until there is // // no/a very small difference between successive averages // float norm; // int count = 0; // Matrix4 rotation = m; // // do // { // Matrix4 nextRotation; // Matrix4 currInvTranspose = rotation.Transposed().Inversed(); // // // Go through every component in the matrices and find the next matrix // for (int i = 0; i < 4; i++) // for (int j = 0; j < 4; j++) // nextRotation.m[i][j] = 0.5f * (rotation.m[i][j] + currInvTranspose.m[i][j]); // // norm = 0.0f; // for (int i = 0; i < 3; i++) // { // float n = // fabs(rotation.m[i][0] - nextRotation.m[i][0]) + // fabs(rotation.m[i][1] - nextRotation.m[i][1]) + // fabs(rotation.m[i][2] - nextRotation.m[i][2]); // norm = max(norm, n); // } // rotation = nextRotation; // } // while (count++ < 100 && norm > 0.000001f); // // *outRotation = rotation; // // // The scale is simply the removal of the rotation from the non-translated matrix // Matrix4 scaleMatrix = rotation.Inversed() * m; // // *outScale = Vector3(scaleMatrix.m[0][0], scaleMatrix.m[1][1], scaleMatrix.m[2][2]); //}
22.737931
96
0.575978
visualizersdotnl
71a929242d9c405f7e8288708bff8c01d1359c35
1,863
hpp
C++
FinalExam/PNGio.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
FinalExam/PNGio.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
FinalExam/PNGio.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
#pragma once #include <png.h> #include <cstdint> #include <list> #include <array> using std::list; using std::array; // struct for PNG image struct inputImage { int width, height; // width & height of the image png_byte depth; // color depth of the image png_byte color_type; // type of the color data (e.g. PNG_COLOR_TYPE_GRAY, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB_ALPHA ...) png_uint_32 stride; // bytes per row png_bytep *row_pointers; }; // struct for output gray-scale images struct outputImage { png_uint_32 width, height; png_byte *pixels; // width * height }; // struct for storing circles identified by HCT struct circles { list<array<uint32_t, 4>> data; // a list of arrays of size 4, each array contains center-x, center-y, radius, and # of votes }; // This function reads a PNG image file specified by the filename and stores the image data into data int pngRead(const char *filename, inputImage &data); // This function de-allocates memory allocated by pngRead or inputImage struct void pngFree(inputImage &data); // This function saves gray-scale image data into PNG file specified by the filename. int pngWrite(const char *filename, outputImage& data); // This function de-allocates memory for output image struct void pngFree(outputImage &data); // This function allocates memory for grya-scale images stored in outputImage struct with specified width and height. This function also blanks the canvas, i.e. fills the canvas with black color. void blank(outputImage &canvas, png_uint_32 width, png_uint_32 height); // This function draws circles based on the data recorded in the circleData struct void drawCircles(outputImage& canvas, circles& circleData, const png_byte v=0xff);
38.8125
197
0.721417
MetalheadKen
71a9fd975cf1f7c322f09d4adc40cf2502d74143
687
cpp
C++
03-Arrays/subarraysum2.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
03-Arrays/subarraysum2.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
03-Arrays/subarraysum2.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
#include<iostream> using namespace std; int main() { int n;cin>>n; int a[1000]; int currentsum=0; int maxsum=0; int left=-1; int right=-1; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { currentsum=0; for(int k=i;k<=j;k++) { currentsum+= a[k]; } if(currentsum>maxsum){ maxsum= currentsum; left=i; right=j; } } cout<<endl; } cout<<"Maximum Sum is "<<maxsum<<endl; for(int k=left;k<=right;k++) { cout<<a[k]<<","; } return 0; }
17.615385
38
0.404658
ShreyashRoyzada
71add08d7d3fac9fb11e2cd01e74016a21164d1a
1,019
cpp
C++
PAT/A1155.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/A1155.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/A1155.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
#include<cstdio> #include<algorithm> #include<functional> using namespace std; const int MAXN=1e3; int N,heap[MAXN],path[MAXN],cnt; void dfs(int o) { path[cnt++]=heap[o]; int lc=o*2+1,rc=o*2+2; if(lc>=N && rc>=N) for(int i=0; i<cnt; i++) printf("%d%c",path[i],i==cnt-1?'\n':' '); else { if(rc<N) dfs(rc); if(lc<N) dfs(lc); } cnt--; } int main(void) { // freopen("in.txt","r",stdin); while(~scanf("%d",&N)) { for(int i=0; i<N; i++) scanf("%d",&heap[i]); cnt=0; dfs(0); if(is_heap(heap,heap+N,less<int>())) puts("Max Heap"); else if(is_heap(heap,heap+N,greater<int>())) puts("Min Heap"); else puts("Not Heap"); } return 0; } /* 8 98 72 86 60 65 12 23 50 8 8 38 25 58 52 82 70 60 8 10 28 15 12 34 9 8 56 98 86 23 98 86 12 98 72 65 98 72 60 50 Max Heap 8 25 70 8 25 82 8 38 52 8 38 58 60 Min Heap 10 15 8 10 15 9 10 28 34 10 28 12 56 Not Heap */
16.983333
75
0.50736
iphelf
71af7319bc7f7b6ab90ddfa8471be6bdba17c46a
1,248
cpp
C++
genomes/scripts/bounds.cpp
whelena/ginkgo
892b2e9f851f71a491cade6297f74f09f17acf4c
[ "BSD-2-Clause" ]
40
2015-06-15T14:17:15.000Z
2022-02-24T10:53:41.000Z
genomes/scripts/bounds.cpp
whelena/ginkgo
892b2e9f851f71a491cade6297f74f09f17acf4c
[ "BSD-2-Clause" ]
36
2016-04-10T07:35:39.000Z
2022-02-23T17:09:43.000Z
genomes/scripts/bounds.cpp
whelena/ginkgo
892b2e9f851f71a491cade6297f74f09f17acf4c
[ "BSD-2-Clause" ]
28
2015-07-02T21:14:38.000Z
2022-03-09T12:35:26.000Z
#include <iostream> #include <fstream> #include <string> #include <string.h> #include <stdlib.h> #include <vector> using namespace std; int main(int argc, char *argv[]){ ifstream bin_file(argv[1], ios::out); ofstream outfile(argv[2], ios::out); if(argc < 3) { cout << "Provide input and output files" << endl; return 1; } if(!bin_file.good()) { cout << "Unable to open input file: " << argv[1] << endl; return 1; } cout << "[Creating: " << argv[2] << "]" << endl; vector<pair<string, int> > bounds; pair<string, int> p; bool flag = true; string prev_chr; string new_chr; string dump; string chr; int cnt = 0; int loc; bin_file >> dump >> dump; //Ignore bin_file header while (!bin_file.eof()) { cnt++; bin_file >> new_chr >> loc; if (new_chr != prev_chr && flag == false) { p.first = prev_chr; p.second = cnt; bounds.push_back(p); prev_chr = new_chr; } if (new_chr != prev_chr && flag == true) { flag=false; prev_chr=new_chr; } } vector<pair<string, int> >::iterator it; for (it = bounds.begin(); it != bounds.end(); ++it) outfile << it->first << "\t" << it->second << endl; return 0; }
18.086957
61
0.564103
whelena
71afbf4202919189fedbc136b0c88992de25bc30
10,770
cpp
C++
csl/cslbase/tltime.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/tltime.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/tltime.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
// tltime.c Copyright A C Norman 2019 // Released under the modified BSD license - you can find the terms // of that easily enough! // $Id: tltime.cpp 5331 2020-04-25 13:47:28Z arthurcnorman $ // Cygwin and mingw32 both seem to use "emutls" to support the C++11 // keyword "thread_local". This can have performance consequences. // // The first thing is that this code illustrates is that in a worst case // scenario where a small and heavily-used function accesses a thread_local // variable the emutls scheme on x86_64 imposes a penalty that is a factor // of up to 20. The use-case I had in mind was a function like: // void *allocate(size_t n) // { void *r = (void *)fringe; // if ((fringe += n) < limit) return r; // ... // } // where making the variables fringe and limit thread_local can really hurt // overall system-wide performance. // // The resolution proposed here starts by giving up on the flexibility that // C++11 thread_local provides as regards declaring thread_local variables // anywhere and sometimes initializing them at the side of their definition. // It places all values that need to be thread_local (or at least all those // where access will be performance critical) in a structure, and using a // low level scheme to get a thread-specific pointer to that structure. // Allocating and initializing the thread-local structure is not an issue // addressed here! I use the Windows TlsAlloc, TlsSetValue and TlsGetValue // functions. I have two versions of this, one using the official Windows // entrypoints and the other re-implementing TlsGetValue (but omitting // validity checks!) such that it can be expanded in-line in my code. // // To use this one needs to collect all (or most) thread local variables // and replace them with structure members as in // typedef struct thread_locals_ // { uintptr_t fringe; // uintptr_t limit; // ... // } thread_locals; // thread_local thread_locals my_thread_locals; // Then at the startup of your code you need to allocate my_slot as shown // in the main() function here, and in EVERY thread you start you must go // TlsSetValue(my_slot, (void *)&my_thread_locals); // With that done, what used to be a simple reference to a variable, fringe // say, must be rewritten as ((thread_locals *)TlsGetValue(my_slot))->fringe. // or ((thread_locals *)tls_load())->fringe. These long and messy-looking // fragments might perhaps best be concealed via a header file containing // inline uintptr_t &TLfringe() // { return ((thread_locals *)tls_load())->fringe; // } // so that the main source code merely writes TLfringe() where it used to // write just fringe. Furthemore by wrapping the access through a function // like that it will be easy to conditionalize the code so that if C++11 // native thread_local is good enough it can be used: // inline uintptr_t &TLfringe() // { return my_thread_locals->fringe; // } // // // Timings as reported here are sensitive to minor issues such (perhaps) as // the alignment that various code fragments end up relative to where // cache lines fall. However the main message is that at least sometimes // on my Windows 10 host and Cygwin64 I see // simple non-thread-local case 1 // inline code working via GS 1.5 // use of TlsGetValue() 3 // use of C++11 thread_local 30 Cygwin, 15 Mingw // You are in fact entitles to use several different slots if your whole // project is split into several components - but you will then need to adapt // the code here so that each component uses its own "my_slot". #include <time.h> #include <iostream> #include <iomanip> #include <thread> #include <mutex> // The task I will perform will be just incrementing an integer. By // making it an integer in the middle of an array I illustrate that // I could be handling lots of thread-local data not just a single // word. This was set up as a simpler illustration that the use of // a struct as in the explanation above! thread_local int tl_vars[10]; int simple_vars[10]; #if defined __CYGWIN__ || defined __MINGW32__ #define ON_WINDOWS 1 #if __SIZEOF_POINTER__ == 4 #define ON_WINDOWS_32 1 #endif #endif // __CYGWIN__ || __MINGW32__ #ifdef ON_WINDOWS #include <intrin.h> // Provides code to read relative to FS or GS #include <windows.h> // This class exists so that its constructor and destructor can manage // allocation of a slot in the Windows vector of thread local values. class TLS_slot_container { public: int mine; TLS_slot_container() { mine = TlsAlloc(); } ~TLS_slot_container() { TlsFree(mine); } }; // On or before the first call of this the constructor for the // TLS_slot_container will be activated and that will allocate a slot. // These days I expect the C compiler to turn the implementation of this // into little more that a load from a static location in memory. It may // also have a test to see if the call is a first one so it can in that // case do the initialization. // Just one slot-number is needed for my entire program - the same value is // used by every thread. inline int get_my_TEB_slot() { static TLS_slot_container w; return w.mine; } #ifdef CAUTIOUS // The CAUTIOUS option uses the Microsoft API to access thread-local slots, // and so should be robust against potential changes in Windows. inline void *tls_load() { return reinterpret_cast<void *>(TlsGetValue(get_my_TEB_slot())); } std::uintptr_t tls_store(void *v) { return TlsSetValue(get_my_TEB_slot(), v); } #else // CAUTIOUS // The version is intended and expected to behave exactly like the version // that calls the Microsoft-provided functions, except (1) it does not // do even basic sanity checks on the slot-number saved via get_my_TAB_slot() // and (b) it can expand into inline code that then runs faster that the // official version even if it does just the same thing. #ifdef ON_WINDOWS_32 // I abstract away 32 vs 64-bit Windows issues here. The offsets used are from // www.geoffchappell.com/studies/windows/win32/ntdll/structs/teb/index.htm // which has repeated comments about the long term stability of the memory // layout involved. #define read_via_segment_register __readfsdword #define write_via_segment_register __writefsdword #define basic_TLS_offset 0xe10 #define extended_TLS_offset 0xf94 #else #define read_via_segment_register __readgsqword #define write_via_segment_register __writegsqword #define basic_TLS_offset 0x1480 #define extended_TLS_offset 0x1780 #endif // Windows 32 vs 64 bit inline void *extended_tls_load() { void **a = (void **)read_via_segment_register( extended_TLS_offset); return a[get_my_TEB_slot() - 64]; } inline void extended_tls_store(void *v) { void **a = (void **)read_via_segment_register( extended_TLS_offset); a[get_my_TEB_slot() - 64] = v; } inline void *tls_load() { if (get_my_TEB_slot() >= 64) return extended_tls_load(); else return reinterpret_cast<void *>(read_via_segment_register( basic_TLS_offset + sizeof(void *)*get_my_TEB_slot())); } inline void tls_store(void *v) { if (get_my_TEB_slot() >= 64) return extended_tls_store(v); else write_via_segment_register( basic_TLS_offset + sizeof(void *)*get_my_TEB_slot(), reinterpret_cast<std::intptr_t>(v)); } #endif // CAUTIOUS #endif // ON_WINDOWS // Now the four versions that I will compare. I force each to avoid getting // inlines because gcc is so clever that if it can inline them it does not // do anthting at all like the work I intend! Of course in a "real" use-case // the individual functions using data that might want to be thread_local // will be such that optimisation is not so easy, and inlining may be // prevented by complicated code or separate compilation. [[gnu::noinline]] void simple_inc() { simple_vars[5]++; } [[gnu::noinline]] void tl_inc() { tl_vars[5]++; } #ifdef ON_WINDOWS // These two tests are only relevant on Windows-based systems. [[gnu::noinline]] void windows_inc() { (reinterpret_cast<int *>(TlsGetValue(get_my_TEB_slot())))[5]++; } [[gnu::noinline]] void gs_inc() { (reinterpret_cast<int *>(tls_load()))[5]++; } #endif // ON_WINDOWS // This function times a function by calling it 0x40000000 times. It // sets the location to be incremented to zero first and displays the // value it has at the end as a rather crude verification that something // has happened. void timeit(const char *name, void (*fn)(), int *var) { std::cout << "Address of my workspace is " << var << std::endl; std::clock_t c0 = std::clock(); var[5] = 0; for (unsigned int i=0; i<0x40000000; i++) (*fn)(); std::clock_t c1 = std::clock(); std::cout << "incremented value = " << var[5] << " "; std::cout << std::setw(25) << name << " " << std::fixed << std::setprecision(2) << ((c1-c0)/static_cast<double>(CLOCKS_PER_SEC)) << std::flush << std::endl; } std::mutex mm; // Here I run all the three test cases that I have. I use a lock_guard so // that only one instance of this runs at any time, and in particular so // that the output that is generated ends up tidy. void runtests(const char *msg) { std::lock_guard<std::mutex> gg(mm); std::cout << "Running " << msg << std::endl; timeit("simple variable", simple_inc, simple_vars); #if defined ON_WINDOWS // Each thread must set the slot that is relative to ITS version of the GS // segment register to point at the data that it will use. TlsSetValue(get_my_TEB_slot(), reinterpret_cast<void *>()&tl_vars); #ifdef ON_WINDOWS_32 timeit("thread local via FS", gs_inc, tl_vars); #else timeit("thread local via GS", gs_inc, tl_vars); #endif TlsSetValue(get_my_TEB_slot(), reinterpret_cast<void *>()&tl_vars); timeit("Using Windows Tls API", windows_inc, tl_vars); #endif // ON_WINDOWS // The final test uses direct C++11 "thread_local" storage qualification. // It is the "obvious" way to use thread local data. timeit("C++11 thread_local", tl_inc, tl_vars); } int main(int argc, char *argv[]) { #if defined ON_WINDOWS // I deliberately allocate (and waste) over 64 slots to start with so that // the one I end up with will be an "extension slot", which will lead // to the more expensive path through my access code. for (int i=0; i<70; i++) TlsAlloc(); #endif // ON_WINDOWS // Run all tests in the main program... runtests("direct"); // ...then create a thread and run them in it. std::thread t1(runtests, "in a thread"); t1.join(); return 0; } // end of tltime.cpp
36.883562
78
0.705478
arthurcnorman
71b04db4d2e38dcdb2eacb58b34b5fefb1f20b26
1,715
cpp
C++
gen/src/model/Port.cpp
cpp-openapi/dockerctl
44da21c32509fb7e44c93551a41ceb14c42c18b1
[ "Apache-2.0" ]
null
null
null
gen/src/model/Port.cpp
cpp-openapi/dockerctl
44da21c32509fb7e44c93551a41ceb14c42c18b1
[ "Apache-2.0" ]
null
null
null
gen/src/model/Port.cpp
cpp-openapi/dockerctl
44da21c32509fb7e44c93551a41ceb14c42c18b1
[ "Apache-2.0" ]
null
null
null
/* * Port.cpp * * An open port on a container */ #include "Port.h" using namespace openapi; // macro should do the same job. Not really // OPENAP_JSON_CONVERT_FUNCS(Port, IP, PrivatePort, PublicPort, Type) void Port::ToJSON(Json & j) const { // OPENAPI_FOR_EACH(OPENAPI_TO_JSON_MEMBER, __VA_ARGS__) j.AddMember<decltype(this->ip)>(openapi::StringT(OPENAPI_LITERAL(IP)), this->ip); j.AddMember<decltype(this->private_port)>(openapi::StringT(OPENAPI_LITERAL(PrivatePort)), this->private_port); j.AddMember<decltype(this->public_port)>(openapi::StringT(OPENAPI_LITERAL(PublicPort)), this->public_port); j.AddMember<decltype(this->type)>(openapi::StringT(OPENAPI_LITERAL(Type)), this->type); } void Port::FromJSON(const Json & j) { // OPENAPI_FOR_EACH(OPENAPI_FROM_JSON_MEMBER, __VA_ARGS__) if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(IP)))) { using V = remove_optional<decltype(this->ip)>::type; this->ip = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(IP))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(PrivatePort)))) { using V = remove_optional<decltype(this->private_port)>::type; this->private_port = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(PrivatePort))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(PublicPort)))) { using V = remove_optional<decltype(this->public_port)>::type; this->public_port = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(PublicPort))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(Type)))) { using V = remove_optional<decltype(this->type)>::type; this->type = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(Type))); } }
35.729167
114
0.695627
cpp-openapi
71b0f782717d87abd9736880fcde2d5e0bfe6ab8
640
cpp
C++
src/context/StringType.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
src/context/StringType.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
src/context/StringType.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
#include "StringType.h" bool StringType::IsBooleanType() { return false; } bool StringType::IsFloatType() { return false; } bool StringType::IsIntType() { return false; } bool StringType::IsStringType() { return true; } bool StringType::IsVoidType() { return false; } bool StringType::IsClassType() { return false; } bool StringType::IsNullType() { return false; } bool StringType::IsSameType(AbstractType * other_type) { return other_type->IsStringType(); } string StringType::Symbol() { return string("string"); } string StringType::JasminSymbol() { return string("Ljava/lang/String;"); }
12.54902
54
0.682813
pougetat
71b183e0cbec056814a6fde953c91c890475351d
15,257
cpp
C++
data/112.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/112.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/112.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
int Rgpz , u7, nT//a ,M4ElL /*d*/,DhV , xKKv7, Aev7f ,puj, E,hI, TGe,oN /*G6Iat*/ , //k aA, //U6 zWZLO ,//DEw MTL ,rq , a9 //Xt ,vu5 ,eHB,v8Y , osHw/*jo*/, h ,M,IT,//fpe dq5 ,PEwG, xq, dOu , AzCI, Z3sCV , sOO , LJ , WbN5,z ,pzg8 , duU4, QztyO , oDdEz/*UQ*/, Fndz , GdVz, OkxM,r,Vzf, xi// ,DiZ ,l ,pR ,/*B3O*/ Zjo , G,TFB, /*AJ*/x4 , Qrj , byD, lkDzm , otr, // il,ILc1, E2 , zfJVQ ,/*iCb*/ TG8, rKN,Xaw ,Rh4 ;void f_f0 (){{/**/ volatile int u6Pym, t2, iS5,TPF, R ; { return ; { /*f*/for (int i=1; i<1 ;++i ){ { ; } } }for (int i=1// ;i<2 //SLpVr ;++i){ return ; } { {} {{int cvw;volatile int Fp ;cvw = Fp ;for(int /*b*/i=1;i< 3 ;++i ) { } }/*3a*/if/*faJ*/(true)return ;else { { }} }{ {{ int Ci; /*D08*/volatile int nf8m ; if ( true){ } else Ci=nf8m ; } }} //Hqm {}}} Rh4= R + u6Pym +t2+ iS5 +/**/ TPF ;for (int i=1;i<4 ;++i) { int//3 jIB7QI; volatile int nwae,x , qpA, Q6,s0 ,j ,L, RP ;Rgpz=RP /*c*/+ nwae+x ;jIB7QI= qpA +Q6+s0 +j + L ; }return ; }{ volatile int utJ, X, jgs ,gNV3 ; { int m /*h*/;volatile int gjLk,V2O//OLmIW ,KVH , //d cy0R; m =cy0R + gjLk+ V2O + KVH ; ; return ; { volatile int UEo , traz, s9; return ;for (int i=1 ; i<5/*cR*/;++i ) /*SD*/ { /*H*/if(true) {}else { return ; } }{} if ( true ) return ; else u7 = //bEy s9 + UEo +/*E2iV*/traz; } } {{ { { { }}{} } if( true ){ for(int i=1; i<6 ;++i//G //qPa )for(int i=1; i< 7;++i){} } else{/*y2*/int fG; volatile int kC , tgG,//f i1fUe ;fG =i1fUe + kC+ tgG; } }{for//G (int i=1 ;i<8 ;++i ) if (true) ;//s else ;/*zN*/} return ;{ {} { //artB7 ;{ } } }} nT = gNV3+ utJ + X +jgs ;if( true ){ volatile int kY, D//PRE ,m0v ,Fp4D, y ,v,//rI X7, CYb2J ,MSW; ;for//0pg (int i=1 ; i< 9 //t ;++i )/*P*/; if/*7AW*/ (true) M4ElL =/*G7t*/MSW+ kY + D //fpu + m0v + Fp4D; //xwmY else//SS9 if ( true) if(true){ volatile int T , dDGX , QLP , GPmY , jt ; for (int i=1 ;i<10 ;++i)//5Q DhV = jt+T /*THJt*/+ dDGX +QLP+GPmY; }else //z { ;//6Y5 }/*5Z*/ else xKKv7=/*q*/ y+v + X7+ CYb2J ;} else { volatile int GGui ,HJ0 , UE6F8 , m8 ;{int LHG72 ;volatile int u0I ,xuQ, zbs ;LHG72 //kUlC =zbs +u0I+ xuQ ;for(int i=1; i< 11;++i) if(true ) for (int i=1; i<//su7 12 ;++i )if ( true ) { { } }else{for (int i=1 ; i< 13;++i) {} for (int i=1; i< 14;++i ){}}/*g3*/else { int IZ;volatile int A ,zY ;IZ= zY + A ;} {{ return ; ;}}{ }} Aev7f= m8 +GGui +HJ0 +UE6F8 ; } return ;{//M7 int QzK ;volatile int //D XW9,YI , SBu , i ,Gmo1 , PlIr , BN1j,Yph ,vNQv2QrY ,XhSY,//HV dM ;puj = dM +XW9 +YI+ SBu ;E=/*Sr*/i//SwrMw +/*TCN*/Gmo1 +PlIr+ BN1j ;;{ return ;return ;{ {}} } QzK = Yph +//S vNQv2QrY+XhSY ; } }if (true) {{/*vBrFF*/volatile int G8,AoceGT//6r ,/*N*/Jw//v ; {int F ; volatile int TmL , I1eY,aol ,bE , SbmW,cAwA , /*kc*/wJF ,hfAr ; hI=/*H*/ hfAr + TmL +I1eY; F = aol + bE+ SbmW+ /*7udH*/cAwA +//OHM wJF ; { {} }} TGe = Jw//0Q + G8+AoceGT;for (int i=1 ; i<15;++i ) {{{ } }/*ZJW*/}} /*Fgu*/{ //wVtP /*NV*/ int mf; volatile int Ilv9yon, IoY3 ,Lgys ,J83 ,n7c ,Doz,tq3r /*j*/;return ;/*DJ5*/ if //afE ( true ) return ;else mf =tq3r // +Ilv9yon + IoY3 ; for(int i=1 ; i< 16 ;++i )/*A*/{{ {}}/*ah*/ { ; { {}if (true ) if(true){ } else { } else for (int i=1;i<17 ;++i )/*6*/{ } } }} oN= Lgys+J83 +n7c + Doz /*1*/; }for (int i=1 ;i< 18;++i) return ; {int MHo ;volatile int /*x53S*/ uU4D, IEXNzF , //s caEv ,iOd , UIU ;{return ;/*0*/{ volatile int w8,bi/*vC6b*/;{} aA = //SYjo bi/*w7O*/ + w8; for/*P*/(int i=1/*e*/; i<19 ;++i ) for/*JL*/ (int i=1 ; //H7 i<20;++i//mxs ) return ; }} for (int i=1 ;/*2Tb*/i< 21;++i) MHo =UIU +/*7*/uU4D + IEXNzF //t5 + caEv + iOd ; //PScR } } else//4MB0 return ;;{ volatile int We1m , uuLv6 , h6y3,g ; zWZLO = g + We1m + uuLv6 +h6y3; {{for (int i=1;i<22;++i ) return ; { for /*Smh*/(int i=1 ; i< 23 ;++i )//vdJr if(true ) { }else for (int //Zd8v i=1//4R ;i<24//cZ //PDd ;++i){ }return ; }}//LX8Z { {/*Snw*/ {for(int i=1; i<25;++i ) { } } return ;} { if ( true ){ } else { } } } for (int i=1 ;i<26 ;++i ) { { }{} } ; }{{ for (int i=1 ; i< 27 ;++i ) { volatile int GY9O , px; if ( true );else for(int i=1 ; i<28 ;++i)/*Nflon*/{ }MTL = px//2V + GY9O; } { } } { { } }}{ { { for(int i=1 ;i< 29 ;++i); }//mjqo {}/**/} if (true ){{{}}} else if (true )return// ; else { ;}} }; return ; }void f_f1 () { { volatile int deI//TF1 , Hj ,fE7d , BH,tD ; rq=tD +// deI+ Hj +fE7d +BH ;{ {volatile int kktuj ,Ymz, wIYV ; {{ } }a9 = wIYV + kktuj+Ymz ; } { volatile int /*7E*/ Co ,aj, wsy ; vu5=wsy + Co + aj ; { if/*Z*/( true) { } else ; }}} { if ( //y true)if(true) {{}{ { }}{ volatile int o9A,CI;eHB= CI + o9A ; { }{ } }//inRj }else{ { /*BE0*/for (int i=1;i<30 ;++i/*i1*/){}; } }else { {} }{ volatile int FO9X,kAo1 ,SCn ,F25;{ {} }v8Y=F25 + //ISw FO9X + kAo1 +SCn; { return ; } } if(true );/**/else ;//dZ }{volatile int Y4 ,Nu ,gh2,Jom8E ; { volatile int //f pKhF , CL ,/*Rt*/ FD ; ;if ( true ) osHw = FD +//E pKhF + CL; else { { { } }{ }} if ( true )return ;else ;} if ( true ) //i8 for (int i=1 ; i< 31 ;++i) if( true ) h//FXtgrfC = Jom8E//s44 +Y4+ Nu+ gh2;else ;else //Rbf for (int i=1// ; i< 32;++i ) if ( true){ return ; {volatile int MaB ;M= MaB ;// }} else return ; { int QWMO9x ;//RS volatile int Bn ,FCU ;QWMO9x =FCU + Bn ; ; }} }{//m { if ( true )return ;else{ return ; {} ;} { {return ; } }}{volatile int JHwd//x ,c , P4 /*yu*/ , Ob3;{ {//9 }}//Dlv IT = Ob3//C6 +JHwd + c + P4; if// (true){ {} } else { {{ for//7 (int i=1 ; i< 33 ;++i ) {/*Pn*/ } for (int i=1//Tmw1 ;//Imxo i<34 ;++i )//vX if ( true) /**/{ } else{} } }//4b52 {} { } }} { {for (int i=1 /**/ ; i<35;++i ) {int m4;volatile int//r ZG; m4 =ZG; { } } {{ //U } ;} }for//8IZ (int i=1 ; i< 36;++i) { {; } { } } }return ; if (true ) {int f ; volatile int o6Rq,Eyc , Of , BB;{{ if (true ) {} else ; if ( true ){ {}{ }for (int i=1//DX ;/*zWq*/i<37 ;++i ) { } } else { }} if (true) if (true )return ;else {}else { { }//IR20 { }} {} } for(int i=1; i< 38 ;++i) { {volatile int U; dq5 =U ;return ;}for(int //B i=1 ; i< 39 ;++i ){} /**/ } { int daB ; volatile int PG ,t2ks7 ,qRS03w ,/*eUd*/Y5W ;//wHqM daB =Y5W +PG ;PEwG= /*b*/t2ks7 +qRS03w ;{ } } return ; f = BB +o6Rq + Eyc +/*T*/Of ; { {for (int i=1 ;//lgy i<40;++i) {} }}// } else {{for (int i=1; i<41 ;++i) if ( true /*F*/ ){ { }} else{ { } { }}/*dy*/{ { for (int i=1 ;/*sh*/ i< 42;++i )if( true ) { }else{} } {} } }{ volatile int ugTP ,//t5I1 ZS4 , goAL ; // if ( true ) xq = goAL+ ugTP//7 + ZS4 ;else { { } for (int i=1 ; i<43 ;++i)if(true) /*7*/; else { }}{ {; }} { if ( true) {//H } else { }//WOA for (int i=1 ;i< 44 ;++i /**/) {}/*W*/} {{} } }} }for(int i=1 ; i<45;++i )return ;;{volatile int sSN, mL ,U5 ,OO,CtZu ,T4 , THxD//1xzGJR ;{int/*Z0*/ XI ; volatile int Em0a, //WjLD SPSIg, oB8 ,// fD5v ,/*pWd*/MpC;{{/*ja4*/volatile int KwrlH9N,cKTN ; {}for (int i=1 ;i< 46 ;++i) dOu =cKTN +KwrlH9N ;} {/*zQ*/ { }} ;//tZ } XI = MpC+ Em0a+ SPSIg + oB8+fD5v ; {for(int i=1 ; i< 47;++i ) { { } } { } }//xG6y } AzCI =THxD + sSN + mL/*Gi*/ + U5 +OO +//CWa CtZu+T4 ;for(int i=1 ;i< 48 ;++i) {{ int zlK ;volatile int yXmL , PvSjB //m330 , k7 ; if( true ) zlK= k7 +yXmL+ PvSjB ;else/*f*/ if ( true)/*o27SXKO*/{} else return ; { //9M { }} } {if ( true ) ; else {}} } }{ return ; { //I int JMlhx ; volatile int IxA ,iYB7G//Siz , VwH, al/*5J*/; { for(int i=1 ; i<49;++i) {{ { } } } return ;{} if ( true ){ } else return ; }{{/*4j*/ //QtC int gApP; volatile int NoiaA , b ; if ( true )gApP=/**/ b + NoiaA ; else if ( true ) {/**/ }else { } if( true )/*pI8B*/ { } else{ } }{ }if( true) { return ;} else return ; }if ( true ) for (int i=1 ;//Uf9 i<50// ;++i ) JMlhx=al +IxA+ iYB7G +VwH; //vqva else ; };;{ { {for (int i=1; i< 51;++i ){} // }} { volatile int KR3, fH, gMV ; if (/*Ba*/true /**/){ if(true/*5*/) return ;else{{ } } } else return/*GnU*/ ; {} Z3sCV= gMV +/**/KR3 +fH ;{ { } { } } }{ for (int i=1 ; i<52 ;++i) {{if(true//oQW ) {}else//J61b if/*k*/ ( true)return ; else ; } };} //s71 }}//BEA return ; }void f_f2() /*ZK*/ {{//v0r7 { { { {{ } } }}{volatile int w , kXeL;{ volatile int xXX,RLK;sOO =RLK + xXX;} {;{}}LJ=//R9 kXeL+ w; } return ;{volatile int wqV,rhgIY4 ; ;WbN5=rhgIY4+/*mgUi*/wqV; //Id } }{ volatile int s4x ,/**/ Gc , jTEnyP ; if( true )return ; else //X70fM {//vu2 int /*g*/ zwdA0M ;volatile int cuDd3,ZRs;zwdA0M = ZRs /*y0*/ +cuDd3 ; return ; ;} z = jTEnyP + s4x + Gc ; } { ;{ ; } {for (int i=1;/*5h5*/i</*9c*/53;++i ) /*U0U8*/{{ { } } }for(int i=1 ;i<54 ;++i ) for (int i=1 ; i< 55;++i )//0yfrp return ;} if (/*Uf7O*/ true ) for(int i=1; i<56 ;++i)/*KGy1e4*/if( true ) {/*M*/{ { }{}//t /*s*/} ; { int Fs//Qrp70 ;volatile int cQ , aQ ,pf;if ( true) Fs= //bXif pf +//2C cQ ; else {} pzg8=aQ ;{ } }} else if(true ) {volatile int IWG , IUb, u9iw ;duU4 =u9iw + IWG //Cnr + IUb; {{ }} /**/}else { volatile int trk , ik, v1T,O8oW ; QztyO= O8oW + trk + ik+ v1T ; {volatile int WDTu; //n oDdEz = WDTu ; };/*j3YK*/ /*x*/}else{ ; { return ; } }/*1*/ }{ { { } {} }if ( true) {return ;{ volatile int umyWr, kFbw; { //iL } Fndz=kFbw+ umyWr ;} { { }}} else { volatile int Ke ,Hj3, W, acA3// ;GdVz = acA3 + /**/ Ke//K2Gls +Hj3+W; return ;} if (true) {/*o8k*/{volatile int /*5*/ R6fi7; for(int i=1 ; i<57;++i )OkxM= /*Ia*/ R6fi7 ; } ;} else//2u { volatile int Q,//0sO Y , cEJ8; {}r =cEJ8+ Q +Y; { {} { }}{ {} } /*uPH*/} } } { /*D*/volatile int C ,R0m ,WMze, uqC,/**/xjD; { //Pl if ( true) ;else ; { return ; } if( true){int//rS b5Ta ;volatile int UU ,lutW ,b8FH , htjY/*Y*//*M*/;for(int i=1 ;i<58 ;++i );b5Ta =htjY+UU+ //M6z lutW/*QW*/+ b8FH;//6nYu {/*CoE*/ }{; }/**/ } else { {}} } return ;{ return ;//Y { volatile int Nxq, gb; Vzf //VR =gb + /*QkTi8*/Nxq ; { { }}} }/*Pe9Q*/{volatile int//Xa vp, V, oNt ; xi=oNt +vp + V ; {{}//RRr for (int i=1; i<59 ;++i ) /*AKY*/{ }}{/**/ {} for (int i=1 ; i<60 ;++i ){ } /*ekL*/if( true/*fLD*/) if ( true)if( true )//r { volatile int Exvso , ieUAh ,Om ;DiZ =Om+Exvso+ ieUAh ; { } } else { }//A else ; else return ;}/**/}//4uIQ88 l=xjD + C+R0m + WMze+//yw uqC; }{ { if (true ){volatile int bs,nf;pR= nf /*rV*/ + bs ; { } }else /*0f*/ for (int i=1; i<61 ;++i )/*t*/ ; {int UDsS ; volatile int r4KZ , BT ;{ if //L ( true ) { } else//k { } } UDsS = BT + r4KZ ;{ } { { } }}/*p5*/return ; } {for(int i=1;i<62 ;++i ) if( true){{ } if (true){ { volatile int/*a*/ FgJmJV6 ; Zjo = FgJmJV6; } } else{ { }{ }} //ISG } else{return ;return ; { return ; }for (int i=1; i< 63 ;++i )return ;} { volatile int U90, kENn,bCW ;{ return ; for (int i=1 //tXk ; i< 64 ;++i ) for (int i=1 ; i<//WO 65 ;++i)if //A (true) { }else { }return /*Gx*/ ;} if ( true ) if (true ) for(int i=1; i<66;++i ) ; else{ }else{ } G =bCW+//ql U90+ kENn ; }{ for(int i=1; i<67;++i ) { volatile int q,yfMrQP ,//wm R0; TFB=R0 +q+yfMrQP;/*YXe*/}} ;} {//uz ;return ; {volatile int ekj5, KJLT , amsJ, //y CGW; x4= //RfQ CGW+ekj5 +KJLT + amsJ; {} }{int a2M ; volatile int X8b ,WfE, yR3k9 ; if ( true )// a2M=yR3k9 + X8b+ WfE; else ; {volatile int Q0poj , nA ; Qrj=//R nA+ Q0poj ;return ; } } }} {{ {; for (int i=1/*mig*/ ; i< 68 ;++i) ;}{for(int i=1 ; i<69 ;++i) ;} }return ; if (true){{ {{ }}/**/return /*YUK0*/ ; for (int i=1 ; i< 70;++i ) {//ggR12 /*ln*/}} if( true ) for (int /*F*/ i=1; i<71 ;++i )//n {return ;/*Z2yB*/ {return ; }{ ;} }//qzbMZ else//Tk {{ } {}} if (true ) ; else if ( true ) if (true ) { { {}for(int i=1 ; i< 72 ;++i ) //sw { {} } }return/*r6*/ ; }else {{}}else return ;{ {{{}} } for(int i=1;i<73;++i ) { } ;/**/ } { if ( true ) { if(true) for(int i=1//fP ; i</*s6*/74 ;++i){ } else{}/*eO3n*/{ } /*Bzh*/}else {volatile int ow; byD = ow;}} }else {{int/*2*/ S ; volatile int i0j , dKQ;S/*G*/=dKQ+ i0j ; {volatile int w1 ;/*HH6*/lkDzm = w1;} } ;/*pjRi*/if(true) /*i2*/ { volatile int obB ,Ve9 , je ; otr = je+ obB+Ve9 ;} else ;} } /*Zhn*/return ; } int main () { {/*prxM8*/int N ;volatile int f2zl, mOuB, j2UT , H2Ub, Z3Z6 ; {// volatile int f3WeH ,FcFh , oNEo,IMrF ; /*HU*/{ for(int /*K*/i=1 ;i<75 ;++i) ; } {for (int // i=1; i< /*T*/76 ;++i ) if//c (true ) return 17147934 ; else ; { { } { } }return 2010087196;{} }il =IMrF//bEP +f3WeH +FcFh+ oNEo;}return 1451764732; ;N = Z3Z6 +/*hpEW*/f2zl+ mOuB+j2UT + H2Ub; } { { { int Cmhq ; volatile int//N /*sj*//**/ jpXy9 ,o0, K8HP5,kD,/*MQ*/ZYAb /*k*/,iL3;for(int i=1; //Bij i< 77/*y78*/;++i ) if (true) for (int i=1; i<78//V7 ;++i) { } else Cmhq = iL3 +jpXy9//r52 +o0;/*66Vm*/ILc1 =K8HP5 + /*68ZL*/kD +ZYAb ; } ;; for(int i=1 ; i</*KH*/79 ;++i ) {/**/ /*Ne*/ { } }} ; ;} { { int v9VRI ,//fKo lIC;volatile int IbQi //7s , Jl,kal , Q34 , P9Jx,qx , bZJEP ,qoi, T8M0S,/*uBG*/RCr,BmLC , XeAf ;{ {;/*1*//*V5G*/ {} } }lIC =XeAf+IbQi +Jl+kal; E2=Q34 + P9Jx +qx +bZJEP ;{ if (true ) for (int i=1; i< 80 ;++i// ) { { } ;}else for (int i=1 ;//TJ i< 81//lwJ ;++i) ;{ if ( true) ; else { } }/*B*/ }v9VRI = qoi +T8M0S + RCr + BmLC; }{return 274366465 ; {{ { } return 1919818101 ; {{ }} }} } {for(int i=1 /**/; i<82 ;++i ){ return 1891735511 ;{ { }} }//Abd return 424810962 ; {{for(int i=1// //gRK ; i<83;++i // ){} }if ( true)return 1547636099 ;else return 1011285425; };}{ /*A*/return 1978825989; // return 826721;} //usS } { volatile int /*9yF*/ PJk3//hOr ,Vy, JatV , XSB , ySQa ; //89 zfJVQ= ySQa+ PJk3 + Vy /**/+ JatV+XSB//s ; if ( true) //wn for (int i=1;i< 84;++i );else{{{ int FUxE; volatile int//eBQ pA //W , U6ds; FUxE= U6ds + pA; } } { if// (true ){ ; {} {} } else for (int i=1//R ;i<85;++i ) { {}}{ }{ { }return 697538712 ;}; }} if (true //rw )//1aJ return 420913475;else { int ovB ;volatile int UbQ ,/*o5Pl*/IEdf , eBe, Bs,Iob ,/*6f*/ Ql//R ;/*dlYCo*/ovB =Ql+UbQ//m + IEdf/*Or*/;TG8 =eBe/*jXbOuy*/+ Bs + Iob; return 1980489708 ;/*5p2*/;} { /*5*/; if ( true){ {{int v5Te ; volatile int KVO ,//jT9pk iE ;v5Te= iE+KVO ; } }for (int i=1 ; i<86 ;++i ) if(//BeR true ){volatile int X9ats , GP//ZZ ;{{ /*5*/}}rKN = GP+ X9ats ;return 994250986 ;} else{ { {}/*xCm*/ } } } else return 2061753923; for (int i=1 ; i< 87 ;++i){ volatile int BS1L , KvF9c, NQ ;for(int i=1 ; i< 88 ;++i )/*5*/return 535255701 ; Xaw = NQ + BS1L + KvF9c/*9Z0uf*/ ;}} } //sx ;//Piej ;}/*TDF9*/
10.400136
81
0.457364
TianyiChen
71b186d6347bb2f3f565617bd1181323eddfeef8
703
cpp
C++
kattis/problems/pet.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
kattis/problems/pet.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
kattis/problems/pet.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int winner_number {0}; unsigned int winner_points {0}; for (unsigned int i {0}; i < 5; ++i) { unsigned int points {0}; for (unsigned int j {0}; j < 4; ++j) { unsigned int grade; cin >> grade; points += grade; } if (winner_points < points) { winner_number = i + 1; winner_points = points; } } cout << winner_number << ' ' << winner_points << '\n'; return 0; }
16.738095
58
0.517781
Rkhoiwal
71b6ff277b32eb4d95b5d037136b872971c94da6
270
cpp
C++
2. Search & Sort/07. Alternative Sorting (Easy).cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
2. Search & Sort/07. Alternative Sorting (Easy).cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
2. Search & Sort/07. Alternative Sorting (Easy).cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
//https://practice.geeksforgeeks.org/problems/alternative-sorting1311/1/# vector<int> alternateSort(int arr[], int n) { sort(arr,arr+n);int p=0; vector<int>v(n); for(int i=0;i<=n/2;i++) { v[p++]=arr[n-i-1]; p+1<n?v[p++]=arr[i]:0; } return v; }
18
74
0.577778
thekalyan001
71c1dc3f28f132d37fe2134d13e3edb3bcc2207c
340
cpp
C++
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Qinxin-Yan/USTC_CG-1
80dc240bea879f000196986b98efcd0bbf8dec34
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Qinxin-Yan/USTC_CG-1
80dc240bea879f000196986b98efcd0bbf8dec34
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Qinxin-Yan/USTC_CG-1
80dc240bea879f000196986b98efcd0bbf8dec34
[ "MIT" ]
null
null
null
#include "Warp.h" Warp::Warp() { } Warp::~Warp() { } /*void Warp::add_static_point(QPoint P) { static_point_list.push_back(P); }*/ void Warp::add_map_point(map_pair Pair) { map_pair_list.push_back(Pair); } int Warp::map_pair_length() { return map_pair_list.size(); } map_pair Warp::get_map_pair(int i) { return map_pair_list[i]; }
11.724138
39
0.7
Qinxin-Yan
71c399be913f9582063460f586691cee134df776
830
cpp
C++
Graph(BFS, DFS)/p1890.cpp
vocovoco/Algorithm-Study
ba9d47ae5c28eb5b7810ddef371859b0b101a695
[ "MIT" ]
1
2017-12-20T12:21:01.000Z
2017-12-20T12:21:01.000Z
Graph(BFS, DFS)/p1890.cpp
vocovoco/Algorithm-Study
ba9d47ae5c28eb5b7810ddef371859b0b101a695
[ "MIT" ]
null
null
null
Graph(BFS, DFS)/p1890.cpp
vocovoco/Algorithm-Study
ba9d47ae5c28eb5b7810ddef371859b0b101a695
[ "MIT" ]
null
null
null
#if 1 #include <stdio.h> int main() { int map[101][101] = { 0, }; long long dp[101][101] = { 0, }; int width; scanf("%d", &width); for (int i = 1; i <= width; i++) { for (int j = 1; j <= width; j++) { scanf("%d", &map[i][j]); } } for (int i = (width * 2 - 1); i > 1; i--) { int a, b; if (i > width) { a = width; b = i - width; } else { b = 1; a = i - b; } while (a > 0 && b < width + 1) { if (a + map[a][b] <= width) { if (a + map[a][b] == width && b == width) { dp[a][b]++; } else { dp[a][b] += dp[a + map[a][b]][b]; } } if (b + map[a][b] <= width) { if (b + map[a][b] == width && a == width) { dp[a][b]++; } else { dp[a][b] += dp[a][b + map[a][b]]; } } a--; b++; } } printf("%lld", dp[1][1]); return 0; } #endif
16.27451
47
0.375904
vocovoco
71c67bb0c2829175fbe254522b45edc62e333f8b
1,289
cpp
C++
src/learn/test_libevent.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
src/learn/test_libevent.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
src/learn/test_libevent.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
#include "stdafx.h" #include "test_libevent.h" struct timeval lasttime; int times = 0; static void timeout_cb(evutil_socket_t fd, short e, void *arg) { struct timeval newtime, difference; struct event *timeout = (event *)arg; double elapsed; evutil_gettimeofday(&newtime, NULL); evutil_timersub(&newtime, &lasttime, &difference); elapsed = difference.tv_sec + (difference.tv_usec / 1.0e6); printf("timeout_cb called at %d: %.3f seconds elapsed.\n", (int)newtime.tv_sec, elapsed); lasttime = newtime; if (++times < 5) { struct timeval tv; evutil_timerclear(&tv); tv.tv_sec = 2; event_add(timeout, &tv); } } void test_libevent() { struct event timeout; struct timeval tv; struct event_base *base; WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); (void)WSAStartup(wVersionRequested, &wsaData); /* Initalize the event library */ base = event_base_new(); /* Initalize one event */ event_assign((event *)&timeout, base, -1, 0, timeout_cb, (void*) &timeout); evutil_timerclear(&tv); tv.tv_sec = 2; event_add((event *)&timeout, &tv); evutil_gettimeofday(&lasttime, NULL); event_base_dispatch(base); }
23.017857
79
0.645462
wohaaitinciu
71c84e229d9425e488c02b0cfba33e7b477ceb70
311
cpp
C++
P1134.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1134.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1134.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; int n, ans = 1; int num[4] = {6, 8, 4, 2}; int main() { scanf("%d",&n); for(int p = n; p > 0; p /= 5, ans = ans * num[p%4] %10) for (int i = 1; i <= p%10; i++) if(i != 5) ans = ans * i %10; printf("%d",ans); return 0; }
22.214286
59
0.421222
AndrewWayne
71d568094ded48d09db22efc6ad39d1f040c6eeb
382
cpp
C++
test/Day1.cpp
schoradt/adventofcode-c
09b9b5fc22cadc938190f5d83a895b601896d663
[ "MIT" ]
null
null
null
test/Day1.cpp
schoradt/adventofcode-c
09b9b5fc22cadc938190f5d83a895b601896d663
[ "MIT" ]
null
null
null
test/Day1.cpp
schoradt/adventofcode-c
09b9b5fc22cadc938190f5d83a895b601896d663
[ "MIT" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include "Day1.h" TEST_CASE("Testing Day 1") { Day1 day1; vector<int> input = day1.parseIntegerLines(day1.loadLinesString("199\n200\n208\n210\n200\n207\n240\n269\n260\n263")); CHECK_MESSAGE(7 == day1.process1(input), "test process 1"); CHECK_MESSAGE(5 == day1.process2(input), "test process 2"); }
25.466667
121
0.717277
schoradt
71d7b3bb107ddf1c9f98fcdb0f91391e945d30b0
8,659
cpp
C++
DlgVolumeCalc.cpp
RDamman/SpeakerWorkshop
87a38d04197a07a9a7878b3f60d5e0706782163c
[ "OML" ]
12
2019-06-07T10:06:41.000Z
2021-03-22T22:13:59.000Z
DlgVolumeCalc.cpp
RDamman/SpeakerWorkshop
87a38d04197a07a9a7878b3f60d5e0706782163c
[ "OML" ]
1
2019-05-09T07:38:12.000Z
2019-07-10T04:20:55.000Z
DlgVolumeCalc.cpp
RDamman/SpeakerWorkshop
87a38d04197a07a9a7878b3f60d5e0706782163c
[ "OML" ]
3
2020-09-08T08:27:33.000Z
2021-05-13T09:25:43.000Z
// DlgVolumeCalc.cpp : implementation file // #include "stdafx.h" #include "audtest.h" #include "DlgVolumeCalc.h" #include "Utils.h" #include "Math.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- typedef struct tagCALCVOLUME { float fVolume; float fDepth; float fHeight; float fWidth; float fRatio; } VOLUMECALC; // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- bool CDlgVolumeCalc::m_bIsShowing = false; // is it showing???? static WINDOWPLACEMENT g_wpWindowPlace = {0,0}; ///////////////////////////////////////////////////////////////////////////// // CDlgVolumeCalc dialog ///////////////////////////////////////////////////////////////////////////// // ------------------------------------------------------------------------- // CDlgVolumeCalc // ------------------------------------------------------------------------- CDlgVolumeCalc::CDlgVolumeCalc(CWnd* pParent /*=NULL*/) : CDialog(CDlgVolumeCalc::IDD, pParent), m_cfEdits() { //{{AFX_DATA_INIT(CDlgVolumeCalc) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_bIsShowing = true; // we have it now } // ------------------------------------------------------------------------- // DoDataExchange // ------------------------------------------------------------------------- void CDlgVolumeCalc::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); m_cfEdits.DDX_All( pDX); //{{AFX_DATA_MAP(CDlgVolumeCalc) DDX_Control(pDX, IDC_STDWIDTH, m_czStdWidth); DDX_Control(pDX, IDC_STDVOLUME, m_czStdVolume); DDX_Control(pDX, IDC_STDHEIGHT, m_czStdHeight); DDX_Control(pDX, IDC_STDDEPTH, m_czStdDepth); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgVolumeCalc, CDialog) //{{AFX_MSG_MAP(CDlgVolumeCalc) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN1, OnDeltaposSpin) ON_EN_CHANGE(IDC_WIDTH, OnChangeWidth) ON_EN_CHANGE(IDC_VOLUME, OnChangeVolume) ON_EN_CHANGE(IDC_DEPTH, OnChangeDepth) ON_EN_CHANGE(IDC_HEIGHT, OnChangeHeight) ON_WM_CLOSE() ON_WM_LBUTTONUP() ON_WM_RBUTTONUP() ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN2, OnDeltaposSpin) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN3, OnDeltaposSpin) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN4, OnDeltaposSpin) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN5, OnDeltaposSpin) ON_BN_CLICKED(IDC_USERATIO, OnUseratio) //}}AFX_MSG_MAP END_MESSAGE_MAP() // ------------------------------------------------------------------------- // recalc_Values // ------------------------------------------------------------------------- void CDlgVolumeCalc::recalc_Values(bool bCalcVolume) { if ( m_fVolume < .000001f) m_fVolume = .000001f; if ( bCalcVolume) { m_fVolume = .000001f * m_fDepth * m_fHeight * m_fWidth; } else { float fold = .000001f * m_fDepth * m_fHeight * m_fWidth; float fratio = m_fVolume / fold; fratio = (float )exp( log( fratio) / 3); m_fHeight *= fratio; m_fWidth *=fratio; m_fDepth = m_fVolume / ( .000001f * m_fHeight * m_fWidth); // to be exact } UpdateData( FALSE); } ///////////////////////////////////////////////////////////////////////////// // CDlgVolumeCalc message handlers ///////////////////////////////////////////////////////////////////////////// // ------------------------------------------------------------------------- // OnInitDialog // ------------------------------------------------------------------------- BOOL CDlgVolumeCalc::OnInitDialog() { { // initialize the spinner format group FormatGroup cfdata[6] = { {IDC_VOLUME, IDC_SPIN4, 0.0f, 19900000.0f, &m_fVolume}, {IDC_HEIGHT, IDC_SPIN1, 0.0f, 19900000.0f, &m_fHeight}, {IDC_WIDTH, IDC_SPIN2, 0.0f, 19900000.0f, &m_fWidth}, {IDC_DEPTH, IDC_SPIN3, 0.0f, 19900000.0f, &m_fDepth}, {IDC_RATIO, IDC_SPIN5, 0.0f, 19900000.0f, &m_fRatio}, {0,0,0.0f,0.0f,NULL} }; m_cfEdits.AttachGroup( this, cfdata); GroupMetric cfgrp[5] = { { IDC_VOLUME, IDC_STDVOLUME, mtCuMeter }, { IDC_HEIGHT, IDC_STDHEIGHT, mtCm }, { IDC_WIDTH, IDC_STDWIDTH, mtCm }, { IDC_DEPTH, IDC_STDDEPTH, mtCm }, { 0, 0, mtNone } }; m_cfEdits.AttachMetrics( cfgrp); } CDialog::OnInitDialog(); { VOLUMECALC clc; CAudtestApp *capp = (CAudtestApp *)AfxGetApp(); if ( ! capp->ReadRegistry( IDS_VOLCALCINFO, &clc, sizeof(clc))) { m_fVolume = clc.fVolume; m_fHeight = clc.fHeight; m_fWidth = clc.fWidth; m_fDepth = clc.fDepth; m_fRatio = clc.fRatio; } else { m_fVolume = 1.0f; m_fHeight = 1.0f; m_fWidth = 1.0f; m_fDepth = 1.0f; m_fRatio = 1.0f; } } recalc_Values( true); UpdateData( FALSE); if ( g_wpWindowPlace.length == sizeof( g_wpWindowPlace)) // it's not empty, set back there SetWindowPlacement( &g_wpWindowPlace); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // ------------------------------------------------------------------------- // OnDeltaposSpin // ------------------------------------------------------------------------- void CDlgVolumeCalc::OnDeltaposSpin(NMHDR* pNMHDR, LRESULT* pResult) { m_cfEdits.ProcessAllDelta( pNMHDR); *pResult = 0; } // ----------------------------------------------------------------------------------------- // OnChangeVolume,... // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnChangeVolume() { if ( GetDlgItem( IDC_VOLUME) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( false); } } void CDlgVolumeCalc::OnChangeWidth() { if ( GetDlgItem( IDC_WIDTH) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( true); } } void CDlgVolumeCalc::OnChangeDepth() { if ( GetDlgItem( IDC_DEPTH) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( true); } } void CDlgVolumeCalc::OnChangeHeight() { if ( GetDlgItem( IDC_HEIGHT) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( true); } } // ----------------------------------------------------------------------------------------- // OnClose // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnClose() { if (! VerboseUpdateData( TRUE)) return; { VOLUMECALC clc; CAudtestApp *capp = (CAudtestApp *)AfxGetApp(); clc.fVolume = m_fVolume; clc.fHeight = m_fHeight; clc.fWidth = m_fWidth; clc.fDepth = m_fDepth; clc.fRatio = m_fRatio; capp->WriteRegistry( IDS_VOLCALCINFO, &clc, sizeof(clc)); } g_wpWindowPlace.length = sizeof( g_wpWindowPlace); GetWindowPlacement( & g_wpWindowPlace); CDialog::OnClose(); DestroyWindow(); } // ----------------------------------------------------------------------------------------- // PostNcDestroy // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::PostNcDestroy() { CDialog::PostNcDestroy(); m_bIsShowing = false; delete this; // per microsoft, kill us here } // ----------------------------------------------------------------------------------------- // OnLButtonUp // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnLButtonUp(UINT nFlags, CPoint point) { if ( ! m_cfEdits.ProcessLeftClick( nFlags, point)) CDialog::OnLButtonUp(nFlags, point); } // ----------------------------------------------------------------------------------------- // OnRButtonUp // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnRButtonUp(UINT nFlags, CPoint point) { if ( ! m_cfEdits.ProcessRightClick( nFlags, point)) CDialog::OnRButtonUp(nFlags, point); } // ----------------------------------------------------------------------------------------- // OnUseRatio // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnUseratio() { float ftotal, fratio; if ( VerboseUpdateData( TRUE)) { m_fHeight = 1.0f; m_fWidth = m_fRatio; m_fDepth = m_fRatio * m_fRatio; ftotal = .000001f * m_fDepth * m_fHeight * m_fWidth; fratio = m_fVolume / ftotal; fratio = (float )exp( log( fratio) / 3); // cube root it m_fHeight *= fratio; m_fWidth *= fratio; m_fDepth *= fratio; recalc_Values( true); } }
26.975078
92
0.494861
RDamman
71d84de8bc7087a21e5a617b0828c7683b10eb62
2,649
cpp
C++
Visualizer/Visualizer.cpp
VendorSniper/reg
825dd4c638ca9be58abd6fcf62989a9c1899b61a
[ "MIT" ]
null
null
null
Visualizer/Visualizer.cpp
VendorSniper/reg
825dd4c638ca9be58abd6fcf62989a9c1899b61a
[ "MIT" ]
null
null
null
Visualizer/Visualizer.cpp
VendorSniper/reg
825dd4c638ca9be58abd6fcf62989a9c1899b61a
[ "MIT" ]
null
null
null
#include "Visualizer.h" reg::Visualizer::Visualizer(vtkImageData *image) { Initialize(image); Execute(image); } void reg::Visualizer::Execute(vtkImageData *image) { Wrapper<vtkRenderWindow>::Get()->AddRenderer(Wrapper<vtkRenderer>::Get()); Wrapper<vtkRenderWindowInteractor>::Get()->SetRenderWindow( Wrapper<vtkRenderWindow>::Get()); Wrapper<vtkRenderWindow>::Get()->Render(); Wrapper<vtkImageShiftScale>::Get()->SetInputData( Wrapper<vtkImageData>::Get()); Wrapper<vtkImageShiftScale>::Get()->SetScale( 5); ///< increase brightness by a factor of 5 Wrapper<vtkImageShiftScale>::Get()->Update(); Wrapper<vtkImageThreshold>::Get()->SetInputData( Wrapper<vtkImageShiftScale>::Get()->GetOutput()); Wrapper<vtkImageThreshold>::Get()->ThresholdBetween( 110, std::numeric_limits<double>::max()); ///< inclusive range of grey values Wrapper<vtkImageThreshold>::Get() ->ReplaceOutOn(); ///< specify replace values not in inclusive range Wrapper<vtkImageThreshold>::Get()->SetOutValue( 0); ///< set non-included values to 0 Wrapper<vtkImageThreshold>::Get()->Update(); Wrapper<vtkSmartVolumeMapper>::Get()->SetBlendModeToComposite(); // Wrapper<vtkSmartVolumeMapper>::Get()->SetInputData(Wrapper<vtkImageThreshold>::Get()->GetOutput()); Wrapper<vtkSmartVolumeMapper>::Get()->SetInputData( Wrapper<vtkImageData>::Get()); Wrapper<vtkVolumeProperty>::Get()->SetScalarOpacity( CompositeOpacity::Get()); ///< explicitly specify no opacity std::cout << *Wrapper<vtkVolumeProperty>::Get()->GetScalarOpacity() << std::endl; Wrapper<vtkVolumeProperty>::Get()->ShadeOff(); Wrapper<vtkVolumeProperty>::Get()->SetInterpolationType( VTK_LINEAR_INTERPOLATION); Wrapper<vtkVolume>::Get()->SetMapper(Wrapper<vtkSmartVolumeMapper>::Get()); Wrapper<vtkVolume>::Get()->SetProperty(Wrapper<vtkVolumeProperty>::Get()); Wrapper<vtkRenderer>::Get()->AddViewProp(Wrapper<vtkVolume>::Get()); Wrapper<vtkRenderer>::Get()->ResetCamera(); Wrapper<vtkRenderWindow>::Get()->Render(); Wrapper<vtkRenderWindowInteractor>::Get()->Start(); } void reg::Visualizer::Initialize(vtkImageData *image) { Wrapper<vtkImageData>::Set(image); Wrapper<vtkRenderer>::Allocate(); Wrapper<vtkRenderWindow>::Allocate(); Wrapper<vtkRenderWindowInteractor>::Allocate(); Wrapper<vtkSmartVolumeMapper>::Allocate(); Wrapper<vtkVolume>::Allocate(); Wrapper<vtkVolumeProperty>::Allocate(); CompositeOpacity::Allocate(); Wrapper<vtkImageShiftScale>::Allocate(); Wrapper<vtkImageThreshold>::Allocate(); }
44.898305
105
0.702529
VendorSniper
71d885eb80a49039d76e763b48f31c8a840120a0
40,544
cpp
C++
sbg/src/libpdb/Atomo.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2022-01-02T01:48:05.000Z
2022-01-02T01:48:05.000Z
sbg/src/libpdb/Atomo.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2021-11-10T10:50:08.000Z
2021-11-10T10:50:08.000Z
sbg/src/libpdb/Atomo.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2021-12-03T03:29:39.000Z
2021-12-03T03:29:39.000Z
/*Implementation of the different methods of the Atom Class*/ #include <stdio.h> #include "Atomo.h" using namespace std; /*Table with the principal elements*/ Element Table_Elements::table_Elements[NUM_ELEMENTS]= { // Symbol Symbol group period number weight atomic cov vdw en Element((char*)"Carbon", C , "C ", 14, 2, 6.0, 12.011, 0.77, 0.77, 1.85, 2.55), // 0 Element((char*)"Hydrogen", H, "H ", 1, 1, 1.0, 1.00797, 0.78, 0.3, 1.2, 2.2), // 1 Element((char*)"Nitrogen", N, "N ", 15, 2, 7.0, 14.00674, 0.71, 0.7, 1.54, 3.04), // 2 Element((char*)"Oxygen", O, "O ", 16, 2, 8.0, 15.9994, 0.6, 0.66, 1.4, 3.44), // 3 Element((char*)"Phosphorus",P, "P ", 15, 3, 15.0, 30.973762, 1.15, 1.10, 1.9, 2.19), // 4 Element((char*)"Sulphur", S, "S ", 16, 3, 16.0, 32.066, 1.04, 1.04, 1.85, 2.58), // 5 Element((char*)"Calcium", CA, "CA", 2, 4, 20.0, 40.078, 1.97, 1.74, 1.367, 1.0), // 6 Mon: vdw radius taken from Rosetta Element((char*)"Iron", FE, "FE", 8, 4, 26.0, 55.845, 1.24, 1.16, 0.650, 1.83),// 7 Mon: vdw radius taken from Rosetta Element((char*)"Magnesium", MG, "MG", 2, 3, 12.0, 24.30506, 1.6, 1.36, 1.185, 1.31), // 8 Mon: vdw radius taken from Rosetta Element((char*)"Manganese", MN, "MN", 7, 4, 25.0, 54.93805, 1.24, 1.77, 1.0, 1.55), // 9 Mon: vdw radius manually set to 100pm Element((char*)"Sodium", NA, "NA", 1, 3, 11.0, 22.989768, 1.54, 0.0, 1.364, 0.93), // 10 Mon: 2.31A is a huge vdw radius for an ion... Element((char*)"Zinc", ZN, "ZN", 12, 4, 30.0, 65.39, 1.33, 1.25, 1.090, 1.65),// 11 Mon: vdw radius taken from Rosetta Element((char*)"Nickel", NI, "NI", 10, 4, 28.0, 58.6934, 1.25, 1.15, 0.0, 1.91), // 12 Element((char*)"Copper", CU, "CU", 11, 4, 29.0, 63.546, 1.28, 1.17, 0.70, 1.9), // 13 Mon: vdw radius manually set to 70pm Element((char*)"Potassium", K, "K ", 1, 4, 19.0, 39.0983, 2.27, 2.03, 1.764, 0.82), // 14 Mon: 2.31A is a huge vdw radius for an ion... Element((char*)"Cobalt", CO, "CO", 9, 4, 27.0, 58.9332, 1.25, 1.16, 0.8 , 1.88), // 15 Mon: vdw radius manually set to 80pm Element((char*)"Aluminum", AL, "AL", 13, 3, 13.0, 26.981539, 1.43, 1.25, 2.05, 1.61), // 16 Element((char*)"Bromine", BR, "BR", 17, 4, 35.0, 79.904, 0.0, 1.14, 1.95, 2.96), // 17 Element((char*)"Chlorine", CL, "CL", 17, 3, 17.0, 35.4527, 0.0, 0.99, 1.81, 3.16), // 18 Element((char*)"Chromium", CR, "CR", 6, 4, 24.0, 51.9961, 1.25, 0.0, 0.0, 1.66), // 19 Element((char*)"Silicon", SI, "SI", 14, 3, 14.0, 28.0855, 1.17, 1.17, 2.0, 1.9), // 20 Element((char*)"Cadmium", CD, "CD", 12, 5, 48.0, 112.411, 1.49, 1.41, 0.0, 1.69), // 21 Element((char*)"Gold", AU, "AU", 11, 6, 79.0, 196.96654, 1.44, 1.34, 0.0, 2.0), // 22 Element((char*)"Silver", AG, "AG", 11, 5, 47.0, 107.8682, 1.44, 1.34, 0.0, 1.93), // 23 Element((char*)"Platinum", PT, "PT", 10, 6, 78.0, 195.08, 1.38, 1.29, 0.0, 2.54), // 24 Element((char*)"Mercury", HG, "HG", 12, 6, 80.0, 200.59, 1.60, 1.44, 0.0, 1.8), // 25 Element((char*)"Iodine", I, "I ", 17, 5, 53.0, 126.904, 1.40, 1.39, 1.98, 2.96), // 26 Element((char*)"Fluorine", F, "F ", 17, 2, 9.0, 18.998, 0.42, 0.71, 1.47, 3.98), // 27 Element((char*)"Deuterium", D, "D ", 1, 1, 1.0, 2.01410, 0.78, 0.3, 1.2, 2.2) // 28 }; // PyRosetta's metallic ions with available .parms file: (must have vdw radius, otherwise they do not generate a density map, e.g. in rcd) // PyRosetta.namespace.ubuntu.release-72/database/chemical/residue_type_sets/fa_standard/residue_types/metal_ions //residue_types/metal_ions/CA.params //residue_types/metal_ions/CO.params //residue_types/metal_ions/CU.params //residue_types/metal_ions/FE.params //residue_types/metal_ions/FE2.params //residue_types/metal_ions/K.params //residue_types/metal_ions/MG.params //residue_types/metal_ions/MN.params //residue_types/metal_ions/NA.params //residue_types/metal_ions/ZN.params Atom_type *atom_types; int num_atom_type; Atom_type atom_types_Rosseta[54]= { // at name hybridation polar chrge vdw soft deep acept donor Avol Asolpar {0 , "CNH2", SP2_HYBRID, APOLAR, 0.550, 2.0000, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 1 CNH2 // carbonyl C in Asn and Gln and guanidyl C in Arg {0 , "COO ", SP2_HYBRID, APOLAR, 0.620, 2.0000, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 2 COO // carboxyl C in Asp and Glu {0 , "CH1 ", SP3_HYBRID, APOLAR, -0.090, 2.0000, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 3 CH1 // aliphatic C with one H (Val, Ile, Thr) {0 , "CH2 ", SP3_HYBRID, APOLAR, -0.180, 2.0000, 2.1400, 0.1142, false, false, 0.01918, -0.0010}, // 4 CH2 // aliphatic C with two H (other residues) {0 , "CH3 ", SP3_HYBRID, APOLAR, -0.270, 2.0000, 2.1400, 0.1811, false, false, 0.01918, -0.0010}, // 5 CH3 // aliphatic C with three H (Ala) {0 , "aroC", SP2_HYBRID, APOLAR, -0.115, 2.0000, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 6 aroC // aromatic ring C (His, Phe, Tyr, Trp) {2 , "Ntrp", SP2_HYBRID, POLAR, -0.610, 1.7500, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 7 Ntrp // N in Trp side-chain {2 , "Nhis", RING_HYBRID,POLAR, -0.530, 1.7500, 1.7500, 0.2384, true, false, -0.03910, -0.0016}, // 8 Nhis // N in His side-chain {2 , "NH2O", SP2_HYBRID, POLAR, -0.470, 1.7500, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 9 NH2O // N in Asn and Gln side-chain {2 , "Nlys", SP3_HYBRID, POLAR, -0.620, 1.7500, 1.7500, 0.2384, false, true, -0.12604, -0.0016}, // 10 NLYS // N in Lys side-chain, N-terminus? {2 , "Narg", SP2_HYBRID, POLAR, -0.750, 1.7500, 1.7500, 0.2384, false, true, -0.06256, -0.0016}, // 11 Narg // N in Arg side-chain **** -7.0, 07/08/01 ... too many buried Arg {2 , "Npro", SP2_HYBRID, APOLAR, -0.370, 1.7500, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 12 Npro // N in Pro backbone {3 , "OH ", SP3_HYBRID, POLAR, -0.660, 1.5500, 1.6585, 0.1591, true, true, -0.04255, -0.0025}, // 13 OH // hydroxyl O in Ser, Thr and Tyr {3 , "ONH2", SP2_HYBRID, POLAR, -0.550, 1.5500, 1.5500, 0.1591, true, false, -0.03128, -0.0025}, // 14 ONH2 // carbonyl O in Asn and Gln **** -5.85, 07/08/01 ... too many buried Asn,Arg {3 , "OOC ", SP2_HYBRID, POLAR, -0.760, 1.5500, 1.5500, 0.2100, true, false, -0.06877, -0.0025}, // 15 OOC // carboyxl O in Asp and Glu {5 , "S ", SP3_HYBRID, POLAR, -0.160, 1.9000, 2.0330, 0.1600, false, false, 0.02576, -0.0021}, // 16 S // sulfur in Cys and Met {2 , "Nbb ", SP2_HYBRID, POLAR, -0.470, 1.7500, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 17 Nbb // backbone N' {0 , "CAbb", SP3_HYBRID, APOLAR, 0.070, 2.0000, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 18 CAbb // backbone CA {0 , "CObb", SP2_HYBRID, APOLAR, 0.510, 2.0000, 2.1400, 0.1400, false, false, 0.01918, -0.0010}, // 19 CObb // backbone C' {0 , "OCbb", SP2_HYBRID, POLAR, -0.510, 1.5500, 1.6585, 0.1591, true, false, -0.03128, -0.0025}, // 20 OCbb // backbone O' {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false, 0.000, -0.0011}, // 21 Phos // nucleic acid P (from S) {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 22 Hpol // polar H {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 23 Hapo // nonpolar H {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 24 Haro // aromatic H {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 25 HNbb // backbone HN {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.4000, 1.4000, 0.0500, true, true, 0.000, 0.0005}, // 26 H2O // H2O {99, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false, 0.000, -0.0011}, // 27 F // F wild guess {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false, 0.000, -0.0011}, // 28 Cl // Cl wild guess {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false, 0.000, -0.0011}, // 29 Br // Br wild guess {99, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false, 0.000, -0.0011}, // 30 I // I wild guess {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false, 0.000, -0.0011}, // 31 Zn2p // Zn2p wild guess {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false, 0.000, -0.0011}, // 32 Fe2p // Fe2p wild guess {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false, 0.000, -0.0011}, // 33 Fe3p // Fe3p wild guess {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false, 0.000, -0.0011}, // 34 Mg2p // Mg2p wild guess {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false, 0.000, -0.0011}, // 35 Ca2p // Ca2p wild guess {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false, 0.000, 0.000}, // 36 Na1p // Na1p wild guess {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false, 0.000, 0.000}, // 37 K1p // K1p wild guess {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 38 1 ASP/GLU // V01 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 39 2 ASP/GLU // V02 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 40 3 ASN/GLN or BB // V03 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 41 4 ASN/GLN or BB // V04 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 42 5 ASN/GLN or BB // V05 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 43 6 SER OG // V06 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 44 7 SER CB // V07 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 45 8 CYS SG // V08 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 46 9 CYS CB // V09 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 47 10 ARG NH // V10 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 48 11 ARG NE // V11 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 49 12 LYS NZ // V12 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 50 13 LYS CE // V13 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 51 14 HIS ND // V14 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 52 15 HIS NE // V15 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 53 16 HIS CB // V16 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000} // 54 17 HPOL // V17 }; //NUEVOS RADIOS DE VDW Atom_type atom_types_ICM[54]= { // at name hybridation polar chrge vdw soft deep acept donor Avol Asolpar {0 , "CNH2", SP2_HYBRID, APOLAR, 0.550, 1.8100, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 1 CNH2 // carbonyl C in Asn and Gln and guanidyl C in Arg {0 , "COO ", SP2_HYBRID, APOLAR, 0.620, 1.7600, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 2 COO // carboxyl C in Asp and Glu {0 , "CH1 ", SP3_HYBRID, APOLAR, -0.090, 2.0100, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 3 CH1 // aliphatic C with one H (Val, Ile, Thr) {0 , "CH2 ", SP3_HYBRID, APOLAR, -0.180, 1.9200, 2.1400, 0.1142, false, false, 0.01918, -0.0010}, // 4 CH2 // aliphatic C with two H (other residues) {0 , "CH3 ", SP3_HYBRID, APOLAR, -0.270, 1.9200, 2.1400, 0.1811, false, false, 0.01918, -0.0010}, // 5 CH3 // aliphatic C with three H (Ala) {0 , "aroC", SP2_HYBRID, APOLAR, -0.115, 1.7400, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 6 aroC // aromatic ring C (His, Phe, Tyr, Trp) {2 , "Ntrp", SP2_HYBRID, POLAR, -0.610, 1.6600, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 7 Ntrp // N in Trp side-chain {2 , "Nhis", RING_HYBRID,POLAR, -0.530, 1.6500, 1.7500, 0.2384, true, false, -0.03910, -0.0016}, // 8 Nhis // N in His side-chain {2 , "NH2O", SP2_HYBRID, POLAR, -0.470, 1.6200, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 9 NH2O // N in Asn and Gln side-chain {2 , "Nlys", SP3_HYBRID, POLAR, -0.620, 1.6700, 1.7500, 0.2384, false, true, -0.12604, -0.0016}, // 10 NLYS // N in Lys side-chain, N-terminus? {2 , "Narg", SP2_HYBRID, POLAR, -0.750, 1.6700, 1.7500, 0.2384, false, true, -0.06256, -0.0016}, // 11 Narg // N in Arg side-chain **** -7.0, 07/08/01 ... too many buried Arg {2 , "Npro", SP2_HYBRID, APOLAR, -0.370, 1.6700, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 12 Npro // N in Pro backbone {3 , "OH ", SP3_HYBRID, POLAR, -0.660, 1.5400, 1.6585, 0.1591, true, true, -0.04255, -0.0025}, // 13 OH // hydroxyl O in Ser, Thr and Tyr {3 , "ONH2", SP2_HYBRID, POLAR, -0.550, 1.5200, 1.5500, 0.1591, true, false, -0.03128, -0.0025}, // 14 ONH2 // carbonyl O in Asn and Gln **** -5.85, 07/08/01 ... too many buried Asn,Arg {3 , "OOC ", SP2_HYBRID, POLAR, -0.760, 1.4900, 1.5500, 0.2100, true, false, -0.06877, -0.0025}, // 15 OOC // carboyxl O in Asp and Glu {4 , "S ", SP3_HYBRID, POLAR, -0.160, 1.9400, 2.0330, 0.1600, false, false, 0.02576, -0.0021}, // 16 S // sulfur in Cys and Met {2 , "Nbb ", SP2_HYBRID, POLAR, -0.470, 1.7000, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 17 Nbb // backbone N' {0 , "CAbb", SP3_HYBRID, APOLAR, 0.070, 1.9000, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 18 CAbb // backbone CA {0 , "CObb", SP2_HYBRID, APOLAR, 0.510, 1.7500, 2.1400, 0.1400, false, false, 0.01918, -0.0010}, // 19 CObb // backbone C' {0 , "OCbb", SP2_HYBRID, POLAR, -0.510, 1.4900, 1.6585, 0.1591, true, false, -0.03128, -0.0025}, // 20 OCbb // backbone O' {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false, 0.000, -0.0011}, // 21 Phos // nucleic acid P (from S) {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 22 Hpol // polar H {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 23 Hapo // nonpolar H {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 24 Haro // aromatic H {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 25 HNbb // backbone HN {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.4000, 1.4000, 0.0500, true, true, 0.000, 0.0005}, // 26 H2O // H2O {27, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false, 0.000, -0.0011}, // 27 F // F wild guess {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false, 0.000, -0.0011}, // 28 Cl // Cl wild guess {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false, 0.000, -0.0011}, // 29 Br // Br wild guess {26, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false, 0.000, -0.0011}, // 30 I // I wild guess {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false, 0.000, -0.0011}, // 31 Zn2p // Zn2p wild guess {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false, 0.000, -0.0011}, // 32 Fe2p // Fe2p wild guess {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false, 0.000, -0.0011}, // 33 Fe3p // Fe3p wild guess {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false, 0.000, -0.0011}, // 34 Mg2p // Mg2p wild guess {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false, 0.000, -0.0011}, // 35 Ca2p // Ca2p wild guess {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false, 0.000, 0.000}, // 36 Na1p // Na1p wild guess {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false, 0.000, 0.000}, // 37 K1p // K1p wild guess {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 38 1 ASP/GLU // V01 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 39 2 ASP/GLU // V02 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 40 3 ASN/GLN or BB // V03 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 41 4 ASN/GLN or BB // V04 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 42 5 ASN/GLN or BB // V05 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 43 6 SER OG // V06 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 44 7 SER CB // V07 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 45 8 CYS SG // V08 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 46 9 CYS CB // V09 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 47 10 ARG NH // V10 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 48 11 ARG NE // V11 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 49 12 LYS NZ // V12 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 50 13 LYS CE // V13 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 51 14 HIS ND // V14 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 52 15 HIS NE // V15 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 53 16 HIS CB // V16 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000} // 54 17 HPOL // V17 }; Atom_type atom_types_EEF1[31]= { // Solo he rellenado con EEF1 at, vdw, soft, deep // at name hybridation polar chrge vdw soft deep acept donor // Rmin/2 Rmin/2 emin {1 , "H", SP2_HYBRID, APOLAR, 0.550, 0.8000, 0.8000, 0.04980, false, false}, // 1 {1 , "HC", SP2_HYBRID, APOLAR, 0.620, 0.6000, 0.6000, 0.04980, false, false}, // 2 {1 , "HA", SP3_HYBRID, APOLAR, -0.090, 1.4680, 1.4680, 0.04500, false, false}, // 3 {0 , "CT", SP3_HYBRID, APOLAR, -0.180, 2.4900, 2.4900, 0.02620, false, false}, // 4 {0 , "C", SP3_HYBRID, APOLAR, -0.270, 2.1000, 2.1000, 0.12000, false, false}, // 5 {0 , "CH1E", SP2_HYBRID, APOLAR, -0.115, 2.3650, 2.3650, 0.04860, false, false}, // 6 {0 , "CH2E", SP2_HYBRID, POLAR, -0.610, 2.2350, 2.2350, 0.11420, false, true}, // 7 {0 , "CH3E", RING_HYBRID,POLAR, -0.530, 2.1650, 2.1650, 0.18110, true, false}, // 8 {0 , "CR1E", SP2_HYBRID, POLAR, -0.470, 2.1000, 2.1000, 0.12000, false, true}, // 9 {2 , "N", SP3_HYBRID, POLAR, -0.620, 1.6000, 1.6000, 0.23840, false, true}, // 10 {2 , "NR", SP2_HYBRID, POLAR, -0.750, 1.6000, 1.6000, 0.23840, false, true}, // 11 {2 , "NP", SP2_HYBRID, APOLAR, -0.370, 1.6000, 1.6000, 0.23840, false, true}, // 12 {2 , "NH1", SP3_HYBRID, POLAR, -0.660, 1.6000, 1.6000, 0.23840, true, true}, // 13 {2 , "NH2", SP2_HYBRID, POLAR, -0.550, 1.6000, 1.6000, 0.23840, true, false}, // 14 {2 , "NH3", SP2_HYBRID, POLAR, -0.760, 1.6000, 1.6000, 0.23840, true, false}, // 15 {2 , "NC2", SP3_HYBRID, POLAR, -0.160, 1.6000, 1.6000, 0.23840, false, false}, // 16 {3 , "O", SP2_HYBRID, POLAR, -0.470, 1.6000, 1.6000, 0.15910, false, true}, // 17 {3 , "OC", SP3_HYBRID, APOLAR, 0.070, 1.6000, 1.6000, 0.64690, false, false}, // 18 {3 , "OH1", SP2_HYBRID, APOLAR, 0.510, 1.6000, 1.6000, 0.15910, false, false}, // 19 {3 , "OH2", SP2_HYBRID, POLAR, -0.510, 1.7398, 1.7398, 0.07580, true, false}, // 20 {5 , "S", SP3_HYBRID, APOLAR, -0.160, 1.8900, 1.8900, 0.04300, false, false}, // 21 {5 , "SH1E",H_HYBRID, APOLAR, 0.430, 1.8900, 1.8900, 0.04300, false, false}, // 22 {7 , "FE", H_HYBRID, APOLAR, 0.095, 0.6500, 0.6500, 0.00000, false, false}, // 23 {99 , "OS", H_HYBRID, APOLAR, 0.115, 1.6000, 1.6000, 0.15910, false, false}, // 24 {99 , "CR", H_HYBRID, APOLAR, 0.310, 2.1000, 2.1000, 0.12000, false, false}, // 25 {99 , "CM", SP3_HYBRID, POLAR, 0.000, 2.4900, 2.4900, 0.02620, true, true}, // 26 {99, "OM", SP3_HYBRID, APOLAR, -0.250, 1.6000, 1.6000, 0.15910, false, false}, // 27 {99, "LP", SP3_HYBRID, APOLAR, -0.130, 0.2245, 0.2245, 0.04598, false, false}, // 28 {99, "HT", SP3_HYBRID, APOLAR, -0.100, 0.8000, 0.8000, 0.04980, false, false}, // 29 {99, "OT", SP3_HYBRID, APOLAR, -0.090, 1.6000, 1.6000, 0.15910, false, false}, // 30 {99, "CAL", SP3_HYBRID, POLAR, 2.000, 1.7100, 1.7100, 0.12000, false, false} // 31 }; Atom_type atom_types_Sybil[45]= { // at name hybridation polar chrge vdw soft deep acept donor Avol Asolpar {0 , "C2 ", SP2_HYBRID, APOLAR, 0.510, 2.0000, 2.1400, 0.1400, false, false, 0.01918, -0.0010}, // 1 {0 , "C3 ", SP3_HYBRID, APOLAR,-0.270, 2.0000, 2.1400, 0.1811, false, false, 0.01918, -0.0010}, // 2 {0 , "Car ", SP2_HYBRID, APOLAR,-0.115, 2.0000, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 3 {0 , "Ccat", SP2_HYBRID, APOLAR,-0.115, 2.0000, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 4 {2 , "N3 ", SP3_HYBRID, POLAR, -0.620, 1.7500, 1.7500, 0.2384, true, true, -0.12604, -0.0016}, // 5 {2 , "Nam ", SP2_HYBRID, POLAR, -0.470, 1.7500, 1.8725, 0.2384, false, true,-0.03910, -0.0016}, // 6 {2 , "Npl3", SP2_HYBRID, POLAR, -0.370, 1.7500, 1.8725, 0.2384, false, true,-0.03910, -0.0016}, // 7 {3 , "O2 ", SP2_HYBRID, POLAR, -0.510, 1.5500, 1.6585, 0.1591, true, false,-0.03128, -0.0025}, // 8 {3 , "O3 ", SP3_HYBRID, POLAR, -0.660, 1.5500, 1.6585, 0.1591, true, true,-0.04255, -0.0025}, // 9 {3 , "Oco2", SP2_HYBRID, POLAR, -0.760, 1.5500, 1.5500, 0.2100, true, false,-0.06877, -0.0025}, //10 {5 , "S3 ", SP3_HYBRID, POLAR, -0.160, 1.9000, 2.0330, 0.1600, false, false, 0.02576, -0.0021}, //11 //from here it is the same as Rosseta {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false, 0.000, -0.0011}, // 12 {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 13 {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 14 {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 15 {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 16 {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.4000, 1.4000, 0.0500, true, true, 0.000, 0.0005}, // 17 {27, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false, 0.000, -0.0011}, // 18 {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false, 0.000, -0.0011}, // 19 {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false, 0.000, -0.0011}, // 20 {26, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false, 0.000, -0.0011}, // 21 {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false, 0.000, -0.0011}, // 22 {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false, 0.000, -0.0011}, // 23 {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false, 0.000, -0.0011}, // 24 {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false, 0.000, -0.0011}, // 25 {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false, 0.000, -0.0011}, // 26 {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false, 0.000, 0.000}, // 27 {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false, 0.000, 0.000}, // 28 {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 29 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 30 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 31 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 32 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 33 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 34 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 35 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 36 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 37 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 38 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 39 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 40 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 41 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 42 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 43 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 44 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000} // 45 }; /* //NUEVOS RADIOS DE VDW a partir de tablas de Julio Kovacs Atom_type atom_types[54]= { // at name hybridation polar chrge vdw soft deep acept donor {0 , "CNH2", SP2_HYBRID, APOLAR, 0.550, 1.7000, 2.0000, 0.1200, false, false}, // 1 CNH2 // carbonyl C in Asn and Gln and guanidyl C in Arg {0 , "COO ", SP2_HYBRID, APOLAR, 0.620, 1.7000, 2.0000, 0.1200, false, false}, // 2 COO // carboxyl C in Asp and Glu {0 , "CH1 ", SP3_HYBRID, APOLAR, -0.090, 1.7000, 2.1400, 0.0486, false, false}, // 3 CH1 // aliphatic C with one H (Val, Ile, Thr) {0 , "CH2 ", SP3_HYBRID, APOLAR, -0.180, 1.7000, 2.1400, 0.1142, false, false}, // 4 CH2 // aliphatic C with two H (other residues) {0 , "CH3 ", SP3_HYBRID, APOLAR, -0.270, 1.7000, 2.1400, 0.1811, false, false}, // 5 CH3 // aliphatic C with three H (Ala) {0 , "aroC", SP2_HYBRID, APOLAR, -0.115, 1.7400, 2.1400, 0.1200, false, false}, // 6 aroC // aromatic ring C (His, Phe, Tyr, Trp) {1 , "Ntrp", SP2_HYBRID, POLAR, -0.610, 1.5000, 1.7500, 0.2384, false, true}, // 7 Ntrp // N in Trp side-chain {1 , "Nhis", RING_HYBRID,POLAR, -0.530, 1.5000, 1.7500, 0.2384, true, false}, // 8 Nhis // N in His side-chain {1 , "NH2O", SP2_HYBRID, POLAR, -0.470, 1.5000, 1.7500, 0.2384, false, true}, // 9 NH2O // N in Asn and Gln side-chain {1 , "Nlys", SP3_HYBRID, POLAR, -0.620, 1.5000, 1.7500, 0.2384, false, true}, // 10 NLYS // N in Lys side-chain, N-terminus? {1 , "Narg", SP2_HYBRID, POLAR, -0.750, 1.5000, 1.7500, 0.2384, false, true}, // 11 Narg // N in Arg side-chain **** -7.0, 07/08/01 ... too many buried Arg {1 , "Npro", SP2_HYBRID, APOLAR, -0.370, 1.5000, 1.8725, 0.2384, false, true}, // 12 Npro // N in Pro backbone {2 , "OH ", SP3_HYBRID, POLAR, -0.660, 1.4000, 1.6585, 0.1591, true, true}, // 13 OH // hydroxyl O in Ser, Thr and Tyr {2 , "ONH2", SP2_HYBRID, POLAR, -0.550, 1.4000, 1.5500, 0.1591, true, false}, // 14 ONH2 // carbonyl O in Asn and Gln **** -5.85, 07/08/01 ... too many buried Asn,Arg {2 , "OOC ", SP2_HYBRID, POLAR, -0.760, 1.4000, 1.5500, 0.2100, true, false}, // 15 OOC // carboyxl O in Asp and Glu {3 , "S ", SP3_HYBRID, POLAR, -0.160, 1.8500, 2.0330, 0.1600, false, false}, // 16 S // sulfur in Cys and Met {2 , "Nbb ", SP2_HYBRID, POLAR, -0.470, 1.5000, 1.8725, 0.2384, false, true}, // 17 Nbb // backbone N' {0 , "CAbb", SP3_HYBRID, APOLAR, 0.070, 1.7000, 2.1400, 0.0486, false, false}, // 18 CAbb // backbone CA {0 , "CObb", SP2_HYBRID, APOLAR, 0.510, 1.7000, 2.1400, 0.1400, false, false}, // 19 CObb // backbone C' {0 , "OCbb", SP2_HYBRID, POLAR, -0.510, 1.5000, 1.6585, 0.1591, true, false}, // 20 OCbb // backbone O' {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false}, // 21 Phos // nucleic acid P (from S) {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false}, // 22 Hpol // polar H {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.0000, 1.2840, 0.0500, false, false}, // 23 Hapo // nonpolar H {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.0000, 1.2840, 0.0500, false, false}, // 24 Haro // aromatic H {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false}, // 25 HNbb // backbone HN {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.0000, 1.4000, 0.0500, true, true}, // 26 H2O // H2O {99, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false}, // 27 F // F wild guess {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false}, // 28 Cl // Cl wild guess {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false}, // 29 Br // Br wild guess {99, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false}, // 30 I // I wild guess {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false}, // 31 Zn2p // Zn2p wild guess {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false}, // 32 Fe2p // Fe2p wild guess {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false}, // 33 Fe3p // Fe3p wild guess {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false}, // 34 Mg2p // Mg2p wild guess {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false}, // 35 Ca2p // Ca2p wild guess {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false}, // 36 Na1p // Na1p wild guess {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false}, // 37 K1p // K1p wild guess {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 38 1 ASP/GLU // V01 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 39 2 ASP/GLU // V02 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 40 3 ASN/GLN or BB // V03 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 41 4 ASN/GLN or BB // V04 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 42 5 ASN/GLN or BB // V05 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 43 6 SER OG // V06 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 44 7 SER CB // V07 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 45 8 CYS SG // V08 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 46 9 CYS CB // V09 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 47 10 ARG NH // V10 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 48 11 ARG NE // V11 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 49 12 LYS NZ // V12 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 50 13 LYS CE // V13 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 51 14 HIS ND // V14 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 52 15 HIS NE // V15 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 53 16 HIS CB // V16 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false} // 54 17 HPOL // V17 }; */ /*Default constructor*/ Atom::Atom() { /*The atom is created with the firts element of the table*/ element= Table_Elements::getElement(0); pdbSerialNumber=0; strcpy(pdbName," C "); pdbocc=0.0; pdbfact=0.0; position[0]=0.0; position[1]=0.0; position[2]=0.0; charge=0; father=NULL; bonds=NULL; num_bonds=0; } /*Constructor. e: Element Object of the atom. The Object element is copied in another object, not assignated p: three-dimension position of the atom ch: charge of the atom*/ Atom::Atom(Element *e, Tcoor p,float ch,char name[5],int serial, float occ, float fact) { element=e; strcpy(pdbName,name); position[0]=p[0]; position[1]=p[1]; position[2]=p[2]; charge=ch; pdbSerialNumber=serial; pdbocc=occ; pdbfact=fact; father=NULL; bonds=NULL; num_bonds=0; } /*Constructor from template */ Atom::Atom(Atom_type atom_type, char name[5], float *p, int serial) { element= Table_Elements::getElement(atom_type.at); strcpy(pdbName,name); position[0]=p[0]; position[1]=p[1]; position[2]=p[2]; //printf("%s %f %f %f\n",name, position[0],position[1],position[2]); charge=atom_type.chrge; pdbSerialNumber=serial; pdbocc=1.0; pdbfact=1.0; father=NULL; bonds=NULL; num_bonds=0; } /*Constructor. Copy of another atom. The only difference between both atoms is the name n: name of the new atom. a: atom to copy */ Atom::Atom(Atom *a) { element=a->getElement(); strcpy(pdbName,a->getPdbName()); Tcoor pos; a->getPosition(pos); position[0]=pos[0]; position[1]=pos[1]; position[2]=pos[2]; charge=a->getCharge(); pdbSerialNumber=a->getPdbSerial(); pdbocc=a->getPdbocc(); pdbfact=a->getPdbfact(); father=NULL; bonds=NULL; num_bonds=0; } /*Destructor*/ Atom::~Atom() { //std::cout<<"Atomo eliminado"<<std::endl; if(num_bonds>0) free(bonds); } /*Get the position of the atom*/ void Atom::getPosition(Tcoor coor) { coor[0]=position[0]; coor[1]=position[1]; coor[2]=position[2]; } /*Get the charge of the atom*/ float Atom::getCharge() { return charge; } /*Get the object Element of the atom*/ Element* Atom::getElement() { return element; } int Atom::getPdbSerial() { return pdbSerialNumber; } char* Atom::getPdbName() { return pdbName; } float Atom::getPdbocc() { return pdbocc; } float Atom::getPdbfact() { return pdbfact; } /*Set new position for the atom*/ void Atom::setPosition(Tcoor pos) { position[0]=pos[0]; position[1]=pos[1]; position[2]=pos[2]; } /*Set new Charge for the atom*/ void Atom::setCharge(float ch) { charge=ch; } void Atom::setPdbSerial(int serial) { pdbSerialNumber=serial; } void Atom::setPdbName(char n[5]) { strcpy(pdbName,n); } void Atom::setPdbocc(float occ) { pdbocc=occ; } void Atom::setPdbfact(float fact) { pdbfact=fact; } /*move an offset the position of the atom */ bool Atom::move(Tcoor offset) { position[0]+=offset[0]; position[1]+=offset[1]; position[2]+=offset[2]; return true; } /*move an offset the position of the atom */ bool Atom::moven(Tcoor offset) { position[0]-=offset[0]; position[1]-=offset[1]; position[2]-=offset[2]; return true; } char *Atom::getName() { return pdbName; } bool Atom::initAll() { return true; } bool Atom::moveAll(Tcoor offset) { return move(offset); } bool Atom::moveAlln(Tcoor offset) { return moven(offset); } TElement Atom::getClass() { return pdb_atom; } TMOL Atom::getMolType() { PDB_Container *f; f=(PDB_Container*)getFather(); if(f!=NULL) return f->getMolType(); else return tmol_null; } int Atom::get_numBonds() { return num_bonds; } Bond* Atom::getBond(int i) { if( i>num_bonds ) return NULL; else { return bonds[i]; } } void Atom::insertBond(Bond *b) { num_bonds++; bonds=(Bond**)realloc(bonds,sizeof(Bond*)*num_bonds); bonds[num_bonds-1]=b; } bool Atom::removeBond(Bond *b) { int i,j; for(i=0;i<num_bonds;i++) { if(b==bonds[i]) { for(j=i+1;j<num_bonds;j++) bonds[j-1]=bonds[j]; num_bonds--; bonds=(Bond**)realloc(bonds,sizeof(Bond*)*num_bonds); return true; } } return false; } Bond::Bond(Atom* i, Atom *f, int l) { final=f; init=i; link=l; } Bond::~Bond() { } int Bond::getLink() { return link; } Atom * Bond::getInit() { return init; } Atom *Bond::getFinal() { return final; }
64.355556
212
0.540475
chaconlab
71e29fe3e2fab124ea2d209703403d9144b07590
18,789
cpp
C++
Src/media/NiceConnection.cpp
MrsZ/licode-windows
578a779ddd200a7dbf5e84e0b5b0376c0c39827a
[ "MIT" ]
60
2018-10-23T02:41:46.000Z
2022-03-16T07:40:52.000Z
Src/media/NiceConnection.cpp
gupar/licode-windows
578a779ddd200a7dbf5e84e0b5b0376c0c39827a
[ "MIT" ]
3
2018-10-25T11:10:06.000Z
2020-11-29T09:47:05.000Z
Src/media/NiceConnection.cpp
gupar/licode-windows
578a779ddd200a7dbf5e84e0b5b0376c0c39827a
[ "MIT" ]
46
2018-10-29T06:56:03.000Z
2022-02-18T07:07:17.000Z
/* * NiceConnection.cpp */ #include <nice/nice.h> #include <cstdio> #include <string> #include <cstring> #include <vector> #include "NiceConnection.h" #include "SdpInfo.h" using std::memcpy; // If true (and configured properly below) erizo will generate relay candidates for itself // MOSTLY USEFUL WHEN ERIZO ITSELF IS BEHIND A NAT #define SERVER_SIDE_TURN 0 namespace erizo { DEFINE_LOGGER(NiceConnection, "NiceConnection") void cb_nice_recv(NiceAgent* agent, guint stream_id, guint component_id, guint len, gchar* buf, gpointer user_data) { if (user_data == NULL || len == 0) { return; } NiceConnection* nicecon = reinterpret_cast<NiceConnection*>(user_data); nicecon->queueData(component_id, reinterpret_cast<char*> (buf), static_cast<unsigned int> (len)); } void cb_new_candidate(NiceAgent *agent, guint stream_id, guint component_id, gchar *foundation, gpointer user_data) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); std::string found(foundation); conn->getCandidate(stream_id, component_id, found); } void cb_candidate_gathering_done(NiceAgent *agent, guint stream_id, gpointer user_data) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); conn->gatheringDone(stream_id); } void cb_component_state_changed(NiceAgent *agent, guint stream_id, guint component_id, guint state, gpointer user_data) { if (state == NICE_COMPONENT_STATE_CONNECTED) { } else if (state == NICE_COMPONENT_STATE_FAILED) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); conn->updateComponentState(component_id, NICE_FAILED); } } void cb_new_selected_pair(NiceAgent *agent, guint stream_id, guint component_id, gchar *lfoundation, gchar *rfoundation, gpointer user_data) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); conn->updateComponentState(component_id, NICE_READY); } NiceConnection::NiceConnection(MediaType med, const std::string &transport_name, const std::string& connection_id, NiceConnectionListener* listener, unsigned int iceComponents, const IceConfig& iceConfig, std::string username, std::string password) : mediaType(med), connection_id_(connection_id), agent_(NULL), loop_(NULL), listener_(listener), candsDelivered_(0), iceState_(NICE_INITIAL), iceComponents_(iceComponents), username_(username), password_(password), iceConfig_(iceConfig), receivedLastCandidate_(false) { localCandidates.reset(new std::vector<CandidateInfo>()); transportName.reset(new std::string(transport_name)); for (unsigned int i = 1; i <= iceComponents_; i++) { comp_state_list_[i] = NICE_INITIAL; } g_type_init(); } NiceConnection::~NiceConnection() { ELOG_DEBUG("%s, message: destroying", toLog()); this->close(); ELOG_DEBUG("%s, message: destroyed", toLog()); } packetPtr NiceConnection::getPacket() { cCSLock Lock(queueMutex_); while (niceQueue_.empty()) { cCSUnlock Unlock(Lock); cond_.Wait(); if (this->checkIceState() >= NICE_FINISHED) { ELOG_DEBUG("%s, message: finished in getPacket thread", toLog()); packetPtr p(new dataPacket()); p->length = -1; return p; } } packetPtr p(niceQueue_.front()); niceQueue_.pop(); Lock.Unlock(); return p; } void NiceConnection::close() { cCSLock Lock(closeMutex_); if (this->checkIceState() == NICE_FINISHED) { return; } ELOG_DEBUG("%s, message:closing", toLog()); this->updateIceState(NICE_FINISHED); if (loop_ != NULL) { g_main_loop_quit(loop_); } if (loop_ != NULL) { ELOG_DEBUG("%s, message:Unrefing loop", toLog()); g_main_loop_unref(loop_); loop_ = NULL; } cond_.Set(); listener_ = NULL; m_Thread_.join(); if (agent_ != NULL) { ELOG_DEBUG("%s, message: unrefing agent", toLog()); g_object_unref(agent_); agent_ = NULL; } if (context_ != NULL) { ELOG_DEBUG("%s, message: Unrefing context", toLog()); g_main_context_unref(context_); context_ = NULL; } ELOG_DEBUG("%s, message: closed, this: %p", toLog(), this); } void NiceConnection::queueData(unsigned int component_id, char* buf, int len) { if (this->checkIceState() == NICE_READY) { cCSLock Lock(queueMutex_); if (niceQueue_.size() < 1000) { packetPtr p_(new dataPacket()); memcpy(p_->data, buf, len); p_->comp = component_id; p_->length = len; niceQueue_.push(p_); cond_.Set(); } } } int NiceConnection::sendData(unsigned int compId, const void* buf, int len) { int val = -1; if (this->checkIceState() == NICE_READY) { val = nice_agent_send(agent_, 1, compId, len, reinterpret_cast<const gchar*>(buf)); } if (val != len) { ELOG_DEBUG("%s, message: Sending less data than expected, sent: %d, to_send: %d", toLog(), val, len); } return val; } void NiceConnection::start() { cCSLock Lock(closeMutex_); if (this->checkIceState() != NICE_INITIAL) { return; } context_ = g_main_context_new(); ELOG_DEBUG("%s, message: creating Nice Agent", toLog()); //nice_debug_enable(FALSE); nice_debug_disable(true); // Create a nice agent agent_ = nice_agent_new(context_, NICE_COMPATIBILITY_RFC5245); loop_ = g_main_loop_new(context_, FALSE); m_Thread_ = std::thread(&NiceConnection::mainLoop, this); GValue controllingMode = { 0 }; g_value_init(&controllingMode, G_TYPE_BOOLEAN); g_value_set_boolean(&controllingMode, false); g_object_set_property(G_OBJECT(agent_), "controlling-mode", &controllingMode); GValue checks = { 0 }; g_value_init(&checks, G_TYPE_UINT); g_value_set_uint(&checks, 100); g_object_set_property(G_OBJECT(agent_), "max-connectivity-checks", &checks); if (iceConfig_.stunServer.compare("") != 0 && iceConfig_.stunPort != 0) { GValue val = { 0 }, val2 = { 0 }; g_value_init(&val, G_TYPE_STRING); g_value_set_string(&val, iceConfig_.stunServer.c_str()); g_object_set_property(G_OBJECT(agent_), "stun-server", &val); g_value_init(&val2, G_TYPE_UINT); g_value_set_uint(&val2, iceConfig_.stunPort); g_object_set_property(G_OBJECT(agent_), "stun-server-port", &val2); ELOG_DEBUG("%s, message:setting stun, stunServer: %s, stunPort: %d", toLog(), iceConfig_.stunServer.c_str(), iceConfig_.stunPort); } // Connect the signals g_signal_connect(G_OBJECT(agent_), "candidate-gathering-done", G_CALLBACK(cb_candidate_gathering_done), this); g_signal_connect(G_OBJECT(agent_), "component-state-changed", G_CALLBACK(cb_component_state_changed), this); g_signal_connect(G_OBJECT(agent_), "new-selected-pair", G_CALLBACK(cb_new_selected_pair), this); g_signal_connect(G_OBJECT(agent_), "new-candidate", G_CALLBACK(cb_new_candidate), this); // Create a new stream and start gathering candidates ELOG_DEBUG("%s, message: adding stream, iceComponents: %d", toLog(), iceComponents_); nice_agent_add_stream(agent_, iceComponents_); gchar *ufrag = NULL, *upass = NULL; nice_agent_get_local_credentials(agent_, 1, &ufrag, &upass); ufrag_ = std::string(ufrag); g_free(ufrag); upass_ = std::string(upass); g_free(upass); // Set our remote credentials. This must be done *after* we add a stream. if (username_.compare("") != 0 && password_.compare("") != 0) { ELOG_DEBUG("%s, message: setting remote credentials in constructor, ufrag:%s, pass:%s", toLog(), username_.c_str(), password_.c_str()); this->setRemoteCredentials(username_, password_); } // Set Port Range: If this doesn't work when linking the file libnice.sym has to be modified to include this call if (iceConfig_.minPort != 0 && iceConfig_.maxPort != 0) { ELOG_DEBUG("%s, message: setting port range, minPort: %d, maxPort: %d", toLog(), iceConfig_.minPort, iceConfig_.maxPort); nice_agent_set_port_range(agent_, (guint)1, (guint)1, (guint)iceConfig_.minPort, (guint)iceConfig_.maxPort); } if (iceConfig_.turnServer.compare("") != 0 && iceConfig_.turnPort != 0) { ELOG_DEBUG("%s, message: configuring TURN, turnServer: %s , turnPort: %d, turnUsername: %s, turnPass: %s", toLog(), iceConfig_.turnServer.c_str(), iceConfig_.turnPort, iceConfig_.turnUsername.c_str(), iceConfig_.turnPass.c_str()); for (unsigned int i = 1; i <= iceComponents_ ; i++) { nice_agent_set_relay_info(agent_, 1, i, iceConfig_.turnServer.c_str(), // TURN Server IP iceConfig_.turnPort, // TURN Server PORT iceConfig_.turnUsername.c_str(), // Username iceConfig_.turnPass.c_str(), // Pass NICE_RELAY_TYPE_TURN_UDP); } } if (agent_) { for (unsigned int i = 1; i <= iceComponents_; i++) { nice_agent_attach_recv(agent_, 1, i, context_, cb_nice_recv, this); } } ELOG_DEBUG("%s, message: gathering, this: %p", toLog(), this); nice_agent_gather_candidates(agent_, 1); } void NiceConnection::mainLoop() { // Start gathering candidates and fire event loop ELOG_DEBUG("%s, message: starting g_main_loop, this: %p", toLog(), this); if (agent_ == NULL) { return; } g_main_loop_run(loop_); ELOG_DEBUG("%s, message: finished g_main_loop, this: %p", toLog(), this); } bool NiceConnection::setRemoteCandidates(const std::vector<CandidateInfo> &candidates, bool isBundle) { if (agent_ == NULL) { this->close(); return false; } GSList* candList = NULL; ELOG_DEBUG("%s, message: setting remote candidates, candidateSize: %lu, mediaType: %d", toLog(), candidates.size(), this->mediaType); for (unsigned int it = 0; it < candidates.size(); it++) { NiceCandidateType nice_cand_type; CandidateInfo cinfo = candidates[it]; // If bundle we will add the candidates regardless the mediaType if (cinfo.componentId != 1 || (!isBundle && cinfo.mediaType != this->mediaType )) continue; switch (cinfo.hostType) { case HOST: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; case SRFLX: nice_cand_type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE; break; case PRFLX: nice_cand_type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE; break; case RELAY: nice_cand_type = NICE_CANDIDATE_TYPE_RELAYED; break; default: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; } if (cinfo.hostPort == 0) { continue; } NiceCandidate* thecandidate = nice_candidate_new(nice_cand_type); thecandidate->username = strdup(cinfo.username.c_str()); thecandidate->password = strdup(cinfo.password.c_str()); thecandidate->stream_id = (guint) 1; thecandidate->component_id = cinfo.componentId; thecandidate->priority = cinfo.priority; thecandidate->transport = NICE_CANDIDATE_TRANSPORT_UDP; nice_address_set_from_string(&thecandidate->addr, cinfo.hostAddress.c_str()); nice_address_set_port(&thecandidate->addr, cinfo.hostPort); std::ostringstream host_info; host_info << "hostType: " << cinfo.hostType << ", hostAddress: " << cinfo.hostAddress << ", hostPort: " << cinfo.hostPort; if (cinfo.hostType == RELAY || cinfo.hostType == SRFLX) { nice_address_set_from_string(&thecandidate->base_addr, cinfo.rAddress.c_str()); nice_address_set_port(&thecandidate->base_addr, cinfo.rPort); ELOG_DEBUG("%s, message: adding relay or srflx remote candidate, %s, rAddress: %s, rPort: %d", toLog(), host_info.str().c_str(), cinfo.rAddress.c_str(), cinfo.rPort); } else { ELOG_DEBUG("%s, message: adding remote candidate, %s, priority: %d, componentId: %d, ufrag: %s, pass: %s", toLog(), host_info.str().c_str(), cinfo.priority, cinfo.componentId, cinfo.username.c_str(), cinfo.password.c_str()); } candList = g_slist_prepend(candList, thecandidate); } // TODO(pedro): Set Component Id properly, now fixed at 1 nice_agent_set_remote_candidates(agent_, (guint) 1, 1, candList); #ifndef _DEBUG g_slist_free_full(candList, (GDestroyNotify)&nice_candidate_free); #endif // _DEBUG return true; } void NiceConnection::gatheringDone(uint stream_id) { ELOG_DEBUG("%s, message: gathering done, stream_id: %u", toLog(), stream_id); this->updateIceState(NICE_CANDIDATES_RECEIVED); } void NiceConnection::getCandidate(uint stream_id, uint component_id, const std::string &foundation) { GSList* lcands = nice_agent_get_local_candidates(agent_, stream_id, component_id); // We only want to get the new candidates if (candsDelivered_ <= g_slist_length(lcands)) { lcands = g_slist_nth(lcands, (candsDelivered_)); } for (GSList* iterator = lcands; iterator; iterator = iterator->next) { char address[NICE_ADDRESS_STRING_LEN], baseAddress[NICE_ADDRESS_STRING_LEN]; NiceCandidate *cand = reinterpret_cast<NiceCandidate*>(iterator->data); nice_address_to_string(&cand->addr, address); nice_address_to_string(&cand->base_addr, baseAddress); candsDelivered_++; if (strstr(address, ":") != NULL) { // We ignore IPv6 candidates at this point continue; } CandidateInfo cand_info; cand_info.componentId = cand->component_id; cand_info.foundation = cand->foundation; cand_info.priority = cand->priority; cand_info.hostAddress = std::string(address); cand_info.hostPort = nice_address_get_port(&cand->addr); cand_info.mediaType = mediaType; /* * NICE_CANDIDATE_TYPE_HOST, * NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE, * NICE_CANDIDATE_TYPE_PEER_REFLEXIVE, * NICE_CANDIDATE_TYPE_RELAYED, */ switch (cand->type) { case NICE_CANDIDATE_TYPE_HOST: cand_info.hostType = HOST; break; case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE: cand_info.hostType = SRFLX; cand_info.rAddress = std::string(baseAddress); cand_info.rPort = nice_address_get_port(&cand->base_addr); break; case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE: cand_info.hostType = PRFLX; break; case NICE_CANDIDATE_TYPE_RELAYED: char turnAddres[NICE_ADDRESS_STRING_LEN]; nice_address_to_string(&cand->turn->server, turnAddres); cand_info.hostType = RELAY; cand_info.rAddress = std::string(baseAddress); cand_info.rPort = nice_address_get_port(&cand->base_addr); break; default: break; } cand_info.netProtocol = "udp"; cand_info.transProtocol = std::string(*transportName.get()); cand_info.username = ufrag_; cand_info.password = upass_; // localCandidates->push_back(cand_info); if (this->getNiceListener() != NULL) this->getNiceListener()->onCandidate(cand_info, this); } // for nice_agent_get_local_candidates, the caller owns the returned GSList as well as the candidates // contained within it. // let's free everything in the list, as well as the list. g_slist_free_full(lcands, (GDestroyNotify)&nice_candidate_free); } void NiceConnection::setRemoteCredentials(const std::string& username, const std::string& password) { ELOG_DEBUG("%s, message: setting remote credentials, ufrag: %s, pass: %s", toLog(), username.c_str(), password.c_str()); nice_agent_set_remote_credentials(agent_, (guint) 1, username.c_str(), password.c_str()); } void NiceConnection::setNiceListener(NiceConnectionListener *listener) { this->listener_ = listener; } NiceConnectionListener* NiceConnection::getNiceListener() { return this->listener_; } void NiceConnection::updateComponentState(unsigned int compId, IceState state) { ELOG_DEBUG("%s, message: new ice component state, newState: %u, transportName: %s, componentId %u, iceComponents: %u", toLog(), state, transportName->c_str(), compId, iceComponents_); comp_state_list_[compId] = state; if (state == NICE_READY) { for (unsigned int i = 1; i <= iceComponents_; i++) { if (comp_state_list_[i] != NICE_READY) { return; } } } else if (state == NICE_FAILED) { if (receivedLastCandidate_) { ELOG_WARN("%s, message: component failed, transportName: %s, componentId: %u", toLog(), transportName->c_str(), compId); for (unsigned int i = 1; i <= iceComponents_; i++) { if (comp_state_list_[i] != NICE_FAILED) { return; } } } else { ELOG_WARN("%s, message: failed and not received all candidates, newComponentState:%u", toLog(), state); return; } } this->updateIceState(state); } IceState NiceConnection::checkIceState() { return iceState_; } void NiceConnection::updateIceState(IceState state) { if (state <= iceState_) { if (state != NICE_READY) ELOG_WARN("%s, message: unexpected ice state transition, iceState:%u, newIceState: %u", toLog(), iceState_, state); return; } ELOG_INFO("%s, message: iceState transition, transportName: %s, iceState: %u, newIceState: %u, this: %p", toLog(), transportName->c_str(), this->iceState_, state, this); this->iceState_ = state; switch (iceState_) { case NICE_FINISHED: return; case NICE_FAILED: ELOG_WARN("%s, message: Ice Failed", toLog()); break; case NICE_READY: case NICE_CANDIDATES_RECEIVED: break; default: break; } // Important: send this outside our state lock. Otherwise, serious risk of deadlock. if (this->listener_ != NULL) this->listener_->updateIceState(state, this); } CandidatePair NiceConnection::getSelectedPair() { char ipaddr[NICE_ADDRESS_STRING_LEN]; CandidatePair selectedPair; NiceCandidate* local, *remote; nice_agent_get_selected_pair(agent_, 1, 1, &local, &remote); nice_address_to_string(&local->addr, ipaddr); selectedPair.erizoCandidateIp = std::string(ipaddr); selectedPair.erizoCandidatePort = nice_address_get_port(&local->addr); ELOG_DEBUG("%s, message: selected pair, local_addr: %s, local_port: %d", toLog(), ipaddr, nice_address_get_port(&local->addr)); nice_address_to_string(&remote->addr, ipaddr); selectedPair.clientCandidateIp = std::string(ipaddr); selectedPair.clientCandidatePort = nice_address_get_port(&remote->addr); ELOG_INFO("%s, message: selected pair, remote_addr: %s, remote_port: %d", toLog(), ipaddr, nice_address_get_port(&remote->addr)); return selectedPair; } void NiceConnection::setReceivedLastCandidate(bool hasReceived) { ELOG_DEBUG("%s, message: setting hasReceivedLastCandidate, hasReceived: %u", toLog(), hasReceived); this->receivedLastCandidate_ = hasReceived; } } /* namespace erizo */
35.788571
120
0.685295
MrsZ
71efeb962cdec0a3b8a8e5b183162b74971fbcea
558
cpp
C++
qir/qat/Rules/Patterns/AnyPattern.cpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/Rules/Patterns/AnyPattern.cpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/Rules/Patterns/AnyPattern.cpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "Rules/IOperandPrototype.hpp" #include "Rules/Patterns/AnyPattern.hpp" namespace microsoft { namespace quantum { AnyPattern::AnyPattern() = default; AnyPattern::~AnyPattern() = default; bool AnyPattern::match(Value* instr, Captures& captures) const { return success(instr, captures); } AnyPattern::Child AnyPattern::copy() const { return std::make_shared<AnyPattern>(); } } // namespace quantum } // namespace microsoft
21.461538
66
0.68638
troelsfr
71f0a2f96e955c70479d6ea2c73fe6650449df67
3,076
cpp
C++
Code/System/Core/FileSystem/Platform/FileSystem_Win32.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/System/Core/FileSystem/Platform/FileSystem_Win32.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/System/Core/FileSystem/Platform/FileSystem_Win32.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#ifdef _WIN32 #include "../FileSystem.h" #include "System/Core/Platform/PlatformHelpers_Win32.h" #include "System/Core/Algorithm/Hash.h" #include "System/Core/Math/Math.h" #include <windows.h> #include <shlwapi.h> #include <shlobj.h> #include <shellapi.h> #include <fstream> #include "../Time/Timers.h" #include "../Logging/Log.h" //------------------------------------------------------------------------- namespace KRG::FileSystem { char const Path::s_pathDelimiter = '\\'; //------------------------------------------------------------------------- String Path::GetFullPathString( char const* pPath ) { char fullpath[256] = { 0 }; if ( pPath != nullptr && pPath[0] != 0 ) { // Warning: this function is slow, so use sparingly DWORD length = GetFullPathNameA( pPath, 256, fullpath, nullptr ); KRG_ASSERT( length != 0 && length != 255 ); // Ensure directory paths have the final slash appended DWORD const result = GetFileAttributesA( fullpath ); if ( result != INVALID_FILE_ATTRIBUTES && ( result & FILE_ATTRIBUTE_DIRECTORY ) && fullpath[length - 1] != Path::s_pathDelimiter ) { fullpath[length] = Path::s_pathDelimiter; fullpath[length + 1] = 0; } } return String( fullpath ); } //------------------------------------------------------------------------- Path GetCurrentProcessPath() { return Path( Platform::Win32::GetCurrentModulePath() ).GetParentDirectory(); } //------------------------------------------------------------------------- bool LoadFile( Path const& path, TVector<Byte>& fileData ) { KRG_ASSERT( path.IsFile() ); // Open file handle HANDLE hFile = CreateFile( path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr ); if ( hFile == INVALID_HANDLE_VALUE ) { return false; } // Get file size LARGE_INTEGER fileSizeLI; if ( !GetFileSizeEx( hFile, &fileSizeLI ) ) { CloseHandle( hFile ); return false; } // Allocate destination memory size_t const fileSize = (size_t) ( fileSizeLI.QuadPart ); fileData.resize( fileSize ); // Read file static constexpr DWORD const defaultReadBufferSize = 65536; DWORD bytesRead = 0; DWORD remainingBytesToRead = (DWORD) fileSize; Byte* pBuffer = fileData.data(); while ( remainingBytesToRead != 0 ) { DWORD const numBytesToRead = Math::Min( defaultReadBufferSize, remainingBytesToRead ); ReadFile( hFile, pBuffer, numBytesToRead, &bytesRead, nullptr ); pBuffer += bytesRead; remainingBytesToRead -= bytesRead; } CloseHandle( hFile ); return true; } } #endif
31.71134
143
0.516255
JuanluMorales
71f37e064e4f31b9d0fed5724c98725d1715ef6f
2,894
hpp
C++
include/nexus/quic/detail/connection_impl.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
6
2021-10-31T10:33:30.000Z
2022-03-25T20:54:58.000Z
include/nexus/quic/detail/connection_impl.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
include/nexus/quic/detail/connection_impl.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
#pragma once #include <boost/intrusive/list.hpp> #include <nexus/quic/detail/connection_state.hpp> #include <nexus/quic/detail/service.hpp> #include <nexus/quic/detail/stream_impl.hpp> #include <nexus/udp.hpp> struct lsquic_conn; struct lsquic_stream; namespace nexus::quic::detail { struct accept_operation; struct socket_impl; struct connection_impl : public connection_context, public boost::intrusive::list_base_hook<>, public service_list_base_hook { service<connection_impl>& svc; socket_impl& socket; connection_state::variant state; explicit connection_impl(socket_impl& socket); ~connection_impl(); void service_shutdown(); using executor_type = boost::asio::any_io_executor; executor_type get_executor() const; connection_id id(error_code& ec) const; udp::endpoint remote_endpoint(error_code& ec) const; void connect(stream_connect_operation& op); stream_impl* on_connect(lsquic_stream* stream); template <typename Stream, typename CompletionToken> decltype(auto) async_connect(Stream& stream, CompletionToken&& token) { auto& s = stream.impl; return boost::asio::async_initiate<CompletionToken, void(error_code)>( [this, &s] (auto h) { using Handler = std::decay_t<decltype(h)>; using op_type = stream_connect_async<Handler, executor_type>; auto p = handler_allocate<op_type>(h, std::move(h), get_executor(), s); auto op = handler_ptr<op_type, Handler>{p, &p->handler}; connect(*op); op.release(); // release ownership }, token); } void accept(stream_accept_operation& op); stream_impl* on_accept(lsquic_stream* stream); template <typename Stream, typename CompletionToken> decltype(auto) async_accept(Stream& stream, CompletionToken&& token) { auto& s = stream.impl; return boost::asio::async_initiate<CompletionToken, void(error_code)>( [this, &s] (auto h) { using Handler = std::decay_t<decltype(h)>; using op_type = stream_accept_async<Handler, executor_type>; auto p = handler_allocate<op_type>(h, std::move(h), get_executor(), s); auto op = handler_ptr<op_type, Handler>{p, &p->handler}; accept(*op); op.release(); // release ownership }, token); } bool is_open() const; void go_away(error_code& ec); void close(error_code& ec); void on_close(); void on_handshake(int status); void on_remote_goaway(); void on_remote_close(int app_error, uint64_t code); void on_incoming_stream_closed(stream_impl& s); void on_accepting_stream_closed(stream_impl& s); void on_connecting_stream_closed(stream_impl& s); void on_open_stream_closing(stream_impl& s); void on_open_stream_closed(stream_impl& s); void on_closing_stream_closed(stream_impl& s); }; } // namespace nexus::quic::detail
32.886364
81
0.701451
cbodley
71f65b43654fd22565096dbb1c2584d29ee356b3
104
hpp
C++
redvoid/src/Logger.hpp
fictionalist/RED-VOID
01bacd893f095748d784e494c80a6a9c96481acc
[ "MIT" ]
1
2021-01-04T01:31:34.000Z
2021-01-04T01:31:34.000Z
redvoid/src/Logger.hpp
fictionalist/RED-VOID
01bacd893f095748d784e494c80a6a9c96481acc
[ "MIT" ]
null
null
null
redvoid/src/Logger.hpp
fictionalist/RED-VOID
01bacd893f095748d784e494c80a6a9c96481acc
[ "MIT" ]
1
2021-01-05T00:55:47.000Z
2021-01-05T00:55:47.000Z
#pragma once #include <string> namespace Logger { bool init(); void log(std::string pattern, ...); }
13
36
0.663462
fictionalist
71fa3188959942010b1f365a7c1f2e06b69a368c
1,148
hpp
C++
graphExplorer/graphExplorer/lubySequence.hpp
fq00/lubySequenceEAs
6a107de687b3c2e159c8486ccc7eb02385c351c6
[ "MIT" ]
null
null
null
graphExplorer/graphExplorer/lubySequence.hpp
fq00/lubySequenceEAs
6a107de687b3c2e159c8486ccc7eb02385c351c6
[ "MIT" ]
null
null
null
graphExplorer/graphExplorer/lubySequence.hpp
fq00/lubySequenceEAs
6a107de687b3c2e159c8486ccc7eb02385c351c6
[ "MIT" ]
null
null
null
// // lubySequence.hpp // graphExplorer // // Created by Francesco Quinzan on 06.09.17. // Copyright © 2017 Francesco Quinzan. All rights reserved. // #ifndef lubySequence_hpp #define lubySequence_hpp #include <vector> #include <limits> #include <thread> #include "EA.hpp" using namespace std; /* overloaded vector to compute the sum */ class vec : public std::vector<unsigned long>{ public : unsigned long sum(){ unsigned long sum = 0; if(std::vector<unsigned long>::size() != 0){ for(unsigned long i = 0; i < std::vector<unsigned long>::size(); i++) sum = sum + std::vector<unsigned long>::at(i); } return sum; } }; class ls{ //public : /* variables for Luby sequence */ class EA * alg; unsigned long maxStep; class vec sequence; /* make actual Luby Sequence */ void makeSequence(); public: ls(class EA * EA, unsigned long maxStep){ ls::alg = EA; ls::maxStep = maxStep; ls::makeSequence(); } void run(std::vector<unsigned long> *); }; #endif /* lubySequence_hpp */
18.819672
81
0.587979
fq00
9f95c942849cae822a980f8e016e7fb0726c9233
2,903
cpp
C++
tests/world/test_terrain.cpp
Bycob/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
16
2021-03-14T16:30:32.000Z
2022-03-18T13:41:53.000Z
tests/world/test_terrain.cpp
Tzian/world
3ebb33305acd2a751cf44099b07c1e5d47578194
[ "MIT" ]
1
2020-04-21T12:59:37.000Z
2020-04-23T17:49:03.000Z
tests/world/test_terrain.cpp
Tzian/world
3ebb33305acd2a751cf44099b07c1e5d47578194
[ "MIT" ]
4
2020-03-08T14:04:50.000Z
2020-12-03T08:51:04.000Z
#include <catch/catch.hpp> #include <world/core.h> #include <world/terrain.h> using namespace world; TEST_CASE("Terrain - getExactHeightAt", "[terrain]") { Terrain terrain(2); terrain(0, 0) = 1; terrain(0, 1) = 0; terrain(1, 0) = 0; terrain(1, 1) = 1; SECTION("getExactHeightAt trivial coordinates") { REQUIRE(terrain.getExactHeightAt(0, 0) == Approx(1)); REQUIRE(terrain.getExactHeightAt(0, 1) == Approx(0)); REQUIRE(terrain.getExactHeightAt(1, 0) == Approx(0)); REQUIRE(terrain.getExactHeightAt(1, 1) == Approx(1)); } SECTION("getExactHeightAt non trivial coordinates") { REQUIRE(terrain.getExactHeightAt(0.5, 0) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(0, 0.5) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(0.5, 1) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(1, 0.5) == Approx(0.5)); } terrain(0, 0) = 0.1; terrain(0, 1) = 0.4; terrain(1, 0) = 0.5; terrain(1, 1) = 0.7; SECTION("getExactHeightAt trivial coordinates, non trivial heights") { REQUIRE(terrain.getExactHeightAt(0, 0) == Approx(0.1)); REQUIRE(terrain.getExactHeightAt(0, 1) == Approx(0.4)); REQUIRE(terrain.getExactHeightAt(1, 0) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(1, 1) == Approx(0.7)); } SECTION("getExactHeightAt non trivial coordinates, non trivial heights") { std::stringstream str; for (double y = 1; y >= -0.02; y -= 0.05) { for (double x = 0; x <= 1.01; x += 0.05) { str << terrain.getExactHeightAt(x, y) << " "; } str << std::endl; } INFO(str.str()); REQUIRE(terrain.getExactHeightAt(0.5, 0) == Approx(0.3)); REQUIRE(terrain.getExactHeightAt(0, 0.5) == Approx(0.25)); REQUIRE(terrain.getExactHeightAt(0.5, 1) == Approx(0.55)); REQUIRE(terrain.getExactHeightAt(1, 0.5) == Approx(0.6)); } SECTION("Slope") { Terrain terrain2(3); terrain2.setBounds(0, 0, 0, 1, 1, 1); SECTION("X slope") { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { terrain2(x, y) = x / 2.; } } CHECK(terrain2.getSlope(1, 1) == Approx(1)); CHECK(terrain2.getSlope(0, 0) == Approx(1)); } SECTION("X Y slope") { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { terrain2(x, y) = (x + y) / 4.; } } CHECK(terrain2.getSlope(1, 1) == Approx(sqrt(2.) / 2.)); } } } TEST_CASE("Terrain - Mesh generation benchmark", "[terrain][!benchmark]") { Terrain terrain(129); BENCHMARK("Create a mesh") { Mesh *mesh = terrain.createMesh(); delete mesh; } }
31.554348
78
0.529452
Bycob
9f961d3d37347d99a083232bf2ce7b47d1265203
13,941
hpp
C++
tests/functional/coherence/util/ObservableMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/functional/coherence/util/ObservableMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/functional/coherence/util/ObservableMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "common/TestUtils.hpp" #include "mock/CommonMocks.hpp" #include "coherence/lang.ns" #include "coherence/net/NamedCache.hpp" #include "coherence/util/ArrayList.hpp" #include "coherence/util/Filter.hpp" #include "coherence/util/MapEvent.hpp" #include "coherence/util/MapListener.hpp" #include "coherence/util/filter/AlwaysFilter.hpp" #include "coherence/util/filter/NeverFilter.hpp" #include "coherence/util/ObservableMap.hpp" using coherence::net::NamedCache; using coherence::util::ArrayList; using coherence::util::Filter; using coherence::util::MapEvent; using coherence::util::MapListener; using coherence::util::ObservableMap; using coherence::util::filter::AlwaysFilter; using coherence::util::filter::NeverFilter; using namespace mock; using namespace std; namespace { bool matchListenerEvent(ArrayList::View vExpected, ArrayList::View vActual) { MapEvent::View vExpectedEvent = cast<MapEvent::View>(vExpected->get(0)); MapEvent::View vActualEvent = cast<MapEvent::View>(vActual->get(0)); // cout << "\n\n\n************************************************************\n\n\n"; // cout << vExpectedEvent->getKey() << " : " << vActualEvent->getKey() << endl; // cout << vExpectedEvent->getId() << " : " << vActualEvent->getId() << endl; // cout << vExpectedEvent->getOldValue() << " : " << vActualEvent->getOldValue() << endl; // cout << vExpectedEvent->getNewValue() << " : " << vActualEvent->getNewValue() << endl; // cout << vExpectedEvent->getMap() << " : " << vActualEvent->getMap() << endl; return Object::equals(vExpectedEvent->getKey(), vActualEvent->getKey()) && vExpectedEvent->getId() == vActualEvent->getId() && Object::equals(vExpectedEvent->getOldValue(), vActualEvent->getOldValue()) && Object::equals(vExpectedEvent->getNewValue(), vActualEvent->getNewValue()) && vExpectedEvent->getMap() == vActualEvent->getMap(); } } class ObservableMapTest : public CxxTest::TestSuite { public: void testKeyListener() { NamedCache::Handle hCache = ensureCleanCache("dist-observable-map"); // the mock which receives the events MockMapListener::Handle hMockListener = MockMapListener::create(); // the mock used in verifying the MapEvent which is passed to the listener MockMapEvent::Handle hMockMapEvent = MockMapEvent::create(); // map key Object::View vKey = String::create("key"); // values String::View vsInsertedVal = String::create("inserted-val"); String::View vsUpdatedVal = String::create("updated-val"); // set mock listener expectations hMockListener->setStrict(true); hMockListener->entryInserted(hMockMapEvent); // use an argument matcher to assert MapEvent state hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryUpdated(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryDeleted(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->replay(); // setup mock for pattern matcher. hMockMapEvent->setStrict(true); // insert hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_inserted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); // update hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_updated); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); //delete hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_deleted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); hMockMapEvent->replay(); hCache->addKeyListener(hMockListener, vKey, false); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); int64_t nInitialTime = System::currentTimeMillis(); bool fResult = false; while (!fResult && System::currentTimeMillis() - nInitialTime < 10000) { fResult = hMockListener->verifyAndReturnResult(); Thread::sleep(5); } // remove the listener and ensure that further events aren't received hCache->removeKeyListener(hMockListener, vKey); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); hMockListener->verify(); } void testFilterListenerNullFilter() { NamedCache::Handle hCache = ensureCleanCache("dist-observable-map"); // the mock which receives the events MockMapListener::Handle hMockListener = MockMapListener::create(); // the mock used in verifying the MapEvent which is passed to the listener MockMapEvent::Handle hMockMapEvent = MockMapEvent::create(); // map key Object::View vKey = String::create("key"); // values String::View vsInsertedVal = String::create("inserted-val"); String::View vsUpdatedVal = String::create("updated-val"); // set mock listener expectations hMockListener->setStrict(true); hMockListener->entryInserted(hMockMapEvent); // use an argument matcher to assert MapEvent state hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryUpdated(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryDeleted(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->replay(); // setup mock for pattern matcher. hMockMapEvent->setStrict(true); // insert hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_inserted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); // update hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_updated); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); //delete hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_deleted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); hMockMapEvent->replay(); hCache->addFilterListener(hMockListener); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); int64_t nInitialTime = System::currentTimeMillis(); bool fResult = false; while (!fResult && System::currentTimeMillis() - nInitialTime < 10000) { fResult = hMockListener->verifyAndReturnResult(); Thread::sleep(5); } // remove the listener and ensure that further events aren't received hCache->removeFilterListener(hMockListener); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); hMockListener->verify(); } void testFilterListener() { NamedCache::Handle hCache = ensureCleanCache("dist-observable-map"); // the mock which receives the events MockMapListener::Handle hMockListener = MockMapListener::create(); // the mock which shouldn't receive any events due to NeverFilter MockMapListener::Handle hMockNeverListener = MockMapListener::create(); // the mock used in verifying the MapEvent which is passed to the listener MockMapEvent::Handle hMockMapEvent = MockMapEvent::create(); // filter always evaluates to true Filter::View vAlwaysFilter = AlwaysFilter::create(); // filter always evaluates to false Filter::View vNeverFilter = NeverFilter::create(); // map key Object::View vKey = String::create("key"); // values String::View vsInsertedVal = String::create("inserted-val"); String::View vsUpdatedVal = String::create("updated-val"); // set mock listener expectations hMockListener->setStrict(true); hMockListener->entryInserted(hMockMapEvent); // use an argument matcher to assert MapEvent state hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryUpdated(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryDeleted(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->replay(); // mock listener with NeverFilter hMockNeverListener->setStrict(true); hMockNeverListener->replay(); // setup mock for pattern matcher. hMockMapEvent->setStrict(true); // insert hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_inserted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); // update hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_updated); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); //delete hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_deleted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); hMockMapEvent->replay(); hCache->addFilterListener(hMockListener, vAlwaysFilter); hCache->addFilterListener(hMockNeverListener, vNeverFilter); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); int64_t nInitialTime = System::currentTimeMillis(); bool fResult = false; while (!fResult && System::currentTimeMillis() - nInitialTime < 10000) { fResult = hMockListener->verifyAndReturnResult(); Thread::sleep(5); } // remove the listener and ensure that further events aren't received hCache->removeFilterListener(hMockListener, vAlwaysFilter); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); hMockListener->verify(); } };
42.895385
94
0.604476
chpatel3
9fa0c153fc675b4efb68ca66ef5bc763a8c62a69
582
cpp
C++
engine/src/awesome/editor/menu_items/save_scene_as_menu_item.cpp
vitodtagliente/AwesomeEngine
eff06dbad1c4a168437f69800629a7e20619051c
[ "MIT" ]
3
2019-08-15T18:57:20.000Z
2020-01-09T22:19:26.000Z
engine/src/awesome/editor/menu_items/save_scene_as_menu_item.cpp
vitodtagliente/AwesomeEngine
eff06dbad1c4a168437f69800629a7e20619051c
[ "MIT" ]
null
null
null
engine/src/awesome/editor/menu_items/save_scene_as_menu_item.cpp
vitodtagliente/AwesomeEngine
eff06dbad1c4a168437f69800629a7e20619051c
[ "MIT" ]
null
null
null
#include "save_scene_as_menu_item.h" #include <awesome/data/archive.h> #include <awesome/asset/asset.h> #include <awesome/encoding/json.h> #include <awesome/entity/world.h> namespace editor { void SaveSceneAsMenuItem::render() { m_saveFileDialog.render(); } void SaveSceneAsMenuItem::execute() { m_saveFileDialog.open("Save Scene as...", Asset::getExtensionByType(Asset::Type::Scene), [](const std::filesystem::path& path) -> void { if (!path.string().empty()) { World::instance().save(path); } } ); } REFLECT_MENU_ITEM(SaveSceneAsMenuItem) }
20.785714
136
0.69244
vitodtagliente
9fa77f7f0f4bb47b995986a46df2dc868c12fe62
16,389
cpp
C++
Source/Lutefisk3D/Graphics/Technique.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
2
2018-04-14T19:05:23.000Z
2020-05-10T22:42:12.000Z
Source/Lutefisk3D/Graphics/Technique.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
4
2015-06-19T22:32:07.000Z
2017-04-05T06:01:50.000Z
Source/Lutefisk3D/Graphics/Technique.cpp
nemerle/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
1
2015-12-27T15:36:10.000Z
2015-12-27T15:36:10.000Z
// // Copyright (c) 2008-2017 the Urho3D project. // // 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 "Technique.h" #include "Material.h" #include "Lutefisk3D/Core/Context.h" #include "Graphics.h" #include "GraphicsDefs.h" #include "Lutefisk3D/IO/Log.h" #include "Lutefisk3D/Core/ProcessUtils.h" #include "Lutefisk3D/Core/StringUtils.h" #include "Lutefisk3D/Core/Profiler.h" #include "Lutefisk3D/Resource/ResourceCache.h" #include "ShaderVariation.h" #include "Lutefisk3D/Resource/XMLFile.h" namespace Urho3D { const char* blendModeNames[MAX_BLENDMODES+1] = { "replace", "add", "multiply", "alpha", "addalpha", "premulalpha", "invdestalpha", "subtract", "subtractalpha", "zeroinvsrc", nullptr }; static const char* compareModeNames[MAX_COMPAREMODES+1] = { "always", "equal", "notequal", "less", "lessequal", "greater", "greaterequal", nullptr }; static const char* lightingModeNames[] = { "unlit", "pervertex", "perpixel", nullptr }; Pass::Pass(const QString& name) : blendMode_(BLEND_REPLACE), cullMode_(MAX_CULLMODES), depthTestMode_(CMP_LESSEQUAL), lightingMode_(LIGHTING_UNLIT), shadersLoadedFrameNumber_(0), alphaToCoverage_(false), depthWrite_(true) { name_ = name.toLower(); index_ = Technique::GetPassIndex(name_); // Guess default lighting mode from pass name if (index_ == Technique::basePassIndex || index_ == Technique::alphaPassIndex || index_ == Technique::materialPassIndex || index_ == Technique::deferredPassIndex) lightingMode_ = LIGHTING_PERVERTEX; else if (index_ == Technique::lightPassIndex || index_ == Technique::litBasePassIndex || index_ == Technique::litAlphaPassIndex) lightingMode_ = LIGHTING_PERPIXEL; } Pass::~Pass() { } /// Set blend mode. void Pass::SetBlendMode(BlendMode mode) { blendMode_ = mode; } /// Set culling mode override. By default culling mode is read from the material instead. Set the illegal culling mode MAX_CULLMODES to disable override again. void Pass::SetCullMode(CullMode mode) { cullMode_ = mode; } /// Set depth compare mode. void Pass::SetDepthTestMode(CompareMode mode) { depthTestMode_ = mode; } /// Set pass lighting mode, affects what shader variations will be attempted to be loaded. void Pass::SetLightingMode(PassLightingMode mode) { lightingMode_ = mode; } /// Set depth write on/off. void Pass::SetDepthWrite(bool enable) { depthWrite_ = enable; } /// Set alpha-to-coverage on/off. void Pass::SetAlphaToCoverage(bool enable) { alphaToCoverage_ = enable; } /// Set vertex shader name. void Pass::SetVertexShader(const QString& name) { vertexShaderName_ = name; ReleaseShaders(); } /// Set pixel shader name. void Pass::SetPixelShader(const QString& name) { pixelShaderName_ = name; ReleaseShaders(); } /// Set vertex shader defines. Separate multiple defines with spaces. void Pass::SetVertexShaderDefines(const QString& defines) { vertexShaderDefines_ = defines; ReleaseShaders(); } /// Set pixel shader defines. Separate multiple defines with spaces. void Pass::SetPixelShaderDefines(const QString& defines) { pixelShaderDefines_ = defines; ReleaseShaders(); } /// Set vertex shader define excludes. Use to mark defines that the shader code will not recognize, to prevent compiling redundant shader variations. void Pass::SetVertexShaderDefineExcludes(const QString& excludes) { vertexShaderDefineExcludes_ = excludes; ReleaseShaders(); } /// Set pixel shader define excludes. Use to mark defines that the shader code will not recognize, to prevent compiling redundant shader variations. void Pass::SetPixelShaderDefineExcludes(const QString& excludes) { pixelShaderDefineExcludes_ = excludes; ReleaseShaders(); } /// Reset shader pointers. void Pass::ReleaseShaders() { vertexShaders_.clear(); pixelShaders_.clear(); extraVertexShaders_.clear(); extraPixelShaders_.clear(); } /// Mark shaders loaded this frame. void Pass::MarkShadersLoaded(unsigned frameNumber) { shadersLoadedFrameNumber_ = frameNumber; } QString Pass::GetEffectiveVertexShaderDefines() const { // Prefer to return just the original defines if possible if (vertexShaderDefineExcludes_.isEmpty()) return vertexShaderDefines_; QStringList vsDefines = vertexShaderDefines_.split(' '); QStringList vsExcludes = vertexShaderDefineExcludes_.split(' '); for (unsigned i = 0; i < vsExcludes.size(); ++i) vsDefines.removeAll(vsExcludes[i]); return vsDefines.join(" "); } QString Pass::GetEffectivePixelShaderDefines() const { // Prefer to return just the original defines if possible if (pixelShaderDefineExcludes_.isEmpty()) return pixelShaderDefines_; QStringList psDefines = pixelShaderDefines_.split(' '); QStringList psExcludes = pixelShaderDefineExcludes_.split(' '); for (unsigned i = 0; i < psExcludes.size(); ++i) psDefines.removeAll(psExcludes[i]); return psDefines.join(" "); } std::vector<SharedPtr<ShaderVariation> >& Pass::GetVertexShaders(const StringHash& extraDefinesHash) { // If empty hash, return the base shaders if (!extraDefinesHash.Value()) return vertexShaders_; return extraVertexShaders_[extraDefinesHash]; } std::vector<SharedPtr<ShaderVariation> >& Pass::GetPixelShaders(const StringHash& extraDefinesHash) { if (!extraDefinesHash.Value()) return pixelShaders_; return extraPixelShaders_[extraDefinesHash]; } unsigned Technique::basePassIndex = 0; unsigned Technique::alphaPassIndex = 0; unsigned Technique::materialPassIndex = 0; unsigned Technique::deferredPassIndex = 0; unsigned Technique::lightPassIndex = 0; unsigned Technique::litBasePassIndex = 0; unsigned Technique::litAlphaPassIndex = 0; unsigned Technique::shadowPassIndex = 0; HashMap<QString, unsigned> Technique::passIndices; Technique::Technique(Context* context) : Resource(context) { } Technique::~Technique() { } void Technique::RegisterObject(Context* context) { context->RegisterFactory<Technique>(); } bool Technique::BeginLoad(Deserializer& source) { passes_.clear(); cloneTechniques_.clear(); SetMemoryUse(sizeof(Technique)); SharedPtr<XMLFile> xml(new XMLFile(context_)); if (!xml->Load(source)) return false; XMLElement rootElem = xml->GetRoot(); QString globalVS = rootElem.GetAttribute("vs"); QString globalPS = rootElem.GetAttribute("ps"); QString globalVSDefines = rootElem.GetAttribute("vsdefines"); QString globalPSDefines = rootElem.GetAttribute("psdefines"); // End with space so that the pass-specific defines can be appended if (!globalVSDefines.isEmpty()) globalVSDefines += ' '; if (!globalPSDefines.isEmpty()) globalPSDefines += ' '; XMLElement passElem = rootElem.GetChild("pass"); for (;passElem; passElem = passElem.GetNext("pass")) { if (!passElem.HasAttribute("name")) { URHO3D_LOGERROR("Missing pass name"); continue; } Pass* newPass = CreatePass(passElem.GetAttribute("name")); // Append global defines only when pass does not redefine the shader if (passElem.HasAttribute("vs")) { newPass->SetVertexShader(passElem.GetAttribute("vs")); newPass->SetVertexShaderDefines(passElem.GetAttribute("vsdefines")); } else { newPass->SetVertexShader(globalVS); newPass->SetVertexShaderDefines(globalVSDefines + passElem.GetAttribute("vsdefines")); } if (passElem.HasAttribute("ps")) { newPass->SetPixelShader(passElem.GetAttribute("ps")); newPass->SetPixelShaderDefines(passElem.GetAttribute("psdefines")); } else { newPass->SetPixelShader(globalPS); newPass->SetPixelShaderDefines(globalPSDefines + passElem.GetAttribute("psdefines")); } newPass->SetVertexShaderDefineExcludes(passElem.GetAttribute("vsexcludes")); newPass->SetPixelShaderDefineExcludes(passElem.GetAttribute("psexcludes")); if (passElem.HasAttribute("lighting")) { QString lighting = passElem.GetAttributeLower("lighting"); newPass->SetLightingMode((PassLightingMode)GetStringListIndex(lighting, lightingModeNames, LIGHTING_UNLIT)); } if (passElem.HasAttribute("blend")) { QString blend = passElem.GetAttributeLower("blend"); newPass->SetBlendMode((BlendMode)GetStringListIndex(blend, blendModeNames, BLEND_REPLACE)); } if (passElem.HasAttribute("cull")) { QString cull = passElem.GetAttributeLower("cull"); newPass->SetCullMode((CullMode)GetStringListIndex(cull, cullModeNames, MAX_CULLMODES)); } if (passElem.HasAttribute("depthtest")) { QString depthTest = passElem.GetAttributeLower("depthtest"); if (depthTest == "false") newPass->SetDepthTestMode(CMP_ALWAYS); else newPass->SetDepthTestMode((CompareMode)GetStringListIndex(depthTest, compareModeNames, CMP_LESS)); } if (passElem.HasAttribute("depthwrite")) newPass->SetDepthWrite(passElem.GetBool("depthwrite")); if (passElem.HasAttribute("alphatocoverage")) newPass->SetAlphaToCoverage(passElem.GetBool("alphatocoverage")); } return true; } void Technique::ReleaseShaders() { for (SharedPtr<Pass> & pass : passes_) { if(pass) pass->ReleaseShaders(); } } SharedPtr<Technique> Technique::Clone(const QString& cloneName) const { SharedPtr<Technique> ret(new Technique(context_)); ret->SetName(cloneName); // Deep copy passes for (const auto &i : passes_) { Pass* srcPass = i.Get(); if (!srcPass) continue; Pass* newPass = ret->CreatePass(srcPass->GetName()); newPass->SetBlendMode(srcPass->GetBlendMode()); newPass->SetDepthTestMode(srcPass->GetDepthTestMode()); newPass->SetLightingMode(srcPass->GetLightingMode()); newPass->SetDepthWrite(srcPass->GetDepthWrite()); newPass->SetAlphaToCoverage(srcPass->GetAlphaToCoverage()); newPass->SetVertexShader(srcPass->GetVertexShader()); newPass->SetPixelShader(srcPass->GetPixelShader()); newPass->SetVertexShaderDefines(srcPass->GetVertexShaderDefines()); newPass->SetPixelShaderDefines(srcPass->GetPixelShaderDefines()); newPass->SetVertexShaderDefineExcludes(srcPass->GetVertexShaderDefineExcludes()); newPass->SetPixelShaderDefineExcludes(srcPass->GetPixelShaderDefineExcludes()); } return ret; } Pass* Technique::CreatePass(const QString& name) { Pass* oldPass = GetPass(name); if (oldPass) return oldPass; SharedPtr<Pass> newPass(new Pass(name)); unsigned passIndex = newPass->GetIndex(); //TODO: passes_ is essentialy an pass_id => Pass dictionary, mark it as one if (passIndex >= passes_.size()) passes_.resize(passIndex + 1); passes_[passIndex] = newPass; // Calculate memory use now SetMemoryUse(unsigned(sizeof(Technique) + GetNumPasses() * sizeof(Pass))); return newPass; } void Technique::RemovePass(const QString& name) { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); if (i == passIndices.end()) return; if (MAP_VALUE(i) < passes_.size() && passes_[MAP_VALUE(i)].Get()) { passes_[MAP_VALUE(i)].Reset(); SetMemoryUse((unsigned)(sizeof(Technique) + GetNumPasses() * sizeof(Pass))); } } bool Technique::HasPass(const QString& name) const { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); return i != passIndices.end() ? HasPass(MAP_VALUE(i)) : false; } Pass* Technique::GetPass(const QString& name) const { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); return i != passIndices.end() ? GetPass(MAP_VALUE(i)) : nullptr; } Pass* Technique::GetSupportedPass(const QString& name) const { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); return i != passIndices.end() ? GetSupportedPass(MAP_VALUE(i)) : nullptr; } unsigned Technique::GetNumPasses() const { unsigned ret = 0; for (std::vector<SharedPtr<Pass> >::const_iterator i = passes_.begin(); i != passes_.end(); ++i) { if (i->Get()) ++ret; } return ret; } std::vector<QString> Technique::GetPassNames() const { std::vector<QString> ret; ret.reserve(passes_.size()); for (const SharedPtr<Pass> &pass : passes_) { if (pass) ret.push_back(pass->GetName()); } return ret; } std::vector<Pass*> Technique::GetPasses() const { std::vector<Pass*> ret; ret.reserve(passes_.size()); for (const SharedPtr<Pass> &pass : passes_) { if (pass) ret.push_back(pass); } return ret; } SharedPtr<Technique> Technique::CloneWithDefines(const QString& vsDefines, const QString& psDefines) { // Return self if no actual defines if (vsDefines.isEmpty() && psDefines.isEmpty()) return SharedPtr<Technique>(this); std::pair<StringHash, StringHash> key = std::make_pair(StringHash(vsDefines), StringHash(psDefines)); // Return existing if possible auto iter = cloneTechniques_.find(key); if (iter != cloneTechniques_.end()) return MAP_VALUE(iter); // Set same name as the original for the clones to ensure proper serialization of the material. This should not be a problem // since the clones are never stored to the resource cache iter = cloneTechniques_.insert(std::make_pair(key, Clone(GetName()))).first; for (Pass *pass : MAP_VALUE(iter)->passes_) { if (!pass) continue; if (!vsDefines.isEmpty()) pass->SetVertexShaderDefines(pass->GetVertexShaderDefines() + " " + vsDefines); if (!psDefines.isEmpty()) pass->SetPixelShaderDefines(pass->GetPixelShaderDefines() + " " + psDefines); } return MAP_VALUE(iter); } unsigned Technique::GetPassIndex(const QString& passName) { // Initialize built-in pass indices on first call if (passIndices.empty()) { basePassIndex = passIndices["base"] = 0; alphaPassIndex = passIndices["alpha"] = 1; materialPassIndex = passIndices["material"] = 2; deferredPassIndex = passIndices["deferred"] = 3; lightPassIndex = passIndices["light"] = 4; litBasePassIndex = passIndices["litbase"] = 5; litAlphaPassIndex = passIndices["litalpha"] = 6; shadowPassIndex = passIndices["shadow"] = 7; } QString nameLower = passName.toLower(); HashMap<QString, unsigned>::iterator i = passIndices.find(nameLower); if (i != passIndices.end()) return MAP_VALUE(i); unsigned newPassIndex = passIndices.size(); passIndices[nameLower] = newPassIndex; return newPassIndex; } }
30.981096
159
0.680273
Lutefisk3D
9fab6047b372e0878f52e5aaa59da9c9b6b8641e
1,777
cpp
C++
cpp/A0153/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:13.000Z
2021-11-26T14:34:34.000Z
cpp/A0153/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:49.000Z
2021-11-28T11:28:49.000Z
cpp/A0153/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
null
null
null
// URL : https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/ // Author : Modnar // Date : 2020/03/14 // Thanks : armeria(@leetcode.cn) #include <bits/stdc++.h> /* ************************* */ /** * 暴力搜索 * 直接遍历,获取最小元素即可。 * 本题存在一个简单优化,当发现某两个值之间发生“递减”,则可直接返回最小值。 */ // Complexity: Time: O(n) Space: O(1) // Time: 8ms(44.19%) Memory: 11.5MB(5.04%) class Solution { public: int findMin(std::vector<int> &nums) { // 本题不存在nums为空的情况,故此处可免去判断以加速 int min_val = nums[0]; for (int i = 0; i != nums.size(); ++i) if (nums[i] < min_val) return nums[i]; return min_val; } }; /* ************************* */ /** * 二分搜索 * 充分利用题中所提到的数组元素不重复,这样,对于任意两个元素均可进行“偏序比较”。 * 首先需要明确以下几点:二分过程中,左右端点值为l、r,中间值为mid。如果nums[mid] > * nums[r],说明最小值一定在右半部分(相对mid来说);否则(nums[mid] < nums[r]),就说明 * 最小值一定在左半部分(相对mid来说)。 * 细分来说,思考以下方面: * 1. 循环条件l < r,且l <= mid,mid更贴近l,而mid < r; * 2. 在while循环内,nums[mid]要么小于nums[r],要么大于,而不会等于,这也就是循环 * 内直接使用else判断的原因。 */ namespace AnsOne { // Thanks: armeria(@leetcode.cn) // Solution: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/solution/er-fen-cha-zhao-wei-shi-yao-zuo-you-bu-dui-cheng-z/ // Time: 0ms(100.00%) Memory: 11.7MB(5.04%) class Solution { public: int findMin(std::vector<int> &nums) { int l = 0, r = nums.size() - 1; while (l < r) { int mid = l + ((r - l) >> 1); if (nums[mid] > nums[r]) { l = mid + 1; } else { r = mid; } } return nums[l]; } }; } int main(int argc, const char *argv[]) { return EXIT_SUCCESS; }
26.924242
147
0.517727
Modnars
9fb0b2bd4169c0347f4c5c58708b5fc551f12dbe
12,100
cc
C++
test/common/t__xdrbuf.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
3
2016-05-09T15:29:29.000Z
2017-11-22T06:16:18.000Z
test/common/t__xdrbuf.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
test/common/t__xdrbuf.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2008,2009,2010, CodeSLoop Team Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 t__xdrbuf.cc @brief Tests to verify xdr utilities */ #ifndef DEBUG #define DEBUG #endif /* DEBUG */ #include "codesloop/common/xdrbuf.hh" #include "codesloop/common/pbuf.hh" #include "codesloop/common/zfile.hh" #include "codesloop/common/mpool.hh" #include "codesloop/common/common.h" #include "codesloop/common/test_timer.h" #include "codesloop/common/str.hh" #include "codesloop/common/ustr.hh" #include "codesloop/common/exc.hh" #include <assert.h> using namespace csl::common; /** @brief contains tests related to xdr buffer */ namespace test_xdrbuf { /** @test baseline for performance comparison */ void baseline() { pbuf pb; xdrbuf xb(pb); assert( xb.position() == 0 ); } /** @test copy constructor */ void test_copy() { pbuf pb; xdrbuf xb(pb); xdrbuf xc(xb); assert( xb == xc ); } /** @test integer de/serialization */ void test_longlong() { pbuf pb; xdrbuf xb(pb); uint64_t a = 0xdeadbabedeadbabeLL; uint64_t b; xb << a; xb.rewind(); xb >> b; assert( a == b ); assert( xb.position() == sizeof(int64_t) ); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); } /** @test integer de/serialization */ void test_int() { pbuf pb; xdrbuf xb(pb); unsigned int a = 0xbaddad; unsigned int b; xb << a; xb.rewind(); xb >> b; assert( a == b ); assert( xb.position() == sizeof(int32_t) ); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); } /** @test string de/serialization */ void test_string() { pbuf pb; xdrbuf xb(pb); xb << L"Hello World"; str hw; xb.rewind(); assert( pb.size() == sizeof(wchar_t)*11+sizeof(int64_t) ); xb >> hw; assert( hw.size() == 11 ); assert( hw == "Hello World" ); assert( xb.position() > 10 ); /* save position */ xdrbuf xx(xb); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); caught = false; try { /* add invalid pointer */ xx << reinterpret_cast<const char *>(0); str zz; xx >> zz; } catch( csl::common::exc e ) { str es; e.to_string(es); FPRINTF(stderr,L"Exception caught: %ls\n",es.c_str()); caught = true; } /* this should not throw an exception, will add as zero length string */ assert( caught == false ); } /** @test string de/serialization */ void test_ustring() { pbuf pb; xdrbuf xb(pb); xb << "Hello World"; ustr hw; xb.rewind(); assert( pb.size() == 20 ); xb >> hw; assert( hw.size() == 11 ); assert( hw == "Hello World" ); assert( xb.position() > 10 ); /* save position */ xdrbuf xx(xb); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); caught = false; try { /* add invalid pointer */ xx << reinterpret_cast<const char *>(0); str zz; xx >> zz; } catch( csl::common::exc e ) { str es; e.to_string(es); FPRINTF(stderr,L"Exception caught: %ls\n",es.c_str()); caught = true; } /* this should not throw an exception, will add as zero length string */ assert( caught == false ); } /** @test xdrbuf::bindata_t de/serialization */ void test_bin() { zfile zf; assert( zf.read_file("random.204800") == true ); assert( zf.get_size() == 204800 ); mpool<> mp; unsigned char * ptr = reinterpret_cast<unsigned char *>(mp.allocate(zf.get_size())); assert( ptr != 0 ); assert( zf.get_data(ptr) == true ); pbuf pb; xdrbuf xb(pb); xb << xdrbuf::bindata_t(ptr,zf.get_size()); unsigned char * ptr2 = reinterpret_cast<unsigned char *>(mp.allocate(zf.get_size())); assert( ptr2 != 0 ); xb.rewind(); uint64_t sz; assert( xb.get_data(ptr2,sz,204808) == true ); assert( xb.position() == 204808 ); assert( sz == zf.get_size() ); assert( sz == 204800 ); assert( ::memcmp( ptr, ptr2, static_cast<size_t>(sz) ) == 0 ); } /** @test pbuf de/serialization */ void test_pbuf() { zfile zf; assert( zf.read_file("random.2048") == true ); assert( zf.get_size() == 2048 ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); pbuf pb; xdrbuf xb(pb); xb << ptr; assert( pb.size() == 2056 ); xb.rewind(); pbuf ptr2; xb >> ptr2; assert( ptr2.size() == 2048 ); assert( ptr == ptr2 ); } /** @test reading 2048 bytes of garbage integer */ void garbage_int_small() { zfile zf; assert( zf.read_file("random.2048") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { unsigned int i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* integer garbage cannot be validated, thus eof condition is checked */ assert( exc_caught == csl::common::exc::rs_xdr_eof ); } /** @test reading 204800 bytes of garbage integer */ void garbage_int_large() { zfile zf; assert( zf.read_file("random.204800") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 204800 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); unsigned long j = 0; while( true ) { unsigned int i; xb >> i; j += sizeof(int32_t); assert( xb.position() == j ); }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* integer garbage cannot be validated, thus eof condition is checked */ assert( exc_caught == csl::common::exc::rs_xdr_eof ); } /** @test reading 2048 bytes of garbage string */ void garbage_string_small() { zfile zf; assert( zf.read_file("random.2048") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { str i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage string does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } /** @test reading 204800 bytes of garbage string */ void garbage_string_large() { zfile zf; assert( zf.read_file("random.204800") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 204800 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { str i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage string does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } /** @test reading 2048 bytes of garbage binary data to pbuf */ void garbage_pbuf_small() { zfile zf; assert( zf.read_file("random.2048") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { pbuf i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage binary data does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } /** @test reading 204800 bytes of garbage binary data to pbuf */ void garbage_pbuf_large() { zfile zf; assert( zf.read_file("random.204800") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 204800 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { pbuf i; xb >> i; assert( i.size() == xb.position() ); }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage binary data does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } } // end of test_xdrbuf using namespace test_xdrbuf; int main() { csl_common_print_results( "baseline ", csl_common_test_timer_v0(baseline),"" ); csl_common_print_results( "test_copy ", csl_common_test_timer_v0(test_copy),"" ); csl_common_print_results( "test_int ", csl_common_test_timer_v0(test_int),"" ); csl_common_print_results( "test_longlong ", csl_common_test_timer_v0(test_longlong),"" ); csl_common_print_results( "test_string ", csl_common_test_timer_v0(test_string),"" ); csl_common_print_results( "test_ustring ", csl_common_test_timer_v0(test_ustring),"" ); csl_common_print_results( "test_bin ", csl_common_test_timer_v0(test_bin),"" ); csl_common_print_results( "test_pbuf ", csl_common_test_timer_v0(test_pbuf),"" ); csl_common_print_results( "garbage_int_small ", csl_common_test_timer_v0(garbage_int_small),"" ); csl_common_print_results( "garbage_int_large ", csl_common_test_timer_v0(garbage_int_large),"" ); csl_common_print_results( "garbage_string_small ", csl_common_test_timer_v0(garbage_string_small),"" ); csl_common_print_results( "garbage_string_large ", csl_common_test_timer_v0(garbage_string_large),"" ); csl_common_print_results( "garbage_pbuf_small ", csl_common_test_timer_v0(garbage_pbuf_small),"" ); csl_common_print_results( "garbage_pbuf_large ", csl_common_test_timer_v0(garbage_pbuf_large),"" ); return 0; } /* EOF */
23.495146
105
0.594215
codesloop
9fb10a609bba3beeed23f82451423f8c42959681
1,227
cpp
C++
_includes/leet310/leet310_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet310/leet310_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet310/leet310_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { vector<int> vec[n+1]; int degree[n+1]; for(int i=0;i<=n;i++) degree[i]=0; for(int i=0;i<n-1;i++){ int a=edges[i].first; int b=edges[i].second; vec[a].push_back(b); vec[b].push_back(a); degree[a]++; degree[b]++; } queue<int >qq; for(int i=0;i<n;i++) if(degree[i]==1) qq.push(i); while(n>2){ int sz=qq.size(); for(int i=0;i<sz;i++){ int temp=qq.front();//cout<<temp<<" "; qq.pop(); n--; for(auto j=vec[temp].begin();j!=vec[temp].end();j++){ degree[*j]--; if(degree[*j]==1) qq.push(*j); } } } vector<int> rs; if(qq.empty()){rs.push_back(0);return rs;} while(!qq.empty()){ rs.push_back(qq.front()); qq.pop(); } return rs; } };
24.54
74
0.354523
mingdaz
9fb38af70a117431bbc2af22d78c136261cc0063
1,656
cpp
C++
src/http/http_request.cpp
Mojiajun/tinyreactor
94adab8941b1d4cf46297adec9f14d7ce26c44d8
[ "MIT" ]
1
2020-10-19T07:57:32.000Z
2020-10-19T07:57:32.000Z
src/http/http_request.cpp
Mojiajun/tinyreactor
94adab8941b1d4cf46297adec9f14d7ce26c44d8
[ "MIT" ]
null
null
null
src/http/http_request.cpp
Mojiajun/tinyreactor
94adab8941b1d4cf46297adec9f14d7ce26c44d8
[ "MIT" ]
null
null
null
// // Created by mojiajun on 2020/3/6. // #include "http_request.h" using namespace tinyreactor; bool HttpRequest::setMethod(const char *start, const char *end) { assert(method_ == kInvalid); std::string m(start, end); if (m == "GET") { method_ = kGet; } else if (m == "POST") { method_ = kPost; } else if (m == "HEAD") { method_ = kHead; } else if (m == "PUT") { method_ = kPut; } else if (m == "DELETE") { method_ = kDelete; } else { method_ = kInvalid; } return method_ != kInvalid; } const char *HttpRequest::methodString() const { const char *result = "UNKNOWN"; switch (method_) { case kGet:result = "GET"; break; case kPost:result = "POST"; break; case kHead:result = "HEAD"; break; case kPut:result = "PUT"; break; case kDelete:result = "DELETE"; break; default:break; } return result; } void HttpRequest::addHeader(const char *start, const char *colon, const char *end) { std::string field(start, colon); ++colon; while (colon < end && isspace(*colon)) { ++colon; } std::string value(colon, end); while (!value.empty() && isspace(value[value.size() - 1])) { value.resize(value.size() - 1); } headers_[field] = value; } std::string HttpRequest::getHeader(const std::string &field) const { std::string result; std::map<std::string, std::string>::const_iterator it = headers_.find(field); if (it != headers_.end()) { result = it->second; } return result; }
25.090909
84
0.551329
Mojiajun
9fb3953228e99b21cb2bf39dc0a6ec9819a8d14a
7,885
hpp
C++
include/veriblock/blockchain/pop/vbk_block_tree.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
include/veriblock/blockchain/pop/vbk_block_tree.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
include/veriblock/blockchain/pop/vbk_block_tree.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 Xenios SEZC // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #ifndef ALT_INTEGRATION_INCLUDE_VERIBLOCK_BLOCKCHAIN_VBK_BLOCK_TREE_HPP_ #define ALT_INTEGRATION_INCLUDE_VERIBLOCK_BLOCKCHAIN_VBK_BLOCK_TREE_HPP_ #include <utility> #include <veriblock/blockchain/blocktree.hpp> #include <veriblock/blockchain/pop/fork_resolution.hpp> #include <veriblock/blockchain/pop/pop_state_machine.hpp> #include <veriblock/blockchain/vbk_block_addon.hpp> #include <veriblock/blockchain/vbk_chain_params.hpp> #include <veriblock/entities/btcblock.hpp> #include <veriblock/finalizer.hpp> #include <veriblock/storage/payloads_index.hpp> namespace altintegration { // defined in vbk_block_tree.cpp extern template struct BlockIndex<BtcBlock>; extern template struct BlockTree<BtcBlock, BtcChainParams>; extern template struct BaseBlockTree<BtcBlock>; extern template struct BlockIndex<VbkBlock>; extern template struct BlockTree<VbkBlock, VbkChainParams>; extern template struct BaseBlockTree<VbkBlock>; /** * @class VbkBlockTree * * Veriblock block tree. * * @invariant stores only valid payloads. */ struct VbkBlockTree : public BlockTree<VbkBlock, VbkChainParams> { using VbkTree = BlockTree<VbkBlock, VbkChainParams>; using BtcTree = BlockTree<BtcBlock, BtcChainParams>; using index_t = VbkTree::index_t; using payloads_t = typename index_t::payloads_t; using pid_t = typename payloads_t::id_t; using endorsement_t = typename index_t::endorsement_t; using PopForkComparator = PopAwareForkResolutionComparator<VbkBlock, VbkChainParams, BtcTree, VbkBlockTree>; ~VbkBlockTree() override = default; VbkBlockTree(const VbkChainParams& vbkp, const BtcChainParams& btcp, PayloadsProvider& storagePayloads, PayloadsIndex& payloadsIndex); //! efficiently connect `index` to current tree, loaded from disk //! - recovers all pointers (pprev, pnext, endorsedBy) //! - recalculates chainWork //! - does validation of endorsements //! - recovers tips array //! @invariant NOT atomic. bool loadBlock(const index_t& index, ValidationState& state) override; BtcTree& btc() { return cmp_.getProtectingBlockTree(); } const BtcTree& btc() const { return cmp_.getProtectingBlockTree(); } PopForkComparator& getComparator() { return cmp_; } const PopForkComparator& getComparator() const { return cmp_; } PayloadsIndex& getPayloadsIndex() { return payloadsIndex_; } bool loadTip(const hash_t& hash, ValidationState& state) override; /** * @invariant atomic: adds either all or none of the payloads */ bool addPayloads(const VbkBlock::hash_t& hash, const std::vector<payloads_t>& payloads, ValidationState& state); void removePayloads(const hash_t& hash, const std::vector<pid_t>& pids); void removePayloads(const block_t& block, const std::vector<pid_t>& pids); void removePayloads(index_t& index, const std::vector<pid_t>& pids); /** * If we add payloads to the VBK tree in the following order: A1, B2, A3. * * Ending up with the tree looking like this: * A(1,3)-o-o-o-B(2) * * It is only safe to use this function to remove them in the opposite order: * A3, B2, A1; or A3, B2. * * It is unsafe to use this function to remove them in any other order eg: * B2, A3, A1; or just B2. */ void unsafelyRemovePayload(const Blob<24>& hash, const pid_t& pid); void unsafelyRemovePayload(const block_t& block, const pid_t& pid); void unsafelyRemovePayload(index_t& index, const pid_t& pid, bool shouldDetermineBestChain = true); std::string toPrettyString(size_t level = 0) const; using base::setState; bool setState(index_t& to, ValidationState& state) override; void overrideTip(index_t& to) override; void removeSubtree(index_t& toRemove) override; private: bool validateBTCContext(const payloads_t& vtb, ValidationState& state); /** * Add, apply and validate a payload to a block that's currently applied * * Will add duplicates. * The containing block must be applied * @invariant atomic: leaves the state unchanged on failure * @return: true/false on success/failure */ bool addPayloadToAppliedBlock(index_t& index, const payloads_t& payload, ValidationState& state); void determineBestChain(index_t& candidate, ValidationState& state) override; PopForkComparator cmp_; PayloadsProvider& payloadsProvider_; PayloadsIndex& payloadsIndex_; }; template <> void assertBlockCanBeRemoved(const BlockIndex<BtcBlock>& index); template <> void assertBlockCanBeRemoved(const BlockIndex<VbkBlock>& index); template <> std::vector<CommandGroup> payloadsToCommandGroups( VbkBlockTree& tree, const std::vector<VTB>& pop, const std::vector<uint8_t>& containinghash); template <> void payloadToCommands(VbkBlockTree& tree, const VTB& pop, const std::vector<uint8_t>& containingHash, std::vector<CommandPtr>& cmds); template <typename JsonValue> JsonValue ToJSON(const BlockIndex<VbkBlock>& i) { auto obj = json::makeEmptyObject<JsonValue>(); json::putStringKV(obj, "chainWork", i.chainWork.toHex()); std::vector<uint256> endorsements; for (const auto& e : i.getContainingEndorsements()) { endorsements.push_back(e.first); } json::putArrayKV(obj, "containingEndorsements", endorsements); std::vector<uint256> endorsedBy; for (const auto* e : i.endorsedBy) { endorsedBy.push_back(e->id); } json::putArrayKV(obj, "endorsedBy", endorsedBy); json::putIntKV(obj, "height", i.getHeight()); json::putKV(obj, "header", ToJSON<JsonValue>(i.getHeader())); json::putIntKV(obj, "status", i.getStatus()); json::putIntKV(obj, "ref", i.refCount()); auto stored = json::makeEmptyObject<JsonValue>(); json::putArrayKV(stored, "vtbids", i.getPayloadIds<VTB>()); json::putKV(obj, "stored", stored); return obj; } template <typename JsonValue> JsonValue ToJSON(const BlockIndex<BtcBlock>& i) { auto obj = json::makeEmptyObject<JsonValue>(); json::putStringKV(obj, "chainWork", i.chainWork.toHex()); json::putIntKV(obj, "height", i.getHeight()); json::putKV(obj, "header", ToJSON<JsonValue>(i.getHeader())); json::putIntKV(obj, "status", i.getStatus()); json::putIntKV(obj, "ref", i.refCount()); return obj; } // HACK: getBlockIndex accepts either hash_t or prev_block_hash_t // then, depending on what it received, it should do trim LE on full hash to // receive short hash, which is stored inside a map. In this weird case, when // Block=VbkBlock, we may call `getBlockIndex(block->previousBlock)`, it is a // call `getBlockIndex(Blob<12>). But when `getBlockIndex` accepts it, it does // an implicit cast to full hash (hash_t), adding zeroes in the end. Then, // .trimLE returns 12 zeroes. // // This hack allows us to inject explicit conversion hash_t (Blob<24>) -> // prev_block_hash_t (Blob<12>). template <> template <> inline BaseBlockTree<VbkBlock>::prev_block_hash_t BaseBlockTree<VbkBlock>::makePrevHash<BaseBlockTree<VbkBlock>::hash_t>( const hash_t& h) const { // do an explicit cast from hash_t -> prev_block_hash_t return h.template trimLE<prev_block_hash_t::size()>(); } inline void PrintTo(const VbkBlockTree& tree, std::ostream* os) { *os << tree.toPrettyString(); } } // namespace altintegration #endif // ALT_INTEGRATION_INCLUDE_VERIBLOCK_BLOCKCHAIN_VBK_BLOCK_TREE_HPP_
36.674419
79
0.703361
Dmytro-Kyparenko
9fc070a77f05979a683d6d8f19821838d8eaadd8
402
hpp
C++
day10/los.hpp
bcafuk/AoC-2019
5ff9b86f8483cd7a6e229d572ae9e34b894eb574
[ "Zlib" ]
null
null
null
day10/los.hpp
bcafuk/AoC-2019
5ff9b86f8483cd7a6e229d572ae9e34b894eb574
[ "Zlib" ]
null
null
null
day10/los.hpp
bcafuk/AoC-2019
5ff9b86f8483cd7a6e229d572ae9e34b894eb574
[ "Zlib" ]
2
2020-11-02T09:24:35.000Z
2020-12-02T09:46:27.000Z
#ifndef AOC_2019_DAY10_LOS_HPP #define AOC_2019_DAY10_LOS_HPP #include <cstddef> #include <set> #include "Location.hpp" std::set<Location> getVisible(const std::set<Location> &asteroids, const Location &origin, coordinate size); inline size_t countVisible(const std::set<Location> &asteroids, const Location &origin, coordinate size) { return getVisible(asteroids, origin, size).size(); } #endif
25.125
108
0.776119
bcafuk
9fc0ab3bd2d8693cef845cc80c3064733410334d
445
cpp
C++
SKYLINE.cpp
Akki5/spoj-solutions
9169830415eb4f888ba0300eb47a423166b8d938
[ "MIT" ]
1
2019-05-23T20:03:40.000Z
2019-05-23T20:03:40.000Z
SKYLINE.cpp
Akki5/spoj-solutions
9169830415eb4f888ba0300eb47a423166b8d938
[ "MIT" ]
null
null
null
SKYLINE.cpp
Akki5/spoj-solutions
9169830415eb4f888ba0300eb47a423166b8d938
[ "MIT" ]
1
2021-08-28T16:48:42.000Z
2021-08-28T16:48:42.000Z
#include<stdio.h> int arr[1005][1005]={{0}}; void catalan() { int i,j; for(i=0;i<1005;i++) { for(j=0;j<=i;j++) { if(j==0) arr[i][j]=1; else arr[i][j]=(arr[i][j-1]+arr[i-1][j])%1000000; } } } int main() { catalan(); int t; scanf("%d",&t); while(t) { printf("%d\n",arr[t][t]); scanf("%d",&t); } return 0; }
15.344828
60
0.357303
Akki5
9fc1608f0ef16a533eeb38a1a847e6cc9fe70607
1,473
cpp
C++
890. Find and Replace Pattern.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
890. Find and Replace Pattern.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
890. Find and Replace Pattern.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string>res; for (auto& s: words) { if (isValid(s, pattern)) { res.push_back(s); } } return res; } bool isValid(string& a, string& b) { unordered_map<char, char>m, t; int n = a.size(), l = b.size(); if (n != l) { return false; } for (int i = 0; i < n; ++i) { if (m.count(a[i]) || t.count(b[i])) { if (m[a[i]] == b[i] && t[b[i]] == a[i]) { continue; } else { return false; } } m[a[i]] = b[i]; t[b[i]] = a[i]; } return true; } }; class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string>res; for (auto& s: words) { if (normalize(s) == normalize(pattern)) { res.push_back(s); } } return res; } string normalize(string& s) { unordered_map<char, char>m; string res; char c = 'a'; for (auto& x: s) { if (!m.count(x)) { m[x] = c++; } } for (auto& x: s) { res.push_back(m[x]); } return res; } };
23.758065
81
0.395791
rajeev-ranjan-au6
9fc1d4d7fa89f2790b17bd8b59789645edc8221b
41,199
cpp
C++
src/vehicle_status.cpp
PX4/micrortps_agent
f7fee30b4a88d0627b2f92ca141277ace1a13597
[ "BSD-3-Clause" ]
3
2020-11-14T08:35:19.000Z
2022-01-25T05:21:14.000Z
src/vehicle_status.cpp
PX4/micrortps_agent
f7fee30b4a88d0627b2f92ca141277ace1a13597
[ "BSD-3-Clause" ]
1
2021-06-10T11:41:17.000Z
2021-06-10T11:41:17.000Z
src/vehicle_status.cpp
PX4/micrortps_agent
f7fee30b4a88d0627b2f92ca141277ace1a13597
[ "BSD-3-Clause" ]
2
2020-10-13T08:16:05.000Z
2021-06-03T05:57:31.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /*! * @file vehicle_status.cpp * This source file contains the definition of the described types in the IDL file. * * This file was generated by the tool gen. */ #ifdef _WIN32 // Remove linker warning LNK4221 on Visual Studio namespace { char dummy; } #endif #include "vehicle_status.h" #include <fastcdr/Cdr.h> #include <fastcdr/exceptions/BadParamException.h> using namespace eprosima::fastcdr::exception; #include <utility> vehicle_status::vehicle_status() { // m_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@358c99f5 m_timestamp_ = 0; // m_nav_state_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3ee0fea4 m_nav_state_ = 0; // m_nav_state_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@48524010 m_nav_state_timestamp_ = 0; // m_arming_state_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@4b168fa9 m_arming_state_ = 0; // m_hil_state_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@1a84f40f m_hil_state_ = 0; // m_failsafe_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@23282c25 m_failsafe_ = false; // m_failsafe_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@7920ba90 m_failsafe_timestamp_ = 0; // m_system_type_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6b419da m_system_type_ = 0; // m_system_id_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3b2da18f m_system_id_ = 0; // m_component_id_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@5906ebcb m_component_id_ = 0; // m_vehicle_type_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@258e2e41 m_vehicle_type_ = 0; // m_is_vtol_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3d299e3 m_is_vtol_ = false; // m_is_vtol_tailsitter_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@55a561cf m_is_vtol_tailsitter_ = false; // m_vtol_fw_permanent_stab_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3b938003 m_vtol_fw_permanent_stab_ = false; // m_in_transition_mode_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6f3b5d16 m_in_transition_mode_ = false; // m_in_transition_to_fw_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@78b1cc93 m_in_transition_to_fw_ = false; // m_rc_signal_lost_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6646153 m_rc_signal_lost_ = false; // m_data_link_lost_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@21507a04 m_data_link_lost_ = false; // m_data_link_lost_counter_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@143640d5 m_data_link_lost_counter_ = 0; // m_high_latency_data_link_lost_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6295d394 m_high_latency_data_link_lost_ = false; // m_engine_failure_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@475e586c m_engine_failure_ = false; // m_mission_failure_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@657c8ad9 m_mission_failure_ = false; // m_geofence_violated_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@436a4e4b m_geofence_violated_ = false; // m_failure_detector_status_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@f2f2cc1 m_failure_detector_status_ = 0; // m_onboard_control_sensors_present_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3a079870 m_onboard_control_sensors_present_ = 0; // m_onboard_control_sensors_enabled_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3b2cf7ab m_onboard_control_sensors_enabled_ = 0; // m_onboard_control_sensors_health_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@2aa5fe93 m_onboard_control_sensors_health_ = 0; // m_latest_arming_reason_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@5c1a8622 m_latest_arming_reason_ = 0; // m_latest_disarming_reason_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@5ad851c9 m_latest_disarming_reason_ = 0; // m_armed_time_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6156496 m_armed_time_ = 0; // m_takeoff_time_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3c153a1 m_takeoff_time_ = 0; } vehicle_status::~vehicle_status() { } vehicle_status::vehicle_status(const vehicle_status &x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; } vehicle_status::vehicle_status(vehicle_status &&x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; } vehicle_status& vehicle_status::operator=(const vehicle_status &x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; return *this; } vehicle_status& vehicle_status::operator=(vehicle_status &&x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; return *this; } size_t vehicle_status::getMaxCdrSerializedSize(size_t current_alignment) { size_t initial_alignment = current_alignment; current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); return current_alignment - initial_alignment; } size_t vehicle_status::getCdrSerializedSize(const vehicle_status& data, size_t current_alignment) { (void)data; size_t initial_alignment = current_alignment; current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); return current_alignment - initial_alignment; } void vehicle_status::serialize(eprosima::fastcdr::Cdr &scdr) const { scdr << m_timestamp_; scdr << m_nav_state_; scdr << m_nav_state_timestamp_; scdr << m_arming_state_; scdr << m_hil_state_; scdr << m_failsafe_; scdr << m_failsafe_timestamp_; scdr << m_system_type_; scdr << m_system_id_; scdr << m_component_id_; scdr << m_vehicle_type_; scdr << m_is_vtol_; scdr << m_is_vtol_tailsitter_; scdr << m_vtol_fw_permanent_stab_; scdr << m_in_transition_mode_; scdr << m_in_transition_to_fw_; scdr << m_rc_signal_lost_; scdr << m_data_link_lost_; scdr << m_data_link_lost_counter_; scdr << m_high_latency_data_link_lost_; scdr << m_engine_failure_; scdr << m_mission_failure_; scdr << m_geofence_violated_; scdr << m_failure_detector_status_; scdr << m_onboard_control_sensors_present_; scdr << m_onboard_control_sensors_enabled_; scdr << m_onboard_control_sensors_health_; scdr << m_latest_arming_reason_; scdr << m_latest_disarming_reason_; scdr << m_armed_time_; scdr << m_takeoff_time_; } void vehicle_status::deserialize(eprosima::fastcdr::Cdr &dcdr) { dcdr >> m_timestamp_; dcdr >> m_nav_state_; dcdr >> m_nav_state_timestamp_; dcdr >> m_arming_state_; dcdr >> m_hil_state_; dcdr >> m_failsafe_; dcdr >> m_failsafe_timestamp_; dcdr >> m_system_type_; dcdr >> m_system_id_; dcdr >> m_component_id_; dcdr >> m_vehicle_type_; dcdr >> m_is_vtol_; dcdr >> m_is_vtol_tailsitter_; dcdr >> m_vtol_fw_permanent_stab_; dcdr >> m_in_transition_mode_; dcdr >> m_in_transition_to_fw_; dcdr >> m_rc_signal_lost_; dcdr >> m_data_link_lost_; dcdr >> m_data_link_lost_counter_; dcdr >> m_high_latency_data_link_lost_; dcdr >> m_engine_failure_; dcdr >> m_mission_failure_; dcdr >> m_geofence_violated_; dcdr >> m_failure_detector_status_; dcdr >> m_onboard_control_sensors_present_; dcdr >> m_onboard_control_sensors_enabled_; dcdr >> m_onboard_control_sensors_health_; dcdr >> m_latest_arming_reason_; dcdr >> m_latest_disarming_reason_; dcdr >> m_armed_time_; dcdr >> m_takeoff_time_; } /*! * @brief This function sets a value in member timestamp_ * @param _timestamp_ New value for member timestamp_ */ void vehicle_status::timestamp_(uint64_t _timestamp_) { m_timestamp_ = _timestamp_; } /*! * @brief This function returns the value of member timestamp_ * @return Value of member timestamp_ */ uint64_t vehicle_status::timestamp_() const { return m_timestamp_; } /*! * @brief This function returns a reference to member timestamp_ * @return Reference to member timestamp_ */ uint64_t& vehicle_status::timestamp_() { return m_timestamp_; } /*! * @brief This function sets a value in member nav_state_ * @param _nav_state_ New value for member nav_state_ */ void vehicle_status::nav_state_(uint8_t _nav_state_) { m_nav_state_ = _nav_state_; } /*! * @brief This function returns the value of member nav_state_ * @return Value of member nav_state_ */ uint8_t vehicle_status::nav_state_() const { return m_nav_state_; } /*! * @brief This function returns a reference to member nav_state_ * @return Reference to member nav_state_ */ uint8_t& vehicle_status::nav_state_() { return m_nav_state_; } /*! * @brief This function sets a value in member nav_state_timestamp_ * @param _nav_state_timestamp_ New value for member nav_state_timestamp_ */ void vehicle_status::nav_state_timestamp_(uint64_t _nav_state_timestamp_) { m_nav_state_timestamp_ = _nav_state_timestamp_; } /*! * @brief This function returns the value of member nav_state_timestamp_ * @return Value of member nav_state_timestamp_ */ uint64_t vehicle_status::nav_state_timestamp_() const { return m_nav_state_timestamp_; } /*! * @brief This function returns a reference to member nav_state_timestamp_ * @return Reference to member nav_state_timestamp_ */ uint64_t& vehicle_status::nav_state_timestamp_() { return m_nav_state_timestamp_; } /*! * @brief This function sets a value in member arming_state_ * @param _arming_state_ New value for member arming_state_ */ void vehicle_status::arming_state_(uint8_t _arming_state_) { m_arming_state_ = _arming_state_; } /*! * @brief This function returns the value of member arming_state_ * @return Value of member arming_state_ */ uint8_t vehicle_status::arming_state_() const { return m_arming_state_; } /*! * @brief This function returns a reference to member arming_state_ * @return Reference to member arming_state_ */ uint8_t& vehicle_status::arming_state_() { return m_arming_state_; } /*! * @brief This function sets a value in member hil_state_ * @param _hil_state_ New value for member hil_state_ */ void vehicle_status::hil_state_(uint8_t _hil_state_) { m_hil_state_ = _hil_state_; } /*! * @brief This function returns the value of member hil_state_ * @return Value of member hil_state_ */ uint8_t vehicle_status::hil_state_() const { return m_hil_state_; } /*! * @brief This function returns a reference to member hil_state_ * @return Reference to member hil_state_ */ uint8_t& vehicle_status::hil_state_() { return m_hil_state_; } /*! * @brief This function sets a value in member failsafe_ * @param _failsafe_ New value for member failsafe_ */ void vehicle_status::failsafe_(bool _failsafe_) { m_failsafe_ = _failsafe_; } /*! * @brief This function returns the value of member failsafe_ * @return Value of member failsafe_ */ bool vehicle_status::failsafe_() const { return m_failsafe_; } /*! * @brief This function returns a reference to member failsafe_ * @return Reference to member failsafe_ */ bool& vehicle_status::failsafe_() { return m_failsafe_; } /*! * @brief This function sets a value in member failsafe_timestamp_ * @param _failsafe_timestamp_ New value for member failsafe_timestamp_ */ void vehicle_status::failsafe_timestamp_(uint64_t _failsafe_timestamp_) { m_failsafe_timestamp_ = _failsafe_timestamp_; } /*! * @brief This function returns the value of member failsafe_timestamp_ * @return Value of member failsafe_timestamp_ */ uint64_t vehicle_status::failsafe_timestamp_() const { return m_failsafe_timestamp_; } /*! * @brief This function returns a reference to member failsafe_timestamp_ * @return Reference to member failsafe_timestamp_ */ uint64_t& vehicle_status::failsafe_timestamp_() { return m_failsafe_timestamp_; } /*! * @brief This function sets a value in member system_type_ * @param _system_type_ New value for member system_type_ */ void vehicle_status::system_type_(uint8_t _system_type_) { m_system_type_ = _system_type_; } /*! * @brief This function returns the value of member system_type_ * @return Value of member system_type_ */ uint8_t vehicle_status::system_type_() const { return m_system_type_; } /*! * @brief This function returns a reference to member system_type_ * @return Reference to member system_type_ */ uint8_t& vehicle_status::system_type_() { return m_system_type_; } /*! * @brief This function sets a value in member system_id_ * @param _system_id_ New value for member system_id_ */ void vehicle_status::system_id_(uint8_t _system_id_) { m_system_id_ = _system_id_; } /*! * @brief This function returns the value of member system_id_ * @return Value of member system_id_ */ uint8_t vehicle_status::system_id_() const { return m_system_id_; } /*! * @brief This function returns a reference to member system_id_ * @return Reference to member system_id_ */ uint8_t& vehicle_status::system_id_() { return m_system_id_; } /*! * @brief This function sets a value in member component_id_ * @param _component_id_ New value for member component_id_ */ void vehicle_status::component_id_(uint8_t _component_id_) { m_component_id_ = _component_id_; } /*! * @brief This function returns the value of member component_id_ * @return Value of member component_id_ */ uint8_t vehicle_status::component_id_() const { return m_component_id_; } /*! * @brief This function returns a reference to member component_id_ * @return Reference to member component_id_ */ uint8_t& vehicle_status::component_id_() { return m_component_id_; } /*! * @brief This function sets a value in member vehicle_type_ * @param _vehicle_type_ New value for member vehicle_type_ */ void vehicle_status::vehicle_type_(uint8_t _vehicle_type_) { m_vehicle_type_ = _vehicle_type_; } /*! * @brief This function returns the value of member vehicle_type_ * @return Value of member vehicle_type_ */ uint8_t vehicle_status::vehicle_type_() const { return m_vehicle_type_; } /*! * @brief This function returns a reference to member vehicle_type_ * @return Reference to member vehicle_type_ */ uint8_t& vehicle_status::vehicle_type_() { return m_vehicle_type_; } /*! * @brief This function sets a value in member is_vtol_ * @param _is_vtol_ New value for member is_vtol_ */ void vehicle_status::is_vtol_(bool _is_vtol_) { m_is_vtol_ = _is_vtol_; } /*! * @brief This function returns the value of member is_vtol_ * @return Value of member is_vtol_ */ bool vehicle_status::is_vtol_() const { return m_is_vtol_; } /*! * @brief This function returns a reference to member is_vtol_ * @return Reference to member is_vtol_ */ bool& vehicle_status::is_vtol_() { return m_is_vtol_; } /*! * @brief This function sets a value in member is_vtol_tailsitter_ * @param _is_vtol_tailsitter_ New value for member is_vtol_tailsitter_ */ void vehicle_status::is_vtol_tailsitter_(bool _is_vtol_tailsitter_) { m_is_vtol_tailsitter_ = _is_vtol_tailsitter_; } /*! * @brief This function returns the value of member is_vtol_tailsitter_ * @return Value of member is_vtol_tailsitter_ */ bool vehicle_status::is_vtol_tailsitter_() const { return m_is_vtol_tailsitter_; } /*! * @brief This function returns a reference to member is_vtol_tailsitter_ * @return Reference to member is_vtol_tailsitter_ */ bool& vehicle_status::is_vtol_tailsitter_() { return m_is_vtol_tailsitter_; } /*! * @brief This function sets a value in member vtol_fw_permanent_stab_ * @param _vtol_fw_permanent_stab_ New value for member vtol_fw_permanent_stab_ */ void vehicle_status::vtol_fw_permanent_stab_(bool _vtol_fw_permanent_stab_) { m_vtol_fw_permanent_stab_ = _vtol_fw_permanent_stab_; } /*! * @brief This function returns the value of member vtol_fw_permanent_stab_ * @return Value of member vtol_fw_permanent_stab_ */ bool vehicle_status::vtol_fw_permanent_stab_() const { return m_vtol_fw_permanent_stab_; } /*! * @brief This function returns a reference to member vtol_fw_permanent_stab_ * @return Reference to member vtol_fw_permanent_stab_ */ bool& vehicle_status::vtol_fw_permanent_stab_() { return m_vtol_fw_permanent_stab_; } /*! * @brief This function sets a value in member in_transition_mode_ * @param _in_transition_mode_ New value for member in_transition_mode_ */ void vehicle_status::in_transition_mode_(bool _in_transition_mode_) { m_in_transition_mode_ = _in_transition_mode_; } /*! * @brief This function returns the value of member in_transition_mode_ * @return Value of member in_transition_mode_ */ bool vehicle_status::in_transition_mode_() const { return m_in_transition_mode_; } /*! * @brief This function returns a reference to member in_transition_mode_ * @return Reference to member in_transition_mode_ */ bool& vehicle_status::in_transition_mode_() { return m_in_transition_mode_; } /*! * @brief This function sets a value in member in_transition_to_fw_ * @param _in_transition_to_fw_ New value for member in_transition_to_fw_ */ void vehicle_status::in_transition_to_fw_(bool _in_transition_to_fw_) { m_in_transition_to_fw_ = _in_transition_to_fw_; } /*! * @brief This function returns the value of member in_transition_to_fw_ * @return Value of member in_transition_to_fw_ */ bool vehicle_status::in_transition_to_fw_() const { return m_in_transition_to_fw_; } /*! * @brief This function returns a reference to member in_transition_to_fw_ * @return Reference to member in_transition_to_fw_ */ bool& vehicle_status::in_transition_to_fw_() { return m_in_transition_to_fw_; } /*! * @brief This function sets a value in member rc_signal_lost_ * @param _rc_signal_lost_ New value for member rc_signal_lost_ */ void vehicle_status::rc_signal_lost_(bool _rc_signal_lost_) { m_rc_signal_lost_ = _rc_signal_lost_; } /*! * @brief This function returns the value of member rc_signal_lost_ * @return Value of member rc_signal_lost_ */ bool vehicle_status::rc_signal_lost_() const { return m_rc_signal_lost_; } /*! * @brief This function returns a reference to member rc_signal_lost_ * @return Reference to member rc_signal_lost_ */ bool& vehicle_status::rc_signal_lost_() { return m_rc_signal_lost_; } /*! * @brief This function sets a value in member data_link_lost_ * @param _data_link_lost_ New value for member data_link_lost_ */ void vehicle_status::data_link_lost_(bool _data_link_lost_) { m_data_link_lost_ = _data_link_lost_; } /*! * @brief This function returns the value of member data_link_lost_ * @return Value of member data_link_lost_ */ bool vehicle_status::data_link_lost_() const { return m_data_link_lost_; } /*! * @brief This function returns a reference to member data_link_lost_ * @return Reference to member data_link_lost_ */ bool& vehicle_status::data_link_lost_() { return m_data_link_lost_; } /*! * @brief This function sets a value in member data_link_lost_counter_ * @param _data_link_lost_counter_ New value for member data_link_lost_counter_ */ void vehicle_status::data_link_lost_counter_(uint8_t _data_link_lost_counter_) { m_data_link_lost_counter_ = _data_link_lost_counter_; } /*! * @brief This function returns the value of member data_link_lost_counter_ * @return Value of member data_link_lost_counter_ */ uint8_t vehicle_status::data_link_lost_counter_() const { return m_data_link_lost_counter_; } /*! * @brief This function returns a reference to member data_link_lost_counter_ * @return Reference to member data_link_lost_counter_ */ uint8_t& vehicle_status::data_link_lost_counter_() { return m_data_link_lost_counter_; } /*! * @brief This function sets a value in member high_latency_data_link_lost_ * @param _high_latency_data_link_lost_ New value for member high_latency_data_link_lost_ */ void vehicle_status::high_latency_data_link_lost_(bool _high_latency_data_link_lost_) { m_high_latency_data_link_lost_ = _high_latency_data_link_lost_; } /*! * @brief This function returns the value of member high_latency_data_link_lost_ * @return Value of member high_latency_data_link_lost_ */ bool vehicle_status::high_latency_data_link_lost_() const { return m_high_latency_data_link_lost_; } /*! * @brief This function returns a reference to member high_latency_data_link_lost_ * @return Reference to member high_latency_data_link_lost_ */ bool& vehicle_status::high_latency_data_link_lost_() { return m_high_latency_data_link_lost_; } /*! * @brief This function sets a value in member engine_failure_ * @param _engine_failure_ New value for member engine_failure_ */ void vehicle_status::engine_failure_(bool _engine_failure_) { m_engine_failure_ = _engine_failure_; } /*! * @brief This function returns the value of member engine_failure_ * @return Value of member engine_failure_ */ bool vehicle_status::engine_failure_() const { return m_engine_failure_; } /*! * @brief This function returns a reference to member engine_failure_ * @return Reference to member engine_failure_ */ bool& vehicle_status::engine_failure_() { return m_engine_failure_; } /*! * @brief This function sets a value in member mission_failure_ * @param _mission_failure_ New value for member mission_failure_ */ void vehicle_status::mission_failure_(bool _mission_failure_) { m_mission_failure_ = _mission_failure_; } /*! * @brief This function returns the value of member mission_failure_ * @return Value of member mission_failure_ */ bool vehicle_status::mission_failure_() const { return m_mission_failure_; } /*! * @brief This function returns a reference to member mission_failure_ * @return Reference to member mission_failure_ */ bool& vehicle_status::mission_failure_() { return m_mission_failure_; } /*! * @brief This function sets a value in member geofence_violated_ * @param _geofence_violated_ New value for member geofence_violated_ */ void vehicle_status::geofence_violated_(bool _geofence_violated_) { m_geofence_violated_ = _geofence_violated_; } /*! * @brief This function returns the value of member geofence_violated_ * @return Value of member geofence_violated_ */ bool vehicle_status::geofence_violated_() const { return m_geofence_violated_; } /*! * @brief This function returns a reference to member geofence_violated_ * @return Reference to member geofence_violated_ */ bool& vehicle_status::geofence_violated_() { return m_geofence_violated_; } /*! * @brief This function sets a value in member failure_detector_status_ * @param _failure_detector_status_ New value for member failure_detector_status_ */ void vehicle_status::failure_detector_status_(uint8_t _failure_detector_status_) { m_failure_detector_status_ = _failure_detector_status_; } /*! * @brief This function returns the value of member failure_detector_status_ * @return Value of member failure_detector_status_ */ uint8_t vehicle_status::failure_detector_status_() const { return m_failure_detector_status_; } /*! * @brief This function returns a reference to member failure_detector_status_ * @return Reference to member failure_detector_status_ */ uint8_t& vehicle_status::failure_detector_status_() { return m_failure_detector_status_; } /*! * @brief This function sets a value in member onboard_control_sensors_present_ * @param _onboard_control_sensors_present_ New value for member onboard_control_sensors_present_ */ void vehicle_status::onboard_control_sensors_present_(uint64_t _onboard_control_sensors_present_) { m_onboard_control_sensors_present_ = _onboard_control_sensors_present_; } /*! * @brief This function returns the value of member onboard_control_sensors_present_ * @return Value of member onboard_control_sensors_present_ */ uint64_t vehicle_status::onboard_control_sensors_present_() const { return m_onboard_control_sensors_present_; } /*! * @brief This function returns a reference to member onboard_control_sensors_present_ * @return Reference to member onboard_control_sensors_present_ */ uint64_t& vehicle_status::onboard_control_sensors_present_() { return m_onboard_control_sensors_present_; } /*! * @brief This function sets a value in member onboard_control_sensors_enabled_ * @param _onboard_control_sensors_enabled_ New value for member onboard_control_sensors_enabled_ */ void vehicle_status::onboard_control_sensors_enabled_(uint64_t _onboard_control_sensors_enabled_) { m_onboard_control_sensors_enabled_ = _onboard_control_sensors_enabled_; } /*! * @brief This function returns the value of member onboard_control_sensors_enabled_ * @return Value of member onboard_control_sensors_enabled_ */ uint64_t vehicle_status::onboard_control_sensors_enabled_() const { return m_onboard_control_sensors_enabled_; } /*! * @brief This function returns a reference to member onboard_control_sensors_enabled_ * @return Reference to member onboard_control_sensors_enabled_ */ uint64_t& vehicle_status::onboard_control_sensors_enabled_() { return m_onboard_control_sensors_enabled_; } /*! * @brief This function sets a value in member onboard_control_sensors_health_ * @param _onboard_control_sensors_health_ New value for member onboard_control_sensors_health_ */ void vehicle_status::onboard_control_sensors_health_(uint64_t _onboard_control_sensors_health_) { m_onboard_control_sensors_health_ = _onboard_control_sensors_health_; } /*! * @brief This function returns the value of member onboard_control_sensors_health_ * @return Value of member onboard_control_sensors_health_ */ uint64_t vehicle_status::onboard_control_sensors_health_() const { return m_onboard_control_sensors_health_; } /*! * @brief This function returns a reference to member onboard_control_sensors_health_ * @return Reference to member onboard_control_sensors_health_ */ uint64_t& vehicle_status::onboard_control_sensors_health_() { return m_onboard_control_sensors_health_; } /*! * @brief This function sets a value in member latest_arming_reason_ * @param _latest_arming_reason_ New value for member latest_arming_reason_ */ void vehicle_status::latest_arming_reason_(uint8_t _latest_arming_reason_) { m_latest_arming_reason_ = _latest_arming_reason_; } /*! * @brief This function returns the value of member latest_arming_reason_ * @return Value of member latest_arming_reason_ */ uint8_t vehicle_status::latest_arming_reason_() const { return m_latest_arming_reason_; } /*! * @brief This function returns a reference to member latest_arming_reason_ * @return Reference to member latest_arming_reason_ */ uint8_t& vehicle_status::latest_arming_reason_() { return m_latest_arming_reason_; } /*! * @brief This function sets a value in member latest_disarming_reason_ * @param _latest_disarming_reason_ New value for member latest_disarming_reason_ */ void vehicle_status::latest_disarming_reason_(uint8_t _latest_disarming_reason_) { m_latest_disarming_reason_ = _latest_disarming_reason_; } /*! * @brief This function returns the value of member latest_disarming_reason_ * @return Value of member latest_disarming_reason_ */ uint8_t vehicle_status::latest_disarming_reason_() const { return m_latest_disarming_reason_; } /*! * @brief This function returns a reference to member latest_disarming_reason_ * @return Reference to member latest_disarming_reason_ */ uint8_t& vehicle_status::latest_disarming_reason_() { return m_latest_disarming_reason_; } /*! * @brief This function sets a value in member armed_time_ * @param _armed_time_ New value for member armed_time_ */ void vehicle_status::armed_time_(uint64_t _armed_time_) { m_armed_time_ = _armed_time_; } /*! * @brief This function returns the value of member armed_time_ * @return Value of member armed_time_ */ uint64_t vehicle_status::armed_time_() const { return m_armed_time_; } /*! * @brief This function returns a reference to member armed_time_ * @return Reference to member armed_time_ */ uint64_t& vehicle_status::armed_time_() { return m_armed_time_; } /*! * @brief This function sets a value in member takeoff_time_ * @param _takeoff_time_ New value for member takeoff_time_ */ void vehicle_status::takeoff_time_(uint64_t _takeoff_time_) { m_takeoff_time_ = _takeoff_time_; } /*! * @brief This function returns the value of member takeoff_time_ * @return Value of member takeoff_time_ */ uint64_t vehicle_status::takeoff_time_() const { return m_takeoff_time_; } /*! * @brief This function returns a reference to member takeoff_time_ * @return Reference to member takeoff_time_ */ uint64_t& vehicle_status::takeoff_time_() { return m_takeoff_time_; } size_t vehicle_status::getKeyMaxCdrSerializedSize(size_t current_alignment) { size_t current_align = current_alignment; return current_align; } bool vehicle_status::isKeyDefined() { return false; } void vehicle_status::serializeKey(eprosima::fastcdr::Cdr &scdr) const { (void) scdr; }
26.822266
101
0.767446
PX4
9fc2c2a7f7a214ab9d6c5787343529ed720c8d07
36
cpp
C++
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CompileFeatures/cxx_alignas.cpp
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CompileFeatures/cxx_alignas.cpp
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CompileFeatures/cxx_alignas.cpp
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
struct S1 { alignas(8) int n; };
6
19
0.555556
duonglvtnaist
9fc323305aff865969d7b9c2ee63bd7009a1c554
4,413
cpp
C++
src/wire/wire2lua/lua_source_stream.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/wire2lua/lua_source_stream.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/wire2lua/lua_source_stream.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * lua_source_stream.cpp * * Created on: Nov 23, 2017 * Author: zmij */ #include <wire/idl/generator.hpp> #include <wire/idl/syntax_error.hpp> #include <wire/wire2lua/lua_source_stream.hpp> #include <iomanip> namespace wire { namespace idl { namespace lua { namespace { ::std::string const autogenerated = R"~(------------------------------------------------------------------------------ -- THIS FILE IS AUTOGENERATED BY wire2lua PROGRAM -- Any manual modifications can be lost ------------------------------------------------------------------------------ )~"; void write_offset(::std::ostream& os, int space_number) { if (space_number > 0) os << ::std::setw( space_number ) << ::std::setfill(' ') << " "; } } source_stream::source_stream(::std::string const& filename) : stream_{filename}, current_offset_{0}, tab_width_{4} { if (!stream_) { throw ::std::runtime_error("Failed to open output file " + filename); } stream_ << autogenerated; } void source_stream::write_offset(int temp) { stream_ << "\n"; lua::write_offset(stream_, (current_offset_ + temp) * tab_width_); } void source_stream::modify_offset(int delta) { current_offset_ += delta; if (current_offset_ < 0) current_offset_ = 0; } void source_stream::set_offset(int offset) { current_offset_ = offset; if (current_offset_ < 0) current_offset_ = 0; } source_stream& operator << (source_stream& os, mapped_type const& mt) { if (auto pt = ast::dynamic_entity_cast< ast::parametrized_type >(mt.type)) { os << "wire.types." << pt->name(); if (pt->name() == ast::VARIANT) { os << "({ "; for (auto const& p : pt->params()) { switch (p.which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(p) } << ", "; break; default: throw grammar_error(mt.type->decl_position(), "Unexpected variant parameter"); } } os << "})"; } else if (pt->name() == ast::DICTONARY) { // Expect exactly two type params os << "("; for (auto p = pt->params().begin(); p != pt->params().end(); ++p) { if (p != pt->params().begin()) os << ", "; switch (p->which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(*p) }; break; default: throw grammar_error(mt.type->decl_position(), "Unexpected dictionary parameter"); } } os << ")"; } else if (pt->name() == ast::ARRAY) { // Expect exactly two params: type and int os << "("; for (auto p = pt->params().begin(); p != pt->params().end(); ++p) { if (p != pt->params().begin()) os << ", "; switch (p->which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(*p) }; break; case ast::template_param_type::integral: os << ::boost::get< ::std::string >(*p); break; default: throw grammar_error(mt.type->decl_position(), "Unexpected array parameter"); } } os << ")"; } else { os << "("; auto const& p = pt->params().front(); switch (p.which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(p) }; break; default: throw grammar_error(mt.type->decl_position(), "Unexpected " + pt->name() + " parameter"); } os << ")"; } } else if (auto ref = ast::dynamic_entity_cast< ast::reference >(mt.type)) { os << "wire.types.type('proxy')"; } else { os << "wire.types.type('" << mt.type->get_qualified_name() << "')"; } return os; } } /* namespace lua */ } /* namespace idl */ } /* namespace wire */
30.434483
109
0.469748
zmij
9fc4485039011f4bd14e9b94b527b57e8878848e
3,077
cpp
C++
src/GBuffer.cpp
NotCamelCase/JBIC
6304678696b65f66c560ecea91a52b5a1f528a7c
[ "MIT" ]
5
2015-07-24T14:32:09.000Z
2021-06-13T18:02:52.000Z
src/GBuffer.cpp
NotCamelCase/JBIC
6304678696b65f66c560ecea91a52b5a1f528a7c
[ "MIT" ]
null
null
null
src/GBuffer.cpp
NotCamelCase/JBIC
6304678696b65f66c560ecea91a52b5a1f528a7c
[ "MIT" ]
1
2020-09-03T23:30:41.000Z
2020-09-03T23:30:41.000Z
#include <GBuffer.h> #include <Scene.h> GBuffer::GBuffer(Scene* scene, GLuint texUnit) : m_texUnitStart(texUnit), m_fbo(0), m_scene(scene) { assert(fillGBuffer() && "Error creating GBuffer content!"); } GBuffer::~GBuffer() { glDeleteFramebuffers(1, &m_fbo); } bool GBuffer::fillGBuffer() { glGenFramebuffers(1, &m_fbo); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); GLuint renderTex, posTex, normalTex, matKA, matKD, matKS; glGenRenderbuffers(1, &renderTex); glBindRenderbuffer(GL_RENDERBUFFER, renderTex); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_scene->getRenderParams().width, m_scene->getRenderParams().height); posTex = createGBufferTexture(GBufferTexType::VERTEX_ATTRIB_POS); normalTex = createGBufferTexture(GBufferTexType::VERTEX_ATTRIB_NORMAL); matKA = createGBufferTexture(GBufferTexType::MAT_ATTRIB_KA); matKD = createGBufferTexture(GBufferTexType::MAT_ATTRIB_KD); matKS = createGBufferTexture(GBufferTexType::MAT_ATTRIB_KS); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderTex); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, posTex, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normalTex, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, matKA, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, matKD, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT4, GL_TEXTURE_2D, matKS, 0); // Depth - POS - NORMAL - MAT_KA - MAT_KD - MAT_KS GLenum db[] = { GL_NONE, GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4 }; const uint numDrawBuffers = 6; #ifdef DEBUG GLint maxDrawBuffers; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); if (numDrawBuffers > maxDrawBuffers) LOG_ME("Frame buffer attachments exceeding max available draw buffers!!!"); #endif glDrawBuffers(numDrawBuffers, db); glBindFramebuffer(GL_FRAMEBUFFER, 0); return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; } GLuint GBuffer::createGBufferTexture(GBufferTexType texType) { GLuint tex; glGenTextures(1, &tex); glActiveTexture(m_texUnitStart++); glBindTexture(GL_TEXTURE_2D, tex); glTexStorage2D(GL_TEXTURE_2D, 1, getTextureFormat(texType), m_scene->getRenderParams().width, m_scene->getRenderParams().height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return tex; } uint GBuffer::getTextureFormat(GBufferTexType type) { switch (type) { case GBufferTexType::VERTEX_ATTRIB_POS: case GBufferTexType::VERTEX_ATTRIB_NORMAL: return GL_RGB32F; case GBufferTexType::VERTEX_ATTRIB_UV: return GL_RGB32F; case GBufferTexType::MAT_ATTRIB_KA: case GBufferTexType::MAT_ATTRIB_KD: case GBufferTexType::MAT_ATTRIB_KS: return GL_RGB8; } }
35.367816
130
0.809555
NotCamelCase
9fc644cb8aa87a0f9107502f02bc0d85ec21aa35
1,299
cpp
C++
Heap/K_Sorted_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Heap/K_Sorted_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Heap/K_Sorted_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//given an array which is k sorted that means all the elements are atmost 'k' //distance far from where they should be if they would have been sorted //sort the array /* using heap: take first 'k' elements and then heapify it now for i = k to n-1 : pop min from heap and insert arr[i] into heap do this for the rest of the elements This works beacause an element is atmost 'k' distance far from its correct pos so if we take 'k' elements then we are sure to get its correct by having the nearby 'k' elements */ #include<iostream> #include<queue> #include<vector> using namespace std; //comparator for priority queue struct comp{ bool operator()(const int&a ,const int&b){ return a>b; } }; //sorts the array void kSortArray(vector<int> &arr, int k = 3){ int i = 0, j = 0; int n = arr.size(); //create a min priority queue priority_queue<int, vector<int>, comp> pq; //insert the first k elements for(; i<k; i++) pq.push(arr[i]); //now for the rest of the elements for(j = 0; i<n && j<n; i++,j++){ arr[j] = pq.top(); pq.pop(); pq.push(arr[i]); } while(!pq.empty()){ arr[j++] = pq.top(); pq.pop(); } } int main(){ vector<int> arr = {2, 6, 3, 12, 56, 8}; kSortArray(arr,3); for (int i = 0; i < arr.size(); ++i) { cout<<arr[i]<<" "; } cout<<endl; }
21.65
84
0.639723
susantabiswas
9fcf670e1f4b22da78554e8d65612f76447fca22
8,609
cc
C++
src/GRPCClient.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/GRPCClient.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/GRPCClient.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
/* * GRPCClient.cc * * Created on: Jun 7, 2016 * Author: theo */ #include <cassert> #include <unistd.h> #include "GRPCClient.h" GRPCClient::RequestHandler::RequestHandler(GRPCClient *grpc_client, const std::string &addr) : _grpc_client(grpc_client), _addr(addr) {} GRPCClient::RequestHandler::~RequestHandler() { _cq.Shutdown(); } Status GRPCClient::RequestHandler::getStatus() { return (_status); } GRPCClient::ReadRequestHandler::ReadRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_read_args_t *rpc_read_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_read_args(rpc_read_args), _reply_reader(_grpc_client->getStub(addr)-> AsyncRead(&_ctx, GRPCClient::makeReadRequest(_rpc_read_args->read_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::ReadRequestHandler::~ReadRequestHandler() {} void GRPCClient::ReadRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) { _rpc_read_args->status = _reply.status(); if (_rpc_read_args->status) _rpc_read_args->value = new std::string(_reply.value()); } } GRPCClient::WriteRequestHandler::WriteRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_write_args_t *rpc_write_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_write_args(rpc_write_args), _reply_reader(_grpc_client->getStub(_addr)-> AsyncWrite(&_ctx, GRPCClient::makeWriteRequest(_rpc_write_args->write_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::WriteRequestHandler::~WriteRequestHandler() {} void GRPCClient::WriteRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) _rpc_write_args->status = _reply.status(); } GRPCClient::PhaseOneCommitRequestHandler::PhaseOneCommitRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_p1c_args_t *rpc_p1c_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_p1c_args(rpc_p1c_args), _reply_reader(_grpc_client->getStub(_addr)-> AsyncP1C(&_ctx, GRPCClient::makePhaseOneCommitRequest(_rpc_p1c_args->p1c_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::PhaseOneCommitRequestHandler::~PhaseOneCommitRequestHandler() {} void GRPCClient::PhaseOneCommitRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) { for (int i = 0; i < _reply.node_size(); i++) _rpc_p1c_args->nodes->insert(_reply.node(i)); _rpc_p1c_args->vote = _reply.vote(); } } GRPCClient::PhaseTwoCommitRequestHandler::PhaseTwoCommitRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_p2c_args_t *rpc_p2c_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_p2c_args(rpc_p2c_args), _reply_reader(_grpc_client->getStub(_addr)-> AsyncP2C(&_ctx, GRPCClient::makePhaseTwoCommitRequest(_rpc_p2c_args->p2c_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::PhaseTwoCommitRequestHandler::~PhaseTwoCommitRequestHandler() {} void GRPCClient::PhaseTwoCommitRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) for (int i = 0; i < _reply.node_size(); i++) _rpc_p2c_args->nodes->insert(_reply.node(i)); } GRPCClient::~GRPCClient () { _address_to_stub.clear(); _tag_to_handler.clear(); } void GRPCClient::makeStub(const std::string &addr) { std::unique_lock<std::mutex> lock(_mutex1); if (_address_to_stub.find(addr) == _address_to_stub.end()) _address_to_stub[addr] = Mvtkvs::NewStub(grpc::CreateChannel(addr, grpc::InsecureChannelCredentials())); } Mvtkvs::Stub *GRPCClient::getStub(std::string addr) { std::unique_lock<std::mutex> lock(_mutex1); return (_address_to_stub[addr].get()); } ReadRequest GRPCClient::makeReadRequest(const read_args_t *read_args) { ReadRequest res; res.set_tid(read_args->tid); res.set_start_ts(read_args->start_ts); res.set_key(read_args->key); return (res); } WriteRequest GRPCClient::makeWriteRequest(const write_args_t *write_args) { WriteRequest res; res.set_tid(write_args->tid); res.set_key(write_args->key); res.set_value(*(write_args->value)); return (res); } PhaseOneCommitRequest GRPCClient::makePhaseOneCommitRequest(const p1c_args_t *p1c_args) { PhaseOneCommitRequest res; res.set_tid(p1c_args->tid); res.set_start_ts(p1c_args->start_ts); res.set_commit_ts(p1c_args->commit_ts); for (std::set<uint64_t>::iterator it = p1c_args->read_nodes->begin(); it != p1c_args->read_nodes->end(); ++it) res.add_read_node(*it); for (std::set<uint64_t>::iterator it = p1c_args->write_nodes->begin(); it != p1c_args->write_nodes->end(); ++it) res.add_write_node(*it); return (res); } PhaseTwoCommitRequest GRPCClient::makePhaseTwoCommitRequest(const p2c_args_t *p2c_args) { PhaseTwoCommitRequest res; res.set_tid(p2c_args->tid); res.set_vote(p2c_args->vote); return (res); } bool GRPCClient::syncRPC(const std::string &addr, request_t request, void *args) { ClientContext ctx; Status status; makeStub(addr); switch (request) { case (TREAD): { rpc_read_args_t *rpc_read_args = (rpc_read_args_t *) args; ReadRequest request = GRPCClient::makeReadRequest(rpc_read_args->read_args); ReadReply reply; _mutex1.lock(); status = _address_to_stub[addr]->Read(&ctx, request, &reply); _mutex1.unlock(); rpc_read_args->status = status.ok() && reply.status(); if (rpc_read_args->status) rpc_read_args->value->assign(reply.value()); break; } case (TWRITE): { rpc_write_args_t *rpc_write_args = (rpc_write_args_t *) args; WriteRequest request = GRPCClient::makeWriteRequest(rpc_write_args->write_args); WriteReply reply; _mutex1.lock(); status = _address_to_stub[addr]->Write(&ctx, request, &reply); _mutex1.unlock(); rpc_write_args->status = status.ok() && reply.status(); break; } case (TP1C): { rpc_p1c_args_t *rpc_p1c_args = (rpc_p1c_args_t *) args; PhaseOneCommitRequest request = GRPCClient::makePhaseOneCommitRequest(rpc_p1c_args->p1c_args); PhaseOneCommitReply reply; _mutex1.lock(); status = _address_to_stub[addr]->P1C(&ctx, request, &reply); _mutex1.unlock(); if (status.ok()) { for (int i = 0; i < reply.node_size(); i++) rpc_p1c_args->nodes->insert(reply.node(i)); rpc_p1c_args->vote = reply.vote(); } break; } case (TP2C): { rpc_p2c_args_t *rpc_p2c_args = (rpc_p2c_args_t *) args; PhaseTwoCommitRequest request = GRPCClient::makePhaseTwoCommitRequest(rpc_p2c_args->p2c_args); PhaseTwoCommitReply reply; _mutex1.lock(); status = _address_to_stub[addr]->P2C(&ctx, request, &reply); _mutex1.unlock(); if (status.ok()) { for (int i = 0; i < reply.node_size(); i++) rpc_p2c_args->nodes->insert(reply.node(i)); } break; } } return (status.ok()); } void GRPCClient::asyncRPC(const std::string &addr, uint64_t tag, request_t request, void *args) { GRPCClient::RequestHandler *handler = NULL; makeStub(addr); switch(request) { case (TREAD): { handler = new ReadRequestHandler(this, addr, (rpc_read_args_t *) args); break; } case (TWRITE): { handler = new WriteRequestHandler(this, addr, (rpc_write_args_t *) args); break; } case (TP1C): { handler = new PhaseOneCommitRequestHandler(this, addr, (rpc_p1c_args_t *) args); break; } case (TP2C): { handler = new PhaseTwoCommitRequestHandler(this, addr, (rpc_p2c_args_t *) args); break; } } _mutex2.lock(); _tag_to_handler[tag] = handler; _mutex2.unlock(); } bool GRPCClient::waitAsyncReply(uint64_t tag) { bool res; std::unique_lock<std::mutex> lock(_mutex2); _tag_to_handler[tag]->proceed(); res = _tag_to_handler[tag]->getStatus().ok(); if (res) { _tag_to_handler.erase(tag); delete _tag_to_handler[tag]; } return (res); }
30.856631
120
0.66988
mkaguilera
9fdb09273c63226f542a55c84cc12ba9588c67ce
2,924
hpp
C++
Includes/Rosetta/PlayMode/Managers/CostManager.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Includes/Rosetta/PlayMode/Managers/CostManager.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Includes/Rosetta/PlayMode/Managers/CostManager.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_PLAYMODE_COST_MANAGER_HPP #define ROSETTASTONE_PLAYMODE_COST_MANAGER_HPP #include <Rosetta/PlayMode/Auras/AdaptiveCostEffect.hpp> #include <optional> namespace RosettaStone::PlayMode { //! //! \brief CostManager class. //! //! This class manages the cost of the card. It is affected by cost aura, //! adaptive effect and enchantment. //! class CostManager { public: //! Default constructor. CostManager() = default; //! Calculates the value of the cost by considering the factors //! such as cost aura, adaptive effect and enchantment. //! \return cost The original value of the cost. //! \return The final value of the cost. int GetCost(int cost); //! Queues the update. void QueueUpdate(); //! Applies older entity's cost enchantments to the new one. //! \param newCardCost The cost of new card. //! \return The applied value of the cost. int EntityChanged(int newCardCost); //! Adds the aura that affects the cost. //! \param effectOp The effect operator to affect the cost value. //! \param value The value to affect the cost value. void AddCostAura(EffectOperator effectOp, int value); //! Removes the aura that affects the cost. //! \param effectOp The effect operator to affect the cost value. //! \param value The value to affect the cost value. void RemoveCostAura(EffectOperator effectOp, int value); //! Activates the adaptive effect that affects the cost. //! \param effect The adaptive cost effect to change the cost value. void ActivateAdaptiveEffect(AdaptiveCostEffect* effect); //! Updates the adaptive effect that affects the cost. //! \param value The value that affects the cost value to update. void UpdateAdaptiveEffect(int value = -1); //! Deactivates the adaptive effect that affects the cost. void DeactivateAdaptiveEffect(); //! Adds the enchantment that affects the cost. //! \param effectOp The effect operator to affect the cost value. //! \param value The value to affect the cost value. void AddCostEnchantment(EffectOperator effectOp, int value); private: //! Internal method of GetCost(). //! \return cost The original value of the cost. //! \return The final value of the cost. int GetCostInternal(int cost); std::vector<std::pair<EffectOperator, int>> m_costEffects; std::vector<std::pair<EffectOperator, int>> m_costEnchantments; int m_cachedValue = 0; bool m_toBeUpdated = true; AdaptiveCostEffect* m_adaptiveCostEffect = nullptr; }; } // namespace RosettaStone::PlayMode #endif // ROSETTASTONE_PLAYMODE_COST_MANAGER_HPP
35.228916
79
0.718194
Hearthstonepp
9fe9571953e4d4146a418a8b4c8819d9753e8af5
2,374
hpp
C++
Aha/Aha/Math/Color.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
null
null
null
Aha/Aha/Math/Color.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
null
null
null
Aha/Aha/Math/Color.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
1
2018-04-27T05:48:41.000Z
2018-04-27T05:48:41.000Z
// // Color.hpp // Aha // // Created by Priyanshi Thakur on 01/05/18. // Copyright © 2018 Saurabh Sinha. All rights reserved. // #pragma once #include "../Math/Vec3.hpp" #include "../Math/Vec4.hpp" namespace aha { class Color : public Vec4f { public: Color() : Vec4f() { ; } Color(const Color& color) : Vec4f(color) { ; } Color(const Vec3f& color, float alpha) : Color(color.r, color.g, color.b, alpha) { ; } Color(const Vec3i& color, int alpha) : Color(color.r / 255.f, color.g / 255.f, color.b / 255.f, alpha / 255.f) { ; } Color(const Vec3f& color) : Color(color, 1.0f) { ; } Color(const Vec3i& color) : Color(color, 255) { ; } Color(const Vec4f& color) : Vec4f(color.r, color.g, color.b, color.a) { ; } Color(const Vec4i& color) : Vec4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f) { ; } Color(float intensity, float alpha) : Color(Vec3f(intensity, intensity, alpha)) { ; } Color(int intensity, int alpha) : Color(Vec3i(intensity, intensity, alpha)) { ; } Color(float r, float g, float b, float a) : Vec4f(r, g, b, a) { ; } Color(int r, int g, int b, int a) : Color(Vec4i(r, g, b, a)) { ; } const Color& operator =(const Color& rhs) { r = rhs.r; g = rhs.g; b = rhs.g; a = rhs.a; return *this; } Color contrastingColor() const { float luminance = 0.299f + 0.587f + 0.144f + 0.f; return Color(luminance < 0.5f ? 1.f : 0.f, 1.f); } /// Allows for conversion between this Color and NanoVG's representation. inline operator NVGcolor () const { NVGcolor color; color.r = r; color.g = g; color.b = b; color.a = a; return color; } }; }
21.981481
118
0.420388
templateguy
9ff59d3cac54cd8209ed57751e49f24f08645d63
1,263
cpp
C++
Evaluate Reverse Polish Notation.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
2
2020-06-25T12:46:13.000Z
2021-07-06T06:34:33.000Z
Evaluate Reverse Polish Notation.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
Evaluate Reverse Polish Notation.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
class Solution { public: int evalRPN(vector<string>& tokens) { stack<long> st; int n=tokens.size(); for(string str : tokens){ if(str=="+" || str=="-" || str=="*" || str=="/"){ int num1, num2; if(!st.empty()){ num1 = st.top(); st.pop(); } if(!st.empty()){ num2 = st.top(); st.pop(); } long result = 0; char ch = str[0]; switch(ch){ case '+' : result = num2 + num1; break; case '-' : result = num2 - num1; break; case '/' : result = num2 / num1; break; case '*' : result = num2*num1; break; } st.push(result); } else{ int n=atoi(str.c_str()); st.push(n); } } return st.top(); } };
28.704545
62
0.262866
durgirajesh
b003e2a6c476dbee85b20b2d39d445b8d735481f
781
cpp
C++
splus.tech/Source.cpp
sehe/splus.tech
c476305ef23253bb268d977aaf5b7f6ac60d9b3f
[ "MIT" ]
2
2020-06-30T16:36:06.000Z
2021-08-05T11:52:25.000Z
splus.tech/Source.cpp
sehe/splus.tech
c476305ef23253bb268d977aaf5b7f6ac60d9b3f
[ "MIT" ]
null
null
null
splus.tech/Source.cpp
sehe/splus.tech
c476305ef23253bb268d977aaf5b7f6ac60d9b3f
[ "MIT" ]
1
2020-07-07T01:26:34.000Z
2020-07-07T01:26:34.000Z
#include <string> #include <iostream> #include <vector> #include "WebS.h" #include <algorithm> #include "menu.h" using namespace std; int main(int argc, char* argv[]) { if (argc > 1 && argv[1][0] == '/') { if (argv[1][1] == 's') { string IP = argv[2]; int port = stoi(argv[3]); WebS siteserv(IP.c_str(), port); if (siteserv.init() != 0) { return 0; } cout << "Server started" << endl; siteserv.run(); system("pause"); } if (argv[1][1] == '?') { help_menu_view(); } if (argv[1][1] == 'm') { man_menu_view(); } } else { string IP = "0.0.0.0"; int port = 80; WebS siteserv(IP.c_str(), port); if (siteserv.init() != 0) { return 0; } cout << "Server started" << endl; siteserv.run(); system("pause"); } return 0; }
18.595238
37
0.541613
sehe
b004e46b025814211cde93694094cc7a960cc93c
39,694
cpp
C++
Source/HeliumRain/UI/Menus/FlareSkirmishSetupMenu.cpp
zhyinty/HeliumRain
0096b9c9e9d0c0949d18624ea74b4991fdd175a2
[ "BSD-3-Clause" ]
646
2016-07-18T19:16:35.000Z
2022-03-27T17:16:57.000Z
Source/HeliumRain/UI/Menus/FlareSkirmishSetupMenu.cpp
zhyinty/HeliumRain
0096b9c9e9d0c0949d18624ea74b4991fdd175a2
[ "BSD-3-Clause" ]
2
2020-06-22T07:23:11.000Z
2020-06-29T07:01:32.000Z
Source/HeliumRain/UI/Menus/FlareSkirmishSetupMenu.cpp
zhyinty/HeliumRain
0096b9c9e9d0c0949d18624ea74b4991fdd175a2
[ "BSD-3-Clause" ]
114
2016-07-19T00:52:44.000Z
2022-01-27T06:09:42.000Z
#include "HeliumRain/UI/Menus/FlareSkirmishSetupMenu.h" #include "../../Flare.h" #include "../../Data/FlareCompanyCatalog.h" #include "../../Data/FlareSpacecraftCatalog.h" #include "../../Data/FlareSpacecraftComponentsCatalog.h" #include "../../Data/FlareCustomizationCatalog.h" #include "../../Data/FlareOrbitalMap.h" #include "../../Game/FlareGame.h" #include "../../Game/FlareSaveGame.h" #include "../../Game/FlareSkirmishManager.h" #include "../../Game/FlareGameUserSettings.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlarePlayerController.h" #define LOCTEXT_NAMESPACE "FlareSkirmishSetupMenu" #define MAX_ASTEROIDS 50 #define MAX_DEBRIS_PERCENTAGE 25 /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareSkirmishSetupMenu::Construct(const FArguments& InArgs) { // Data MenuManager = InArgs._MenuManager; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); int32 SideWidth = 0.65 * Theme.ContentWidth; int32 Width = 1 * Theme.ContentWidth; int32 LabelWidth = 0.225 * Theme.ContentWidth; int32 ListHeight = 880; // Build structure ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SNew(SOverlay) // Main + SOverlay::Slot() [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Center) .Padding(Theme.ContentPadding) [ SNew(STextBlock) .Text(LOCTEXT("SkirmishSetupTitle", "New skirmish")) .TextStyle(&Theme.SpecialTitleFont) ] // Content + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) // Sector settings + SHorizontalBox::Slot() .HAlign(HAlign_Left) .AutoWidth() [ SNew(SBox) .WidthOverride(SideWidth) [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Left) .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("SkirmishSectorSettingssTitle", "Settings")) .TextStyle(&Theme.SubTitleFont) ] // Opponent selector + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(LabelWidth) .Padding(FMargin(0, 20, 0, 0)) [ SNew(STextBlock) .Text(LOCTEXT("EnemyLabel", "Enemy company")) .TextStyle(&Theme.TextFont) ] ] // List + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SAssignNew(CompanySelector, SFlareDropList<FFlareCompanyDescription>) .OptionsSource(&MenuManager->GetPC()->GetGame()->GetCompanyCatalog()->Companies) .OnGenerateWidget(this, &SFlareSkirmishSetupMenu::OnGenerateCompanyComboLine) .HeaderWidth(6) .ItemWidth(6) [ SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::OnGetCurrentCompanyComboLine) .TextStyle(&Theme.TextFont) ] ] ] ] // Planet selector + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(LabelWidth) .Padding(FMargin(0, 20, 0, 0)) [ SNew(STextBlock) .Text(LOCTEXT("PlanetLabel", "Planetary body")) .TextStyle(&Theme.TextFont) ] ] // List + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SAssignNew(PlanetSelector, SFlareDropList<FFlareSectorCelestialBodyDescription>) .OptionsSource(&MenuManager->GetPC()->GetGame()->GetOrbitalBodies()->OrbitalBodies) .OnGenerateWidget(this, &SFlareSkirmishSetupMenu::OnGeneratePlanetComboLine) .HeaderWidth(6) .ItemWidth(6) [ SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::OnGetCurrentPlanetComboLine) .TextStyle(&Theme.TextFont) ] ] ] ] // Altitude + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth) [ SNew(STextBlock) .Text(LOCTEXT("AltitudeLabel", "Altitude")) .TextStyle(&Theme.TextFont) ] ] // Slider + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SAssignNew(AltitudeSlider, SSlider) .Value(0) .Style(&Theme.SliderStyle) ] // Label + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth / 2) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareSkirmishSetupMenu::GetAltitudeValue) ] ] ] ] // Asteroids + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth) [ SNew(STextBlock) .Text(LOCTEXT("AsteroidLabel", "Asteroids")) .TextStyle(&Theme.TextFont) ] ] // Slider + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SAssignNew(AsteroidSlider, SSlider) .Value(0) .Style(&Theme.SliderStyle) .OnValueChanged(this, &SFlareSkirmishSetupMenu::OnAsteroidSliderChanged, true) ] // Label + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth / 2) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareSkirmishSetupMenu::GetAsteroidValue) ] ] ] ] // Debris + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth) [ SNew(STextBlock) .Text(LOCTEXT("DebrisLabel", "Debris density")) .TextStyle(&Theme.TextFont) ] ] // Slider + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SAssignNew(DebrisSlider, SSlider) .Value(0) .Style(&Theme.SliderStyle) .OnValueChanged(this, &SFlareSkirmishSetupMenu::OnDebrisSliderChanged, true) ] // Label + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth / 2) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareSkirmishSetupMenu::GetDebrisValue) ] ] ] ] // Icy + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Icy + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.SmallContentPadding) [ SAssignNew(IcyButton, SFlareButton) .Text(LOCTEXT("Icy", "Icy sector")) .HelpText(LOCTEXT("IcyInfo", "This sector will encompass an icy cloud of water particles")) .Toggle(true) ] // Debris + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.SmallContentPadding) [ SAssignNew(MetalDebrisButton, SFlareButton) .Text(LOCTEXT("MetallicDebris", "Battle debris")) .HelpText(LOCTEXT("MetallicDebrisInfo", "This sector will feature remains of a battle, instead of asteroid fragments")) .Toggle(true) ] ] ] ] // Player fleet + SHorizontalBox::Slot() .HAlign(HAlign_Fill) [ SNew(SBox) .WidthOverride(Width) [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Left) .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::GetPlayerFleetTitle) .TextStyle(&Theme.SubTitleFont) ] // Add ship + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("AddPlayerShip", "Add ship")) .HelpText(this, &SFlareSkirmishSetupMenu::GetAddToPlayerFleetText) .IsDisabled(this, &SFlareSkirmishSetupMenu::IsAddToPlayerFleetDisabled) .OnClicked(this, &SFlareSkirmishSetupMenu::OnOrderShip, true) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("ClearPlayerFleet", "Clear fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnClearFleet, true) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("SortFleet", "Sort fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnSortPlayerFleet) ] ] + SVerticalBox::Slot() [ SNew(SBox) .HeightOverride(ListHeight) [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() .Padding(Theme.ContentPadding) [ SAssignNew(PlayerSpacecraftList, SListView<TSharedPtr<FFlareSkirmishSpacecraftOrder>>) .ListItemsSource(&PlayerSpacecraftListData) .SelectionMode(ESelectionMode::None) .OnGenerateRow(this, &SFlareSkirmishSetupMenu::OnGenerateSpacecraftLine) ] ] ] ] ] // Enemy fleet + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() [ SNew(SBox) .WidthOverride(Width) [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Left) .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::GetEnemyFleetTitle) .TextStyle(&Theme.SubTitleFont) ] // Add ship + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("AddEnemyShip", "Add ship")) .HelpText(this, &SFlareSkirmishSetupMenu::GetAddToEnemyFleetText) .IsDisabled(this, &SFlareSkirmishSetupMenu::IsAddToEnemyFleetDisabled) .OnClicked(this, &SFlareSkirmishSetupMenu::OnOrderShip, false) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("ClearEnemyFleet", "Clear fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnClearFleet, false) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("AutomaticFleet", "Automatic fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnAutoCreateEnemyFleet) ] ] + SVerticalBox::Slot() [ SNew(SBox) .HeightOverride(ListHeight) [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() .Padding(Theme.ContentPadding) [ SAssignNew(EnemySpacecraftList, SListView<TSharedPtr<FFlareSkirmishSpacecraftOrder>>) .ListItemsSource(&EnemySpacecraftListData) .SelectionMode(ESelectionMode::None) .OnGenerateRow(this, &SFlareSkirmishSetupMenu::OnGenerateSpacecraftLine) ] ] ] ] ] ] // Start + SVerticalBox::Slot() .HAlign(HAlign_Left) .VAlign(VAlign_Bottom) .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("Back", "Back")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnMainMenu) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Icon(FFlareStyleSet::GetIcon("Load")) .Text(LOCTEXT("Start", "Start skirmish")) .HelpText(this, &SFlareSkirmishSetupMenu::GetStartHelpText) .IsDisabled(this, &SFlareSkirmishSetupMenu::IsStartDisabled) .OnClicked(this, &SFlareSkirmishSetupMenu::OnStartSkirmish) ] ] ] // Customization overlay + SOverlay::Slot() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SAssignNew(UpgradeBox, SBackgroundBlur) .BlurRadius(Theme.BlurRadius) .BlurStrength(Theme.BlurStrength) .HAlign(HAlign_Left) .VAlign(VAlign_Top) .Visibility(EVisibility::Collapsed) [ SNew(SBorder) .BorderImage(&Theme.BackgroundBrush) [ SNew(SVerticalBox) // Top line + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(SHorizontalBox) // Icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("ShipUpgradeMedium")) ] // Title + SHorizontalBox::Slot() .HAlign(HAlign_Fill) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text(LOCTEXT("ShipUpgradeTitle", "Upgrade spacecraft")) .TextStyle(&Theme.TitleFont) ] // Close button + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() [ SNew(SFlareButton) .Text(FText()) .Icon(FFlareStyleSet::GetIcon("Delete")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnCloseUpgradePanel) .Width(1) ] ] // Upgrades + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(SHorizontalBox) // Engine + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(0.25 * Theme.ContentWidth) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("EngineUpgradeTitle", "Orbital engines")) .TextStyle(&Theme.SubTitleFont) ] + SVerticalBox::Slot() .VAlign(VAlign_Top) [ SAssignNew(OrbitalEngineBox, SVerticalBox) ] ] ] // RCS + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(0.25 * Theme.ContentWidth) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("RCSUpgradeTitle", "RCS")) .TextStyle(&Theme.SubTitleFont) ] + SVerticalBox::Slot() .VAlign(VAlign_Top) [ SAssignNew(RCSBox, SVerticalBox) ] ] ] // Weapons + SHorizontalBox::Slot() .AutoWidth() [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("WeaponUpgradeTitle", "Weapons")) .TextStyle(&Theme.SubTitleFont) ] + SVerticalBox::Slot() .VAlign(VAlign_Top) [ SNew(SBox) .HeightOverride(900) [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() [ SAssignNew(WeaponBox, SHorizontalBox) ] ] ] ] ] ] ] ] ]; } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareSkirmishSetupMenu::Setup() { SetEnabled(false); SetVisibility(EVisibility::Collapsed); } void SFlareSkirmishSetupMenu::Enter() { FLOG("SFlareSkirmishSetupMenu::Enter"); SetEnabled(true); SetVisibility(EVisibility::Visible); FCHECK(PlayerSpacecraftListData.Num() == 0); FCHECK(EnemySpacecraftListData.Num() == 0); // Setup lists CompanySelector->RefreshOptions(); PlanetSelector->RefreshOptions(); CompanySelector->SetSelectedIndex(0); PlanetSelector->SetSelectedIndex(0); // Start doing the setup MenuManager->GetGame()->GetSkirmishManager()->StartSetup(); // Empty lists PlayerSpacecraftListData.Empty(); EnemySpacecraftListData.Empty(); PlayerSpacecraftList->RequestListRefresh(); EnemySpacecraftList->RequestListRefresh(); } void SFlareSkirmishSetupMenu::Exit() { SetEnabled(false); SetVisibility(EVisibility::Collapsed); UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); FCHECK(PlayerSpacecraftListData.Num() <= MyGameSettings->MaxShipsInSector); FCHECK(EnemySpacecraftListData.Num() <= MyGameSettings->MaxShipsInSector); // Empty lists WeaponBox->ClearChildren(); PlayerSpacecraftListData.Empty(); EnemySpacecraftListData.Empty(); PlayerSpacecraftList->RequestListRefresh(); EnemySpacecraftList->RequestListRefresh(); } /*---------------------------------------------------- Content callbacks ----------------------------------------------------*/ FText SFlareSkirmishSetupMenu::GetAltitudeValue() const { return FText::AsNumber(FMath::RoundToInt(100.0f * AltitudeSlider->GetValue())); } FText SFlareSkirmishSetupMenu::GetAsteroidValue() const { return FText::AsNumber(FMath::RoundToInt(MAX_ASTEROIDS * AsteroidSlider->GetValue())); } FText SFlareSkirmishSetupMenu::GetDebrisValue() const { return FText::AsNumber(FMath::RoundToInt(100.0f * DebrisSlider->GetValue())); } FText SFlareSkirmishSetupMenu::GetPlayerFleetTitle() const { UFlareSpacecraftComponentsCatalog* Catalog = MenuManager->GetGame()->GetShipPartsCatalog(); int32 CombatValue = 0; for (auto Order : PlayerSpacecraftListData) { CombatValue += Order->Description->CombatPoints; for (auto Weapon : Order->WeaponTypes) { CombatValue += Catalog->Get(Weapon)->CombatPoints; } } return FText::Format(LOCTEXT("PlayerFleetTitleFormat", "Player fleet ({0})"), CombatValue); } FText SFlareSkirmishSetupMenu::GetEnemyFleetTitle() const { UFlareSpacecraftComponentsCatalog* Catalog = MenuManager->GetGame()->GetShipPartsCatalog(); int32 CombatValue = 0; for (auto Order : EnemySpacecraftListData) { CombatValue += Order->Description->CombatPoints; for (auto Weapon : Order->WeaponTypes) { CombatValue += Catalog->Get(Weapon)->CombatPoints; } } return FText::Format(LOCTEXT("EnemyFleetTitleFormat", "Enemy fleet ({0})"), CombatValue); } TSharedRef<ITableRow> SFlareSkirmishSetupMenu::OnGenerateSpacecraftLine(TSharedPtr<FFlareSkirmishSpacecraftOrder> Item, const TSharedRef<STableViewBase>& OwnerTable) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); const FFlareSpacecraftDescription* Desc = Item->Description; // Structure return SNew(SFlareListItem, OwnerTable) .Width(16) .Height(2) .Content() [ SNew(SHorizontalBox) // Picture + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) .VAlign(VAlign_Top) [ SNew(SImage) .Image(&Desc->MeshPreviewBrush) ] // Main infos + SHorizontalBox::Slot() .Padding(Theme.ContentPadding) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(STextBlock) .Text(Desc->Name) .TextStyle(&Theme.NameFont) ] + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(STextBlock) .Text(Desc->Description) .TextStyle(&Theme.TextFont) .WrapTextAt(0.7 * Theme.ContentWidth) ] ] ] // Action buttons + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Text(FText()) .HelpText(LOCTEXT("UpgradeSpacecraftInfo", "Upgrade this spacecraft")) .Icon(FFlareStyleSet::GetIcon("ShipUpgradeSmall")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeSpacecraft, Item) .Width(1) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Text(FText()) .HelpText(LOCTEXT("RemoveSpacecraftInfo", "Remove this spacecraft")) .Icon(FFlareStyleSet::GetIcon("Delete")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnRemoveSpacecraft, Item) .Width(1) ] ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SFlareButton) .Text(LOCTEXT("DuplicateSpacecraft", "Copy")) .HelpText(LOCTEXT("DuplicateSpacecraftInfo", "Add a copy of this spacecraft and upgrades")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnDuplicateSpacecraft, Item) .Width(2) ] ] ]; } TSharedRef<SWidget> SFlareSkirmishSetupMenu::OnGenerateCompanyComboLine(FFlareCompanyDescription Item) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); return SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(Item.Name) .TextStyle(&Theme.TextFont) ]; } FText SFlareSkirmishSetupMenu::OnGetCurrentCompanyComboLine() const { const FFlareCompanyDescription Item = CompanySelector->GetSelectedItem(); return Item.Name; } FText Capitalize(const FText& Text) { FString Lowercase = Text.ToString().ToLower(); FString FirstChar = Lowercase.Left(1).ToUpper(); FString Remainder = Lowercase.Right(Lowercase.Len() - 1); return FText::FromString(FirstChar + Remainder); } TSharedRef<SWidget> SFlareSkirmishSetupMenu::OnGeneratePlanetComboLine(FFlareSectorCelestialBodyDescription Item) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); return SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(Capitalize(Item.CelestialBodyName)) .TextStyle(&Theme.TextFont) ]; } FText SFlareSkirmishSetupMenu::OnGetCurrentPlanetComboLine() const { const FFlareSectorCelestialBodyDescription Item = PlanetSelector->GetSelectedItem(); return Capitalize(Item.CelestialBodyName); } bool SFlareSkirmishSetupMenu::IsStartDisabled() const { UFlareSkirmishManager* SkirmishManager = MenuManager->GetGame()->GetSkirmishManager(); FText Unused; if (!CanStartPlaying(Unused)) { return true; } return false; } FText SFlareSkirmishSetupMenu::GetAddToPlayerFleetText() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); if (PlayerSpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector) { return LOCTEXT("TooManyPlayerShips", "You can't add more ships than the limit defined in settings"); } else { return LOCTEXT("OKPlayerShips", "Add a new ship to the player fleet"); } } FText SFlareSkirmishSetupMenu::GetAddToEnemyFleetText() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); if (EnemySpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector) { return LOCTEXT("TooManyEnemyShips", "You can't add more ships than the limit defined in settings"); } else { return LOCTEXT("OKEnemyShips", "Add a new ship to the enemy fleet"); } } bool SFlareSkirmishSetupMenu::IsAddToPlayerFleetDisabled() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); return (PlayerSpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector); } bool SFlareSkirmishSetupMenu::IsAddToEnemyFleetDisabled() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); return (EnemySpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector); } FText SFlareSkirmishSetupMenu::GetStartHelpText() const { UFlareSkirmishManager* SkirmishManager = MenuManager->GetGame()->GetSkirmishManager(); FText Reason; if (!CanStartPlaying(Reason)) { return Reason; } return LOCTEXT("StartHelpText", "Start the skirmish now"); } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareSkirmishSetupMenu::OnAsteroidSliderChanged(float Value, bool ForPlayer) { } void SFlareSkirmishSetupMenu::OnDebrisSliderChanged(float Value, bool ForPlayer) { } void SFlareSkirmishSetupMenu::OnClearFleet(bool ForPlayer) { if (ForPlayer) { PlayerSpacecraftListData.Empty(); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.Empty(); EnemySpacecraftList->RequestListRefresh(); } } static bool SortByCombatValue(const TSharedPtr<FFlareSkirmishSpacecraftOrder>& Ship1, const TSharedPtr<FFlareSkirmishSpacecraftOrder>& Ship2) { FCHECK(Ship1->Description); FCHECK(Ship2->Description); if (Ship1->Description->CombatPoints > Ship2->Description->CombatPoints) { return true; } else { return false; } } void SFlareSkirmishSetupMenu::OnSortPlayerFleet() { PlayerSpacecraftListData.Sort(SortByCombatValue); PlayerSpacecraftList->RequestListRefresh(); } void SFlareSkirmishSetupMenu::OnAutoCreateEnemyFleet() { // Settings float NerfRatio = 0.9f; float ShipRatio = 0.9f; float DiversityRatio = 0.6f; // Data UFlareSpacecraftCatalog* SpacecraftCatalog = MenuManager->GetGame()->GetSpacecraftCatalog(); UFlareSpacecraftComponentsCatalog* PartsCatalog = MenuManager->GetGame()->GetShipPartsCatalog(); // Get player value int32 PlayerLargeShips = 0; int32 PlayerCombatValue = 0; for (auto Order : PlayerSpacecraftListData) { PlayerCombatValue += Order->Description->CombatPoints; for (auto Weapon : Order->WeaponTypes) { PlayerCombatValue += PartsCatalog->Get(Weapon)->CombatPoints; } if (Order->Description->Size == EFlarePartSize::L) { PlayerLargeShips++; } } // Define objectives bool IsHighValueFleet = (PlayerCombatValue > 25); int32 TargetCombatValue = IsHighValueFleet ? NerfRatio * PlayerCombatValue : PlayerCombatValue; int32 TargetShipCombatValue = IsHighValueFleet ? ShipRatio * TargetCombatValue : TargetCombatValue; int32 CurrentCombatValue = 0; // Add ships, starting with the most powerful EnemySpacecraftListData.Empty(); for (int32 Index = SpacecraftCatalog->ShipCatalog.Num() - 1; Index >= 0; Index--) { for (const UFlareSpacecraftCatalogEntry* Spacecraft : SpacecraftCatalog->ShipCatalog) { int32 RemainingCombatValue = TargetShipCombatValue - CurrentCombatValue; if (Spacecraft->Data.CombatPoints > 0 && Spacecraft->Data.CombatPoints < RemainingCombatValue) { // Define how much of this ship we want float RawShipCount = (DiversityRatio * RemainingCombatValue) / (float)Spacecraft->Data.CombatPoints; int32 ShipCount = IsHighValueFleet ? FMath::FloorToInt(RawShipCount) : FMath::CeilToInt(RawShipCount); // Order all copies for (int OrderIndex = 0; OrderIndex < ShipCount; OrderIndex++) { TSharedPtr<FFlareSkirmishSpacecraftOrder> Order = FFlareSkirmishSpacecraftOrder::New(&Spacecraft->Data); Order->ForPlayer = false; SetOrderDefaults(Order); EnemySpacecraftListData.Add(Order); CurrentCombatValue += Spacecraft->Data.CombatPoints; } } } // Value exceeded, break off if (CurrentCombatValue >= TargetShipCombatValue) { break; } } // Upgrade ships, starting with the least powerful for (int32 Index = EnemySpacecraftListData.Num() - 1; Index >= 0; Index--) { // Value exceeded, break off int32 RemainingCombatValue = TargetCombatValue - CurrentCombatValue; if (RemainingCombatValue <= 0) { break; } // Get data TSharedPtr<FFlareSkirmishSpacecraftOrder> Order = EnemySpacecraftListData[Index]; FFlareSpacecraftComponentDescription* BestAntiLargeWeapon = NULL; FFlareSpacecraftComponentDescription* BestAntiSmallWeapon = NULL; float BestAntiLarge = 0; float BestAntiSmall = 0; // Find best weapons against specific archetypes TArray<FFlareSpacecraftComponentDescription*> WeaponList; PartsCatalog->GetWeaponList(WeaponList, Order->Description->Size); for (FFlareSpacecraftComponentDescription* Weapon : WeaponList) { int32 UpgradeCombatValue = Order->WeaponTypes.Num() * Weapon->CombatPoints; if (UpgradeCombatValue > RemainingCombatValue) { continue; } // TODO : this algorithm always ends up using missiles if it upgrades at all, make it more diverse float AntiLarge = Weapon->WeaponCharacteristics.AntiLargeShipValue; if (AntiLarge > BestAntiLarge) { BestAntiLarge = AntiLarge; BestAntiLargeWeapon = Weapon; } float AntiSmall = Weapon->WeaponCharacteristics.AntiSmallShipValue; if (AntiSmall > BestAntiSmall) { BestAntiSmall = AntiSmall; BestAntiSmallWeapon = Weapon; } } // Assign one anti-L weapon to each L ship, else use anti small FFlareSpacecraftComponentDescription* UpgradeWeapon = NULL; if (PlayerLargeShips && BestAntiLargeWeapon) { UpgradeWeapon = BestAntiLargeWeapon; PlayerLargeShips--; } else if (BestAntiSmallWeapon) { UpgradeWeapon = BestAntiSmallWeapon; } // Upgrade if (UpgradeWeapon) { for (int32 WeaponIndex = 0; WeaponIndex < Order->WeaponTypes.Num(); WeaponIndex++) { Order->WeaponTypes[WeaponIndex] = UpgradeWeapon->Identifier; CurrentCombatValue += UpgradeWeapon->CombatPoints; } } } EnemySpacecraftList->RequestListRefresh(); } void SFlareSkirmishSetupMenu::OnOrderShip(bool ForPlayer) { IsOrderingForPlayer = ForPlayer; FFlareMenuParameterData Data; Data.OrderForPlayer = ForPlayer; Data.Skirmish = MenuManager->GetGame()->GetSkirmishManager(); MenuManager->OpenSpacecraftOrder(Data, FOrderDelegate::CreateSP(this, &SFlareSkirmishSetupMenu::OnOrderShipConfirmed)); } void SFlareSkirmishSetupMenu::OnOrderShipConfirmed(FFlareSpacecraftDescription* Spacecraft) { auto Order = FFlareSkirmishSpacecraftOrder::New(Spacecraft); Order->ForPlayer = IsOrderingForPlayer; SetOrderDefaults(Order); // Add ship if (IsOrderingForPlayer) { PlayerSpacecraftListData.AddUnique(Order); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.AddUnique(Order); EnemySpacecraftList->RequestListRefresh(); } } void SFlareSkirmishSetupMenu::OnUpgradeSpacecraft(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { const FFlareSpacecraftDescription* Desc = Order->Description; UFlareSpacecraftComponentsCatalog* Catalog = MenuManager->GetGame()->GetShipPartsCatalog(); TArray<FFlareSpacecraftComponentDescription*> PartList; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); // Prepare data FText Text = LOCTEXT("PickComponentFormat", "{0}\n({1} value)"); FText HelpText = LOCTEXT("PickComponentHelp", "Upgrade with this component"); // Reset lists OrbitalEngineBox->ClearChildren(); RCSBox->ClearChildren(); WeaponBox->ClearChildren(); UpgradeBox->SetVisibility(EVisibility::Visible); // Engines Catalog->GetEngineList(PartList, Desc->Size); for (auto Engine : PartList) { FLinearColor Color = (Order->EngineType == Engine->Identifier) ? Theme.FriendlyColor : Theme.NeutralColor; OrbitalEngineBox->InsertSlot(0) .Padding(FMargin(0, 10)) [ SNew(SFlareRoundButton) .Icon(&Engine->MeshPreviewBrush) .Text(Engine->Name) .HelpText(HelpText) .InvertedBackground(true) .HighlightColor(Color) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeEngine, Order, Engine->Identifier) ]; } // RCS PartList.Empty(); Catalog->GetRCSList(PartList, Desc->Size); for (auto RCS : PartList) { FLinearColor Color = (Order->RCSType == RCS->Identifier) ? Theme.FriendlyColor : Theme.NeutralColor; RCSBox->InsertSlot(0) .Padding(FMargin(0, 10)) [ SNew(SFlareRoundButton) .Icon(&RCS->MeshPreviewBrush) .Text(RCS->Name) .HelpText(HelpText) .InvertedBackground(true) .HighlightColor(Color) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeRCS, Order, RCS->Identifier) ]; } // Weapons PartList.Empty(); Catalog->GetWeaponList(PartList, Desc->Size); for (int32 Index = 0; Index < Order->Description->WeaponGroups.Num(); Index++) { // Create vertical structure const FFlareSpacecraftSlotGroupDescription& Slot = Order->Description->WeaponGroups[Index]; TSharedPtr<SVerticalBox> WeaponSlot; WeaponBox->AddSlot() [ SNew(SBox) .WidthOverride(0.25 * Theme.ContentWidth) [ SAssignNew(WeaponSlot, SVerticalBox) ] ]; for (auto Weapon : PartList) { FText NameText = FText::Format(Text, Weapon->Name, FText::AsNumber(Weapon->CombatPoints)); FLinearColor Color = (Order->WeaponTypes[Index] == Weapon->Identifier) ? Theme.FriendlyColor : Theme.NeutralColor; WeaponSlot->AddSlot() .Padding(FMargin(0, 10)) [ SNew(SFlareRoundButton) .Icon(&Weapon->MeshPreviewBrush) .Text(NameText) .HelpText(HelpText) .InvertedBackground(true) .HighlightColor(Color) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeWeapon, Order, Index, Weapon->Identifier) ]; } } SlatePrepass(FSlateApplicationBase::Get().GetApplicationScale()); } void SFlareSkirmishSetupMenu::OnRemoveSpacecraft(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { if (Order->ForPlayer) { PlayerSpacecraftListData.Remove(Order); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.Remove(Order); EnemySpacecraftList->RequestListRefresh(); } } void SFlareSkirmishSetupMenu::OnDuplicateSpacecraft(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { // Copy order TSharedPtr<FFlareSkirmishSpacecraftOrder> NewOrder = FFlareSkirmishSpacecraftOrder::New(Order->Description); NewOrder->EngineType = Order->EngineType; NewOrder->RCSType = Order->RCSType; NewOrder->WeaponTypes = Order->WeaponTypes; NewOrder->ForPlayer = Order->ForPlayer; // Add order if (Order->ForPlayer) { PlayerSpacecraftListData.Add(NewOrder); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.Add(NewOrder); EnemySpacecraftList->RequestListRefresh(); } } void SFlareSkirmishSetupMenu::OnUpgradeEngine(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order, FName Upgrade) { Order->EngineType = Upgrade; OnUpgradeSpacecraft(Order); } void SFlareSkirmishSetupMenu::OnUpgradeRCS(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order, FName Upgrade) { Order->RCSType = Upgrade; OnUpgradeSpacecraft(Order); } void SFlareSkirmishSetupMenu::OnUpgradeWeapon(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order, int32 GroupIndex, FName Upgrade) { const FFlareSpacecraftDescription* Desc = Order->Description; for (int32 Index = 0; Index < Order->Description->WeaponGroups.Num(); Index++) { if (Index == GroupIndex) { Order->WeaponTypes[Index] = Upgrade; } } OnUpgradeSpacecraft(Order); } void SFlareSkirmishSetupMenu::OnCloseUpgradePanel() { UpgradeBox->SetVisibility(EVisibility::Collapsed); } void SFlareSkirmishSetupMenu::OnStartSkirmish() { UFlareSkirmishManager* Skirmish = MenuManager->GetGame()->GetSkirmishManager(); // Add ships for (auto Order : PlayerSpacecraftListData) { Skirmish->AddShip(true, *Order.Get()); } PlayerSpacecraftListData.Empty(); for (auto Order : EnemySpacecraftListData) { Skirmish->AddShip(false, *Order.Get()); } EnemySpacecraftListData.Empty(); // Set sector settings Skirmish->GetData().SectorAltitude = AltitudeSlider->GetValue(); Skirmish->GetData().AsteroidCount = MAX_ASTEROIDS * AsteroidSlider->GetValue(); Skirmish->GetData().MetallicDebris = MetalDebrisButton->IsActive(); Skirmish->GetData().SectorDescription.CelestialBodyIdentifier = PlanetSelector->GetSelectedItem().CelestialBodyIdentifier; Skirmish->GetData().SectorDescription.IsIcy = IcyButton->IsActive(); Skirmish->GetData().SectorDescription.DebrisFieldInfo.DebrisFieldDensity = MAX_DEBRIS_PERCENTAGE * DebrisSlider->GetValue(); // Override company color with current settings FFlareCompanyDescription& PlayerCompanyData = Skirmish->GetData().PlayerCompanyData; const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); PlayerCompanyData.CustomizationBasePaintColor = CurrentCompanyData->CustomizationBasePaintColor; PlayerCompanyData.CustomizationPaintColor = CurrentCompanyData->CustomizationPaintColor; PlayerCompanyData.CustomizationOverlayColor = CurrentCompanyData->CustomizationOverlayColor; PlayerCompanyData.CustomizationLightColor = CurrentCompanyData->CustomizationLightColor; PlayerCompanyData.CustomizationPatternIndex = CurrentCompanyData->CustomizationPatternIndex; // Set enemy name Skirmish->GetData().EnemyCompanyName = CompanySelector->GetSelectedItem().ShortName; // Create the game Skirmish->StartPlay(); } void SFlareSkirmishSetupMenu::OnMainMenu() { MenuManager->GetGame()->GetSkirmishManager()->EndSkirmish(); MenuManager->OpenMenu(EFlareMenu::MENU_Main); } /*---------------------------------------------------- Helpers ----------------------------------------------------*/ bool SFlareSkirmishSetupMenu::CanStartPlaying(FText& Reason) const { Reason = FText(); if (PlayerSpacecraftListData.Num() == 0) { Reason = LOCTEXT("SkirmishCantStartNoPlayer", "You don't have enough ships to start playing"); return false; } else if (EnemySpacecraftListData.Num() == 0) { Reason = LOCTEXT("SkirmishCantStartNoEnemy", "Your enemy doesn't have enough ships to start playing"); return false; } return true; } void SFlareSkirmishSetupMenu::SetOrderDefaults(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { if (Order->Description->Size == EFlarePartSize::S) { Order->EngineType = FName("engine-thresher"); Order->RCSType = FName("rcs-coral"); for (auto& Slot : Order->Description->WeaponGroups) { Order->WeaponTypes.Add(FName("weapon-eradicator")); } } else { Order->EngineType = FName("pod-thera"); Order->RCSType = FName("rcs-rift"); for (auto& Slot : Order->Description->WeaponGroups) { Order->WeaponTypes.Add(FName("weapon-artemis")); } } } #undef LOCTEXT_NAMESPACE
26.114474
165
0.665617
zhyinty
b00fbb2b5fdd0175dcfcb55263d3d40ca7e11b07
326
cpp
C++
cpp/4353.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
9
2021-01-15T13:36:39.000Z
2022-02-23T03:44:46.000Z
cpp/4353.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
1
2021-07-31T17:11:26.000Z
2021-08-02T01:01:03.000Z
cpp/4353.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; #define double long double const double PI = acos(-1); int main() { fastio; cout << fixed << setprecision(3); for (double D, V; cin >> D >> V && D;) { const double val = D * D * D - V * 6 / PI; cout << cbrt(val) << '\n'; } }
21.733333
45
0.592025
jinhan814
b0134943ddeb234b4e3a57a75b3d09037c4e9db3
9,060
cpp
C++
src/items/value_item_map.cpp
kitsudaiki/libKitsunemimiSakuraParser
5cc3c2de7717b01b02912c9a2e0dc578877e963d
[ "Apache-2.0" ]
null
null
null
src/items/value_item_map.cpp
kitsudaiki/libKitsunemimiSakuraParser
5cc3c2de7717b01b02912c9a2e0dc578877e963d
[ "Apache-2.0" ]
54
2020-08-27T21:40:28.000Z
2021-12-30T20:56:13.000Z
src/items/value_item_map.cpp
kitsudaiki/libKitsunemimiSakuraParser
5cc3c2de7717b01b02912c9a2e0dc578877e963d
[ "Apache-2.0" ]
null
null
null
/** * @file value_item_map.h * * @author Tobias Anker <[email protected]> * * @copyright Apache License Version 2.0 * * Copyright 2019 Tobias Anker * * 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 <items/value_item_map.h> #include <libKitsunemimiCommon/common_items/table_item.h> #include <libKitsunemimiCommon/common_items/data_items.h> namespace Kitsunemimi { namespace Sakura { /** * @brief constructor */ ValueItemMap::ValueItemMap() {} /** * @brief destructor */ ValueItemMap::~ValueItemMap() { clearChildMap(); } /** * @brief copy-constructor */ ValueItemMap::ValueItemMap(const ValueItemMap &other) { // copy items std::map<std::string, ValueItem>::const_iterator it; for(it = other.m_valueMap.begin(); it != other.m_valueMap.end(); it++) { ValueItem value = it->second; m_valueMap.insert(std::make_pair(it->first, value)); } // copy child-maps std::map<std::string, ValueItemMap*>::const_iterator itChilds; for(itChilds = other.m_childMaps.begin(); itChilds != other.m_childMaps.end(); itChilds++) { ValueItemMap* newValue = new ValueItemMap(*itChilds->second); m_childMaps.insert(std::make_pair(itChilds->first, newValue)); } } /** * @brief assignmet-operator */ ValueItemMap& ValueItemMap::operator=(const ValueItemMap &other) { if(this != &other) { // delet old items this->m_valueMap.clear(); // copy items std::map<std::string, ValueItem>::const_iterator it; for(it = other.m_valueMap.begin(); it != other.m_valueMap.end(); it++) { ValueItem value = it->second; this->m_valueMap.insert(std::make_pair(it->first, value)); } clearChildMap(); // copy child-maps std::map<std::string, ValueItemMap*>::const_iterator itChilds; for(itChilds = other.m_childMaps.begin(); itChilds != other.m_childMaps.end(); itChilds++) { ValueItemMap* newValue = new ValueItemMap(*itChilds->second); this->m_childMaps.insert(std::make_pair(itChilds->first, newValue)); } } return *this; } /** * @brief add a new key-value-pair to the map * * @param key key of the new entry * @param value data-item of the new entry * @param force true, to override, if key already exist. * * @return true, if new pair was inserted, false, if already exist and force-flag was false */ bool ValueItemMap::insert(const std::string &key, DataItem* value, bool force) { ValueItem valueItem; valueItem.item = value->copy(); return insert(key, valueItem, force); } /** * @brief add a new key-value-pair to the map * * @param key key of the new entry * @param value value-item of the new entry * @param force true, to override, if key already exist. * * @return true, if new pair was inserted, false, if already exist and force-flag was false */ bool ValueItemMap::insert(const std::string &key, ValueItem &value, bool force) { std::map<std::string, ValueItem>::iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end() && force == false) { return false; } if(it != m_valueMap.end()) { it->second = value; } else { m_valueMap.insert(std::make_pair(key, value)); } return true; } /** * @brief add a new key-value-pair to the map * * @param key key of the new entry * @param value new child-map * @param force true, to override, if key already exist. * * @return true, if new pair was inserted, false, if already exist and force-flag was false */ bool ValueItemMap::insert(const std::string &key, ValueItemMap* value, bool force) { std::map<std::string, ValueItemMap*>::iterator it; it = m_childMaps.find(key); if(it != m_childMaps.end() && force == false) { return false; } if(it != m_childMaps.end()) { it->second = value; } else { m_childMaps.insert(std::make_pair(key, value)); } return true; } /** * @brief check if the map contains a specific key * * @param key key to identify the entry * * @return true, if key exist inside the map, else false */ bool ValueItemMap::contains(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return true; } std::map<std::string, ValueItemMap*>::const_iterator childIt; childIt = m_childMaps.find(key); if(childIt != m_childMaps.end()) { return true; } return false; } /** * @brief remove a value-item from the map * * @param key key to identify the entry * * @return true, if item was found and removed, else false */ bool ValueItemMap::remove(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { m_valueMap.erase(it); return true; } std::map<std::string, ValueItemMap*>::const_iterator childIt; childIt = m_childMaps.find(key); if(childIt != m_childMaps.end()) { m_childMaps.erase(childIt); return true; } return false; } /** * @brief get data-item inside a value-item of the map as string * * @param key key to identify the value * * @return item as string, if found, else empty string */ std::string ValueItemMap::getValueAsString(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return it->second.item->toString(); } return ""; } /** * @brief get data-item inside a value-item of the map * * @param key key to identify the value * * @return pointer to the data-item, if found, else a nullptr */ DataItem* ValueItemMap::get(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return it->second.item; } return nullptr; } /** * @brief get a value-item from the map * * @param key key to identify the value * * @return requested value-item, if found, else an empty uninitialized value-item */ ValueItem ValueItemMap::getValueItem(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return it->second; } return ValueItem(); } /** * @brief size get number of object in the map * * @return number of object inside the map */ uint64_t ValueItemMap::size() { return m_valueMap.size(); } /** * @brief ValueItemMap::toString * * @return */ const std::string ValueItemMap::toString() { // init table output TableItem table; table.addColumn("key"); table.addColumn("value"); // fill table std::map<std::string, ValueItem>::const_iterator it; for(it = m_valueMap.begin(); it != m_valueMap.end(); it++) { table.addRow(std::vector<std::string>{it->first, it->second.item->toString()}); } return table.toString(); } /** * @brief ValueItemMap::getValidationMap * @param validationMap */ void ValueItemMap::getValidationMap(std::map<std::string, FieldDef> &validationMap) const { std::map<std::string, ValueItem>::const_iterator it; for(it = m_valueMap.begin(); it != m_valueMap.end(); it++) { ValueItem value = it->second; FieldDef::IO_ValueType ioType = FieldDef::INPUT_TYPE; if(value.type == ValueItem::OUTPUT_PAIR_TYPE) { ioType = FieldDef::OUTPUT_TYPE; } const bool isReq = value.item->getString() == "?"; validationMap.emplace(it->first, FieldDef(ioType, value.fieldType, isReq, value.comment)); } } /** * @brief ValueItemMap::clearChildMap */ void ValueItemMap::clearChildMap() { // clear old child map std::map<std::string, ValueItemMap*>::const_iterator itChilds; for(itChilds = m_childMaps.begin(); itChilds != m_childMaps.end(); itChilds++) { ValueItemMap* oldMap = itChilds->second; delete oldMap; } m_childMaps.clear(); } } // namespace Sakura } // namespace Kitsunemimi
23.410853
98
0.620751
kitsudaiki
b0180077b6f31c48a6686f5e574a09fc4d7de072
577
cpp
C++
code/cpp/StringAnagram.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/StringAnagram.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/StringAnagram.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
bool detect_anagram(char* src, char* anagram) { int isrc=0, iana=0; while(*src != '\0') { char* iter = anagram; while(*iter != '\0' && *src != ' ') { if(*src == *iter) { iana++; break; } iter++; } if(*src != ' ') isrc++; src++; } if(iana == isrc) return true; else return false; } void main() { char *src=strdup("eleven plus two"); char *a = strdup("so plew veluent"); bool st = detect_anagram(src, a); }
19.233333
45
0.410745
analgorithmaday
b01c6c73dd8f078d4ab0b4d34dc115116ace8f4c
2,640
hpp
C++
sal/memory.hpp
svens/sal.lib
8dee6a0ace5a5e4e8616f9cff98ea86ee8c4761c
[ "MIT" ]
3
2017-03-21T20:39:25.000Z
2018-03-27T10:45:45.000Z
sal/memory.hpp
svens/sal.lib
8dee6a0ace5a5e4e8616f9cff98ea86ee8c4761c
[ "MIT" ]
49
2016-04-17T10:48:35.000Z
2018-12-29T10:00:55.000Z
sal/memory.hpp
svens/sal.lib
8dee6a0ace5a5e4e8616f9cff98ea86ee8c4761c
[ "MIT" ]
1
2017-03-21T20:48:24.000Z
2017-03-21T20:48:24.000Z
#pragma once /** * \file sal/memory.hpp * Iterator and memory pointer helpers. */ #include <sal/config.hpp> #include <iterator> #include <memory> __sal_begin namespace __bits { template <typename T> constexpr bool is_const_ref_v = false; template <typename T> constexpr bool is_const_ref_v<const T &> = true; template <typename It> constexpr void ensure_iterator_constraints () noexcept { static_assert( std::is_pod_v<typename std::iterator_traits<It>::value_type>, "expected iterator to point to POD type" ); static_assert( std::is_base_of_v< std::random_access_iterator_tag, typename std::iterator_traits<It>::iterator_category >, "expected random access iterator" ); } // internal helper: silence MSVC silly-warning C4996 (Checked Iterators) template <typename It> inline auto make_output_iterator (It first, It) noexcept { #if defined(_MSC_VER) return stdext::make_unchecked_array_iterator(first); #else return first; #endif } } // namespace __bits /** * Return \a it as pointer casted to uint8_t pointer. \a it can be iterator or * unrelated type of pointer. */ template <typename It> inline auto to_ptr (It it) noexcept { __bits::ensure_iterator_constraints<It>(); if constexpr (__bits::is_const_ref_v<decltype(*it)>) { return reinterpret_cast<const uint8_t *>(std::addressof(*it)); } else { return reinterpret_cast<uint8_t *>(std::addressof(*it)); } } /** * Return \a it as pointer casted to uint8_t pointer. \a it can be iterator or * unrelated type of pointer. */ constexpr std::nullptr_t to_ptr (std::nullptr_t) noexcept { return nullptr; } /** * Return memory region [\a first, \a last) size in bytes. * If \a first > \a last, result is undefined. */ template <typename It> constexpr size_t range_size (It first, It last) noexcept { __bits::ensure_iterator_constraints<It>(); return std::distance(first, last) * sizeof(typename std::iterator_traits<It>::value_type); } /** * Return memory region [\a first, \a last) size in bytes. * If \a first > \a last, result is undefined. */ constexpr size_t range_size (std::nullptr_t, std::nullptr_t) noexcept { return 0; } /** * Return iterator casted to uint8_t pointer to past last item in range * [\a first, \a last). */ template <typename It> inline auto to_end_ptr (It first, It last) noexcept { return to_ptr(first) + range_size(first, last); } /** * Return iterator casted to uint8_t pointer to past last item in range * [\a first, \a last). */ constexpr std::nullptr_t to_end_ptr (std::nullptr_t, std::nullptr_t) noexcept { return nullptr; } __sal_end
20.952381
78
0.708333
svens
b01d33fdb12f244bb0018a7e9dee1924b576cfda
295
hpp
C++
lib/Timing.hpp
CraGL/SubdivisionSkinning
c593a7a4e38a49716e9d3981824871a7b6c29324
[ "Apache-2.0" ]
19
2017-03-29T00:14:00.000Z
2021-11-27T15:44:44.000Z
lib/Timing.hpp
Myzhencai/SubdivisionSkinning
c593a7a4e38a49716e9d3981824871a7b6c29324
[ "Apache-2.0" ]
1
2019-05-08T21:48:11.000Z
2019-05-08T21:48:11.000Z
lib/Timing.hpp
Myzhencai/SubdivisionSkinning
c593a7a4e38a49716e9d3981824871a7b6c29324
[ "Apache-2.0" ]
5
2017-04-23T17:52:44.000Z
2020-06-28T18:00:26.000Z
#ifndef __Timing_hpp__ #define __Timing_hpp__ void tic( const char* label = 0 ) ; void toc( const char* label = 0 ) ; struct Tick { Tick( const char* alabel = 0 ) : label( alabel ) { tic( label ); } ~Tick() { toc( label ); } const char* label; }; #endif /* __Timing_hpp__ */
18.4375
70
0.60339
CraGL
b02162aa82a4900b6ed9d5d2a109dd088a465dc4
945
cpp
C++
Word.cpp
dennistrukhin/C-Virtual-machine
644be1f45c0d2804f93bddbfb4728e3d0c9fee5a
[ "MIT" ]
null
null
null
Word.cpp
dennistrukhin/C-Virtual-machine
644be1f45c0d2804f93bddbfb4728e3d0c9fee5a
[ "MIT" ]
null
null
null
Word.cpp
dennistrukhin/C-Virtual-machine
644be1f45c0d2804f93bddbfb4728e3d0c9fee5a
[ "MIT" ]
null
null
null
// // Created by Dennis Trukhin on 21/04/2018. // #include <iostream> #include "Word.h" Word::Word(const char * word) { for (int i = 0; i < 4; i++) { w[i] = (unsigned char)word[i]; } } Word::Word(const unsigned char * word) { for (int i = 0; i < 4; i++) { w[i] = word[i]; } } unsigned char *Word::getWord() { return w; } void Word::dump() { std::cout << w[0] << w[1] << w[2] << w[3] << ' '; } float Word::asFloat() { float f; unsigned char b[] = {w[3], w[2], w[1], w[0]}; memcpy(&f, &b, sizeof(f)); return f; } int Word::asInt() { int f; unsigned char b[] = {w[3], w[2], w[1], w[0]}; memcpy(&f, &b, sizeof(f)); return f; } unsigned char *Word::asString() { return w; } bool Word::is(unsigned char *c) { for (int i = 0; i < WORD_SIZE; i++) { if (w[i] != c[i]) { return false; } } return true; } Word::Word() = default;
16.875
53
0.479365
dennistrukhin
b026fa1f34f46df9c8d3c941550ec74b12d0c415
24
cpp
C++
src/render/Renderer.cpp
Vasile2k/Luminica
13250c6b536b0634e2f4ea95b7b75b0dee18705d
[ "Apache-2.0" ]
null
null
null
src/render/Renderer.cpp
Vasile2k/Luminica
13250c6b536b0634e2f4ea95b7b75b0dee18705d
[ "Apache-2.0" ]
null
null
null
src/render/Renderer.cpp
Vasile2k/Luminica
13250c6b536b0634e2f4ea95b7b75b0dee18705d
[ "Apache-2.0" ]
null
null
null
#include "Renderer.hpp"
12
23
0.75
Vasile2k
b02b5686a6056ba162952d42e3ab0eba21e908e3
220
hpp
C++
mlog/string_builder.hpp
Lowdham/mlog
034134ec2048fb78084f4772275b5f67efeec433
[ "MIT" ]
2
2021-06-19T04:14:14.000Z
2021-08-30T15:39:49.000Z
mlog/string_builder.hpp
Lowdham/mlog
034134ec2048fb78084f4772275b5f67efeec433
[ "MIT" ]
1
2021-06-21T15:58:19.000Z
2021-06-22T02:04:39.000Z
mlog/string_builder.hpp
Lowdham/mlog
034134ec2048fb78084f4772275b5f67efeec433
[ "MIT" ]
null
null
null
// This file is part of mlog #ifndef MLOG_STRING_BUILDER_HPP_ #define MLOG_STRING_BUILDER_HPP_ #include "fwd.hpp" namespace mlog { // class StringBuilder {}; } // namespace mlog #endif // !MLOG_STRING_BUILDER_HPP_
15.714286
36
0.754545
Lowdham
b02e04da92fbfad6cc2e8612b93c7612590bc135
279
cpp
C++
old/main.cpp
melkir/AwesomeScheduler
852a11dffc4996dc20bd0ef53143f3145cf37935
[ "MIT" ]
null
null
null
old/main.cpp
melkir/AwesomeScheduler
852a11dffc4996dc20bd0ef53143f3145cf37935
[ "MIT" ]
null
null
null
old/main.cpp
melkir/AwesomeScheduler
852a11dffc4996dc20bd0ef53143f3145cf37935
[ "MIT" ]
null
null
null
#include "Scheduler.h" #include "FCFSStrategy.h" int main() { FCFSStrategy fcfs; Scheduler scheduler(fcfs); scheduler.addProcess("A"); scheduler.addProcess("B"); scheduler.addProcess("C"); scheduler.addProcess("D"); scheduler.run(8); return 0; }
19.928571
30
0.65233
melkir
b034396b580e32fa8e069f41aeadf742429fa745
536
cpp
C++
CodeForces/Contest/386/G/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
CodeForces/Contest/386/G/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
CodeForces/Contest/386/G/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; const int N=2e5+10; int n,t,k,a[N],v[N]; int main(){ scanf("%d%d%d",&n,&t,&k); rep(i,2,t+1)scanf("%d",&a[i]); int mink=0,maxk=n-t; a[1]=1; rep(i,2,t+1)mink+=max(0,a[i-1]-a[i]); rep(i,1,t+1)a[i]+=a[i-1]; if(k<mink||k>maxk){puts("-1");return 0;} rep(i,2,t+1){ int p=a[i-1]; per(j,a[i],a[i-1]+1){ printf("%d %d\n",j,p); if(k&&) } } return 0; }
20.615385
47
0.533582
sjj118
b035424cc48f2e0b6b73ed14e5fde247329448fb
645
cpp
C++
src/Text/StringUtils/Base64.cpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
3
2015-09-15T06:57:50.000Z
2021-03-16T19:05:02.000Z
src/Text/StringUtils/Base64.cpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
2
2015-09-26T12:41:10.000Z
2015-12-08T08:41:37.000Z
src/Text/StringUtils/Base64.cpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
1
2015-07-09T02:56:34.000Z
2015-07-09T02:56:34.000Z
#include "RadonFramework/precompiled.hpp" #include "RadonFramework/Text/StringUtils/Base64.hpp" #include "RadonFramework/backend/stringcoders/modp_b64.h" namespace RadonFramework::Text::StringUtils { RF_Type::String Base64Converter::Encode(const RF_Type::String &Source) { std::string str = modp::b64_encode(Source.c_str(), Source.Length()); RF_Type::String result(str.c_str(), str.size()); return result; } RF_Type::String Base64Converter::Decode(const RF_Type::String &Source) { std::string str = modp::b64_decode(Source.c_str(), Source.Length()); RF_Type::String result(str.c_str(), str.size()); return result; } }
30.714286
72
0.733333
tak2004
b0402173786ab45d7b6d30e8add62bd93b85462d
4,907
cpp
C++
src/org/apache/poi/hssf/extractor/EventBasedExcelExtractor.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/hssf/extractor/EventBasedExcelExtractor.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/hssf/extractor/EventBasedExcelExtractor.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/hssf/extractor/EventBasedExcelExtractor.java #include <org/apache/poi/hssf/extractor/EventBasedExcelExtractor.hpp> #include <java/io/IOException.hpp> #include <java/lang/IllegalStateException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/RuntimeException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <java/lang/StringBuilder.hpp> #include <java/lang/Throwable.hpp> #include <org/apache/poi/POIDocument.hpp> #include <org/apache/poi/hssf/eventusermodel/FormatTrackingHSSFListener.hpp> #include <org/apache/poi/hssf/eventusermodel/HSSFEventFactory.hpp> #include <org/apache/poi/hssf/eventusermodel/HSSFRequest.hpp> #include <org/apache/poi/hssf/extractor/EventBasedExcelExtractor_TextListener.hpp> #include <org/apache/poi/poifs/filesystem/DirectoryNode.hpp> #include <org/apache/poi/poifs/filesystem/POIFSFileSystem.hpp> template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::hssf::extractor::EventBasedExcelExtractor::EventBasedExcelExtractor(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::hssf::extractor::EventBasedExcelExtractor::EventBasedExcelExtractor(::poi::poifs::filesystem::DirectoryNode* dir) : EventBasedExcelExtractor(*static_cast< ::default_init_tag* >(0)) { ctor(dir); } poi::hssf::extractor::EventBasedExcelExtractor::EventBasedExcelExtractor(::poi::poifs::filesystem::POIFSFileSystem* fs) : EventBasedExcelExtractor(*static_cast< ::default_init_tag* >(0)) { ctor(fs); } void poi::hssf::extractor::EventBasedExcelExtractor::init() { _includeSheetNames = true; _formulasNotResults = false; } void poi::hssf::extractor::EventBasedExcelExtractor::ctor(::poi::poifs::filesystem::DirectoryNode* dir) { super::ctor(static_cast< ::poi::POIDocument* >(nullptr)); init(); _dir = dir; } void poi::hssf::extractor::EventBasedExcelExtractor::ctor(::poi::poifs::filesystem::POIFSFileSystem* fs) { ctor(npc(fs)->getRoot()); super::setFilesystem(fs); } poi::hpsf::DocumentSummaryInformation* poi::hssf::extractor::EventBasedExcelExtractor::getDocSummaryInformation() { throw new ::java::lang::IllegalStateException(u"Metadata extraction not supported in streaming mode, please use ExcelExtractor"_j); } poi::hpsf::SummaryInformation* poi::hssf::extractor::EventBasedExcelExtractor::getSummaryInformation() { throw new ::java::lang::IllegalStateException(u"Metadata extraction not supported in streaming mode, please use ExcelExtractor"_j); } void poi::hssf::extractor::EventBasedExcelExtractor::setIncludeCellComments(bool includeComments) { throw new ::java::lang::IllegalStateException(u"Comment extraction not supported in streaming mode, please use ExcelExtractor"_j); } void poi::hssf::extractor::EventBasedExcelExtractor::setIncludeHeadersFooters(bool includeHeadersFooters) { throw new ::java::lang::IllegalStateException(u"Header/Footer extraction not supported in streaming mode, please use ExcelExtractor"_j); } void poi::hssf::extractor::EventBasedExcelExtractor::setIncludeSheetNames(bool includeSheetNames) { _includeSheetNames = includeSheetNames; } void poi::hssf::extractor::EventBasedExcelExtractor::setFormulasNotResults(bool formulasNotResults) { _formulasNotResults = formulasNotResults; } java::lang::String* poi::hssf::extractor::EventBasedExcelExtractor::getText() { ::java::lang::String* text = nullptr; try { auto tl = triggerExtraction(); text = npc(npc(tl)->_text)->toString(); if(!npc(text)->endsWith(u"\n"_j)) { text = ::java::lang::StringBuilder().append(text)->append(u"\n"_j)->toString(); } } catch (::java::io::IOException* e) { throw new ::java::lang::RuntimeException(static_cast< ::java::lang::Throwable* >(e)); } return text; } poi::hssf::extractor::EventBasedExcelExtractor_TextListener* poi::hssf::extractor::EventBasedExcelExtractor::triggerExtraction() /* throws(IOException) */ { auto tl = new EventBasedExcelExtractor_TextListener(this); auto ft = new ::poi::hssf::eventusermodel::FormatTrackingHSSFListener(tl); npc(tl)->_ft = ft; auto factory = new ::poi::hssf::eventusermodel::HSSFEventFactory(); auto request = new ::poi::hssf::eventusermodel::HSSFRequest(); npc(request)->addListenerForAllRecords(ft); npc(factory)->processWorkbookEvents(request, _dir); return tl; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::hssf::extractor::EventBasedExcelExtractor::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.extractor.EventBasedExcelExtractor", 54); return c; } java::lang::Class* poi::hssf::extractor::EventBasedExcelExtractor::getClass0() { return class_(); }
36.619403
154
0.745058
pebble2015