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
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
7e35e04e7066acddba00032e0e0d836f78a4b3bf
150
hpp
C++
sdk/include/XWordLayerPage.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/XWordLayerPage.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/XWordLayerPage.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
#pragma once #include "xwordlayerbase.hpp" class XWordLayerPage : public XWordLayerBase { public: XWordLayerPage(void); ~XWordLayerPage(void); };
13.636364
29
0.766667
qianxj
7e3eb1c55aaf1ef9676ec529bcb9284f39af1ef6
3,846
hpp
C++
src/libArrhenius/Fitting/detail/EffectiveExposuresLinearRegression.hpp
CD3/libArrhenius
2cf65c9935c1661c6150ddfd86a999cf2fff2691
[ "MIT" ]
null
null
null
src/libArrhenius/Fitting/detail/EffectiveExposuresLinearRegression.hpp
CD3/libArrhenius
2cf65c9935c1661c6150ddfd86a999cf2fff2691
[ "MIT" ]
null
null
null
src/libArrhenius/Fitting/detail/EffectiveExposuresLinearRegression.hpp
CD3/libArrhenius
2cf65c9935c1661c6150ddfd86a999cf2fff2691
[ "MIT" ]
null
null
null
#ifndef Fitting_detail_EffectiveExposuresLinearRegression_hpp #define Fitting_detail_EffectiveExposuresLinearRegression_hpp /** @file EffectiveExposuresLinearRegression.hpp * @brief * @author C.D. Clark III * @date 07/07/17 */ #include <Eigen/Dense> #include "../../Utils/LinearRegression.hpp" namespace libArrhenius { /** @class ArrheniusFit<Real,EffectiveExposuresLinearRegression> * @brief Implements the "effective exposure" method from "Arrhenius Model Thermal Damage Coefficients for Birefringence Loss in Rabbit Myocardium" Pearse, Raghavan, and Thomsen (2003). * @author C.D. Clark III */ template<typename Real> class ArrheniusFit<Real,EffectiveExposuresLinearRegression> : public ArrheniusFitBase<Real> { public: ArrheniusFit() {}; virtual ~ArrheniusFit() {}; typedef typename ArrheniusFitBase<Real>::Return Return; Return exec() const { Return ret; ArrheniusIntegral<Real> integrator; std::vector<Real*> const &t = this->t; std::vector<Real*> const &T = this->T; std::vector<size_t> const &N = this->N; // construct effective exposure parameters for each profile Eigen::Matrix<Real,Eigen::Dynamic,1> logteff(N.size()),invTeff(N.size()); // Get a range for Ea to evaluate A over // If the caller has specified a bound use it. // otherwise, calculate one Real Ea_lb = 1; Real Ea_ub = 2; if( this->minEa ) { Ea_lb = this->minEa.get(); } if( this->maxEa ) { Ea_ub = this->maxEa.get(); } else { // If Ea is too large, then the Arrhenius integral will // return zero. The point at which this happens depends on the // data type being used. Basically, higher-precision types can // evaluate the integral at larger Ea's before reaching zero. // So, we know Ea can't be larger than the smallest value that // gives zero for the integral. This gives us an initial upper bound on Ea. for( size_t i = 0; i < N.size(); i++ ) { int prec = std::numeric_limits<Real>::digits - 3; eps_tolerance<Real> tol( prec ); boost::uintmax_t maxit = 100; Real guess = 1e2; // a place to start Real factor = 2; // multiplication factor to use when searching for upper bound auto Ea_ub_range = bracket_and_solve_root( [&](Real Ea){ integrator.setEa(Ea); integrator.setA(1); return integrator(N[i],t[i],T[i]);}, guess, factor, false, tol, maxit ); // use the smallest Ea for the upper bound. if( i == 0 || Ea_ub_range.first < Ea_ub ) Ea_ub = Ea_ub_range.first; } } // compute a set of (Ea,log(A)) pairs for(size_t i = 0; i < N.size(); i++) { // We'll calculate (Ea,log(A)) pairs for every half decade int emin = static_cast<int>(log10(Ea_lb)); int emax = static_cast<int>(log10(Ea_ub)); Real de = 0.1; int num = 1+static_cast<int>((emax - emin) / de); Eigen::Matrix<Real,Eigen::Dynamic,1> Eas(num),logAs(num); for(int j = 0; j < num; ++j) { Eas[j] = pow(10,emin + de*j); integrator.setEa(Eas[j]); integrator.setA(1); logAs[j] = -log( integrator(N[i], t[i], T[i]) ); } auto linreg = RUC::LinearRegression(Eas,logAs); // linreg[0] is 'b', // linreg[1] is 'm' for the fit logteff[i] = -linreg[0]; invTeff[i] = linreg[1]*Constants::MKS::R; } // now perform linear regression with effective parameters auto linreg = RUC::LinearRegression( invTeff, logteff ); ret.A = exp(-linreg[0]); ret.Ea = linreg[1]*Constants::MKS::R; return ret; } protected: }; } #endif // include protector
30.52381
186
0.605564
CD3
7e3eb3056e49f2e70b9e611a8112a220d9bc46ac
1,261
cpp
C++
main.cpp
dynamic21/radixSort
50a5e0a5099ad29b7dc73344c4098b76b4ff504f
[ "MIT" ]
null
null
null
main.cpp
dynamic21/radixSort
50a5e0a5099ad29b7dc73344c4098b76b4ff504f
[ "MIT" ]
null
null
null
main.cpp
dynamic21/radixSort
50a5e0a5099ad29b7dc73344c4098b76b4ff504f
[ "MIT" ]
null
null
null
#include <iostream> #include <chrono> #include <ratio> #include <algorithm> #include "RadixSort256.h" using std::cout; using std::endl; using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::steady_clock; unsigned int state = 90354; unsigned int xorshift32() { state ^= state << 13; state ^= state >> 17; state ^= state << 5; return state; } void GenerateRandomData(unsigned int *arr, int count) { for (int i = 0; i < count; i++) arr[i] = xorshift32() % 100; } int main() { int COUNT = 1000000; unsigned int *arr = new unsigned int[COUNT]; for (int r = 0; r < 10; r++) { steady_clock::time_point t1 = steady_clock::now(); GenerateRandomData(arr, COUNT); RadixSort256(arr, COUNT); steady_clock::time_point t2 = steady_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); cout << "Time: " << time_span.count() << endl; } // cout << endl; // cout << "Sorted list: " << endl; // for (int i = 0; i < COUNT; i++) // cout << i << ": " << arr[i] << endl; // for (int i = 1; i < COUNT; i++) // if (arr[i] < arr[i - 1]) // cout << "error" << endl; delete[] arr; }
25.22
78
0.564631
dynamic21
7e495eb59fd165d6dd0dbde975d7646571686708
529
hpp
C++
include/Module/Controller/Controller_static/Controller_static.hpp
FredrikBlomgren/aff3ct
fa616bd923b2dcf03a4cf119cceca51cf810d483
[ "MIT" ]
315
2016-06-21T13:32:14.000Z
2022-03-28T09:33:59.000Z
include/Module/Controller/Controller_static/Controller_static.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
153
2017-01-17T03:51:06.000Z
2022-03-24T15:39:26.000Z
include/Module/Controller/Controller_static/Controller_static.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
119
2017-01-04T14:31:58.000Z
2022-03-21T08:34:16.000Z
/*! * \file * \brief Class module::Controller_static. */ #ifndef CONTROLLER_STATIC_HPP_ #define CONTROLLER_STATIC_HPP_ #include <cstdint> #include "Module/Controller/Controller.hpp" namespace aff3ct { namespace module { class Controller_static : public Controller { public: Controller_static(const size_t init_path = 0); virtual ~Controller_static() = default; virtual Controller_static* clone() const; protected: virtual void _control(int8_t *out, const size_t frame_id); }; } } #endif /* CONTROLLER_STATIC_HPP_ */
17.064516
59
0.761815
FredrikBlomgren
7e4c5f877456ed5f0506b145b8adfc7c1d4cbbfb
1,294
cpp
C++
src/cpp/114. Flatten Binary Tree to Linked List.cpp
yjjnls/D.S.A-Leet
be19c3ccc1f704e75590786fdfd4cd3ab4818d4f
[ "MIT" ]
222
2018-09-25T08:46:31.000Z
2022-02-07T12:33:42.000Z
src/cpp/114. Flatten Binary Tree to Linked List.cpp
yjjnls/D.S.A-Leet
be19c3ccc1f704e75590786fdfd4cd3ab4818d4f
[ "MIT" ]
1
2017-11-23T04:39:48.000Z
2017-11-23T04:39:48.000Z
src/cpp/114. Flatten Binary Tree to Linked List.cpp
yjjnls/D.S.A-Leet
be19c3ccc1f704e75590786fdfd4cd3ab4818d4f
[ "MIT" ]
12
2018-10-05T03:16:05.000Z
2020-12-19T04:25:33.000Z
/* Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 click to show hints. Hints: If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <common.hpp> class Solution { public: void flatten(TreeNode *root) { if (root == NULL) { return; } TreeNode dummy(0); res_ = &dummy; preorder(root); root->left = NULL; root->right = dummy.right->right; } void preorder(TreeNode *root) { if (root != NULL) { TreeNode *node = new TreeNode(root->val); res_->right = node; res_ = res_->right; preorder(root->left); preorder(root->right); } } private: TreeNode *res_; }; //看似是简单的先序遍历,难点在于要在同一棵树上既遍历,又修改
18.225352
71
0.493818
yjjnls
7e5859f938508c753bef8d842abad7cf8e31e173
1,221
cpp
C++
codeforces/G - AI robots/Wrong answer on test 2.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/G - AI robots/Wrong answer on test 2.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/G - AI robots/Wrong answer on test 2.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Dec/04/2019 14:26 * solution_verdict: Wrong answer on test 2 language: GNU C++14 * run_time: 15 ms memory_used: 100 KB * problem: https://codeforces.com/contest/1045/problem/G ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; typedef tree<int,null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>Ordered_Set; const int N=1e6,inf=1e9; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,k;cin>>n>>k;map<int,Ordered_Set>mp; long long ans=0; for(int i=1;i<=n;i++) { int x,r,q;cin>>x>>r>>q; for(int j=q-k;j<=q+k;j++) { if(!mp.count(j))continue; ans+=mp[j].size(); ans-=mp[j].order_of_key(x-r); } mp[q].insert(x+r); } cout<<ans<<endl; return 0; }
37
111
0.470106
kzvd4729
7e58f3f558918fc4821fc27bd4312424e8b8a2f3
1,806
cpp
C++
vel_test.cpp
akalberer/robi_plugin
6e8a2d4b0abc516be67156ab0809a58ad3b829dd
[ "Apache-2.0" ]
null
null
null
vel_test.cpp
akalberer/robi_plugin
6e8a2d4b0abc516be67156ab0809a58ad3b829dd
[ "Apache-2.0" ]
null
null
null
vel_test.cpp
akalberer/robi_plugin
6e8a2d4b0abc516be67156ab0809a58ad3b829dd
[ "Apache-2.0" ]
null
null
null
#include <gazebo/gazebo_config.h> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> // Gazebo's API has changed between major releases. These changes are // accounted for with #if..#endif blocks in this file. #if GAZEBO_MAJOR_VERSION < 6 #include <gazebo/gazebo.hh> #else #include <gazebo/gazebo_client.hh> #endif ///////////////////////////////////////////////// int main(int _argc, char **_argv) { // Load gazebo as a client #if GAZEBO_MAJOR_VERSION < 6 gazebo::setupClient(_argc, _argv); #else gazebo::client::setup(_argc, _argv); #endif // Create our node for communication gazebo::transport::NodePtr node(new gazebo::transport::Node()); node->Init(); // Publish to the robi topics gazebo::transport::PublisherPtr pub_left = node->Advertise<gazebo::msgs::Vector3d>("~/robi_model/robi_cmd_left"); gazebo::transport::PublisherPtr pub_right = node->Advertise<gazebo::msgs::Vector3d>("~/robi_model/robi_cmd_right"); // Wait for a subscriber to connect to this publisher pub_left->WaitForConnection(); pub_right->WaitForConnection(); // Create a a vector3 message gazebo::msgs::Vector3d msg_left; gazebo::msgs::Vector3d msg_right; // Set the velocity in the x-component #if GAZEBO_MAJOR_VERSION < 6 gazebo::msgs::Set(&msg_left, gazebo::math::Vector3(std::atof(_argv[1]), 0, 0)); gazebo::msgs::Set(&msg_right, gazebo::math::Vector3(std::atof(_argv[2]), 0, 0)); #else gazebo::msgs::Set(&msg_left, ignition::math::Vector3d(std::atof(_argv[1]), 0, 0)); gazebo::msgs::Set(&msg_right, ignition::math::Vector3d(std::atof(_argv[2]), 0, 0)); #endif // Send the message pub_left->Publish(msg_left); pub_right->Publish(msg_right); // Make sure to shut everything down. #if GAZEBO_MAJOR_VERSION < 6 gazebo::shutdown(); #else gazebo::client::shutdown(); #endif }
30.610169
116
0.708195
akalberer
7e5b26742ad275052bd0c05a66455bdb2dad2ee9
2,778
cpp
C++
tengine/tools/leveleditor/createentitypanel.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
5
2015-07-03T18:42:32.000Z
2017-08-25T10:28:12.000Z
tengine/tools/leveleditor/createentitypanel.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
tengine/tools/leveleditor/createentitypanel.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
#include "createentitypanel.h" #include <glgui/movablepanel.h> #include <glgui/menu.h> #include <glgui/textfield.h> #include <game/entities/baseentity.h> #include "entitypropertiespanel.h" CCreateEntityPanel::CCreateEntityPanel() : glgui::CMovablePanel("Create Entity Tool") { m_hClass = AddControl(new glgui::CMenu("Choose Class")); for (size_t i = 0; i < CBaseEntity::GetNumEntitiesRegistered(); i++) { CEntityRegistration* pRegistration = CBaseEntity::GetEntityRegistration(i); if (!pRegistration->m_bCreatableInEditor) continue; m_hClass->AddSubmenu(pRegistration->m_pszEntityClass+1, this, ChooseClass); } m_hNameLabel = AddControl(new glgui::CLabel("Name:", "sans-serif", 10)); m_hNameLabel->SetAlign(glgui::CLabel::TA_TOPLEFT); m_hNameText = AddControl(new glgui::CTextField()); m_hModelLabel = AddControl(new glgui::CLabel("Model:", "sans-serif", 10)); m_hModelLabel->SetAlign(glgui::CLabel::TA_TOPLEFT); m_hModelText = AddControl(new glgui::CTextField()); m_hModelText->SetContentsChangedListener(this, ModelChanged); m_hPropertiesPanel = AddControl(new CEntityPropertiesPanel(false)); m_hPropertiesPanel->SetVisible(false); m_bReadyToCreate = false; } void CCreateEntityPanel::Layout() { m_hClass->SetWidth(100); m_hClass->SetHeight(30); m_hClass->CenterX(); m_hClass->SetTop(30); float flTop = 70; m_hNameLabel->SetLeft(15); m_hNameLabel->SetTop(flTop); m_hNameText->SetWidth(GetWidth()-30); m_hNameText->CenterX(); m_hNameText->SetTop(flTop+12); flTop += 43; m_hModelLabel->SetLeft(15); m_hModelLabel->SetTop(flTop); m_hModelText->SetWidth(GetWidth()-30); m_hModelText->CenterX(); m_hModelText->SetTop(flTop+12); flTop += 43; m_hPropertiesPanel->SetTop(flTop); m_hPropertiesPanel->SetLeft(10); m_hPropertiesPanel->SetWidth(GetWidth()-20); m_hPropertiesPanel->SetBackgroundColor(Color(10, 10, 10)); if (m_bReadyToCreate) { m_hPropertiesPanel->SetClass("C" + m_hClass->GetText()); m_hPropertiesPanel->SetVisible(true); } BaseClass::Layout(); SetHeight(m_hPropertiesPanel->GetBottom()+15); } void CCreateEntityPanel::ChooseClassCallback(const tstring& sArgs) { tvector<tstring> asTokens; strtok(sArgs, asTokens); m_hClass->SetText(asTokens[1]); m_hClass->Pop(true, true); m_bReadyToCreate = true; Layout(); } void CCreateEntityPanel::ModelChangedCallback(const tstring& sArgs) { if (!m_hModelText->GetText().length()) return; tvector<tstring> asExtensions; tvector<tstring> asExtensionsExclude; asExtensions.push_back(".toy"); asExtensions.push_back(".mat"); asExtensionsExclude.push_back(".mesh.toy"); asExtensionsExclude.push_back(".phys.toy"); asExtensionsExclude.push_back(".area.toy"); m_hModelText->SetAutoCompleteFiles(".", asExtensions, asExtensionsExclude); }
25.027027
77
0.75162
BSVino
7e5e163aa4872b048b703a43679b54e23657bc5e
4,392
hpp
C++
inquiries/signal_inquiry.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
null
null
null
inquiries/signal_inquiry.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
null
null
null
inquiries/signal_inquiry.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
1
2015-09-22T03:32:11.000Z
2015-09-22T03:32:11.000Z
#ifndef HMLIB_INQUIRIES_SIGNALINQUIRY_INC #define HMLIB_INQUIRIES_SIGNALINQUIRY_INC 102 # /*===inquiries::signal_inquiry=== operator()(void)で、取得した値を返さずに、Signalを発信するinquiry inquiries::signal_inquiry v1_02/130421 hmIto 関数型に対応 exceptionsに対応 inquiries::signal_inquiry v1_01/130329 hmIto inquiryで値取得した結果、前回の値と変わりない場合はsignalを発信する、changed_signal_inquiryを追加 コピーコンストラクタ/代入演算子を明示的にprivate化 グローバル関数にconnect関数を追加 inquiries::signal_inquiry v1_00/130328 hmIto 新規作成 */ #include<boost/signals2.hpp> #ifndef HMLIB_EXCEPTIONS_INC # include"../exceptions.hpp" #endif #ifndef HMLIB_INQUIRIES_INQUIRYABSTRUCT_INC # include"inquiry_abstruct.hpp" #endif namespace hmLib{ namespace inquiries{ template<typename T> class signal_inquiry:public inquiry_abstruct{ typedef signal_inquiry<T> my_type; typedef std::function<const T(void)> func_type; typedef boost::signals2::signal<void(const T&)> signal; public: signal Signal; private: func_type func; bool locked; mutex_proxy mx; public: signal_inquiry():func(),locked(false),mx(){} signal_inquiry(my_type&& My_):func(),locked(false),mx(){ std::swap(func,My_.func); std::swap(locked,My_.locked); std::swap(mx,My_.mx); } const my_type& operator=(my_type&& My_){ hmLib_assert(!is_connect(),connected_exception,"signal_inquiry have already connected"); std::swap(func,My_.func); std::swap(locked,My_.locked); std::swap(mx,My_.mx); return *this; } private: signal_inquiry(const my_type& My_); const my_type& operator=(const my_type& My_); public: connection connect(func_type&& func_){ hmLib_assert(!is_connect(),connected_exception,"signal_inquiry have already connected"); func=func_; return create_connection(); } template<typename Mutex_> connection connect(func_type&& func_,Mutex_& mx_){ hmLib_assert(!is_connect(),connected_exception,"signal_inquiry have already connected"); func=func_; mx=mutex_proxy(mx_); return create_connection(); } void operator()(void)const{ hmLib_assert(is_connect(),unconnected_exception,"signal_inquiry have not connected yet"); if(mx.is_proxy()){ std::lock_guard<mutex_proxy> Lock(mx); Signal(func_()); }else{ Signal(func_()); } } }; template<typename T> class revise_signal_inquiry:public inquiry_abstruct{ typedef revise_signal_inquiry<T> my_type; typedef std::function<const T(void)> func_type; typedef boost::signals2::signal<void(const T&)> signal; public: signal Signal; private: bool Active; T last_val; func_type func; bool locked; mutex_proxy mx; public: revise_signal_inquiry():func(),locked(false),mx(),Active(false){} revise_signal_inquiry(my_type&& My_):func(),locked(false),mx(),Active(false){ std::swap(func,My_.func); std::swap(locked,My_.locked); std::swap(mx,My_.mx); std::swap(Active,My_.Active); std::swap(last_val,My_.last_val); } const my_type& operator=(my_type&& My_){ hmLib_assert(!is_connect(),connected_exception,"revise_signal_inquiry have already connected"); std::swap(func,My_.func); std::swap(locked,My_.locked); std::swap(mx,My_.mx); std::swap(Active,My_.Active); std::swap(last_val,My_.last_val); return *this; } private: revise_signal_inquiry(const my_type& My_); const my_type& operator=(const my_type& My_); public: connection connect(func_type&& func_){ hmLib_assert(!is_connect(),connected_exception,"revise_signal_inquiry have already connected"); func=func_; Active=false; return create_connection(); } template<typename Mutex_> connection connect(func_type&& func_,Mutex_& mx_){ hmLib_assert(!is_connect(),connected_exception,"revise_signal_inquiry have already connected"); func=func_; Active=false; mx=mutex_proxy(mx_); return create_connection(); } void operator()(void)const{ hmLib_assert(is_connect(),unconnected_exception,"revise_signal_inquiry have not connected yet"); if(mx.is_proxy()){ std::lock_guard<mutex_proxy> Lock(mx); T tmp=func_(); if(Active==false || tmp!=last_val){ Active=true; val=std::move(tmp); Signal(val); } }else{ T tmp=func_(); if(Active==false || tmp!=last_val){ Active=true; val=std::move(tmp); Signal(val); } } } }; } } # #endif
29.28
100
0.704918
hmito
7e625505690c6f2af92b66cca26db8f2c3b2b189
16,701
hpp
C++
include/strf/detail/format_functions.hpp
eyalroz/strf
94cd5aef40530269da0727178017cb4a8992c5dc
[ "BSL-1.0" ]
null
null
null
include/strf/detail/format_functions.hpp
eyalroz/strf
94cd5aef40530269da0727178017cb4a8992c5dc
[ "BSL-1.0" ]
18
2019-12-13T15:52:26.000Z
2020-01-17T14:51:33.000Z
include/strf/detail/format_functions.hpp
eyalroz/strf
94cd5aef40530269da0727178017cb4a8992c5dc
[ "BSL-1.0" ]
1
2021-12-23T05:53:22.000Z
2021-12-23T05:53:22.000Z
#ifndef STRF_DETAIL_FORMAT_FUNCTIONS_HPP #define STRF_DETAIL_FORMAT_FUNCTIONS_HPP // 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) #include <strf/detail/common.hpp> #include <cstring> namespace strf { namespace detail{ template < class From , class To , template <class ...> class List , class ... T > struct fmt_replace_impl2 { template <class U> using f = std::conditional_t<std::is_same<From, U>::value, To, U>; using type = List<f<T> ...>; }; template <class From, class List> struct fmt_replace_impl; template < class From , template <class ...> class List , class ... T> struct fmt_replace_impl<From, List<T ...> > { template <class To> using type_tmpl = typename strf::detail::fmt_replace_impl2 < From, To, List, T...>::type; }; template <typename FmtA, typename FmtB, typename ValueWithFormat> struct fmt_forward_switcher { template <typename FmtAInit> static const typename FmtB::template fn<ValueWithFormat>& f(const FmtAInit&, const ValueWithFormat& v) { return v; } template <typename FmtAInit> static typename FmtB::template fn<ValueWithFormat>&& f(const FmtAInit&, ValueWithFormat&& v) { return v; } }; template <typename FmtA, typename ValueWithFormat> struct fmt_forward_switcher<FmtA, FmtA, ValueWithFormat> { template <typename FmtAInit> static constexpr STRF_HD FmtAInit&& f(std::remove_reference_t<FmtAInit>& fa, const ValueWithFormat&) { return static_cast<FmtAInit&&>(fa); } template <typename FmtAInit> static constexpr STRF_HD FmtAInit&& f(std::remove_reference_t<FmtAInit>&& fa, const ValueWithFormat&) { return static_cast<FmtAInit&&>(fa); } }; } // namespace detail template <typename List, typename From, typename To> using fmt_replace = typename strf::detail::fmt_replace_impl<From, List> ::template type_tmpl<To>; template <typename ValueType, class ... Fmts> class value_with_format; template <typename ValueType, class ... Fmts> class value_with_format : public Fmts::template fn<value_with_format<ValueType, Fmts ...>> ... { public: template <typename ... OhterFmts> using replace_fmts = strf::value_with_format<ValueType, OhterFmts ...>; explicit constexpr STRF_HD value_with_format(const ValueType& v) : _value(v) { } template <typename OtherValueType> constexpr STRF_HD value_with_format ( const ValueType& v , const strf::value_with_format<OtherValueType, Fmts...>& f ) : Fmts::template fn<value_with_format<ValueType, Fmts...>> ( static_cast < const typename Fmts :: template fn<value_with_format<OtherValueType, Fmts...>>& >(f) ) ... , _value(v) { } template <typename OtherValueType> constexpr STRF_HD value_with_format ( const ValueType& v , strf::value_with_format<OtherValueType, Fmts...>&& f ) : Fmts::template fn<value_with_format<ValueType, Fmts...>> ( static_cast < typename Fmts :: template fn<value_with_format<OtherValueType, Fmts...>> &&>(f) ) ... , _value(static_cast<ValueType&&>(v)) { } template <typename ... F, typename ... FInit> constexpr STRF_HD value_with_format ( const ValueType& v , strf::tag<F...> , FInit&& ... finit ) : F::template fn<value_with_format<ValueType, Fmts...>> (std::forward<FInit>(finit)) ... , _value(v) { } template <typename ... OtherFmts> constexpr STRF_HD value_with_format ( const strf::value_with_format<ValueType, OtherFmts...>& f ) : Fmts::template fn<value_with_format<ValueType, Fmts...>> ( static_cast < const typename OtherFmts :: template fn<value_with_format<ValueType, OtherFmts ...>>& >(f) ) ... , _value(f.value()) { } template <typename ... OtherFmts> constexpr STRF_HD value_with_format ( strf::value_with_format<ValueType, OtherFmts...>&& f ) : Fmts::template fn<value_with_format<ValueType, Fmts...>> ( static_cast < typename OtherFmts :: template fn<value_with_format<ValueType, OtherFmts ...>>&& >(f) ) ... , _value(static_cast<ValueType&&>(f.value())) { } template <typename Fmt, typename FmtInit, typename ... OtherFmts> constexpr STRF_HD value_with_format ( const strf::value_with_format<ValueType, OtherFmts...>& f , strf::tag<Fmt> , FmtInit&& fmt_init ) : Fmts::template fn<value_with_format<ValueType, Fmts...>> ( strf::detail::fmt_forward_switcher < Fmt , Fmts , strf::value_with_format<ValueType, OtherFmts...> > :: template f<FmtInit>(fmt_init, f) ) ... , _value(f.value()) { } constexpr STRF_HD const ValueType& value() const { return _value; } constexpr STRF_HD ValueType& value() { return _value; } private: ValueType _value; }; template <bool Active> struct alignment_format_q; enum class text_alignment {left, right, split, center}; struct alignment_format_data { char32_t fill = U' '; std::int16_t width = 0; strf::text_alignment alignment = strf::text_alignment::right; }; constexpr STRF_HD bool operator==( strf::alignment_format_data lhs , strf::alignment_format_data rhs ) noexcept { return lhs.fill == rhs.fill && lhs.width == rhs.width && lhs.alignment == rhs.alignment ; } constexpr STRF_HD bool operator!=( strf::alignment_format_data lhs , strf::alignment_format_data rhs ) noexcept { return ! (lhs == rhs); } template <bool Active, class T> class alignment_format_fn { T& as_derived_ref() { T* d = static_cast<T*>(this); return *d; } T&& as_derived_rval_ref() { T* d = static_cast<T*>(this); return static_cast<T&&>(*d); } public: constexpr STRF_HD alignment_format_fn() noexcept { } constexpr STRF_HD explicit alignment_format_fn ( strf::alignment_format_data data) noexcept : _data(data) { } template <bool B, typename U> constexpr STRF_HD explicit alignment_format_fn ( const strf::alignment_format_fn<B, U>& u ) noexcept : _data(u.get_alignment_format_data()) { } constexpr STRF_HD T&& operator<(std::int16_t width) && noexcept { _data.alignment = strf::text_alignment::left; _data.width = width; return as_derived_rval_ref(); } constexpr STRF_HD T&& operator>(std::int16_t width) && noexcept { _data.alignment = strf::text_alignment::right; _data.width = width; return as_derived_rval_ref(); } constexpr STRF_HD T&& operator^(std::int16_t width) && noexcept { _data.alignment = strf::text_alignment::center; _data.width = width; return as_derived_rval_ref(); } constexpr STRF_HD T&& operator%(std::int16_t width) && noexcept { _data.alignment = strf::text_alignment::split; _data.width = width; return as_derived_rval_ref(); } constexpr STRF_HD T&& fill(char32_t ch) && noexcept { _data.fill = ch; return as_derived_rval_ref(); } constexpr STRF_HD std::int16_t width() const noexcept { return _data.width; } constexpr STRF_HD strf::text_alignment alignment() const noexcept { return _data.alignment; } constexpr STRF_HD char32_t fill() const noexcept { return _data.fill; } constexpr STRF_HD alignment_format_data get_alignment_format_data() const noexcept { return _data; } private: strf::alignment_format_data _data; }; template <class T> class alignment_format_fn<false, T> { using derived_type = T; using adapted_derived_type = strf::fmt_replace < T , strf::alignment_format_q<false> , strf::alignment_format_q<true> >; constexpr STRF_HD adapted_derived_type make_adapted() const { return adapted_derived_type{static_cast<const T&>(*this)}; } public: constexpr STRF_HD alignment_format_fn() noexcept { } template <typename U> constexpr STRF_HD explicit alignment_format_fn(const alignment_format_fn<false, U>&) noexcept { } constexpr STRF_HD adapted_derived_type operator<(std::int16_t width) const noexcept { return adapted_derived_type { static_cast<const T&>(*this) , strf::tag<alignment_format_q<true>>{} , strf::alignment_format_data{ U' ' , width , strf::text_alignment::left } }; } constexpr STRF_HD adapted_derived_type operator>(std::int16_t width) const noexcept { return adapted_derived_type { static_cast<const T&>(*this) , strf::tag<alignment_format_q<true>>{} , strf::alignment_format_data{ U' ' , width , strf::text_alignment::right } }; } constexpr STRF_HD adapted_derived_type operator^(std::int16_t width) const noexcept { return adapted_derived_type { static_cast<const T&>(*this) , strf::tag<alignment_format_q<true>>{} , strf::alignment_format_data{ U' ' , width , strf::text_alignment::center } }; } constexpr STRF_HD adapted_derived_type operator%(std::int16_t width) const noexcept { return adapted_derived_type { static_cast<const T&>(*this) , strf::tag<alignment_format_q<true>>{} , strf::alignment_format_data{ U' ' , width , strf::text_alignment::split } }; } constexpr STRF_HD auto fill(char32_t ch) const noexcept { return adapted_derived_type { static_cast<const T&>(*this) , strf::tag<alignment_format_q<true>>{} , strf::alignment_format_data{ ch } }; } constexpr STRF_HD std::int16_t width() const noexcept { return 0; } constexpr STRF_HD strf::text_alignment alignment() const noexcept { return strf::text_alignment::right; } constexpr STRF_HD char32_t fill() const noexcept { return U' '; } constexpr STRF_HD alignment_format_data get_alignment_format_data() const noexcept { return {}; } }; template <bool Active> struct alignment_format_q { template <class T> using fn = strf::alignment_format_fn<Active, T>; }; using alignment_format = strf::alignment_format_q<true>; using empty_alignment_format = strf::alignment_format_q<false>; template <class T> class quantity_format_fn { public: constexpr STRF_HD quantity_format_fn(std::size_t count) noexcept : _count(count) { } constexpr STRF_HD quantity_format_fn() noexcept { } template <typename U> constexpr STRF_HD explicit quantity_format_fn(const quantity_format_fn<U>& u) noexcept : _count(u.count()) { } constexpr STRF_HD T&& multi(std::size_t count) && noexcept { _count = count; return static_cast<T&&>(*this); } constexpr STRF_HD std::size_t count() const noexcept { return _count; } private: std::size_t _count = 1; }; struct quantity_format { template <class T> using fn = strf::quantity_format_fn<T>; }; template <typename T> constexpr STRF_HD auto fmt(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(make_fmt(strf::rank<5>{}, value))>> { return make_fmt(strf::rank<5>{}, value); } template <typename T> constexpr STRF_HD auto hex(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).hex())>> { return fmt(value).hex(); } template <typename T> constexpr STRF_HD auto dec(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).dec())>> { return fmt(value).dec(); } template <typename T> constexpr STRF_HD auto oct(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).oct())>> { return fmt(value).oct(); } template <typename T> constexpr STRF_HD auto bin(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).bin())>> { return fmt(value).bin(); } template <typename T> constexpr STRF_HD auto left(const T& value, std::int16_t width) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value) < width)>> { return fmt(value) < width; } template <typename T> constexpr STRF_HD auto right(const T& value, std::int16_t width) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value) > width)>> { return fmt(value) > width; } template <typename T> constexpr STRF_HD auto split(const T& value, std::int16_t width) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value) % width)>> { return fmt(value) % width; } template <typename T> constexpr STRF_HD auto center(const T& value, std::int16_t width) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value) ^ width)>> { return fmt(value) ^ width; } template <typename T> constexpr STRF_HD auto left(const T& value, std::int16_t width, char32_t fill) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).fill(fill) < width)>> { return fmt(value).fill(fill) < width; } template <typename T> constexpr STRF_HD auto right(const T& value, std::int16_t width, char32_t fill) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).fill(fill) > width)>> { return fmt(value).fill(fill) > width; } template <typename T> constexpr STRF_HD auto split(const T& value, std::int16_t width, char32_t fill) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).fill(fill) % width)>> { return fmt(value).fill(fill) % width; } template <typename T> constexpr STRF_HD auto center(const T& value, std::int16_t width, char32_t fill) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).fill(fill) ^ width)>> { return fmt(value).fill(fill) ^ width; } template <typename T, typename I> constexpr STRF_HD auto multi(const T& value, I count) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).multi(count))>> { return fmt(value).multi(count); } template <typename T> constexpr STRF_HD auto fixed(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).fixed())>> { return fmt(value).fixed(); } template <typename T> constexpr STRF_HD auto sci(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).sci())>> { return fmt(value).sci(); } template <typename T, typename P> constexpr STRF_HD auto fixed(const T& value, P precision) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).fixed().p(precision))>> { return fmt(value).fixed().p(precision); } template <typename T, typename P> constexpr STRF_HD auto sci(const T& value, P precision) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).sci().p(precision))>> { return fmt(value).sci().p(precision); } template <typename T> constexpr STRF_HD auto cv(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).cv())>> { return fmt(value).convert_charset(); // defined in no_cv_format_fn } template <typename T, typename E> constexpr STRF_HD auto cv(const T& value, const E& e) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).cv(e))>> { return fmt(value).convert_charset(e); // defined in no_cv_format_fn } template <typename T> constexpr STRF_HD auto sani(const T& value) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).sani())>> { return fmt(value).sanitize_charset(); // defined in no_cv_format_fn } template <typename T, typename E> constexpr STRF_HD auto sani(const T& value, const E& e) -> std::remove_cv_t<std::remove_reference_t<decltype(fmt(value).sani(e))>> { return fmt(value).sanitize_charset(e); // defined in no_cv_format_fn } } // namespace strf #endif // STRF_DETAIL_FORMAT_FUNCTIONS_HPP
27.514003
119
0.640081
eyalroz
7e62a15f12cd19eb3155c223f549a8e30a98c887
288
cpp
C++
node_modules/lzz-gyp/lzz-source/gram_CreateLineMacro.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/gram_CreateLineMacro.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/gram_CreateLineMacro.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// gram_CreateLineMacro.cpp // #include "gram_CreateLineMacro.h" // gram #include "gram_LineMacro.h" #define LZZ_INLINE inline namespace gram { MacroPtr createLineMacro (util::Loc const & loc, util::Ident const & name) { return new LineMacro (loc, name); } } #undef LZZ_INLINE
18
76
0.722222
SuperDizor
7e63ba68e85aaae572a32e55dcf1a421889e0d2d
4,751
cpp
C++
QtWebApp/httpserver/httpsessionstore.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
QtWebApp/httpserver/httpsessionstore.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
QtWebApp/httpserver/httpsessionstore.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
/** @file @author Stefan Frings */ #include "httpsessionstore.h" #include <QDateTime> #include <QUuid> using namespace stefanfrings; HttpSessionStore::HttpSessionStore( const QSettings* settings, QObject* parent ) : QObject( parent ), m_settings( settings ), m_cookieName( settings->value( "cookieName", "sessionid" ).toByteArray() ), m_expirationTime( settings->value( "expirationTime", 3600000 ).toInt() ) { connect( &m_cleanupTimer, SIGNAL(timeout()), this, SLOT(sessionTimerEvent()) ); m_cleanupTimer.start( 60000 ); #ifdef SUPERVERBOSE qDebug( "HttpSessionStore: Sessions expire after %i milliseconds", m_expirationTime ); #endif } HttpSessionStore::~HttpSessionStore() { m_cleanupTimer.stop(); } QByteArray HttpSessionStore::getSessionId( const HttpRequest& request, HttpResponse& response ) { // The session ID in the response has priority because this one will be used in the next request. m_mutex.lock(); // Get the session ID from the response cookie QByteArray sessionId = response.getCookies().value( m_cookieName ).getValue(); if ( sessionId.isEmpty() ) { // Get the session ID from the request cookie sessionId = request.getCookie( m_cookieName ); } // Clear the session ID if there is no such session in the storage. if ( !sessionId.isEmpty() ) { if ( !sessions.contains( sessionId ) ) { #ifdef SUPERVERBOSE qDebug( "HttpSessionStore: received invalid session cookie with ID %s", sessionId.data() ); #endif sessionId.clear(); } } m_mutex.unlock(); return sessionId; } HttpSession HttpSessionStore::getSession( const HttpRequest& request, HttpResponse& response, bool allowCreate ) { QByteArray sessionId = getSessionId( request, response ); m_mutex.lock(); if ( !sessionId.isEmpty() ) { HttpSession session = sessions.value( sessionId ); if ( !session.isNull() ) { m_mutex.unlock(); // Refresh the session cookie QByteArray cookieName = m_settings->value( "cookieName", "sessionid" ).toByteArray(); QByteArray cookiePath = m_settings->value( "cookiePath" ).toByteArray(); QByteArray cookieComment = m_settings->value( "cookieComment" ).toByteArray(); QByteArray cookieDomain = m_settings->value( "cookieDomain" ).toByteArray(); response.setCookie( HttpCookie( cookieName, session.getId(), m_expirationTime / 1000, cookiePath, cookieComment, cookieDomain, false, false, "Lax" ) ); session.setLastAccess(); return session; } } // Need to create a new session if ( allowCreate ) { QByteArray cookieName = m_settings->value( "cookieName", "sessionid" ).toByteArray(); QByteArray cookiePath = m_settings->value( "cookiePath" ).toByteArray(); QByteArray cookieComment = m_settings->value( "cookieComment" ).toByteArray(); QByteArray cookieDomain = m_settings->value( "cookieDomain" ).toByteArray(); HttpSession session( true ); #ifdef SUPERVERBOSE qDebug( "HttpSessionStore: create new session with ID %s", session.getId().data() ); #endif sessions.insert( session.getId(), session ); response.setCookie( HttpCookie( cookieName, session.getId(), m_expirationTime / 1000, cookiePath, cookieComment, cookieDomain, false, false, "Lax" ) ); m_mutex.unlock(); return session; } // Return a null session m_mutex.unlock(); return HttpSession(); } HttpSession HttpSessionStore::getSession( const QByteArray& id ) { m_mutex.lock(); HttpSession session = sessions.value( id ); m_mutex.unlock(); session.setLastAccess(); return session; } void HttpSessionStore::sessionTimerEvent() { m_mutex.lock(); qint64 now = QDateTime::currentMSecsSinceEpoch(); QMap<QByteArray, HttpSession>::iterator i = sessions.begin(); while ( i != sessions.end() ) { QMap<QByteArray, HttpSession>::iterator prev = i; ++i; HttpSession session = prev.value(); qint64 lastAccess = session.getLastAccess(); if ( ( now - lastAccess ) > m_expirationTime ) { #ifdef SUPERVERBOSE qDebug( "HttpSessionStore: session %s expired", session.getId().data() ); #endif emit sessionDeleted( session.getId() ); sessions.erase( prev ); } } m_mutex.unlock(); } /** Delete a session */ void HttpSessionStore::removeSession( const HttpSession& session ) { m_mutex.lock(); emit sessionDeleted( session.getId() ); sessions.remove( session.getId() ); m_mutex.unlock(); }
37.706349
114
0.651442
cbcalves
7e68539b774399938d58b8bfe3a5a14ca9165d05
831
cc
C++
gui/PiiGuiUtil.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-19T22:14:18.000Z
2020-04-13T23:27:20.000Z
gui/PiiGuiUtil.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
null
null
null
gui/PiiGuiUtil.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-16T05:43:15.000Z
2019-01-29T07:57:11.000Z
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiGuiUtil.h" #include <QPixmap> #include <QColor> namespace PiiGui { QIcon createIcon(int width, int height, const QColor& color) { QPixmap pixmap(width, height); pixmap.fill(color); return QIcon(pixmap); } }
28.655172
69
0.736462
topiolli
7e6a18bdebd08be0c3e756333d1f8c71687414f7
2,887
cc
C++
src/TBUI/TBUIWindow.cc
floooh/oryol-turbobadger
dd0afc300629efc6bd1c90e829895e3148916ad6
[ "MIT" ]
8
2016-12-18T21:42:42.000Z
2019-01-11T02:36:25.000Z
src/TBUI/TBUIWindow.cc
floooh/oryol-turbobadger
dd0afc300629efc6bd1c90e829895e3148916ad6
[ "MIT" ]
1
2019-10-09T15:19:31.000Z
2019-10-10T10:02:48.000Z
src/TBUI/TBUIWindow.cc
floooh/oryol-turbobadger
dd0afc300629efc6bd1c90e829895e3148916ad6
[ "MIT" ]
1
2019-01-11T02:36:27.000Z
2019-01-11T02:36:27.000Z
//------------------------------------------------------------------------------ // TBUIWindow.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "TBUI/TBUI.h" #include "TBUIWindow.h" #include "tb_skin.h" #include "tb_node_tree.h" #include "tb_widgets_reader.h" namespace Oryol { //------------------------------------------------------------------------------ TBUIWindow::TBUIWindow() { TBUI::getRootWidget()->AddChild(this); } //------------------------------------------------------------------------------ TBUIWindow::~TBUIWindow() { // FIXME? } //------------------------------------------------------------------------------ void TBUIWindow::LoadResourceFile(const URL& url) { tb::TBNode node; node.ReadFile(url.AsCStr()); this->LoadResource(node); } //------------------------------------------------------------------------------ void TBUIWindow::LoadResource(tb::TBNode& node) { // see TurboBadger DemoWindow class tb::g_widgets_reader->LoadNodeTree(this, &node); // Get title from the WindowInfo section (or use "" if not specified) this->SetText(node.GetValueString("WindowInfo>title", "")); const tb::TBRect parent_rect(0, 0, this->GetParent()->GetRect().w, this->GetParent()->GetRect().h); const tb::TBDimensionConverter *dc = tb::g_tb_skin->GetDimensionConverter(); tb::TBRect window_rect = this->GetResizeToFitContentRect(); // Use specified size or adapt to the preferred content size. tb::TBNode *tmp = node.GetNode("WindowInfo>size"); if (tmp && tmp->GetValue().GetArrayLength() == 2) { window_rect.w = dc->GetPxFromString(tmp->GetValue().GetArray()->GetValue(0)->GetString(), window_rect.w); window_rect.h = dc->GetPxFromString(tmp->GetValue().GetArray()->GetValue(1)->GetString(), window_rect.h); } // Use the specified position or center in parent. tmp = node.GetNode("WindowInfo>position"); if (tmp && tmp->GetValue().GetArrayLength() == 2) { window_rect.x = dc->GetPxFromString(tmp->GetValue().GetArray()->GetValue(0)->GetString(), window_rect.x); window_rect.y = dc->GetPxFromString(tmp->GetValue().GetArray()->GetValue(1)->GetString(), window_rect.y); } else { window_rect = window_rect.CenterIn(parent_rect); } // Make sure the window is inside the parent, and not larger. window_rect = window_rect.MoveIn(parent_rect).Clip(parent_rect); this->SetRect(window_rect); // Ensure we have focus - now that we've filled the window with possible focusable // widgets. EnsureFocus was automatically called when the window was activated (by // adding the window to the root), but then we had nothing to focus. // Alternatively, we could add the window after setting it up properly. this->EnsureFocus(); } } // namespace Oryol
38.493333
113
0.567371
floooh
7e72627530f2f17c81b95e249cd7663751040b9e
2,259
cpp
C++
apps/hls_examples/stereo_hls/run_cuda.cpp
akifoezkan/Halide-HLS
1eee3f38f32722f3e725c29a5b7a084275062a7f
[ "MIT" ]
71
2016-11-17T19:22:21.000Z
2022-01-10T10:03:58.000Z
apps/hls_examples/stereo_hls/run_cuda.cpp
akifoezkan/Halide-HLS
1eee3f38f32722f3e725c29a5b7a084275062a7f
[ "MIT" ]
79
2019-02-22T03:27:45.000Z
2022-02-24T23:03:28.000Z
apps/hls_examples/stereo_hls/run_cuda.cpp
akifoezkan/Halide-HLS
1eee3f38f32722f3e725c29a5b7a084275062a7f
[ "MIT" ]
22
2017-04-16T11:44:34.000Z
2022-03-26T13:27:10.000Z
#include <cstdio> #include <cstdlib> #include <cassert> #include <math.h> #include "pipeline_cuda.h" #include "pipeline_native.h" #include "benchmark.h" #include "halide_image.h" #include "halide_image_io.h" #include "opencv2/gpu/gpu.hpp" #include "opencv2/highgui/highgui.hpp" using namespace Halide::Tools; using namespace cv; int main(int argc, char **argv) { if (argc < 5) { printf("Usage: ./run left.png left-remap.png right0224.png right-remap.png\n"); return 0; } int iter = 5; Image<uint8_t> left = load_image(argv[1]); Image<uint8_t> left_remap = load_image(argv[2]); Image<uint8_t> right = load_image(argv[3]); Image<uint8_t> right_remap = load_image(argv[4]); Image<uint8_t> out_native(left.width(), left.height()); Image<uint8_t> out_cuda(left.width(), left.height()); printf("\nstart timing code...\n"); // Timing code. Timing doesn't include copying the input data to // the gpu or copying the output back. double min_t = benchmark(iter, 10, [&]() { pipeline_native(right, left, right_remap, left_remap, out_native); }); printf("CPU program runtime: %g\n", min_t * 1e3); save_image(out_native, "out_native.png"); // Timing code. Timing doesn't include copying the input data to // the gpu or copying the output back. double min_t2 = benchmark(iter, 10, [&]() { pipeline_cuda(right, left, right_remap, left_remap, out_cuda); }); printf("Halide CUDA program runtime: %g\n", min_t2 * 1e3); save_image(out_cuda, "out_cuda.png"); Mat cv_left = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE ); Mat cv_right = imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE ); gpu::GpuMat d_left(cv_left); gpu::GpuMat d_right(cv_right); gpu::GpuMat d_disp(cv_left.size(), CV_8U); int ndisparities = 16*4; /**< Range of disparity */ int SADWindowSize = 9; /**< Size of the block window. Must be odd */ gpu::StereoBM_GPU bm(gpu::StereoBM_GPU::BASIC_PRESET, ndisparities, SADWindowSize); double min_t3 = benchmark(iter, 10, [&]() { bm(d_left, d_right, d_disp); }); printf("OpenCV CUDA program runtime: %g\n", min_t3 * 1e3); //save_image(out_cuda, "out_cuda.png"); return 0; }
31.816901
87
0.658256
akifoezkan
7e78894fc5934b19935dcbf538dd14c855edbad9
84,567
cpp
C++
test/sentence_break_09.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
null
null
null
test/sentence_break_09.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
1
2021-03-05T12:56:59.000Z
2021-03-05T13:11:53.000Z
test/sentence_break_09.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
3
2019-10-30T18:38:15.000Z
2021-03-05T12:10:13.000Z
// Warning! This file is autogenerated. #include <boost/text/sentence_break.hpp> #include <gtest/gtest.h> #include <algorithm> TEST(sentence, breaks_9) { // ÷ 0300 × 0085 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] <NEXT LINE (NEL)> (Sep) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x85 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0085 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] <NEXT LINE (NEL)> (Sep) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x85 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0009 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] <CHARACTER TABULATION> (Sp) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x9 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0009 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] <CHARACTER TABULATION> (Sp) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x9 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0061 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] LATIN SMALL LETTER A (Lower) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x61 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0061 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] LATIN SMALL LETTER A (Lower) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x61 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0041 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] LATIN CAPITAL LETTER A (Upper) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x41 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0041 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] LATIN CAPITAL LETTER A (Upper) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x41 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 01BB ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] LATIN LETTER TWO WITH STROKE (OLetter) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x1bb }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 01BB ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] LATIN LETTER TWO WITH STROKE (OLetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x1bb }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0030 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] DIGIT ZERO (Numeric) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x30 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0030 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] DIGIT ZERO (Numeric) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x30 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 002E ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] FULL STOP (ATerm) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x2e }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 002E ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] FULL STOP (ATerm) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x2e }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0021 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] EXCLAMATION MARK (STerm) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x21 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0021 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] EXCLAMATION MARK (STerm) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x21 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0022 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] QUOTATION MARK (Close) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x22 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0022 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] QUOTATION MARK (Close) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x22 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 002C ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] COMMA (SContinue) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x2c }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 002C ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [998.0] COMMA (SContinue) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x2c }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 00AD ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] SOFT HYPHEN (Format_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0xad }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 00AD ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [5.0] SOFT HYPHEN (Format_FE) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0xad }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0300 × 0300 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING GRAVE ACCENT (Extend_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x300, 0x300 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0300 × 0308 × 0300 ÷ // ÷ [0.2] COMBINING GRAVE ACCENT (Extend_FE) × [5.0] COMBINING DIAERESIS (Extend_FE) × [5.0] COMBINING GRAVE ACCENT (Extend_FE) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x300, 0x308, 0x300 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 000D × 000A ÷ 0061 × 000A ÷ 0308 ÷ // ÷ [0.2] <CARRIAGE RETURN (CR)> (CR) × [3.0] <LINE FEED (LF)> (LF) ÷ [4.0] LATIN SMALL LETTER A (Lower) × [998.0] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_FE) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0xd, 0xa, 0x61, 0xa, 0x308 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 2, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 2, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0061 × 0308 ÷ // ÷ [0.2] LATIN SMALL LETTER A (Lower) × [5.0] COMBINING DIAERESIS (Extend_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x61, 0x308 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0020 × 200D × 0646 ÷ // ÷ [0.2] SPACE (Sp) × [5.0] ZERO WIDTH JOINER (Extend_FE) × [998.0] ARABIC LETTER NOON (OLetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x20, 0x200d, 0x646 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0646 × 200D × 0020 ÷ // ÷ [0.2] ARABIC LETTER NOON (OLetter) × [5.0] ZERO WIDTH JOINER (Extend_FE) × [998.0] SPACE (Sp) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x646, 0x200d, 0x20 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0028 × 0022 × 0047 × 006F × 002E × 0022 × 0029 × 0020 ÷ 0028 × 0048 × 0065 × 0020 × 0064 × 0069 × 0064 × 002E × 0029 ÷ // ÷ [0.2] LEFT PARENTHESIS (Close) × [998.0] QUOTATION MARK (Close) × [998.0] LATIN CAPITAL LETTER G (Upper) × [998.0] LATIN SMALL LETTER O (Lower) × [998.0] FULL STOP (ATerm) × [9.0] QUOTATION MARK (Close) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] SPACE (Sp) ÷ [11.0] LEFT PARENTHESIS (Close) × [998.0] LATIN CAPITAL LETTER H (Upper) × [998.0] LATIN SMALL LETTER E (Lower) × [998.0] SPACE (Sp) × [998.0] LATIN SMALL LETTER D (Lower) × [998.0] LATIN SMALL LETTER I (Lower) × [998.0] LATIN SMALL LETTER D (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) ÷ [0.3] { std::array<uint32_t, 17> cps = {{ 0x28, 0x22, 0x47, 0x6f, 0x2e, 0x22, 0x29, 0x20, 0x28, 0x48, 0x65, 0x20, 0x64, 0x69, 0x64, 0x2e, 0x29 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 12, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 13, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 14, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 15, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 16, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 17, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); } // ÷ 0028 × 201C × 0047 × 006F × 003F × 201D × 0029 × 0020 ÷ 0028 × 0048 × 0065 × 0020 × 0064 × 0069 × 0064 × 002E × 0029 ÷ // ÷ [0.2] LEFT PARENTHESIS (Close) × [998.0] LEFT DOUBLE QUOTATION MARK (Close) × [998.0] LATIN CAPITAL LETTER G (Upper) × [998.0] LATIN SMALL LETTER O (Lower) × [998.0] QUESTION MARK (STerm) × [9.0] RIGHT DOUBLE QUOTATION MARK (Close) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] SPACE (Sp) ÷ [11.0] LEFT PARENTHESIS (Close) × [998.0] LATIN CAPITAL LETTER H (Upper) × [998.0] LATIN SMALL LETTER E (Lower) × [998.0] SPACE (Sp) × [998.0] LATIN SMALL LETTER D (Lower) × [998.0] LATIN SMALL LETTER I (Lower) × [998.0] LATIN SMALL LETTER D (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) ÷ [0.3] { std::array<uint32_t, 17> cps = {{ 0x28, 0x201c, 0x47, 0x6f, 0x3f, 0x201d, 0x29, 0x20, 0x28, 0x48, 0x65, 0x20, 0x64, 0x69, 0x64, 0x2e, 0x29 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 12, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 13, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 14, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 15, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 16, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 17, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 17); } // ÷ 0055 × 002E × 0053 × 002E × 0041 × 0300 × 002E × 0020 × 0069 × 0073 ÷ // ÷ [0.2] LATIN CAPITAL LETTER U (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER S (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER A (Upper) × [5.0] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] FULL STOP (ATerm) × [8.0] SPACE (Sp) × [8.0] LATIN SMALL LETTER I (Lower) × [998.0] LATIN SMALL LETTER S (Lower) ÷ [0.3] { std::array<uint32_t, 10> cps = {{ 0x55, 0x2e, 0x53, 0x2e, 0x41, 0x300, 0x2e, 0x20, 0x69, 0x73 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); } // ÷ 0055 × 002E × 0053 × 002E × 0041 × 0300 × 003F × 0020 ÷ 0048 × 0065 ÷ // ÷ [0.2] LATIN CAPITAL LETTER U (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER S (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER A (Upper) × [5.0] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] QUESTION MARK (STerm) × [9.0] SPACE (Sp) ÷ [11.0] LATIN CAPITAL LETTER H (Upper) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 10> cps = {{ 0x55, 0x2e, 0x53, 0x2e, 0x41, 0x300, 0x3f, 0x20, 0x48, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 10); } // ÷ 0055 × 002E × 0053 × 002E × 0041 × 0300 × 002E ÷ // ÷ [0.2] LATIN CAPITAL LETTER U (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER S (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER A (Upper) × [5.0] COMBINING GRAVE ACCENT (Extend_FE) × [998.0] FULL STOP (ATerm) ÷ [0.3] { std::array<uint32_t, 7> cps = {{ 0x55, 0x2e, 0x53, 0x2e, 0x41, 0x300, 0x2e }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); } // ÷ 0033 × 002E × 0034 ÷ // ÷ [0.2] DIGIT THREE (Numeric) × [998.0] FULL STOP (ATerm) × [6.0] DIGIT FOUR (Numeric) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x33, 0x2e, 0x34 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0063 × 002E × 0064 ÷ // ÷ [0.2] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [8.0] LATIN SMALL LETTER D (Lower) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x63, 0x2e, 0x64 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0043 × 002E × 0064 ÷ // ÷ [0.2] LATIN CAPITAL LETTER C (Upper) × [998.0] FULL STOP (ATerm) × [8.0] LATIN SMALL LETTER D (Lower) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x43, 0x2e, 0x64 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0063 × 002E × 0044 ÷ // ÷ [0.2] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER D (Upper) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x63, 0x2e, 0x44 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0043 × 002E × 0044 ÷ // ÷ [0.2] LATIN CAPITAL LETTER C (Upper) × [998.0] FULL STOP (ATerm) × [7.0] LATIN CAPITAL LETTER D (Upper) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x43, 0x2e, 0x44 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 0074 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [8.0] RIGHT PARENTHESIS (Close) × [8.0] RIGHT SINGLE QUOTATION MARK (Close) × [8.0] NO-BREAK SPACE (Sp) × [8.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 10> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0xa0, 0x74, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 10); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 ÷ 0054 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] RIGHT SINGLE QUOTATION MARK (Close) × [9.0] NO-BREAK SPACE (Sp) ÷ [11.0] LATIN CAPITAL LETTER T (Upper) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 10> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0xa0, 0x54, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 2018 × 0028 × 0074 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [8.0] RIGHT PARENTHESIS (Close) × [8.0] RIGHT SINGLE QUOTATION MARK (Close) × [8.0] NO-BREAK SPACE (Sp) × [8.0] LEFT SINGLE QUOTATION MARK (Close) × [998.0] LEFT PARENTHESIS (Close) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 12> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0xa0, 0x2018, 0x28, 0x74, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 12, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 12); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 ÷ 2018 × 0028 × 0054 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] RIGHT SINGLE QUOTATION MARK (Close) × [9.0] NO-BREAK SPACE (Sp) ÷ [11.0] LEFT SINGLE QUOTATION MARK (Close) × [998.0] LEFT PARENTHESIS (Close) × [998.0] LATIN CAPITAL LETTER T (Upper) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 12> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0xa0, 0x2018, 0x28, 0x54, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 12); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 12, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 12); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 0308 × 0074 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [8.0] RIGHT PARENTHESIS (Close) × [8.0] RIGHT SINGLE QUOTATION MARK (Close) × [8.0] NO-BREAK SPACE (Sp) × [5.0] COMBINING DIAERESIS (Extend_FE) × [8.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 11> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0xa0, 0x308, 0x74, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 11); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 0308 ÷ 0054 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] RIGHT SINGLE QUOTATION MARK (Close) × [9.0] NO-BREAK SPACE (Sp) × [5.0] COMBINING DIAERESIS (Extend_FE) ÷ [11.0] LATIN CAPITAL LETTER T (Upper) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 11> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0xa0, 0x308, 0x54, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 11); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 8); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 8, cps.end()) - cps.begin(), 11); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 0308 ÷ 0054 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] RIGHT SINGLE QUOTATION MARK (Close) × [5.0] COMBINING DIAERESIS (Extend_FE) ÷ [11.0] LATIN CAPITAL LETTER T (Upper) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 10> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0x2019, 0x308, 0x54, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 7, cps.end()) - cps.begin(), 10); } // ÷ 0065 × 0074 × 0063 × 002E × 0029 × 000A ÷ 0308 × 0054 × 0068 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [9.0] RIGHT PARENTHESIS (Close) × [9.0] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_FE) × [998.0] LATIN CAPITAL LETTER T (Upper) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 10> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x29, 0xa, 0x308, 0x54, 0x68, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 6, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 6, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 6, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 6, cps.end()) - cps.begin(), 10); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 6, cps.end()) - cps.begin(), 10); } // ÷ 0074 × 0068 × 0065 × 0020 × 0072 × 0065 × 0073 × 0070 × 002E × 0020 × 006C × 0065 × 0061 × 0064 × 0065 × 0072 × 0073 × 0020 × 0061 × 0072 × 0065 ÷ // ÷ [0.2] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER H (Lower) × [998.0] LATIN SMALL LETTER E (Lower) × [998.0] SPACE (Sp) × [998.0] LATIN SMALL LETTER R (Lower) × [998.0] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER S (Lower) × [998.0] LATIN SMALL LETTER P (Lower) × [998.0] FULL STOP (ATerm) × [8.0] SPACE (Sp) × [8.0] LATIN SMALL LETTER L (Lower) × [998.0] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER A (Lower) × [998.0] LATIN SMALL LETTER D (Lower) × [998.0] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER R (Lower) × [998.0] LATIN SMALL LETTER S (Lower) × [998.0] SPACE (Sp) × [998.0] LATIN SMALL LETTER A (Lower) × [998.0] LATIN SMALL LETTER R (Lower) × [998.0] LATIN SMALL LETTER E (Lower) ÷ [0.3] { std::array<uint32_t, 21> cps = {{ 0x74, 0x68, 0x65, 0x20, 0x72, 0x65, 0x73, 0x70, 0x2e, 0x20, 0x6c, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x20, 0x61, 0x72, 0x65 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 8, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 9, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 10, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 11, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 12, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 13, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 14, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 15, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 16, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 17, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 18, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 19, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 20, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 21, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 21); } // ÷ 5B57 × 002E ÷ 5B57 ÷ // ÷ [0.2] CJK UNIFIED IDEOGRAPH-5B57 (OLetter) × [998.0] FULL STOP (ATerm) ÷ [11.0] CJK UNIFIED IDEOGRAPH-5B57 (OLetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x5b57, 0x2e, 0x5b57 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 0065 × 0074 × 0063 × 002E ÷ 5B83 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) ÷ [11.0] CJK UNIFIED IDEOGRAPH-5B83 (OLetter) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x5b83 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0065 × 0074 × 0063 × 002E × 3002 ÷ // ÷ [0.2] LATIN SMALL LETTER E (Lower) × [998.0] LATIN SMALL LETTER T (Lower) × [998.0] LATIN SMALL LETTER C (Lower) × [998.0] FULL STOP (ATerm) × [8.1] IDEOGRAPHIC FULL STOP (STerm) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x65, 0x74, 0x63, 0x2e, 0x3002 }}; EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_sentence_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_sentence_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); } }
84.567
762
0.610758
eightysquirrels
7e89a30c1193d3d680b666d757afb045e093e1f4
1,747
cpp
C++
test/strassen_multiplication.cpp
ArnabBir/scalable-matrix-computation
c636434643ffe2a8d7ec619793775922a946f18e
[ "MIT" ]
null
null
null
test/strassen_multiplication.cpp
ArnabBir/scalable-matrix-computation
c636434643ffe2a8d7ec619793775922a946f18e
[ "MIT" ]
null
null
null
test/strassen_multiplication.cpp
ArnabBir/scalable-matrix-computation
c636434643ffe2a8d7ec619793775922a946f18e
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <time.h> #include <limits> #include <iostream> #include <stdio.h> #include <math.h> #include<unistd.h> #include <sys/time.h> #include <sys/resource.h> #include "../src/matrix/matrix.cpp" #include "../src/matmul/matmul.cpp" using namespace std; int main(){ Matrix m1(2048, 2048, 0); m1.randomize(); //cout<<"Matrix 1 : "<<endl; //m1.display_matrix(); Matrix m2(2048, 2048, 0); m2.randomize(); //cout<<"Matrix 2 : "<<endl; //m2.display_matrix(); //matmul multiplier = matmul(true); // int start_naive_multiplication = clock(); // Matrix m = m1.multiply(m2); // int stop_naive_multiplication = clock(); //sleep(1); // cout<<"Product Matrix : "<<endl; // //m.display_matrix(); // cout<<start_naive_multiplication<<" "<<stop_naive_multiplication<<endl; // cout<<"Time = "<<(stop_naive_multiplication - start_naive_multiplication)/double(CLOCKS_PER_SEC)*1000<<endl; struct rusage usage; int start_strassen_multiply = clock(); Matrix m_ = m1.strassen_multiply(m2); int stop_strassen_multiply = clock(); getrusage(RUSAGE_SELF, &usage); cout<<"resident set size = "<<usage.ru_maxrss<<endl; cout<<"user time = "<<(usage.ru_utime.tv_sec*1000000.0 + usage.ru_utime.tv_usec)/double(CLOCKS_PER_SEC)*1000<<endl; cout<<"sys time = "<<(usage.ru_stime.tv_sec *1000000.0 + usage.ru_stime.tv_usec)/double(CLOCKS_PER_SEC)*1000<<endl; //cout<<"Strassen Product Matrix : "<<endl; //m_.display_matrix(); //cout<<start_strassen_multiply<<" "<<stop_strassen_multiply<<endl; cout<<"Time = "<<(stop_strassen_multiply - start_strassen_multiply)/double(CLOCKS_PER_SEC)*1000<<endl; return 0; }
31.196429
124
0.656554
ArnabBir
7e8bb395d97682a5f12c55de8e03aa24e60838d4
153
hpp
C++
src/Global.hpp
skytranlong/AxpFileManager
3bc1643d528bf61440468e8a0b38791f35cf39c9
[ "WTFPL" ]
null
null
null
src/Global.hpp
skytranlong/AxpFileManager
3bc1643d528bf61440468e8a0b38791f35cf39c9
[ "WTFPL" ]
null
null
null
src/Global.hpp
skytranlong/AxpFileManager
3bc1643d528bf61440468e8a0b38791f35cf39c9
[ "WTFPL" ]
2
2021-11-10T07:18:29.000Z
2022-01-06T07:45:54.000Z
#ifndef GLOBAL_HPP #define GLOBAL_HPP #include <QTemporaryDir> namespace Global { QTemporaryDir& getTempDir(); }; #endif // GLOBAL_HPP
12.75
33
0.686275
skytranlong
7e8bb4728b5279bf4c5bbdc6c61b7b57604fe1ea
3,697
cpp
C++
src/framework/wiced-43xxx/apps/E9000SPC/E9000SPC.cpp
OlafFilies/magnetic-angle-sensor
87618e9df29ab278e2af5eea7d9120769e197f9f
[ "MIT" ]
39
2019-01-08T23:35:11.000Z
2022-03-13T23:43:04.000Z
src/framework/wiced-43xxx/apps/E9000SPC/E9000SPC.cpp
OlafFilies/magnetic-angle-sensor
87618e9df29ab278e2af5eea7d9120769e197f9f
[ "MIT" ]
16
2018-11-18T19:19:41.000Z
2022-02-14T14:09:37.000Z
src/framework/wiced-43xxx/apps/E9000SPC/E9000SPC.cpp
OlafFilies/magnetic-angle-sensor
87618e9df29ab278e2af5eea7d9120769e197f9f
[ "MIT" ]
21
2019-01-18T01:32:47.000Z
2022-02-19T15:51:08.000Z
/*! * \name E9000SPC * \author Infineon Technologies AG * \copyright 2020 Infineon Technologies AG * \version 3.0.1 * \brief This example shows how to handle the TLE5012B-E9000 variant with SPC interface * \details * The TLE5012B-E9000 with SPC interface does not start the DSP automatically in a loop at start up. * It will need a certain trigger on the IFA pin of the sensor. * This trigger must be in a 90 UT time frame at least 12 UT long for the first sensor. By * multiplying the 12 UT with the sensor slave number up to four sensors can be triggered. * This trigger setting UT the unittime must multiplied with the sensors base unittime which * is default 3.0µs. Setting the IFA pin to low and waiting atleast the total trigger time * will set all registers by the DSP. * For more information please read the SPC Interface section of the manual. * The default setup ist: * - unittime =3.0µs, * - total trigger time = 90 * 3.0µs = 270 µs * - t_mlow the time for the first sensor to trigger = 12 * 3.0µs = 36 µs * so we have to set the IFA pin 36µs to low, than back to high and wait (90-12)*3.0µs = 224µs * * SPDX-License-Identifier: MIT * */ #include "../../../../config/tle5012-conf.hpp" #if (TLE5012_FRAMEWORK == TLE5012_FRMWK_WICED) #include <E9000SPC.hpp> //!< \brief WICED_GPIO pin number of IFA #define IFA WICED_GPIO_9 float unitTime = 3.0; //!< \brief UT is default 3.0µs but will be read with getHysteresisMode float triggerTime = 90; //!< \brief trigger total time is default 90UT * 3.0µs float t_mlow = 12; //!< \brief trigger will last default for 12 * 3.0µs // Tle5012b Object Tle5012Wiced Tle5012Sensor = Tle5012Wiced(); errorTypes checkError = NO_ERROR; updTypes upd = UPD_high; void setup() { // Enable Sensor and check the return value WPRINT_APP_INFO(("[TLE5012B] : setup begin -> %u\n", 0)); wiced_rtos_delay_milliseconds( 1000 ); checkError = Tle5012Sensor.begin(); WPRINT_APP_INFO(("[TLE5012B] : Check Error -> %u\n", checkError)); Tle5012Sensor.resetFirmware(); Tle5012Sensor.sBus->triggerUpdate(); wiced_rtos_delay_milliseconds( 1000 ); wiced_gpio_init(IFA, OUTPUT_PUSH_PULL); wiced_gpio_output_high(IFA); // Fetch sensor UT base value uint8_t val = Tle5012Sensor.reg.getHysteresisMode(); unitTime = (val == 0 ? 3.0 : (val == 1 ? 2.5 : (val == 2 ? 2.0 : 1.5 ) ) ); // Fetch SPC Total Trigger Time val = Tle5012Sensor.reg.getHSMplp(); triggerTime = ( val == 0 ? 90 : (t_mlow + 12) ); } void loop() { double a = 0.0; double rr = 0.0; int16_t ra = 0; int16_t r = 0; double t = 0.0; int16_t rt = 0; double s = 0.0; int16_t rs = 0; wiced_gpio_output_low(IFA); wiced_rtos_delay_microseconds( t_mlow + unitTime ); wiced_gpio_output_high(IFA); wiced_rtos_delay_microseconds( (triggerTime - t_mlow) * unitTime ); Tle5012Sensor.getAngleRange(rr); Tle5012Sensor.getAngleValue(a,ra); Tle5012Sensor.getNumRevolutions(r); Tle5012Sensor.getTemperature(t,rt); Tle5012Sensor.getAngleSpeed(s,rs); WPRINT_APP_INFO(("range: %f°\nrevolution: %u\t\n",rr,r)); WPRINT_APP_INFO(("DIR\tangle: %f° %X",a,ra)); WPRINT_APP_INFO((" \ttemp: %f°C %X",t,rt)); WPRINT_APP_INFO((" \tspeed: %f°/s %X\n",s,rs)); wiced_rtos_delay_milliseconds( 1000 ); } /****************************************************** * Function Definitions ******************************************************/ void application_start( ) { wiced_result_t result; /* Initialize the device */ result = wiced_init(); if (result != WICED_SUCCESS) { return; } setup(); while(1) { loop(); } } #endif
27.589552
100
0.659183
OlafFilies
7e8df99410c2223be2133985d5bc42efd7d35867
7,012
cxx
C++
LiverMarkups/VTKWidgets/vtkSlicerSlicingContourRepresentation3D.cxx
ALive-research/Slicer-Liver
3d0b17c812a865f67a4867ff2c8c11de07b7fe3b
[ "BSD-3-Clause" ]
3
2022-01-21T18:16:08.000Z
2022-02-17T09:04:03.000Z
LiverMarkups/VTKWidgets/vtkSlicerSlicingContourRepresentation3D.cxx
SINTEFMedtek/Slicer-Liver
3d0b17c812a865f67a4867ff2c8c11de07b7fe3b
[ "BSD-3-Clause" ]
73
2022-01-15T21:30:50.000Z
2022-03-31T09:54:10.000Z
LiverMarkups/VTKWidgets/vtkSlicerSlicingContourRepresentation3D.cxx
SINTEFMedtek/Slicer-Liver
3d0b17c812a865f67a4867ff2c8c11de07b7fe3b
[ "BSD-3-Clause" ]
2
2022-01-15T21:12:48.000Z
2022-01-19T11:43:29.000Z
/*============================================================================== Distributed under the OSI-approved BSD 3-Clause License. Copyright (c) Oslo University Hospital. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Oslo University Hospital nor the names of Contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file was originally developed by Rafael Palomar (Oslo University Hospital and NTNU) and was supported by The Research Council of Norway through the ALive project (grant nr. 311393). ==============================================================================*/ #include "vtkSlicerSlicingContourRepresentation3D.h" #include "vtkMRMLMarkupsSlicingContourDisplayNode.h" #include "vtkMRMLMarkupsSlicingContourNode.h" // MRML includes #include <qMRMLThreeDWidget.h> #include <vtkMRMLDisplayableManagerGroup.h> #include <vtkMRMLModelDisplayableManager.h> // Slicer includes #include <qSlicerApplication.h> #include <qSlicerLayoutManager.h> // VTK includes #include <vtkCollection.h> #include <vtkOpenGLVertexBufferObject.h> #include <vtkShaderProperty.h> #include <vtkUniforms.h> //------------------------------------------------------------------------------ vtkStandardNewMacro(vtkSlicerSlicingContourRepresentation3D); //------------------------------------------------------------------------------ vtkSlicerSlicingContourRepresentation3D::vtkSlicerSlicingContourRepresentation3D() :Superclass(), Target(nullptr) { } //------------------------------------------------------------------------------ vtkSlicerSlicingContourRepresentation3D::~vtkSlicerSlicingContourRepresentation3D() = default; //------------------------------------------------------------------------------ void vtkSlicerSlicingContourRepresentation3D::PrintSelf(ostream& os, vtkIndent indent) { Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------- void vtkSlicerSlicingContourRepresentation3D::UpdateFromMRML(vtkMRMLNode* caller, unsigned long event, void *callData /*=nullptr*/) { this->Superclass::UpdateFromMRML(caller, event, callData); auto liverMarkupsSlicingContourNode = vtkMRMLMarkupsSlicingContourNode::SafeDownCast(this->GetMarkupsNode()); if (!liverMarkupsSlicingContourNode) { vtkWarningMacro("Invalid slicing contour node."); return; } auto targetModelNode = liverMarkupsSlicingContourNode->GetTarget(); // If the target model node has changed -> Reassign the contour shader if (targetModelNode != this->Target) { this->ShaderHelper->SetTargetModelNode(targetModelNode); this->ShaderHelper->AttachSlicingContourShader(); this->Target = targetModelNode; } auto liverMarkupsSlicingContourDisplayNode = vtkMRMLMarkupsSlicingContourDisplayNode::SafeDownCast(liverMarkupsSlicingContourNode->GetDisplayNode()); if (!liverMarkupsSlicingContourDisplayNode) { vtkWarningMacro("Invalid vtkMRMLMarkupsSlicingContourDisplayNode."); return; } if (liverMarkupsSlicingContourNode->GetNumberOfControlPoints() != 2) { return; } // Recalculate the middle plane and update the shader parameters double point1Position[3] = {1.0f}; double point2Position[3] = {1.0f}; liverMarkupsSlicingContourNode->GetNthControlPointPosition(0, point1Position); liverMarkupsSlicingContourNode->GetNthControlPointPosition(1, point2Position); float middlePointPosition[3] = { static_cast<float>(point2Position[0] + point1Position[0]) / 2.0f, static_cast<float>(point2Position[1] + point1Position[1]) / 2.0f, static_cast<float>(point2Position[2] + point1Position[2]) / 2.0f }; float planeNormal[4] = { static_cast<float>(point2Position[0] - point1Position[0]), static_cast<float>(point2Position[1] - point1Position[1]), static_cast<float>(point2Position[2] - point1Position[2]), 1.0f }; float planeNormalNorm = vtkMath::Normalize(planeNormal); planeNormal[0] /= planeNormalNorm; planeNormal[1] /= planeNormalNorm; planeNormal[2] /= planeNormalNorm; auto VBOs = this->ShaderHelper->GetTargetModelVertexVBOs(); // auto actors = this->ShaderHelper->GetTargetActors(); for(int index = 0; index < VBOs->GetNumberOfItems(); ++index) { auto VBO = vtkOpenGLVertexBufferObject::SafeDownCast(VBOs->GetItemAsObject(index)); if(!VBO) { vtkErrorMacro("Error: could not retrieve vtkOpenGLVertexBufferObject"); return; } //VBO->SetCoordShiftAndScaleMethod(vtkOpenGLVertexBufferObject::AUTO_SHIFT_SCALE); auto scale = VBO->GetScale(); auto shift = VBO->GetShift(); if (scale.size() != 3 || shift.size() != 3) { scale.clear(); scale.push_back(1.0f);scale.push_back(1.0f);scale.push_back(1.0f); shift.clear(); shift.push_back(0.0f);shift.push_back(0.0f);shift.push_back(0.0f); return; } float middlePointPositionScaled[4] = { static_cast<float>((middlePointPosition[0] - shift[0]) * scale[0]), static_cast<float>((middlePointPosition[1] - shift[1]) * scale[1]), static_cast<float>((middlePointPosition[2] - shift[2]) * scale[2]), 1.0f}; auto actor = vtkActor::SafeDownCast(this->ShaderHelper->GetTargetActors()->GetItemAsObject(index)); auto fragmentUniforms = actor->GetShaderProperty()->GetFragmentCustomUniforms(); fragmentUniforms->SetUniform4f("planePositionMC", middlePointPositionScaled); fragmentUniforms->SetUniform4f("planeNormalMC", planeNormal); fragmentUniforms->SetUniformf("contourThickness", 2.0f*(scale[0]+scale[1])/2.0f); fragmentUniforms->SetUniformi("contourVisibility", liverMarkupsSlicingContourDisplayNode->GetVisibility()); } this->NeedToRenderOn(); }
38.527473
131
0.703793
ALive-research
7e93730a5524af2733b0866ee0c6c679294c26a9
2,579
cpp
C++
main.cpp
ei14/qecvec
e097d0a205889ec65362992c4171ae535bc113a5
[ "MIT" ]
null
null
null
main.cpp
ei14/qecvec
e097d0a205889ec65362992c4171ae535bc113a5
[ "MIT" ]
null
null
null
main.cpp
ei14/qecvec
e097d0a205889ec65362992c4171ae535bc113a5
[ "MIT" ]
null
null
null
#include "qecvec.hpp" int main() { printf("\n\n\nVec2f\n\n"); Vec2f a; a = Vec2f::polar(1, 3.14159265); printf("Magnitude 1, phase pi \t %s\n", a.string()); a = Vec2f::zero(); printf("Zero \t %s\n", a.string()); a = Vec2f::up(); printf("Up \t %s\n", a.string()); a = Vec2f::down(); printf("Down \t %s\n", a.string()); a = Vec2f::left(); printf("Left \t %s\n", a.string()); a = Vec2f::right(); printf("Right \t %s\n", a.string()); a = Vec2f::randomUniform(-1, 2); printf("Random from -1 to 2 \t %s\n", a.string()); a = Vec2f(1.5); printf("1.5 * (1, 1) \t %s\n", a.string()); Vec2f b; b = Vec2f(3, 4); printf("(3, 4) \t %s\n", b.string()); b = -b; printf("Negated \t %s\n", b.string()); printf("Normal \t %f\n", b.norm()); b = b.normal(); printf("Normalizeed \t %s\n", b.string()); b = b * 3; printf("Tripled \t %s\n", b.string()); b = b / 2; printf("Halved \t %s\n", b.string()); b = b + a; printf("With (1.5, 1.5) added \t %s\n", b.string()); b = b - 2*a; printf("With 2(1.5, 1.5) subtracted \t %s\n", b.string()); b = b & a; printf("Hadamard times (1.5, 1.5) \t %s\n", b.string()); printf("Dotted with (1.5, 1.5) \t %f\n", b * a); b *= 3; printf("Tripled \t %s\n", b.string()); b /= 2; printf("Halved \t %s\n", b.string()); b += a; printf("With (1.5, 1.5) added \t %s\n", b.string()); b -= 2*a; printf("With 2(1.5, 1.5) subtracted \t %s\n", b.string()); b &= a; printf("Hadamard times (1.5, 1.5) \t %s\n", b.string()); b.normalize(); printf("Normalized \t %s\n", b.string()); Vec2f c = b.copy(); c *= 2; printf("Same \t %s\n", b.string()); printf("Doubled \t %s\n", c.string()); printf("\n\n\nVec3f\n\n"); Vec3f d; d = Vec3f::zero(); printf("Zero \t %s\n", d.string()); d = Vec3f::up(); printf("Up \t %s\n", d.string()); d = Vec3f::down(); printf("Down \t %s\n", d.string()); d = Vec3f::left(); printf("Left \t %s\n", d.string()); d = Vec3f::right(); printf("Right \t %s\n", d.string()); d = Vec3f::forward(); printf("Forward \t %s\n", d.string()); d = Vec3f::backward(); printf("Backward \t %s\n", d.string()); d = Vec3f::randomUniform(-1, 1); printf("Random from -1 to 2 \t %s\n", d.string()); d = Vec3f(1.5); printf("1.5 * (1, 1, 1) \t %s\n", d.string()); d = Vec3f(1, 2, 3); printf("(1, 2, 3) \t %s\n", d.string()); d = Vec3f(a, 2); printf("(1.5, 1.5) followed by a 2 \t %s\n", d.string()); d = Vec3f(2, a); printf("(1.5, 1.5) led by a 2 \t %s\n", d.string()); Vec2f e = d.xy(); printf("First 2 components of (2, 1.5, 1.5) \t %s\n", e.string()); }
19.838462
67
0.519969
ei14
7e9413d2b32c340d01139bd4040b580b3f05eeaf
6,808
cpp
C++
lobster/src/tonative.cpp
RomanVolak/treesheets
5b524a61ca14babd58dc18d941ca9a59a56416c4
[ "Zlib" ]
1,278
2015-01-08T18:17:39.000Z
2022-03-31T22:11:11.000Z
lobster/src/tonative.cpp
RomanVolak/treesheets
5b524a61ca14babd58dc18d941ca9a59a56416c4
[ "Zlib" ]
180
2015-01-02T12:23:18.000Z
2022-03-31T01:52:02.000Z
lobster/src/tonative.cpp
RomanVolak/treesheets
5b524a61ca14babd58dc18d941ca9a59a56416c4
[ "Zlib" ]
139
2015-03-16T09:17:52.000Z
2022-03-30T06:15:04.000Z
// Copyright 2014 Wouter van Oortmerssen. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lobster/stdafx.h" #include "lobster/disasm.h" // Some shared bytecode utilities. #include "lobster/compiler.h" #include "lobster/tonative.h" namespace lobster { int ParseOpAndGetArity(int opc, const int *&ip) { auto arity = ILArity()[opc]; auto ips = ip; switch(opc) { default: { assert(arity != ILUNKNOWNARITY); ip += arity; break; } case IL_CORO: { ip += 2; int n = *ip++; ip += n; arity = int(ip - ips); break; } case IL_FUNSTART: { ip++; // function idx. int n = *ip++; ip += n; int m = *ip++; ip += m; ip++; // keepvar int o = *ip++; // ownedvar ip += o; arity = int(ip - ips); break; } } return arity; } string ToNative(NativeRegistry &natreg, NativeGenerator &ng, string_view bytecode_buffer) { auto bcf = bytecode::GetBytecodeFile(bytecode_buffer.data()); assert(FLATBUFFERS_LITTLEENDIAN); auto code = (const int *)bcf->bytecode()->Data(); // Assumes we're on a little-endian machine. //auto typetable = (const type_elem_t *)bcf->typetable()->Data(); // Same. map<int, const bytecode::Function *> function_lookup; for (flatbuffers::uoffset_t i = 0; i < bcf->functions()->size(); i++) { auto f = bcf->functions()->Get(i); function_lookup[f->bytecodestart()] = f; } ng.FileStart(); auto len = bcf->bytecode()->Length(); vector<int> block_ids(bcf->bytecode_attr()->size(), -1); const int *ip = code; // Skip past 1st jump. assert(*ip == IL_JUMP); ip++; auto starting_point = *ip++; int block_id = 1; while (ip < code + len) { if (bcf->bytecode_attr()->Get((flatbuffers::uoffset_t)(ip - code)) & bytecode::Attr_SPLIT) { auto id = block_ids[ip - code] = block_id++; ng.DeclareBlock(id); } if ((false)) { // Debug corrupt bytecode. ostringstream dss; DisAsmIns(natreg, dss, ip, code, (const type_elem_t *)bcf->typetable()->Data(), bcf); LOG_DEBUG(dss.str()); } int opc = *ip++; if (opc < 0 || opc >= IL_MAX_OPS) { return cat("Corrupt bytecode: ", opc, " at: ", ip - 1 - code); } ParseOpAndGetArity(opc, ip); } ng.BeforeBlocks(block_ids[starting_point], bytecode_buffer); ip = code + 2; bool already_returned = false; while (ip < code + len) { int opc = *ip++; if (opc == IL_FUNSTART) { auto it = function_lookup.find((int)(ip - 1 - code)); ng.FunStart(it != function_lookup.end() ? it->second : nullptr); } auto args = ip; if (bcf->bytecode_attr()->Get((flatbuffers::uoffset_t)(ip - 1 - code)) & bytecode::Attr_SPLIT) { auto cid = block_ids[args - 1 - code]; ng.current_block_id = cid; ng.BlockStart(cid); already_returned = false; } auto arity = ParseOpAndGetArity(opc, ip); auto is_vararg = ILArity()[opc] == ILUNKNOWNARITY; ng.InstStart(); if (opc == IL_JUMP) { already_returned = true; ng.EmitJump(block_ids[args[0]]); } else if ((opc >= IL_JUMPFAIL && opc <= IL_JUMPNOFAILR) || (opc >= IL_IFOR && opc <= IL_VFOR)) { auto id = block_ids[args[0]]; assert(id >= 0); ng.EmitConditionalJump(opc, id); } else { ng.EmitOperands(bytecode_buffer.data(), args, arity, is_vararg); if (ISBCALL(opc) && natreg.nfuns[args[0]]->CanChangeControlFlow()) { ng.SetNextCallTarget(block_ids[ip - code]); } int target = -1; if (opc == IL_CALL || opc == IL_CALLV || opc == IL_CALLVCOND || opc == IL_YIELD || opc == IL_DDCALL) { target = block_ids[ip - code]; } else if (opc == IL_PUSHFUN || opc == IL_CORO) { target = block_ids[args[0]]; } ng.EmitGenericInst(opc, args, arity, is_vararg, target); if (ISBCALL(opc)) { ng.Annotate(natreg.nfuns[args[0]]->name); } else if (opc == IL_PUSHVAR) { ng.Annotate(IdName(bcf, args[0])); } else if (ISLVALVARINS(opc)) { ng.Annotate(IdName(bcf, args[0])); } else if (opc == IL_PUSHSTR) { ostringstream css; EscapeAndQuote(bcf->stringtable()->Get(args[0])->string_view(), css); ng.Annotate(css.str()); } else if (opc == IL_CALL) { auto fs = code + args[0]; assert(*fs == IL_FUNSTART); fs++; ng.Annotate(bcf->functions()->Get(*fs)->name()->string_view()); } if (opc == IL_CALL) { ng.EmitCall(block_ids[args[0]]); already_returned = true; } else if (opc == IL_CALLV || opc == IL_YIELD || opc == IL_COEND || opc == IL_RETURN || opc == IL_DDCALL || // FIXME: make resume a vm op. (ISBCALL(opc) && natreg.nfuns[args[0]]->CanChangeControlFlow())) { ng.EmitCallIndirect(); already_returned = true; } else if (opc == IL_CALLVCOND) { ng.EmitCallIndirectNull(); } } ng.InstEnd(); if (bcf->bytecode_attr()->Get((flatbuffers::uoffset_t)(ip - code)) & bytecode::Attr_SPLIT) { ng.BlockEnd(block_ids[ip - code], already_returned, opc == IL_EXIT); } } ng.CodeEnd(); vector<int> vtables; for (auto bcs : *bcf->vtables()) { int id = -1; if (bcs >= 0) { id = block_ids[bcs]; assert(id >= 0); } vtables.push_back(id); } ng.VTables(vtables); ng.FileEnd(block_ids[starting_point], bytecode_buffer); return ""; } }
37.406593
104
0.522033
RomanVolak
7e9e25787e2697a9798f8b6e19ba25b9a42a05ca
55,881
cpp
C++
Samples/Win7Samples/winbase/imapi/imapiv2/erasesample/erasesample/Utility.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/winbase/imapi/imapiv2/erasesample/erasesample/Utility.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/winbase/imapi/imapiv2/erasesample/erasesample/Utility.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
/*-- Copyright (C) Microsoft Corporation, 2006 Utility functions --*/ #include "stdafx.h" SENSE_INFOMATION AllowedSenseForLongOperations[] = { {SCSI_SENSE_NOT_READY, SCSI_ADSENSE_LUN_NOT_READY, 0xFF, 0}, // not ready {SCSI_SENSE_ILLEGAL_REQUEST, 0xFF, 0xFF, 0}, {SCSI_SENSE_UNIT_ATTENTION, SCSI_ADSENSE_INSUFFICIENT_TIME_FOR_OPERATION, 0xFF, 0}, }; HRESULT PreventAllowMediumRemoval(__in IDiscRecorder2Ex* recorder, const BOOLEAN lockMedia, const BOOLEAN persistentBit) { HRESULT hr = S_OK; CDB cdb; SENSE_DATA sense; RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&sense, sizeof(SENSE_DATA)); if (recorder == NULL) { hr = E_POINTER; } if (SUCCEEDED(hr)) { cdb.MEDIA_REMOVAL.OperationCode = SCSIOP_MEDIUM_REMOVAL; cdb.MEDIA_REMOVAL.Prevent = (lockMedia ? 1 : 0); cdb.MEDIA_REMOVAL.Persistant = (persistentBit ? 1 : 0); hr = recorder->SendCommandNoData((BYTE*)&cdb, sizeof(cdb.MEDIA_REMOVAL), (BYTE*)&sense, IMAPI2_DEFAULT_COMMAND_TIMEOUT ); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { if (!TranslateSenseInfoToHResult(&cdb, &sense, &hr)) { hr = E_FAIL; } } } return hr; } HRESULT SendStartStopUnitCommand(IDiscRecorder2Ex* recorder, const START_STOP_OPTION option) { HRESULT hr = S_OK; if ((option != StopSpinning ) && (option != StartSpinning) && (option != EjectMedia ) && (option != LoadMedia ) ) { hr = E_INVALIDARG; } // Start or stop the disc if (SUCCEEDED(hr)) { CDB cdb; SENSE_DATA sense; ULONG timeout = IMAPI2_DEFAULT_COMMAND_TIMEOUT; RtlZeroMemory(&sense, sizeof(SENSE_DATA)); RtlZeroMemory(&cdb, sizeof(CDB)); cdb.START_STOP.OperationCode = SCSIOP_START_STOP_UNIT; if (option == StopSpinning) { cdb.START_STOP.Start = FALSE; cdb.START_STOP.LoadEject = FALSE; } else if (option == EjectMedia) { cdb.START_STOP.Start = FALSE; cdb.START_STOP.LoadEject = TRUE; } else if (option == StartSpinning) { cdb.START_STOP.Start = TRUE; cdb.START_STOP.LoadEject = FALSE; timeout = IMAPI2_DEFAULT_COMMAND_TIMEOUT * 6; } else if (option == LoadMedia) { cdb.START_STOP.Start = TRUE; cdb.START_STOP.LoadEject = TRUE; timeout = IMAPI2_DEFAULT_COMMAND_TIMEOUT * 6; } hr = recorder->SendCommandNoData((BYTE*)&cdb, sizeof(cdb.START_STOP), (BYTE*)&sense, timeout); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { TranslateSenseInfoToHResult(&cdb, &sense, &hr); } } return hr; } HRESULT GetPhysicalDvdStructure(__in IDiscRecorder2Ex* recorder, __deref_out_bcount_full(*byteSize) BYTE ** dvdStructureInformation, __out ULONG * byteSize) { HRESULT hr = S_OK; BYTE* tmpDescriptor = NULL; ULONG tmpDescriptorSize = 0; // Validate parameters and initialize OUT parameters if (dvdStructureInformation == NULL) { hr = E_POINTER; } else { *dvdStructureInformation = NULL; } if (byteSize == NULL) { hr = E_POINTER; } else { *byteSize = 0; } // Read the DVD structure if (SUCCEEDED(hr)) { hr = recorder->ReadDvdStructure(0, 0, 0, 0, &tmpDescriptor, &tmpDescriptorSize); } if (SUCCEEDED(hr)) { if (tmpDescriptorSize < sizeof(DVD_LAYER_DESCRIPTOR)) { hr = E_IMAPI_RECORDER_INVALID_RESPONSE_FROM_DEVICE; } } // save the results if (SUCCEEDED(hr)) { *dvdStructureInformation = (BYTE*)tmpDescriptor; *byteSize = tmpDescriptorSize; } else { CoTaskMemFreeAndNull(tmpDescriptor); } return hr; } HRESULT GetCurrentPhysicalMediaType(__in IDiscRecorder2Ex* recorder, __out IMAPI_MEDIA_PHYSICAL_TYPE * value) { HRESULT hr = S_OK; IMAPI_MEDIA_PHYSICAL_TYPE tmpValue = IMAPI_MEDIA_TYPE_UNKNOWN; BOOLEAN mediaTypeDetermined = FALSE; BOOLEAN supportsGetConfiguration = TRUE; // avoid legacy checks by default BOOLEAN readDvdStructureCurrent = FALSE; BOOLEAN readDvdStructureSupported = FALSE; CDiscInformation discInfo; if (recorder == NULL) { hr = E_POINTER; } if (value == NULL) { hr = E_POINTER; } else { *value = IMAPI_MEDIA_TYPE_UNKNOWN; } // if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { hr = discInfo.Init(recorder); } // determine if READ_DVD_STRUCTURE is a supported command if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { BYTE* dvdRead = NULL; ULONG dvdReadSize = 0; HRESULT tmpHr = recorder->GetFeaturePage(IMAPI_FEATURE_PAGE_TYPE_DVD_READ, FALSE, &dvdRead, &dvdReadSize ); if (SUCCEEDED(tmpHr)) { // the feature page is supported readDvdStructureSupported = TRUE; // check if DvdRead feature is current // (Data is guaranteed to be the right size by GetFeaturePage) readDvdStructureCurrent = ((PFEATURE_HEADER)dvdRead)->Current ? TRUE : FALSE; } else if (tmpHr == E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED) { hr = S_OK; } else if ((tmpHr != E_IMAPI_RECORDER_NO_SUCH_FEATURE) && (tmpHr != E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT)) { hr = tmpHr; } CoTaskMemFreeAndNull(dvdRead); } // if media is not erasable and is finalized, return a -ROM type if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { // discInfo is either initialized or mediaType has already been determined if ((discInfo.get_DiscStatus() == 0x02) && // complete, non-appendable !discInfo.get_Erasable()) { if (readDvdStructureCurrent) { tmpValue = IMAPI_MEDIA_TYPE_DVDROM; } else { tmpValue = IMAPI_MEDIA_TYPE_CDROM; } mediaTypeDetermined = TRUE; } } // check for DVD+RW media if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { FEATURE_HEADER* feature = NULL; ULONG featureSize = 0; hr = recorder->GetFeaturePage(IMAPI_FEATURE_PAGE_TYPE_DVD_PLUS_RW, TRUE, (BYTE**)&feature, &featureSize ); if (hr == E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED) { hr = S_OK; } else if ((hr == E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT) || (hr == E_IMAPI_RECORDER_NO_SUCH_FEATURE)) { hr = S_OK; } else if (SUCCEEDED(hr)) { tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSRW; mediaTypeDetermined = TRUE; } CoTaskMemFreeAndNull(feature); } // check for DVD+R dual-layer media if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { FEATURE_HEADER* feature = NULL; ULONG featureSize = 0; hr = recorder->GetFeaturePage(IMAPI_FEATURE_PAGE_TYPE_DVD_PLUS_R_DUAL_LAYER, TRUE, (BYTE**)&feature, &featureSize ); if (hr == E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED) { hr = S_OK; } else if ((hr == E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT) || (hr == E_IMAPI_RECORDER_NO_SUCH_FEATURE)) { //Not choosing DVD+R dual layer media due to page DNE or isn't current hr = S_OK; } else if (SUCCEEDED(hr)) { tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSR_DUALLAYER; mediaTypeDetermined = TRUE; } CoTaskMemFreeAndNull(feature); } // check for DVD+R media if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { FEATURE_HEADER* feature = NULL; ULONG featureSize = 0; hr = recorder->GetFeaturePage(IMAPI_FEATURE_PAGE_TYPE_DVD_PLUS_R, TRUE, (BYTE**)&feature, &featureSize ); if (hr == E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED) { hr = S_OK; } else if ((hr == E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT) || (hr == E_IMAPI_RECORDER_NO_SUCH_FEATURE)) { //Not choosing DVD+R media due to page DNE or isn't current\n" hr = S_OK; } else if (SUCCEEDED(hr)) { tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSR; mediaTypeDetermined = TRUE; } CoTaskMemFreeAndNull(feature); } // Use ReadDvdStructure (ignore errors) if ((!mediaTypeDetermined) && SUCCEEDED(hr) && readDvdStructureSupported) { DVD_LAYER_DESCRIPTOR* descriptor = NULL; ULONG descriptorSize = 0; HRESULT tmpHr = GetPhysicalDvdStructure(recorder, (BYTE**)&descriptor, &descriptorSize); if (FAILED(tmpHr)) { // ignore this error, since it's possibly not even DVD media } else if (descriptor->BookType == 0x0) // DVD-ROM { tmpValue = IMAPI_MEDIA_TYPE_DVDROM; mediaTypeDetermined = TRUE; } else if (descriptor->BookType == 0x1) // DVD-RAM { tmpValue = IMAPI_MEDIA_TYPE_DVDRAM; mediaTypeDetermined = TRUE; } else if (descriptor->BookType == 0x2) // DVD-R { if (descriptor->NumberOfLayers == 0x1) // 0x1 indicates 2 layers on this side { tmpValue = IMAPI_MEDIA_TYPE_DVDDASHR_DUALLAYER; } else { tmpValue = IMAPI_MEDIA_TYPE_DVDDASHR; } mediaTypeDetermined = TRUE; } else if (descriptor->BookType == 0x3) // DVD-RW { tmpValue = IMAPI_MEDIA_TYPE_DVDDASHRW; mediaTypeDetermined = TRUE; } else if (descriptor->BookType == 0x9) // DVD+RW { tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSRW; mediaTypeDetermined = TRUE; } else if (descriptor->BookType == 0xA) // DVD+R { tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSR; mediaTypeDetermined = TRUE; } else if (descriptor->BookType == 0xE) // DVD+R Dual Layer { tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSR_DUALLAYER; mediaTypeDetermined = TRUE; } CoTaskMemFreeAndNull(descriptor); descriptorSize = 0; } // use profiles to allow CD-R, CD-RW, randomly writable media to be detected if ((!mediaTypeDetermined) && SUCCEEDED(hr)) { IMAPI_PROFILE_TYPE* profiles = NULL; ULONG profileCount = 0; hr = recorder->GetSupportedProfiles(TRUE, &profiles, &profileCount ); if (hr == E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED) { supportsGetConfiguration = FALSE; // allows legacy checks to occur hr = S_OK; } else if ((hr == E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT) || (hr == E_IMAPI_RECORDER_NO_SUCH_FEATURE)) { //GET_CONFIG returned no PROFILE feature -- THIS IS A DRIVE FIRMWARE BUG hr = S_OK; } else if (FAILED(hr)) { // } else { // according to the specs, the features shall be listed in order // of drive's usage preference. for (ULONG i = 0; (!mediaTypeDetermined) && (i < profileCount); i++) { switch(profiles[i]) { case IMAPI_PROFILE_TYPE_NON_REMOVABLE_DISK: case IMAPI_PROFILE_TYPE_REMOVABLE_DISK: //case IMAPI_PROFILE_TYPE_MO_ERASABLE: //case IMAPI_PROFILE_TYPE_MO_WRITE_ONCE: //case IMAPI_PROFILE_TYPE_AS_MO: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DISK; break; } case IMAPI_PROFILE_TYPE_CDROM: case IMAPI_PROFILE_TYPE_DDCDROM: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_CDROM; break; } case IMAPI_PROFILE_TYPE_CD_RECORDABLE: case IMAPI_PROFILE_TYPE_DDCD_RECORDABLE: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_CDR; break; } case IMAPI_PROFILE_TYPE_CD_REWRITABLE: case IMAPI_PROFILE_TYPE_DDCD_REWRITABLE: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_CDRW; break; } case IMAPI_PROFILE_TYPE_DVDROM: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DVDROM; break; } case IMAPI_PROFILE_TYPE_DVD_RAM: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DVDRAM; break; } case IMAPI_PROFILE_TYPE_DVD_PLUS_R: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSR; break; } case IMAPI_PROFILE_TYPE_DVD_PLUS_RW: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DVDPLUSRW; break; } case IMAPI_PROFILE_TYPE_DVD_DASH_RECORDABLE: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DVDDASHR; break; } case IMAPI_PROFILE_TYPE_DVD_DASH_REWRITABLE: case IMAPI_PROFILE_TYPE_DVD_DASH_RW_SEQUENTIAL: { mediaTypeDetermined = TRUE; tmpValue = IMAPI_MEDIA_TYPE_DVDDASHRW; break; } default: break; } } // end of loop through all profiles } CoTaskMemFreeAndNull(profiles); } // For the final, last-ditch attempt for legacy drives if ((!mediaTypeDetermined) && (!supportsGetConfiguration) && SUCCEEDED(hr)) { // NOTE: this works because -ROM media was determined earlier // discInfo is either initialized // _or_ mediaType has already been determined if (discInfo.get_Erasable()) { tmpValue = IMAPI_MEDIA_TYPE_CDRW; } else { tmpValue = IMAPI_MEDIA_TYPE_CDR; } } // copy the final result to the caller if (SUCCEEDED(hr)) { *value = tmpValue; } return hr; } HRESULT SendSetCDSpeed(__in IDiscRecorder2* discRecorder, const IMAPI_MEDIA_PHYSICAL_TYPE mediaType, const ULONG KBps, const ULONG rotationType) { HRESULT hr = S_OK; IDiscRecorder2Ex* dr2ex = NULL; bool setStreamingFailed = false; ULONG oldSPS = (ULONG)-1; ULONG oldKBps = (ULONG)-1; VARIANT_BOOL oldRotation = VARIANT_FALSE; if (discRecorder == NULL) { hr = E_POINTER; } // Get a DR2Ex pointer if (SUCCEEDED(hr)) { hr = discRecorder->QueryInterface(IID_PPV_ARGS(&dr2ex)); } if (SUCCEEDED(hr)) { // First, get the current drive properties for comparison later hr = UpdateCurrentDriveProperties(discRecorder, mediaType, &oldSPS, &oldKBps, &oldRotation); } // Allocate the buffer for the SET_STREAMING command BYTE* dataBuffer = NULL; if (SUCCEEDED(hr)) { dataBuffer = (BYTE*)LocalAlloc(LPTR, 28*sizeof(BYTE)); if (dataBuffer == NULL) { hr = E_OUTOFMEMORY; } } // Now, try sending a SET_STREAMING command // variables for SET_STREAMING command if (SUCCEEDED(hr)) { // clear out data structures CDB cdb; SENSE_DATA sense; RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&sense, sizeof(SENSE_DATA)); RtlZeroMemory(dataBuffer, 28*sizeof(BYTE)); // create the SET_STREAMING CDB cdb.SET_STREAMING.OperationCode = SCSIOP_SET_STREAMING; cdb.SET_STREAMING.ParameterListLength[0] = 0; cdb.SET_STREAMING.ParameterListLength[1] = 0x1C; // now set up the data buffer (performance descriptor) { LONG endLBA = 0x231260; LONG time = 0x3E8; dataBuffer[0] = (BYTE) (rotationType & 0x3) << 3; // now set the END LBA dataBuffer[8] = (BYTE)((endLBA & 0xFF000000) >> 24); dataBuffer[9] = (BYTE)((endLBA & 0x00FF0000) >> 16); dataBuffer[10] = (BYTE)((endLBA & 0x0000FF00) >> 8); dataBuffer[11] = (BYTE)(endLBA & 0x000000FF); // now set the read time dataBuffer[16] = (BYTE)((time & 0xFF000000) >> 24); dataBuffer[17] = (BYTE)((time & 0x00FF0000) >> 16); dataBuffer[18] = (BYTE)((time & 0x0000FF00) >> 8); dataBuffer[19] = (BYTE)(time & 0x000000FF); // now set the write size dataBuffer[20] = (BYTE)((KBps & 0xFF000000) >> 24); dataBuffer[21] = (BYTE)((KBps & 0x00FF0000) >> 16); dataBuffer[22] = (BYTE)((KBps & 0x0000FF00) >> 8); dataBuffer[23] = (BYTE)(KBps & 0x000000FF); // now set the write time dataBuffer[24] = (BYTE)((time & 0xFF000000) >> 24); dataBuffer[25] = (BYTE)((time & 0x00FF0000) >> 16); dataBuffer[26] = (BYTE)((time & 0x0000FF00) >> 8); dataBuffer[27] = (BYTE)(time & 0x000000FF); } // Send the CBD hr = dr2ex->SendCommandSendDataToDevice((BYTE*)&cdb, (ULONG)12, (BYTE*)&sense, IMAPI2_DEFAULT_COMMAND_TIMEOUT, dataBuffer, (ULONG)28); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { // this usually means the SET_STREAMING did not set the speed properly // In practice this could simply mean that the rotation type did not stick setStreamingFailed = true; } else if (SUCCEEDED(hr)) { // check to make sure the new speed stuck ULONG curSPS = (ULONG)-1; ULONG curKBps = (ULONG)-1; VARIANT_BOOL rotation; hr = UpdateCurrentDriveProperties(discRecorder, mediaType, &curSPS, &curKBps, &rotation); if (curKBps != oldKBps) { // the speed was correctly set setStreamingFailed = false; } else { // either the speed was not set or the speed was not supported // try SET_CD_SPEED setStreamingFailed = true; } } else { // the command itself FAILED setStreamingFailed = true; } } if (setStreamingFailed) { CDB cdb; SENSE_DATA sense; // clear out data structures RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&sense, sizeof(SENSE_DATA)); // create the SET_CD_SPEED CDB cdb.SET_CD_SPEED.OperationCode = SCSIOP_SET_CD_SPEED; cdb.SET_CD_SPEED.RotationControl = rotationType; cdb.SET_CD_SPEED.ReadSpeed[0] = (BYTE)((KBps & 0x0000FF00) >> 8); cdb.SET_CD_SPEED.ReadSpeed[1] = (BYTE)(KBps & 0x000000FF); cdb.SET_CD_SPEED.WriteSpeed[0] = (BYTE)((KBps & 0x0000FF00) >> 8); cdb.SET_CD_SPEED.WriteSpeed[1] = (BYTE)(KBps & 0x000000FF); // Send the CBD hr = dr2ex->SendCommandNoData((BYTE*)&cdb, 12, (BYTE*)&sense, IMAPI2_DEFAULT_COMMAND_TIMEOUT); } LocalFreeAndNull(dataBuffer); return hr; } BOOLEAN BstrIsValidClientName(__in_xcount(SysStringLen(value)) BSTR value) { ULONG stringLength = ::SysStringLen(value); OLECHAR* t = value; // check the length // NOTE: SysStringLen does not include NULL termination // A NULL or empty client name is not acceptable. if (stringLength >= (CDROM_EXCLUSIVE_CALLER_LENGTH-1) || (stringLength == 0) ) { return FALSE; } // NOTE: stringLength is zero when value is NULL, so this is safe for (ULONG i = 0; i < stringLength; i++, t++) { if ( ((*t >= (OLECHAR)'0') && (*t <= (OLECHAR)'9')) || ((*t >= (OLECHAR)'a') && (*t <= (OLECHAR)'z')) || ((*t >= (OLECHAR)'A') && (*t <= (OLECHAR)'Z')) || (*t == (OLECHAR)' ') || (*t == (OLECHAR)'.') || (*t == (OLECHAR)',') || (*t == (OLECHAR)':') || (*t == (OLECHAR)';') || (*t == (OLECHAR)'_') || (*t == (OLECHAR)'-') ) { // nothing... this is a valid char } else { return FALSE; } } return TRUE; } // Helper Functions HRESULT UpdateCurrentDriveProperties(__in IDiscRecorder2* discRecorder, const IMAPI_MEDIA_PHYSICAL_TYPE mediaType, __out ULONG* currentSpeedSectorsPerSecond, __out ULONG* currentSpeedKBps, __out VARIANT_BOOL* currentRotationTypeIsPureCAV) { // two options: GetPerformance->WritePerformance or ModeSense->CDVDCapabilities HRESULT hr = S_OK; IDiscRecorder2Ex* dr2ex = NULL; bool writeSpeedSet = false; if ((discRecorder == NULL) || (currentSpeedSectorsPerSecond == NULL) || (currentSpeedKBps == NULL) || (currentRotationTypeIsPureCAV == NULL)) { hr = E_POINTER; } if (SUCCEEDED(hr)) { hr = discRecorder->QueryInterface(IID_PPV_ARGS(&dr2ex)); } if (SUCCEEDED(hr)) { // some new variables that would be used to get the mode page CDVD_CAPABILITIES_PAGE *page = NULL; ULONG pageSize = 0; LONG tmpKBps = 0; // retrieve the mode page if (SUCCEEDED(hr)) { // the drive may not support GET_PERFORMANCE, so just try legacy page hr = dr2ex->GetModePage(IMAPI_MODE_PAGE_TYPE_LEGACY_CAPABILITIES, IMAPI_MODE_PAGE_REQUEST_TYPE_CURRENT_VALUES, (BYTE**)&page, &pageSize ); } // need to check for malicious data (RPC after all...) if (SUCCEEDED(hr)) { // ensuring that the size is at least 2 allows checking the page->PageLength field. if (pageSize < 2) { hr = E_IMAPI_UNEXPECTED_RESPONSE_FROM_DEVICE; } else if (((ULONG)page->PageLength) + 2 != pageSize) { hr = E_IMAPI_UNEXPECTED_RESPONSE_FROM_DEVICE; } } // parse the results if (SUCCEEDED(hr)) { // check length of the mode page if (page->PageLength < 20) // MMC1 == pageLength 20, size 22 { // does not conform to any mmc spec hr = E_FAIL; } else if (page->PageLength < 24) // MMC2 == pageLength 24, size 26 { // mmc 1.0 no descriptors, nothing obsolete // current write speed is in bytes 20,21 BYTE *bytePage = (BYTE*)page; tmpKBps = ((bytePage[20] << 8) | (bytePage[21] ) ); } else if (page->PageLength < 28) // MMC3,4 == pageLength 28, size 30 { // mmc 2.0 ... everything necessary is marked as obsolete // however, the SET_CD_SPEED section states that the actual // speed will be returned on this page ... so just use it BYTE *bytePage = (BYTE*)page; tmpKBps = ((bytePage[20] << 8) | (bytePage[21] ) ); } else if (page->PageLength >= 28) // MMC3,4 and later w/ descriptors { // mmc 3.0, 4.0 w/descriptors ... currents are not obsolete // current write speed is in bytes 28,29 // current rotation control is in lowest 2 bits of byte 27 BYTE *bytePage = (BYTE*)page; tmpKBps = ((bytePage[28] << 8) | (bytePage[29] ) ); // set the current rotation type if ((bytePage[27] & 0x3) == 0) { *currentRotationTypeIsPureCAV = 0; } else if ((bytePage[27] & 0x3) == 1) { *currentRotationTypeIsPureCAV = 1; } else { // RESERVED value *currentRotationTypeIsPureCAV = 0; } } if (SUCCEEDED(hr)) { // set the write speed if necessary if (writeSpeedSet == false) { *currentSpeedKBps = tmpKBps; hr = FuzzyConvert_KBps2SectorsPerSecond(mediaType, tmpKBps, currentSpeedSectorsPerSecond); } } } } return hr; } HRESULT WaitForReadDiscInfo(__in IDiscRecorder2Ex* recorder, const ULONG secondsToTry, __in_opt PVOID object, __in_opt __callback READ_DISC_INFO_CALLBACK callback) { DECLSPEC_ALIGN(16) DISC_INFORMATION discInfo; HRESULT hr = S_OK; BOOLEAN readDiscInfoSucceeded = FALSE; ULONG attempts = secondsToTry; if (recorder == NULL) { hr = E_POINTER; } if (SUCCEEDED(hr)) { // prevent division resulting in zero attempts if (attempts == 0) { attempts++; } // Loop for a limited time, or until failure or successful Read Disc Info for (; SUCCEEDED(hr) && (!readDiscInfoSucceeded) && (attempts > 0); attempts--) { // Always sleep at least one second Sleep(1000); CDB cdb; SENSE_DATA sense; ULONG bytesReceived; RtlZeroMemory(&sense, sizeof(SENSE_DATA)); RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&discInfo, sizeof(DISC_INFORMATION)); cdb.READ_DISC_INFORMATION.OperationCode = SCSIOP_READ_DISC_INFORMATION; cdb.READ_DISC_INFORMATION.AllocationLength[0] = (UCHAR)(sizeof(DISC_INFORMATION) >> (8*1)); cdb.READ_DISC_INFORMATION.AllocationLength[1] = (UCHAR)(sizeof(DISC_INFORMATION) >> (8*0)); hr = recorder->SendCommandGetDataFromDevice((BYTE*)&cdb, sizeof(cdb.READ_DISC_INFORMATION), (BYTE*)&sense, IMAPI2_DEFAULT_COMMAND_TIMEOUT, (BYTE*)&discInfo, sizeof(DISC_INFORMATION), &bytesReceived ); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { if (IsSenseDataInTable(AllowedSenseForLongOperations, RTL_NUMBER_OF(AllowedSenseForLongOperations), &sense)) { if (callback != NULL) { (*callback)(object, &sense); } hr = S_OK; } else { hr = E_FAIL; TranslateSenseInfoToHResult(&cdb, &sense, &hr); } } else if (SUCCEEDED(hr)) { readDiscInfoSucceeded = TRUE; } } } return hr; } HRESULT ReadMediaCapacity(__in IDiscRecorder2Ex* recorder, __out ULONG* bytesPerBlock, __out ULONG* userSectors) { HRESULT hr = S_OK; READ_CAPACITY_DATA capacity; CDB cdb; SENSE_DATA sense; ULONG retrievedBytes = 0; RtlZeroMemory(&capacity, sizeof(READ_CAPACITY_DATA)); RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&sense, sizeof(SENSE_DATA)); *bytesPerBlock = 2048; *userSectors = 0; if ((recorder == NULL) || (bytesPerBlock == NULL) || (userSectors == NULL)) { hr = E_POINTER; } if (SUCCEEDED(hr)) { cdb.CDB10.OperationCode = SCSIOP_READ_CAPACITY; hr = recorder->SendCommandGetDataFromDevice((BYTE*)&cdb, sizeof(cdb.CDB10), (BYTE*)&sense, 10, // BUGBUG -- different timeout? (BYTE*)&capacity, sizeof(READ_CAPACITY_DATA), &retrievedBytes ); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { if (!TranslateSenseInfoToHResult(&cdb, &sense, &hr)) { hr = E_FAIL; } } else if (FAILED(hr)) { } else if (retrievedBytes < sizeof(READ_CAPACITY_DATA)) { hr = E_IMAPI_RECORDER_INVALID_RESPONSE_FROM_DEVICE; } else { // swap the byte order REVERSE_LONG(&(capacity.LogicalBlockAddress)); REVERSE_LONG(&(capacity.BytesPerBlock)); // fixup zero-size reporting to be correct if ((capacity.LogicalBlockAddress == ((ULONG)-1)) || (capacity.LogicalBlockAddress == 0)) { capacity.LogicalBlockAddress = ((ULONG)-1); } if (CountOfSetBits(capacity.BytesPerBlock) != 1) { hr = E_IMAPI_RECORDER_INVALID_RESPONSE_FROM_DEVICE; } else { *bytesPerBlock = capacity.BytesPerBlock; *userSectors = capacity.LogicalBlockAddress + 1; } } } return hr; } HRESULT RequestAutomaticOPC(__in IDiscRecorder2Ex* recorder) { HRESULT hr = S_OK; CDB cdb; SENSE_DATA sense; RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&sense, sizeof(SENSE_DATA)); if (recorder == NULL) { hr = E_POINTER; } if (SUCCEEDED(hr)) { cdb.SEND_OPC_INFORMATION.OperationCode = SCSIOP_SEND_OPC_INFORMATION; cdb.SEND_OPC_INFORMATION.DoOpc = 1; hr = recorder->SendCommandNoData((BYTE*)&cdb, sizeof(cdb.SEND_OPC_INFORMATION), (BYTE*)&sense, DEFAULT_OPC_TIMEOUT ); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { if (!TranslateSenseInfoToHResult(&cdb, &sense, &hr)) { hr = E_FAIL; } } } return hr; } HRESULT SendSynchronizeCacheCommand(__in IDiscRecorder2Ex* recorder, const ULONG timeout, const BOOLEAN immediate) { HRESULT hr = S_OK; CDB cdb; SENSE_DATA sense; RtlZeroMemory(&cdb, sizeof(CDB)); RtlZeroMemory(&sense, sizeof(SENSE_DATA)); if (recorder == NULL) { hr = E_POINTER; } if (SUCCEEDED(hr)) { cdb.SYNCHRONIZE_CACHE10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE; cdb.SYNCHRONIZE_CACHE10.Immediate = (immediate ? 1 : 0); hr = recorder->SendCommandNoData((BYTE*)&cdb, sizeof(cdb.SYNCHRONIZE_CACHE10), (BYTE*)&sense, timeout ); if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { if (!TranslateSenseInfoToHResult(&cdb, &sense, &hr)) { hr = E_FAIL; } } } return hr; } // Uses the command set to determine if the media is blank with 100% certainty HRESULT GetMediaPhysicallyBlank(__in IDiscRecorder2Ex* discRecorder, __out VARIANT_BOOL* pPhysicallyBlank) { HRESULT hr = S_OK; CDiscInformation discInfo; BOOL bDiscBlank = TRUE; BOOL bFound = FALSE; IMAPI_MEDIA_PHYSICAL_TYPE mediaType = IMAPI_MEDIA_TYPE_UNKNOWN; if ((discRecorder == NULL) || (pPhysicallyBlank == NULL)) { hr = E_POINTER; } // get the current media type if (SUCCEEDED(hr)) { hr = GetCurrentPhysicalMediaType(discRecorder, &mediaType); } // shortcut answer for some media types if (SUCCEEDED(hr)) { if ((mediaType == IMAPI_MEDIA_TYPE_CDROM) || (mediaType == IMAPI_MEDIA_TYPE_DVDROM)) { bDiscBlank = FALSE; bFound = TRUE; } } // Get the DISC_INFO if (SUCCEEDED(hr) && !bFound) { hr = discInfo.Init(discRecorder); } // Check the DISC_INFO data if (SUCCEEDED(hr) && !bFound) { ULONG discStatus = discInfo.get_DiscStatus(); // check disc status is empty if (discStatus != 0) { bDiscBlank = FALSE; } } // Set the output properly if (SUCCEEDED(hr)) { if (bDiscBlank) { *pPhysicallyBlank = VARIANT_TRUE; } else { *pPhysicallyBlank = VARIANT_FALSE; } } return hr; } // Uses heuristics to determine if the media is blank // Mainly used for DVD+RW and DVD-RAM media types // (in fact, for all other media types, heuristically blank = physically blank) // Current heuristic checks: // "media is heuristically blank if..." // . The entire first 2MB of the disc is 0's HRESULT GetMediaHeuristicallyBlank(__in IDiscRecorder2Ex* discRecorder, __out VARIANT_BOOL* pHeuristicallyBlank) { HRESULT hr = S_OK; BOOL bDiscBlank = TRUE; ULONG bytesPerSector = 0; VARIANT_BOOL vbPhysicallyBlank = VARIANT_FALSE; IMAPI_MEDIA_PHYSICAL_TYPE mediaType = IMAPI_MEDIA_TYPE_UNKNOWN; if ((discRecorder == NULL) || (pHeuristicallyBlank == NULL)) { hr = E_POINTER; } if (SUCCEEDED(hr)) { hr = GetMediaPhysicallyBlank(discRecorder, &vbPhysicallyBlank); } if (SUCCEEDED(hr)) { hr = GetCurrentPhysicalMediaType(discRecorder, &mediaType); } // determine how to determine if the media is heuristically blank if (SUCCEEDED(hr) && (vbPhysicallyBlank == VARIANT_TRUE)) { // any media that is physically blank is also heuristically blank bDiscBlank = TRUE; } else if ((mediaType == IMAPI_MEDIA_TYPE_CDROM) || (mediaType == IMAPI_MEDIA_TYPE_CDR) || (mediaType == IMAPI_MEDIA_TYPE_CDRW) || (mediaType == IMAPI_MEDIA_TYPE_DVDROM) || (mediaType == IMAPI_MEDIA_TYPE_DVDPLUSR) || (mediaType == IMAPI_MEDIA_TYPE_DVDPLUSR_DUALLAYER) || (mediaType == IMAPI_MEDIA_TYPE_DVDDASHR) || (mediaType == IMAPI_MEDIA_TYPE_DVDDASHRW) || (mediaType == IMAPI_MEDIA_TYPE_DVDDASHR_DUALLAYER)) { // these media types can deterministically be determined to be blank or not bDiscBlank = (vbPhysicallyBlank == VARIANT_FALSE) ? FALSE : TRUE; } else { // for DVD+RW, DVD-RAM, DISK, and UNKNOWN media types, proceed with heuristic blank detection BOOL bAnswerFound = FALSE; // determine how many bytes per sector if (SUCCEEDED(hr) && !bAnswerFound) { ULONG usedSectors = 0; hr = ReadMediaCapacity(discRecorder, &bytesPerSector, &usedSectors); } // now check the first 2MB of the media if (SUCCEEDED(hr) && !bAnswerFound) { ULONG remainingSectors = ((2 * 1024 * 1024) / bytesPerSector); // 2MB ULONG sectorsThisRead = 0; CDB readCdb; SENSE_DATA senseData; ULONG bufferLength = 0; ULONG retryCnt = 0; ULONG startSector = 0; BYTE* pBuffer = (BYTE*) LocalAlloc(LPTR, 0x10 * bytesPerSector); // check and zero out the buffer if (pBuffer == NULL) { hr = E_OUTOFMEMORY; } else { RtlZeroMemory(pBuffer, 0x10 * bytesPerSector); } // perform the read and check while ((remainingSectors > 0) && bDiscBlank && SUCCEEDED(hr)) { if (remainingSectors < 0x10) { sectorsThisRead = remainingSectors; } else { sectorsThisRead = 0x10; } do { bufferLength = sectorsThisRead * bytesPerSector; RtlZeroMemory( &readCdb, sizeof(CDB) ); readCdb.CDB10.OperationCode = SCSIOP_READ; readCdb.CDB10.LogicalBlockByte0 = HIBYTE( HIWORD( startSector)); readCdb.CDB10.LogicalBlockByte1 = LOBYTE( HIWORD( startSector)); readCdb.CDB10.LogicalBlockByte2 = HIBYTE( LOWORD( startSector)); readCdb.CDB10.LogicalBlockByte3 = LOBYTE( LOWORD( startSector)); readCdb.CDB10.TransferBlocksMsb = HIBYTE( LOWORD( sectorsThisRead)); readCdb.CDB10.TransferBlocksLsb = LOBYTE( LOWORD( sectorsThisRead)); hr = discRecorder->SendCommandGetDataFromDevice( (LPBYTE)&readCdb, sizeof(readCdb.CDB10), (LPBYTE)&senseData, 12, (LPBYTE)pBuffer, bufferLength, &bufferLength ); if ((hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) || (FAILED(hr))) { // retry the read blindly for now Sleep(MILLISECONDS_FROM_SECONDS(2)); retryCnt++; } } while ( (FAILED(hr) || (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA)) && (retryCnt < 5) ); // Translate SENSE_DATA into meaningful hr if (hr == S_IMAPI_COMMAND_HAS_SENSE_DATA) { TranslateSenseInfoToHResult(&readCdb, &senseData, &hr); } // now check the data for equality to 0 if (SUCCEEDED(hr)) { ULONG bytesRead = sectorsThisRead * bytesPerSector; ULONG *checkData = (ULONG*)pBuffer; ULONG bytesChecked = 0; while ((bytesChecked < bytesRead) && bDiscBlank) { if ((*checkData) != 0) { bDiscBlank = FALSE; } else { bytesChecked += sizeof(ULONG); checkData += 1; } } } else { // if the read still failed, we're going to error out so pretend the disc isn't blank bDiscBlank = FALSE; } // increment the read if we still think the disc is blank if (SUCCEEDED(hr) && bDiscBlank) { remainingSectors -= sectorsThisRead; startSector += sectorsThisRead; } } // cleanup LocalFreeAndNull(pBuffer); } } // now set the output properly if (SUCCEEDED(hr)) { if (bDiscBlank) { *pHeuristicallyBlank = VARIANT_TRUE; } else { *pHeuristicallyBlank = VARIANT_FALSE; } } return hr; } BOOLEAN IsSenseDataInTable(__in_ecount(entries) PSENSE_INFOMATION table, const LONG entries, __in PSENSE_DATA senseData) { LONG i; UCHAR sense = senseData->SenseKey & 0xf; UCHAR asc = senseData->AdditionalSenseCode; UCHAR ascq = senseData->AdditionalSenseCodeQualifier; for (i = 0; i < entries; i++ ) { if (((table[i].Sense == 0xFF) || (table[i].Sense == sense)) && ((table[i].Ascq == 0xFF) || (table[i].Ascq == ascq )) && ((table[i].Asc == 0xFF) || (table[i].Asc == asc )) ) { return TRUE; } } return FALSE; } typedef struct _SENSE_ERROR_TABLE { UCHAR SenseKey; UCHAR Asc; UCHAR AscQ; UCHAR Opcode; HRESULT Result; } SENSE_ERROR_TABLE, *PSENSE_ERROR_TABLE; // NOTE: Order of this table is important. // // Taken linearly until a match is found. // btw, a value of 0xFF in Sense/ASC/ASCQ/Opcode is a wildcard match. // Therefore a { 0x00, 0x00, 0xff, 0xff ... } entry will match if both // the Sense and ASC values are zero, regardless of the ASCQ or opcode. // // S_OK is the only allowed SUCCESS table here! const SENSE_ERROR_TABLE GenericErrors[] = { { 0x00, 0x00, 0xFF, 0xFF, S_OK }, // { 0x08, 0xFF, 0xFF, // Blank check { 0xFF, 0x02, 0x06, 0xFF, E_IMAPI_RECORDER_MEDIA_UPSIDE_DOWN }, // standard-defined error (no reference position found) { 0x02, 0x04, 0x01, 0xFF, E_IMAPI_RECORDER_MEDIA_BECOMING_READY }, // standard-defined error (becoming ready) { 0x02, 0x04, 0x03, 0xFF, E_IMAPI_RECORDER_MEDIA_NO_MEDIA }, // !(from ClassInterpretSenseInfo) // { 0x00, 0x04, 0x04, 0xFF, // standard-defined error (background format in progress, need to close disc before eject) { 0x02, 0x04, 0x04, 0xFF, E_IMAPI_RECORDER_MEDIA_FORMAT_IN_PROGRESS }, // standard-defined error (format in progress) { 0x02, 0x04, 0x07, 0xFF, E_IMAPI_RECORDER_MEDIA_BUSY }, // standard-defined error (operation in progress) { 0x02, 0x04, 0x08, 0xFF, E_IMAPI_RECORDER_MEDIA_BUSY }, // standard-defined error (long write in progress) { 0x02, 0x04, 0xFF, 0xFF, E_IMAPI_RECORDER_MEDIA_BECOMING_READY }, // standard-defined error (becoming ready) { 0x02, 0x30, 0xFF, 0xAD, E_IMAPI_RECORDER_DVD_STRUCTURE_NOT_PRESENT }, // incompatible medium installed for READ_DVD_STRUCTURE means it's not there (CD-ROM drive) { 0x03, 0x0C, 0x09, 0x35, S_OK }, // loss of streaming is OK for a synchronize_cache command { 0x03, 0x0C, 0x09, 0xFF, E_IMAPI_LOSS_OF_STREAMING }, // loss of streaming in normal case { 0x04, 0x09, 0x01, 0xFF, E_IMAPI_RECORDER_MEDIA_UPSIDE_DOWN }, // !(Plextor PX-W4012A) { 0x04, 0x09, 0x02, 0xFF, E_IMAPI_RECORDER_MEDIA_INCOMPATIBLE }, // Ricoh DVD+RW when inserting -R media // { 0x01, 0x17, 0xff, 0xFF, // recovered read/write errors! { 0x05, 0x20, 0x00, 0xAD, E_IMAPI_RECORDER_DVD_STRUCTURE_NOT_PRESENT }, // invalid CDB for READ_DVD_STRUCTURE means it's not there (CD-ROM drive) // { 0x05, 0x20, 0x00, 0xFF, // invalid CDB { 0x05, 0x24, 0x00, 0xAD, E_IMAPI_RECORDER_DVD_STRUCTURE_NOT_PRESENT }, // standard-defined error (READ DVD STRUCTURE, LU + Media combination invalid) { 0x05, 0x30, 0x02, 0xAD, E_IMAPI_RECORDER_DVD_STRUCTURE_NOT_PRESENT }, // standard-defined error (READ DVD STRUCTURE for non-dvd media) { 0x05, 0x24, 0x00, 0x5A, E_IMAPI_RECORDER_NO_SUCH_MODE_PAGE }, // invalid field in CDB for MODE_SENSE means unsupported mode page // { 0x05, 0x24, 0x00, 0xFF, // invalid field in CDB { 0x05, 0x26, 0xff, 0x55, E_IMAPI_RECORDER_INVALID_MODE_PARAMETERS }, // invalid parameters for MODE_SELECT means unsupported bits in the mode page // { 0x05, 0x26, 0xff, 0xFF, // invalid parameters provided { 0x07, 0x27, 0xFF, 0xFF, E_IMAPI_RECORDER_MEDIA_WRITE_PROTECTED }, // standard-defined error { 0x06, 0x28, 0x00, 0xFF, E_IMAPI_RECORDER_MEDIA_BECOMING_READY }, // media may have changed! // { 0x06, 0x28, 0xFF, 0xFF, // IMPORT OR EXPORT ELEMENT ACCESSED (6/28/01) -- FORMAT-LAYER MAY HAVE CHANGED (6/28/02) // { 0x06, 0x29, 0xFF, 0xFF, // reset occurred! // { 0x06, 0x2A, 0xFF, 0xFF, // parameters changed // { 0x05, 0x2C, 0x00, 0xFF, // command sequence error == loss of streaming? // { 0x06, 0x2E, 0xFF, 0xFF, // insufficient time for operation == timeout { 0xFF, 0x30, 0xFF, 0xFF, E_IMAPI_RECORDER_MEDIA_INCOMPATIBLE }, // standard-defined error (incompatible media), !(may also be media upside down (Sony DRU-500A)) { 0x02, 0x3A, 0xFF, 0xFF, E_IMAPI_RECORDER_MEDIA_NO_MEDIA }, // standard-defined error (no media in device) // { 0xFF, 0x3E, 0xFF, 0xFF, // timeout?! // { 0xFF, 0x57, 0xFF, 0xFF, // (unable to recover TOC), this means the media/drive combination is incompatible, and will cause coasters! // { 0x05, 0x64, 0x00, 0xFF, // (illegal mode for this track), cmd-dependent error // { 0x05, 0x65, 0x01, 0xFF, // (invalid packet size), write failure // { 0x05, 0x6F, 0xFF, 0xFF, // (copy protection failure) // { 0xFF, 0x72, 0x00, 0xFF, // (session fixation error), write/close session failure // { 0xFF, 0x72, 0x01, 0xFF, // (session fixation error writing lead-in) // { 0xFF, 0x72, 0x02, 0xFF, // (session fixation error writing lead-out) // { 0xFF, 0x72, 0x03, 0xFF, // (session fixation error - incomplete track in session) // { 0xFF, 0x72, 0x04, 0xFF, // (session fixation error - empty/partially written track) // { 0xFF, 0x72, 0x05, 0xFF, // (session fixation error - no more rzone reservations allowed) // { 0xFF, 0x73, 0x00, 0xFF, // (CD Controller error) // { 0xFF, 0x73, 0x01, 0xFF, // (PCA almost full) -- media is going bad, should finalize disc and not use again // { 0xFF, 0x73, 0x02, 0xFF, // (PCA full) -- media is bad, should finalize disc and not use again { 0xFF, 0x73, 0x03, 0xFF, E_IMAPI_RECORDER_MEDIA_SPEED_MISMATCH } // (PCA error) -- may be high-speed media in low-speed drive? // { 0xFF, 0x73, 0x04, 0xFF, // (PMA/RMA update failure) -- this means temp TOC invalid, must finalize disc to keep data! // { 0xFF, 0x73, 0x05, 0xFF, // (PMA/RMA is full) -- this means temp TOC invalid, must finalize disc to keep data! // { 0xFF, 0x73, 0x06, 0xFF, // (PMA/RMA is almost full) -- this means temp TOC invalid, must finalize disc to keep data! // }; const BOOLEAN TranslateSenseInfoToHResult( __in_bcount(1) const CDB* Cdb, // some sense codes are cdb-specific __in_bcount(sizeof(SENSE_DATA)) const SENSE_DATA* Sense, // sense data is key __out HRESULT* HResult // return the hr ) { BOOLEAN translated = FALSE; // do not modify HResult unless match is made! for ( ULONG i = 0; (!translated) && (i < RTL_NUMBER_OF(GenericErrors)); i++ ) { if ( ((GenericErrors[i].SenseKey == 0xFF) || (GenericErrors[i].SenseKey == Sense->SenseKey)) && ((GenericErrors[i].Asc == 0xFF) || (GenericErrors[i].Asc == Sense->AdditionalSenseCode)) && ((GenericErrors[i].AscQ == 0xFF) || (GenericErrors[i].AscQ == Sense->AdditionalSenseCodeQualifier)) && ((GenericErrors[i].Opcode == 0xFF) || (GenericErrors[i].Opcode == Cdb->AsByte[0])) ) { *HResult = GenericErrors[i].Result; translated = TRUE; } } if (!translated) { *HResult = E_FAIL; } return translated; } HRESULT FuzzyConvert_KBps2SectorsPerSecond(const IMAPI_MEDIA_PHYSICAL_TYPE mediaType, const ULONG writeSpeedKBps, __out ULONG *writeSpeedSectorsPerSecond) { // Parameter Verification: skipped, internal only HRESULT hr = S_OK; ULONG finalSpeedSPS = 0; if (IS_CD_MEDIA(mediaType)) { // CD media ... tricky // cd's are harder because we need to determine which data/sector number to use to set it properly // 2324: CD-ROM/XA FORM 2 // 2048: CD-ROM/XA FORM 1 // 2352: // 2336: MODE2 // For now, I standardized on the largest and it seems to work pretty well ... finalSpeedSPS = (writeSpeedKBps * 1000) / 2352; } else if (IS_DVD_MEDIA(mediaType)) { // DVD media ... always the same sector size finalSpeedSPS = (writeSpeedKBps * 1000) / 2048; } else if (mediaType == IMAPI_MEDIA_TYPE_UNKNOWN) { // ARBITRARY DECISION: treat reported blank media speeds as CD finalSpeedSPS = (writeSpeedKBps * 1000) / 2352; } else if (mediaType == IMAPI_MEDIA_TYPE_DISK) { // consider sector sizes on disk media to be 2048 finalSpeedSPS = (writeSpeedKBps * 1000) / 2048; } else { // unsupported media type hr = E_FAIL; } if (SUCCEEDED(hr)) { *writeSpeedSectorsPerSecond = finalSpeedSPS; } return hr; } const HRESULT CreateVariantSafeArrayFromEnums( __in_ecount(valueCount) const LONG * values, __in const ULONG valueCount, __deref_out SAFEARRAY** result ) { HRESULT hr = S_OK; SAFEARRAY* tmpSafeArray = NULL; VARIANT* tmpVariant = NULL; const LONG* tmpItem = values; *result = NULL; // allocate the safearray if (SUCCEEDED(hr)) { tmpSafeArray = ::SafeArrayCreateVector(VT_VARIANT, 0, valueCount); if (tmpSafeArray == NULL) { hr = E_OUTOFMEMORY; } else { tmpVariant = (VARIANT*)tmpSafeArray->pvData; } } // fill in the array if (SUCCEEDED(hr)) { for (ULONG i = 0; i < valueCount; i++, tmpVariant++, tmpItem++) { ::VariantInit(tmpVariant); tmpVariant->vt = VT_I4; tmpVariant->lVal = *tmpItem; } } // return the result or destory the array if (SUCCEEDED(hr)) { *result = tmpSafeArray; } else { // NOTE that this doesn't free any items, which is good. SafeArrayDestroyAndNull(tmpSafeArray); } return hr; }
36.2393
239
0.502425
windows-development
7e9f12e45047b8a5c8fdc530a1bc749f1ca4f919
2,598
cc
C++
squid/squid3-3.3.8.spaceify/test-suite/ESIExpressions.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/test-suite/ESIExpressions.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/test-suite/ESIExpressions.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 86 ESI Expressions * AUTHOR: Robert Collins * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * */ #include "squid.h" #include "esi/Expression.h" int main () { char const *expressions[] = { "!(1==1)", "!(1!=1)", "1!=1", "!1==1", "1==1", "1 <=1","2<=1", "1 < 1", "1 < 2", "-1 < 1","!-1<1", "1>2","2>1","2>=2", "2>3", "1==1&1==1","1==1&1==0", "!('a'<='c')", "(1==1)|('abc'=='def')", "(4!=5)&(4==5)", "(1==1)|(2==3)&(3==4)", /* should be true because of precedence */ "(1 & 4)", "(\"abc\" | \"edf\")", "1==1==1", "!('')", /* End of array */"" }; int results[] = {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0 }; int i = 0; while (strlen (expressions[i])) { int result = ESIExpression::Evaluate (expressions[i]); #if VERBOSEDEBUG printf("Expr '%s' = '%s' (expected %s)\n", expressions[i], result ? "true" : "false", results[i] ? "true" : "false"); #endif if (result != results[i]) return 1; ++i; } return 0; }
32.074074
74
0.537721
spaceify
7ea48d0735537d87e96423a1747f1611ed36ab01
3,822
cpp
C++
src/gazebo_ros_pkgs/gazebo_plugins/src/gazebo_ros_triggered_camera.cpp
snorman35/delivery_robot
a578628464aa4a04ab213d0002e393e868057dc7
[ "MIT" ]
7
2022-02-17T23:29:45.000Z
2022-03-12T09:23:54.000Z
src/gazebo_ros_pkgs/gazebo_plugins/src/gazebo_ros_triggered_camera.cpp
snorman35/delivery_robot
a578628464aa4a04ab213d0002e393e868057dc7
[ "MIT" ]
1
2021-06-05T07:58:03.000Z
2021-06-05T07:58:03.000Z
src/gazebo_ros_pkgs/gazebo_plugins/src/gazebo_ros_triggered_camera.cpp
snorman35/delivery_robot
a578628464aa4a04ab213d0002e393e868057dc7
[ "MIT" ]
1
2018-12-09T22:05:47.000Z
2018-12-09T22:05:47.000Z
/* * Copyright 2017 Open Source Robotics Foundation * * 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 "gazebo_plugins/gazebo_ros_triggered_camera.h" #include <float.h> #include <string> #include <gazebo/sensors/Sensor.hh> #include <gazebo/sensors/CameraSensor.hh> #include <gazebo/sensors/SensorTypes.hh> namespace gazebo { // Register this plugin with the simulator GZ_REGISTER_SENSOR_PLUGIN(GazeboRosTriggeredCamera) //////////////////////////////////////////////////////////////////////////////// // Constructor GazeboRosTriggeredCamera::GazeboRosTriggeredCamera() { } //////////////////////////////////////////////////////////////////////////////// // Destructor GazeboRosTriggeredCamera::~GazeboRosTriggeredCamera() { ROS_DEBUG_STREAM_NAMED("camera","Unloaded"); } void GazeboRosTriggeredCamera::Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf) { // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) { ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. " << "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)"); return; } CameraPlugin::Load(_parent, _sdf); // copying from CameraPlugin into GazeboRosTriggeredCameraUtils this->parentSensor_ = this->parentSensor; this->width_ = this->width; this->height_ = this->height; this->depth_ = this->depth; this->format_ = this->format; this->camera_ = this->camera; GazeboRosCameraUtils::Load(_parent, _sdf); this->SetCameraEnabled(false); this->preRenderConnection_ = event::Events::ConnectPreRender( std::bind(&GazeboRosTriggeredCamera::PreRender, this)); } void GazeboRosTriggeredCamera::Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf, const std::string &_camera_name_suffix, double _hack_baseline) { GazeboRosCameraUtils::Load(_parent, _sdf, _camera_name_suffix, _hack_baseline); this->SetCameraEnabled(false); this->preRenderConnection_ = event::Events::ConnectPreRender( std::bind(&GazeboRosTriggeredCamera::PreRender, this)); } //////////////////////////////////////////////////////////////////////////////// // Update the controller void GazeboRosTriggeredCamera::OnNewFrame(const unsigned char *_image, unsigned int _width, unsigned int _height, unsigned int _depth, const std::string &_format) { this->sensor_update_time_ = this->parentSensor_->LastMeasurementTime(); if ((*this->image_connect_count_) > 0) { this->PutCameraData(_image); this->PublishCameraInfo(); } this->SetCameraEnabled(false); std::lock_guard<std::mutex> lock(this->mutex); this->triggered = std::max(this->triggered-1, 0); } void GazeboRosTriggeredCamera::TriggerCamera() { std::lock_guard<std::mutex> lock(this->mutex); if (!this->parentSensor_) return; this->triggered++; } bool GazeboRosTriggeredCamera::CanTriggerCamera() { return true; } void GazeboRosTriggeredCamera::PreRender() { std::lock_guard<std::mutex> lock(this->mutex); if (this->triggered > 0) { this->SetCameraEnabled(true); } } void GazeboRosTriggeredCamera::SetCameraEnabled(const bool _enabled) { this->parentSensor_->SetActive(_enabled); this->parentSensor_->SetUpdateRate(_enabled ? 0.0 : DBL_MIN); } }
28.522388
99
0.693878
snorman35
7eaadfb2abbb299416c9ad24e80799db58cf0a78
2,412
cpp
C++
lib/malloy/core/http/generator.cpp
0x00002a/malloy
94ececf246ac2bc848235f7806439ef3be1eed73
[ "MIT" ]
22
2021-04-17T17:32:14.000Z
2022-03-29T09:42:03.000Z
lib/malloy/core/http/generator.cpp
0x00002a/malloy
94ececf246ac2bc848235f7806439ef3be1eed73
[ "MIT" ]
98
2021-04-03T18:53:19.000Z
2022-02-06T10:49:30.000Z
lib/malloy/core/http/generator.cpp
0x00002a/malloy
94ececf246ac2bc848235f7806439ef3be1eed73
[ "MIT" ]
3
2021-05-12T15:17:11.000Z
2021-12-28T03:15:46.000Z
#include "generator.hpp" #include "response.hpp" #include "request.hpp" #include <boost/beast/core/file_base.hpp> using namespace malloy::http; response<> generator::ok() { response resp { status::ok }; return resp; } response<> generator::redirect(const status code, const std::string_view location) { const int& icode = static_cast<int>(code); if (icode < 300 || icode >= 400) return generator::server_error("invalid redirection status code."); response resp{ code }; resp.set(field::location, location); resp.prepare_payload(); return resp; } response<> generator::bad_request(std::string_view reason) { response res(status::bad_request); res.set(field::content_type, "text/html"); res.body() = reason; res.prepare_payload(); return res; } response<> generator::not_found(std::string_view resource) { response res(status::not_found); res.set(field::content_type, "text/html"); res.body() = "The resource '" + std::string(resource) + "' was not found."; res.prepare_payload(); return res; } response<> generator::server_error(std::string_view what) { response res(status::internal_server_error); res.set(field::content_type, "text/html"); res.body() = "An error occurred: '" + std::string(what) + "'"; res.prepare_payload(); return res; } auto generator::file(const std::filesystem::path& storage_base_path, std::string_view rel_path) -> file_response { // Sanitize rel_path { // Check for relative paths if (rel_path.find("..") != std::string::npos) return bad_request("resource path must not contain \"..\""); // Drop leading slash, if any if (rel_path.starts_with("/")) rel_path = rel_path.substr(1); } const std::filesystem::path& path = storage_base_path / rel_path; // Check whether this is a valid file path if (!std::filesystem::is_regular_file(path)) return not_found(rel_path); // Get mime type const std::string_view& mime_type = malloy::mime_type(path); // Create response response<boost::beast::http::file_body> resp{status::ok}; resp.set(field::content_type, mime_type); boost::beast::error_code ec; resp.body().open(path.string().c_str(), boost::beast::file_mode::scan, ec); if (ec) { return server_error(ec.message()); } return resp; }
25.659574
112
0.652156
0x00002a
7eab4f6bc1f0da703f921243a5ca48d8802549d6
316
cpp
C++
Chapter12/ex1/usecow.cpp
leonardoaraujodf/cpp_prog
d8d6bea8fa942faa162f0da8221a034e9173bddb
[ "MIT" ]
null
null
null
Chapter12/ex1/usecow.cpp
leonardoaraujodf/cpp_prog
d8d6bea8fa942faa162f0da8221a034e9173bddb
[ "MIT" ]
null
null
null
Chapter12/ex1/usecow.cpp
leonardoaraujodf/cpp_prog
d8d6bea8fa942faa162f0da8221a034e9173bddb
[ "MIT" ]
null
null
null
#include <iostream> #include "cow.h" int main() { Cow c1; Cow c2("Booo", "Nma", 120.25); Cow c3("Abab", "Asho", 150.45); Cow c4(c3); c1.ShowCow(); c2.ShowCow(); c3.ShowCow(); c4.ShowCow(); c1 = c2; c1.ShowCow(); c1 = c3; c1.ShowCow(); c4 = c2; c2.ShowCow(); return 0; }
14.363636
34
0.512658
leonardoaraujodf
7eac7de153c2c70d1e9e664c9441fa25524dee91
715
hpp
C++
include/RED4ext/Types/generated/CParticleModificatorTargetNode.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/CParticleModificatorTargetNode.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/CParticleModificatorTargetNode.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/Types/generated/IParticleModificator.hpp> namespace RED4ext { struct IEvaluatorFloat; struct CParticleModificatorTargetNode : IParticleModificator { static constexpr const char* NAME = "CParticleModificatorTargetNode"; static constexpr const char* ALIAS = NAME; Handle<IEvaluatorFloat> forceScale; // 80 Handle<IEvaluatorFloat> killRadius; // 90 float maxForce; // A0 uint8_t unkA4[0xA8 - 0xA4]; // A4 }; RED4EXT_ASSERT_SIZE(CParticleModificatorTargetNode, 0xA8); } // namespace RED4ext
26.481481
73
0.763636
Cyberpunk-Extended-Development-Team
9d19466492c2406631d239969204e5f19d8f843d
2,140
hpp
C++
source/YoloMouse/Loader/Core/App.hpp
ttcctt/GAME
982ad68a65f17f3926d713283f73ac858b6820e0
[ "Unlicense" ]
158
2015-02-16T20:32:09.000Z
2022-03-24T04:11:07.000Z
source/YoloMouse/Loader/Core/App.hpp
Maqentaer/YoloMouse
48415f1517591e0445b44e73d05f61d3e35b41f2
[ "Unlicense" ]
22
2015-03-03T23:40:54.000Z
2021-11-14T06:28:25.000Z
source/YoloMouse/Loader/Core/App.hpp
Maqentaer/YoloMouse
48415f1517591e0445b44e73d05f61d3e35b41f2
[ "Unlicense" ]
48
2015-06-12T17:50:39.000Z
2022-03-21T20:59:29.000Z
#pragma once #include <Core/Support/Settings.hpp> #include <Core/Support/Singleton.hpp> #include <Core/Windows/InputMonitor.hpp> #include <Core/Windows/ShellUi.hpp> #include <YoloMouse/Loader/Overlay/Cursor/OverlayCursorVault.hpp> namespace Yolomouse { /**/ class App: public Singleton<App>, public InputMonitor::IListener, public ShellUi::IListener { public: /**/ App(); ~App(); /**/ Bool Initialize( HINSTANCE hinstance ); void Shutdown(); /**/ Bool IsInitialized() const; Bool IsElevated() const; /**/ Bool GetElevate() const; const PathString& GetHostPath() const; const PathString& GetUserPath() const; const PathString& GetLogPath() const; private: // impl: InputMonitor::IListener, ShellUi::IListener /**/ void OnKeyCombo( Id combo_id ); Bool OnMenuOption( Id id, Bool enabled ); private: /**/ Bool _InitializePaths(); Bool _InitializeSettings(); Bool _InitializeUi(); Bool _InitializeInput(); Bool _InitializeOptions(); Bool _InitializeOverlay( HINSTANCE hinstance ); void _InstallOverlayCursors(); /**/ void _ShutdownUi(); void _ShutdownInput(); void _ShutdownOverlay(); void _UninstallOverlayCursors(); /**/ void _OptionAbout(); void _OptionErrors(); Bool _OptionAutoStart( Bool enable, Bool save ); void _OptionReduceOverlayLag( Bool enable, Bool save ); Bool _OptionRunAsAdmin(); void _OptionSettingsFolder(); // fields: parameters Bool _elevate; // fields: state Bool _initialized; // fields: info PathString _host_path; PathString _user_path; PathString _log_path; // fields: objects OverlayCursorVault _overlay_cursor_vault; ShellUi& _ui; InputMonitor _input_monitor; Settings _settings; }; }
25.783133
65
0.578037
ttcctt
9d24c9469c942ae510e107f391ee6166775ed4ee
1,423
cc
C++
public/util/file/shared_writer.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
3
2015-05-18T14:52:47.000Z
2018-11-12T07:51:00.000Z
public/util/file/shared_writer.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
null
null
null
public/util/file/shared_writer.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
3
2015-08-04T05:58:18.000Z
2018-11-12T07:51:01.000Z
// Copyright 2012 Room77, Inc. // Author: Nicholas Edelman #include "util/file/shared_writer.h" FLAG_int(shared_writer_sleep_ms, 100, "the number of milliseconds to sleep while waiting for the next results"); namespace util { SharedWriter::SharedWriter(const string& fn) : fn_(fn) { file_.open(fn, ios::out); ASSERT(file_.good()) << "Error unable to open for writing: " << fn; thread(&util::SharedWriter::Flush, this).detach(); } void SharedWriter::Write(const string& entry) { lock_guard<mutex> lg(m_); entries_.push_back(entry); } void SharedWriter::Reset() { lock_guard<mutex> lg(m_); entries_.clear(); file_.close(); file_.open(fn_, ios::out); ASSERT(file_.good()) << "Error unable to REopen for writing: " << fn_; } // // PRIVATE // void SharedWriter::Flush() { while (true) { vector<string> entries; GetEntries(&entries); if (entries.size() > 0) { for (auto it = entries.begin(); it != entries.end(); ++it) { file_ << *it << endl; } file_.flush(); ASSERT(!file_.fail()) << "Error flushing " << entries.size() << " entries to file" << fn_; } else { this_thread::sleep_for(chrono::milliseconds(gFlag_shared_writer_sleep_ms)); } } } void SharedWriter::GetEntries(vector<string> *entries) { lock_guard<mutex> lg(m_); entries->clear(); entries->swap(entries_); } } // namespace util
23.716667
83
0.631764
room77
9d24d3cdf5bc1eaeca3c6044d5f21005565b0339
319
hpp
C++
test/filesystem_mock.hpp
doylehuang/phosphor-hwmon
04da055198fe03f119e53578ac80a6188461b748
[ "Apache-2.0" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
test/filesystem_mock.hpp
doylehuang/phosphor-hwmon
04da055198fe03f119e53578ac80a6188461b748
[ "Apache-2.0" ]
17
2015-10-21T03:34:51.000Z
2021-09-27T17:24:07.000Z
test/filesystem_mock.hpp
doylehuang/phosphor-hwmon
04da055198fe03f119e53578ac80a6188461b748
[ "Apache-2.0" ]
22
2015-10-21T03:31:43.000Z
2021-09-08T07:12:11.000Z
#pragma once #include "hwmonio.hpp" #include <string> #include <gmock/gmock.h> namespace hwmonio { class FileSystemMock : public FileSystemInterface { public: MOCK_CONST_METHOD1(read, int64_t(const std::string&)); MOCK_CONST_METHOD2(write, void(const std::string&, uint32_t)); }; } // namespace hwmonio
15.95
66
0.727273
doylehuang
9d26fd296f0fb0327ed99a77b89985f737abae8b
341
hpp
C++
PlanetaMatchMakerServer/source/message/message_handlers/keep_alive_notice_message_handler.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
6
2019-08-15T09:48:55.000Z
2021-07-25T14:40:59.000Z
PlanetaMatchMakerServer/source/message/message_handlers/keep_alive_notice_message_handler.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
43
2019-12-25T14:54:52.000Z
2022-02-24T17:22:48.000Z
PlanetaMatchMakerServer/source/message/message_handlers/keep_alive_notice_message_handler.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
2
2020-05-06T20:14:44.000Z
2020-06-02T21:21:10.000Z
#pragma once #include "../messages.hpp" #include "../message_handler.hpp" namespace pgl { class keep_alive_notice_message_handler final : public message_handler_base<keep_alive_notice_message> { public: void handle_message(const keep_alive_notice_message& message, std::shared_ptr<message_handle_parameter> param) override; }; }
24.357143
66
0.791789
InstytutXR
9d27235a9cff4bee65f0abb1f9d91f008f277172
3,708
cpp
C++
MatchServer/TestCRCStage.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
MatchServer/TestCRCStage.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
MatchServer/TestCRCStage.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
#include "stdafx.h" #include "TestCRCStage.h" #include "TestCRC32Server.h" #include "MMatchCRC32XORCache.h" TestCRCStage::TestCRCStage( const MUID& uid ) { _ASSERT( MUID(0, 0) != uid ); m_UID = uid; }; TestCRCStage::~TestCRCStage() { } const bool TestCRCStage::WasJoinedPlayer( const MUID uidPlayer ) { TestCRCStagePlayerUIDList::const_iterator end = m_PlayerUIDList.end(); TestCRCStagePlayerUIDList::iterator it = m_PlayerUIDList.begin(); for( ; end != it; ++it ) { if( uidPlayer == (*it) ) { return true; } } return false; } const bool TestCRCStage::AddPlayer( const MUID uidPlayer ) { if( WasJoinedPlayer(uidPlayer) ) { return false; } m_PlayerUIDList.push_back( uidPlayer ); MMATCH_RESOURCECHECKINFO CRC32CacheInfo; CRC32CacheInfo.dwLastRequestTime = 0; CRC32CacheInfo.dwResourceCRC32Cache = 0; CRC32CacheInfo.dwResourceXORCache = 0; m_ResourceCRC32CacheMap.insert( ResourceCRC32CacheMap::value_type(uidPlayer, CRC32CacheInfo) ); return true; } void TestCRCStage::MakeResourceCRC32( TestCRCServer& tServer, const MUID uidPlayer, DWORD& out_crc32, DWORD& out_xor ) { TestCRCPlayer* pPlayer = tServer.GetPlayer( uidPlayer ); if( NULL == pPlayer ) { return; } MMatchCRC32XORCache CRC32Cacher; MMatchItemDesc* pItemDesc = NULL; TestEquipMap& EquipMap = pPlayer->GetEquipMap(); TestEquipMap::const_iterator end = EquipMap.end(); TestEquipMap::iterator it = EquipMap.begin(); CRC32Cacher.Reset(); for( ; end != it; ++it ) { pItemDesc = reinterpret_cast<MMatchItemDesc*>( it->second ); pItemDesc->CacheCRC32( CRC32Cacher ); } mlog( "ResourceCRC : %u\n", CRC32Cacher.GetCRC32() ); out_crc32 = CRC32Cacher.GetCRC32(); out_xor = CRC32Cacher.GetXOR(); } const bool TestCRCStage::SetResourceCRC32( const MUID uidPlayer, const DWORD dwResourceCRC32Cache, const DWORD dwResourceXORCache ) { ResourceCRC32CacheMap::iterator itFind = m_ResourceCRC32CacheMap.find( uidPlayer ); if( m_ResourceCRC32CacheMap.end() == itFind ) { return false; } itFind->second.dwResourceCRC32Cache = dwResourceCRC32Cache; itFind->second.dwResourceXORCache = dwResourceXORCache; itFind->second.dwLastRequestTime = timeGetTime(); return true; } const bool TestCRCStage::EnterBattle( TestCRCServer& tServer, const MUID uidPlayer ) { TestCRCStagePlayerUIDList::const_iterator end = m_PlayerUIDList.end(); TestCRCStagePlayerUIDList::iterator it = m_PlayerUIDList.begin(); DWORD dwCRC32, dwXOR; for( ; end != it; ++it ) { MakeResourceCRC32(tServer, uidPlayer, dwCRC32, dwXOR); if( !SetResourceCRC32(uidPlayer, dwCRC32, dwXOR) ) { return false; } } MakeResourceCRC32(tServer, uidPlayer, dwCRC32, dwXOR); tServer.GetTestNetModule().RequestToClient_ResourceCRC32Cache( uidPlayer, dwCRC32, dwXOR ); return true; } const DWORD TestCRCStage::GetResourceCRC32Cache( const MUID uidPlayer ) { ResourceCRC32CacheMap::iterator itFind = m_ResourceCRC32CacheMap.find( uidPlayer ); if( m_ResourceCRC32CacheMap.end() == itFind ) return 0; return static_cast<DWORD>( itFind->second.dwResourceCRC32Cache ); } const DWORD TestCRCStage::GetResourceXORCache( const MUID uidPlayer ) { ResourceCRC32CacheMap::iterator itFind = m_ResourceCRC32CacheMap.find( uidPlayer ); if( m_ResourceCRC32CacheMap.end() == itFind ) return 0; return static_cast<DWORD>( itFind->second.dwResourceXORCache ); } const bool TestCRCStage::IsValidResourceCRC32Cache( const MUID uidPlayer, const DWORD dwResourceCRC32Cache, const DWORD dwResourceXORCache ) { _ASSERT( 0 != dwResourceCRC32Cache ); return (dwResourceCRC32Cache == GetResourceCRC32Cache( uidPlayer ) && dwResourceXORCache == GetResourceXORCache( uidPlayer )); }
23.922581
140
0.747843
WhyWolfie
9d2e916f888ab4fd08fe9ba53539152150329bab
8,525
cpp
C++
source/windows/brwindowsversion.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/windows/brwindowsversion.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/windows/brwindowsversion.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** Shims for version.dll Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brwindowstypes.h" #if defined(BURGER_WINDOWS) || defined(DOXYGEN) #if !defined(DOXYGEN) // // Handle some annoying defines that some windows SDKs may or may not have // #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #if !defined(_WIN32_WINNT) #define _WIN32_WINNT 0x0501 // Windows XP #endif #include <Windows.h> #include <WinVer.h> typedef BOOL(APIENTRY* VerQueryValueAPtr)( LPCVOID pBlock, LPCSTR lpSubBlock, LPVOID* lplpBuffer, PUINT puLen); typedef BOOL(APIENTRY* VerQueryValueWPtr)( LPCVOID pBlock, LPCWSTR lpSubBlock, LPVOID* lplpBuffer, PUINT puLen); typedef BOOL(APIENTRY* GetFileVersionInfoAPtr)( LPCSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData); typedef BOOL(APIENTRY* GetFileVersionInfoWPtr)( LPCWSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData); typedef DWORD(APIENTRY* GetFileVersionInfoSizeAPtr)( LPCSTR lptstrFilename, LPDWORD lpdwHandle); typedef DWORD(APIENTRY* GetFileVersionInfoSizeWPtr)( LPCWSTR lptstrFilename, LPDWORD lpdwHandle); // Unit tests for pointers // While these tests fail on Codewarrior, it's okay because it's only a // difference in const. // VerQueryValueAPtr gVerQueryValueA = ::VerQueryValueA; // VerQueryValueWPtr gVerQueryValueW = ::VerQueryValueW; // GetFileVersionInfoAPtr gGetFileVersionInfoA = ::GetFileVersionInfoA; // GetFileVersionInfoWPtr gGetFileVersionInfoW = ::GetFileVersionInfoW; // GetFileVersionInfoSizeAPtr gGetFileVersionInfoSizeA = // ::GetFileVersionInfoSizeA; // GetFileVersionInfoSizeWPtr gGetFileVersionInfoSizeW = // ::GetFileVersionInfoSizeW; #endif // // version.dll // /*! ************************************ \brief Load in version.dll and call VerQueryValueA Manually load version.dll if needed and call the Windows function VerQueryValueA() http://msdn.microsoft.com/en-us/library/windows/desktop/ms647464(v=vs.85).aspx \windowsonly \param pBlock The version-information resource returned by the GetFileVersionInfo function. \param pSubBlock A pointer to the version-information value to be retrieved. \param ppBuffer A pointer that contains the address of a pointer to the requested version information in the buffer pointed to by pBlock. \param pLen The size of the buffer pointed to by lplpBuffer, in bytes. \return Returns \ref TRUE if successful, or \ref FALSE otherwise. ***************************************/ uint_t BURGER_API Burger::Windows::VerQueryValueA( const void* pBlock, const char* pSubBlock, void** ppBuffer, uint_t* pLen) { void* pVerQueryValueA = LoadFunctionIndex(CALL_VerQueryValueA); BOOL uResult = FALSE; // Failure if (pVerQueryValueA) { uResult = static_cast<VerQueryValueAPtr>(pVerQueryValueA)( pBlock, pSubBlock, ppBuffer, pLen); } return static_cast<uint_t>(uResult); } /*! ************************************ \brief Load in version.dll and call VerQueryValueW Manually load version.dll if needed and call the Windows function VerQueryValueW() http://msdn.microsoft.com/en-us/library/windows/desktop/ms647464(v=vs.85).aspx \windowsonly \param pBlock The version-information resource returned by the GetFileVersionInfo function. \param pSubBlock A pointer to the version-information value to be retrieved. \param ppBuffer A pointer that contains the address of a pointer to the requested version information in the buffer pointed to by pBlock. \param pLen The size of the buffer pointed to by lplpBuffer, in bytes. \return Returns \ref TRUE if successful, or \ref FALSE otherwise. ***************************************/ uint_t BURGER_API Burger::Windows::VerQueryValueW( const void* pBlock, const uint16_t* pSubBlock, void** ppBuffer, uint_t* pLen) { void* pVerQueryValueW = LoadFunctionIndex(CALL_VerQueryValueW); BOOL uResult = FALSE; // Failure if (pVerQueryValueW) { uResult = static_cast<VerQueryValueWPtr>(pVerQueryValueW)( pBlock, reinterpret_cast<LPCWSTR>(pSubBlock), ppBuffer, pLen); } return static_cast<uint_t>(uResult); } /*! ************************************ \brief Load in version.dll and call GetFileVersionInfoA Manually load version.dll if needed and call the Windows function GetFileVersionInfoA() http://msdn.microsoft.com/en-us/library/windows/desktop/ms647003(v=vs.85).aspx \windowsonly \param ptstrFilename The name of the file \param dwHandle This parameter is ignored. \param dwLen The size, in bytes, of the buffer pointed to by the lpData parameter. \param pData Pointer to a buffer that receives the file-version information. \return Returns \ref TRUE if successful, or \ref FALSE otherwise. ***************************************/ uint_t BURGER_API Burger::Windows::GetFileVersionInfoA( const char* ptstrFilename, uint32_t dwHandle, uint32_t dwLen, void* pData) { void* pGetFileVersionInfoA = LoadFunctionIndex(CALL_GetFileVersionInfoA); BOOL uResult = FALSE; // Failure if (pGetFileVersionInfoA) { uResult = static_cast<GetFileVersionInfoAPtr>(pGetFileVersionInfoA)( ptstrFilename, dwHandle, dwLen, pData); } return static_cast<uint_t>(uResult); } /*! ************************************ \brief Load in version.dll and call GetFileVersionInfoW Manually load version.dll if needed and call the Windows function GetFileVersionInfoW() http://msdn.microsoft.com/en-us/library/windows/desktop/ms647003(v=vs.85).aspx \windowsonly \param ptstrFilename The name of the file \param dwHandle This parameter is ignored. \param dwLen The size, in bytes, of the buffer pointed to by the lpData parameter. \param pData Pointer to a buffer that receives the file-version information. \return Returns \ref TRUE if successful, or \ref FALSE otherwise. ***************************************/ uint_t BURGER_API Burger::Windows::GetFileVersionInfoW( const uint16_t* ptstrFilename, uint32_t dwHandle, uint32_t dwLen, void* pData) { void* pGetFileVersionInfoW = LoadFunctionIndex(CALL_GetFileVersionInfoW); BOOL uResult = FALSE; // Failure if (pGetFileVersionInfoW) { uResult = static_cast<GetFileVersionInfoWPtr>(pGetFileVersionInfoW)( reinterpret_cast<LPCWSTR>(ptstrFilename), dwHandle, dwLen, pData); } return static_cast<uint_t>(uResult); } /*! ************************************ \brief Load in version.dll and call GetFileVersionInfoA Manually load version.dll if needed and call the Windows function GetFileVersionInfoA() http://msdn.microsoft.com/en-us/library/windows/desktop/ms647005(v=vs.85).aspx \windowsonly \param ptstrFilename The name of the file of interest. \param pdwHandle A pointer to a variable that the function sets to zero. \return Returns the number of bytes if successful, or zero otherwise. ***************************************/ uint32_t BURGER_API Burger::Windows::GetFileVersionInfoSizeA( const char* ptstrFilename, unsigned long* pdwHandle) { void* pGetFileVersionInfoSizeA = LoadFunctionIndex(CALL_GetFileVersionInfoSizeA); uint_t uResult = 0; // Failure if (pGetFileVersionInfoSizeA) { uResult = static_cast<GetFileVersionInfoSizeAPtr>( pGetFileVersionInfoSizeA)(ptstrFilename, pdwHandle); } return uResult; } /*! ************************************ \brief Load in version.dll and call GetFileVersionInfoSizeW Manually load version.dll if needed and call the Windows function GetFileVersionInfoSizeW() http://msdn.microsoft.com/en-us/library/windows/desktop/ms647005(v=vs.85).aspx \windowsonly \param ptstrFilename The name of the file of interest. \param pdwHandle A pointer to a variable that the function sets to zero. \return Returns the number of bytes if successful, or zero otherwise. ***************************************/ uint32_t BURGER_API Burger::Windows::GetFileVersionInfoSizeW( const uint16_t* ptstrFilename, unsigned long* pdwHandle) { void* pGetFileVersionInfoSizeW = LoadFunctionIndex(CALL_GetFileVersionInfoSizeW); uint_t uResult = 0; // Failure if (pGetFileVersionInfoSizeW) { uResult = static_cast<GetFileVersionInfoSizeWPtr>(pGetFileVersionInfoSizeW)( reinterpret_cast<LPCWSTR>(ptstrFilename), pdwHandle); } return uResult; } #endif
32.048872
79
0.730674
Olde-Skuul
9d35fa6d9337cc036ee6a7e820c19ad719495ecd
1,393
hpp
C++
include/timer.hpp
FromAlaska/CornHub
d6280e1d66f15cd58fd0d8086c7beeb7b7db3e8b
[ "Unlicense" ]
2
2018-09-24T21:58:50.000Z
2019-04-18T21:32:04.000Z
include/timer.hpp
FromAlaska/CornHub
d6280e1d66f15cd58fd0d8086c7beeb7b7db3e8b
[ "Unlicense" ]
null
null
null
include/timer.hpp
FromAlaska/CornHub
d6280e1d66f15cd58fd0d8086c7beeb7b7db3e8b
[ "Unlicense" ]
null
null
null
// timer.hpp // 26. April 2017 // Created by: // Bryan Burkhardt (bmburkhardt@alaska.edu) // Alexander Eckert (aeckert@alaska.edu) // Jeremiah Jacobson (jjacobson2@alaska.edu) // Jarye Murphy (jmurphy11@alaska.edu) // Cameron Showalter (cjshowalter@alaska.edu) // // Source file for timer #ifndef TIMER_HPP #define TIMER_HPP #include <SFML/System.hpp> #include <SFML/Graphics.hpp> #include <sstream> class Timer { /****** Timer Variables ******/ // Current Time Elapsed Stuff std::stringstream currentTimerStreamSeconds; std::stringstream currentTimerStreamMinutes; std::stringstream currentTimerStreamHours; sf::Time currentTimer; float currentTimeSeconds; float currentTimeMinutes; float currentTimeHours; // Total Time Stuff std::stringstream totalTimerStreamSeconds; std::stringstream totalTimerStreamMinutes; std::stringstream totalTimerStreamHours; sf::Time totalTimer; float totalTimeSeconds; float totalTimeMinutes; float totalTimeHours; // Onscreen Timer Display Stuff std::string currentSec; std::string currentMin; std::string currentHour; std::string totalSec; std::string totalMin; std::string totalHour; public: Timer() = default; /****** Timer Functions ******/ void updateTimer(); std::string selectDisplayTimer(); void displayTimer(); int convertToMinutes(int seconds); int convertToHours(int seconds); }; #endif //TIMER_HPP
22.836066
47
0.750179
FromAlaska
9d37073ab9947fafb822784bb3856529b2ad1a23
230
cc
C++
Carbon/src/carbon/platform/directx11/dx11_shader.cc
jacks-github/Carbon
c6cc0f0c491d2980125556be731c7776976112ea
[ "MIT" ]
null
null
null
Carbon/src/carbon/platform/directx11/dx11_shader.cc
jacks-github/Carbon
c6cc0f0c491d2980125556be731c7776976112ea
[ "MIT" ]
null
null
null
Carbon/src/carbon/platform/directx11/dx11_shader.cc
jacks-github/Carbon
c6cc0f0c491d2980125556be731c7776976112ea
[ "MIT" ]
null
null
null
#include "carbon/platform/directx11/dx11_shader.h" #include "carbon/core/core.h" namespace CR { DX11Shader::DX11Shader(const std::string& path) { CR_LOG("[Warning] Creating Shader: DirectX11 not yet supported\n"); } } // CR
19.166667
69
0.726087
jacks-github
9d405591145320f5b42ea7a556fbf420dee9daa1
2,450
cc
C++
rocks-sys/rocks/cache.cc
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
[ "Apache-2.0" ]
40
2017-05-16T06:10:51.000Z
2021-09-02T01:06:37.000Z
rocks-sys/rocks/cache.cc
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
[ "Apache-2.0" ]
12
2017-06-11T09:42:02.000Z
2020-10-11T23:46:31.000Z
rocks-sys/rocks/cache.cc
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
[ "Apache-2.0" ]
8
2017-05-16T03:44:53.000Z
2020-10-11T22:01:17.000Z
#include "rocksdb/cache.h" #include "rocksdb/persistent_cache.h" #include "rocks/ctypes.hpp" using namespace ROCKSDB_NAMESPACE; using std::shared_ptr; extern "C" { rocks_cache_t* rocks_cache_create_lru(size_t capacity, int num_shard_bits, char strict_capacity_limit, double high_pri_pool_ratio) { rocks_cache_t* c = new rocks_cache_t; c->rep = NewLRUCache(capacity, num_shard_bits, strict_capacity_limit, high_pri_pool_ratio); return c; } rocks_cache_t* rocks_cache_create_clock(size_t capacity, int num_shard_bits, char strict_capacity_limit) { rocks_cache_t* c = new rocks_cache_t; c->rep = NewClockCache(capacity, num_shard_bits, strict_capacity_limit); if (c->rep == nullptr) { delete (c); return nullptr; } return c; } void rocks_cache_destroy(rocks_cache_t* cache) { delete cache; } void rocks_cache_set_capacity(rocks_cache_t* cache, size_t capacity) { cache->rep->SetCapacity(capacity); } size_t rocks_cache_get_capacity(rocks_cache_t* cache) { return cache->rep->GetCapacity(); } size_t rocks_cache_get_usage(rocks_cache_t* cache) { return cache->rep->GetUsage(); } size_t rocks_cache_get_pinned_usage(rocks_cache_t* cache) { return cache->rep->GetPinnedUsage(); } const char* rocks_cache_name(rocks_cache_t* cache) { return cache->rep->Name(); } } // persistent_cache extern "C" { rocks_persistent_cache_t* rocks_new_persistent_cache(const rocks_env_t* env, const char* path, size_t path_len, uint64_t size, const rocks_logger_t* log, unsigned char optimized_for_nvm, rocks_status_t** status) { auto ret = new rocks_persistent_cache_t; auto logger = log == nullptr ? nullptr : log->rep; auto st = NewPersistentCache(env->rep, std::string(path, path_len), size, logger, optimized_for_nvm, &ret->rep); if (SaveError(status, std::move(st))) { delete ret; return nullptr; } else { return ret; } } void rocks_persistent_cache_destroy(rocks_persistent_cache_t* cache) { delete cache; } rocks_persistent_cache_t* rocks_persistent_cache_clone(rocks_persistent_cache_t* cache) { return new rocks_persistent_cache_t{cache->rep}; } cxx_string_t* rocks_persistent_cache_get_printable_options(rocks_persistent_cache_t* cache) { auto str = new std::string(cache->rep->GetPrintableOptions()); return reinterpret_cast<cxx_string_t*>(str); } }
36.029412
114
0.726122
sezaru
9d498dd9d697224b2abb41cc0ecc1297008d2f75
167
hh
C++
sonder/src/math/math.hh
jpanikulam/sonder
ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda
[ "MIT" ]
1
2020-11-24T07:52:39.000Z
2020-11-24T07:52:39.000Z
sonder/src/math/math.hh
jpanikulam/sonder
ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda
[ "MIT" ]
null
null
null
sonder/src/math/math.hh
jpanikulam/sonder
ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda
[ "MIT" ]
null
null
null
namespace sonder { inline constexpr float int_pow(const float base, const unsigned exponent) { return (exponent == 0) ? 1 : (base * int_pow(base, exponent - 1)); } }
33.4
75
0.700599
jpanikulam
9d49e17770420af49c76de15d2add53020c2cbf1
1,209
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/neg_binomial_2_log.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/neg_binomial_2_log.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/neg_binomial_2_log.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LOG_HPP #define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LOG_HPP #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/prob/neg_binomial_2_lpmf.hpp> namespace stan { namespace math { /** * @deprecated use <code>neg_binomial_2_lpmf</code> */ template <bool propto, typename T_n, typename T_location, typename T_precision> typename return_type<T_location, T_precision>::type neg_binomial_2_log(const T_n& n, const T_location& mu, const T_precision& phi) { return neg_binomial_2_lpmf<propto, T_n, T_location, T_precision>(n, mu, phi); } /** * @deprecated use <code>neg_binomial_2_lpmf</code> */ template <typename T_n, typename T_location, typename T_precision> inline typename return_type<T_location, T_precision>::type neg_binomial_2_log(const T_n& n, const T_location& mu, const T_precision& phi) { return neg_binomial_2_lpmf<T_n, T_location, T_precision>(n, mu, phi); } } } #endif
30.225
75
0.632754
yizhang-cae
9d4d6495efd75bcb65d5d61cd9de2d7c411265e1
520
cpp
C++
wchat/userinfoformedit.cpp
CLQM/Qt_IMClient
d7fcd3a19d56ef06cfd908f5206d7d44d94d2ca6
[ "Apache-2.0" ]
null
null
null
wchat/userinfoformedit.cpp
CLQM/Qt_IMClient
d7fcd3a19d56ef06cfd908f5206d7d44d94d2ca6
[ "Apache-2.0" ]
1
2021-03-11T19:44:25.000Z
2021-03-15T15:39:06.000Z
wchat/userinfoformedit.cpp
CLQM/Qt_IMClient
d7fcd3a19d56ef06cfd908f5206d7d44d94d2ca6
[ "Apache-2.0" ]
null
null
null
#include "userinfoformedit.h" #include "ui_userinfoformedit.h" UserInfoFormEdit::UserInfoFormEdit(QWidget *parent) : QWidget(parent), ui(new Ui::UserInfoFormEdit) { ui->setupUi(this); /*使显示内容可修改*/ ui->le_name->setReadOnly(true); ui->le_sign->setReadOnly(true); ui->le_birth->setReadOnly(true); ui->le_sex->setReadOnly(true); ui->le_netAge->setReadOnly(true); } UserInfoFormEdit::~UserInfoFormEdit() { delete ui; } void UserInfoFormEdit::slotUserEditAsk() { this->show(); }
20
53
0.688462
CLQM
9d511680d40986e68f8d504f93124f9453c1c11a
1,785
cpp
C++
examples/opengl_extension_converter.cpp
Ellorion/SimpleLibrary
183cbc9d53fe09e4968497727ce65fe050e9bc77
[ "Unlicense" ]
1
2019-03-23T01:06:31.000Z
2019-03-23T01:06:31.000Z
examples/opengl_extension_converter.cpp
Ellorion/SimpleLibrary
183cbc9d53fe09e4968497727ce65fe050e9bc77
[ "Unlicense" ]
null
null
null
examples/opengl_extension_converter.cpp
Ellorion/SimpleLibrary
183cbc9d53fe09e4968497727ce65fe050e9bc77
[ "Unlicense" ]
null
null
null
#include "src/SLib.h" int main() { String s_ogl_ext = File_ReadAll(S("oglext.txt")); File file_ogl_ext = File_Open(S("extensions.h"), "wb"); Array<String> as_extension = Array_Split(&s_ogl_ext, S("\r\n"), DELIMITER_IGNORE, false); if (!as_extension.count) return 0; File_Write(&file_ogl_ext, S("#pragma once\n\n")); File_Write(&file_ogl_ext, S("#include <gl/glext.h>\n")); File_Write(&file_ogl_ext, S("#include <gl/wglext.h>\n")); File_Write(&file_ogl_ext, S("\n")); FOR_ARRAY(as_extension, it) { String *ts_name = &ARRAY_IT(as_extension, it); if (String_StartWith(ts_name, S("#"), true)) continue; File_Write(&file_ogl_ext, S("PFN")); static String ts_name_upper; String_Clear(&ts_name_upper); String_Append(&ts_name_upper, *ts_name); String_ToUpper(&ts_name_upper); File_Write(&file_ogl_ext, ts_name_upper); File_Write(&file_ogl_ext, S("PROC ")); File_Write(&file_ogl_ext, *ts_name); File_Write(&file_ogl_ext, S(" = 0;\n")); } File_Write(&file_ogl_ext, S("\nvoid\n")); File_Write(&file_ogl_ext, S("Window_InitOpenGL_Ext() {\n")); FOR_ARRAY(as_extension, it) { String *ts_name = &ARRAY_IT(as_extension, it); if (String_StartWith(ts_name, S("#"), true)) continue; File_Write(&file_ogl_ext, S("\t")); File_Write(&file_ogl_ext, *ts_name); File_Write(&file_ogl_ext, S(" = (PFN")); static String ts_name_upper; String_Clear(&ts_name_upper); String_Append(&ts_name_upper, *ts_name); String_ToUpper(&ts_name_upper); File_Write(&file_ogl_ext, ts_name_upper); File_Write(&file_ogl_ext, S("PROC)wglGetProcAddress(\"")); File_Write(&file_ogl_ext, *ts_name); File_Write(&file_ogl_ext, S("\");\n")); } File_Write(&file_ogl_ext, S("}")); File_Close(&file_ogl_ext); }
27.890625
93
0.679552
Ellorion
9d5140a80b10dc2198956f88f4c34daaf3bdba25
238
cpp
C++
AtCoder/ABC161/A/abc161_a.cpp
object-oriented-human/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
1
2022-02-21T15:43:01.000Z
2022-02-21T15:43:01.000Z
AtCoder/ABC161/A/abc161_a.cpp
foooop/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
null
null
null
AtCoder/ABC161/A/abc161_a.cpp
foooop/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define int long long signed main() { ios::sync_with_stdio(false); cin.tie(0); int x, y, z; cin >> x >> y >> z; swap(x, y); swap(x, z); cout << x << ' ' << y << ' ' << z; }
23.8
44
0.508403
object-oriented-human
9d5843720f6482c81e49d316cc64e3906bfa0583
373
hpp
C++
src/parser/types/digit_type.hpp
dondieselkopf/tmp-parser
50a9a6238bb67e6998404825572d5d7f915db841
[ "MIT" ]
null
null
null
src/parser/types/digit_type.hpp
dondieselkopf/tmp-parser
50a9a6238bb67e6998404825572d5d7f915db841
[ "MIT" ]
null
null
null
src/parser/types/digit_type.hpp
dondieselkopf/tmp-parser
50a9a6238bb67e6998404825572d5d7f915db841
[ "MIT" ]
null
null
null
/* * digit_type.hpp * * Created on: 08.11.2015 * Author: sohrmann */ #ifndef DIGIT_TYPE_HPP_ #define DIGIT_TYPE_HPP_ namespace parser { /// next character should be a digit struct digit_type { template <typename ParserType> static bool match(ParserType& parser) { return parser.consume_digit(); } }; } // namespace parser #endif /* DIGIT_TYPE_HPP_ */
15.541667
40
0.699732
dondieselkopf
9d5adf3981739ec83a3a262e48a2bfe662e00b98
65,616
cpp
C++
Blizzlike/Trinity/Scripts/Dungeons/ulduar/ulduar/boss_flame_leviathan.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Dungeons/ulduar/ulduar/boss_flame_leviathan.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Dungeons/ulduar/ulduar/boss_flame_leviathan.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Comment: there is missing code on triggers, * brann bronzebeard needs correct gossip info. * requires more work involving area triggers. * if reached brann speaks through his radio.. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "Cell.h" #include "CellImpl.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CombatAI.h" #include "PassiveAI.h" #include "ObjectMgr.h" #include "SpellInfo.h" #include "SpellScript.h" #include "Vehicle.h" #include "VehicleDefines.h" #include "ulduar.h" #include "Spell.h" enum Spells { SPELL_PURSUED = 62374, SPELL_GATHERING_SPEED = 62375, SPELL_BATTERING_RAM = 62376, SPELL_FLAME_VENTS = 62396, SPELL_MISSILE_BARRAGE = 62400, SPELL_SYSTEMS_SHUTDOWN = 62475, SPELL_OVERLOAD_CIRCUIT = 62399, SPELL_START_THE_ENGINE = 62472, SPELL_SEARING_FLAME = 62402, SPELL_BLAZE = 62292, SPELL_TAR_PASSIVE = 62288, SPELL_SMOKE_TRAIL = 63575, SPELL_ELECTROSHOCK = 62522, SPELL_NAPALM = 63666, SPELL_INVIS_AND_STEALTH_DETECT = 18950, // Passive //TOWER Additional SPELLS SPELL_THORIM_S_HAMMER = 62911, // Tower of Storms SPELL_MIMIRON_S_INFERNO = 62909, // Tower of Flames SPELL_HODIR_S_FURY = 62533, // Tower of Frost SPELL_FREYA_S_WARD = 62906, // Tower of Nature SPELL_FREYA_SUMMONS = 62947, // Tower of Nature //TOWER ap & health spells SPELL_BUFF_TOWER_OF_STORMS = 65076, SPELL_BUFF_TOWER_OF_FLAMES = 65075, SPELL_BUFF_TOWER_OF_FR0ST = 65077, SPELL_BUFF_TOWER_OF_LIFE = 64482, //Additional Spells SPELL_LASH = 65062, SPELL_FREYA_S_WARD_EFFECT_1 = 62947, SPELL_FREYA_S_WARD_EFFECT_2 = 62907, SPELL_AUTO_REPAIR = 62705, AURA_DUMMY_BLUE = 63294, AURA_DUMMY_GREEN = 63295, AURA_DUMMY_YELLOW = 63292, SPELL_LIQUID_PYRITE = 62494, SPELL_DUSTY_EXPLOSION = 63360, SPELL_DUST_CLOUD_IMPACT = 54740, AURA_STEALTH_DETECTION = 18950, SPELL_RIDE_VEHICLE = 46598, }; enum Creatures { NPC_SEAT = 33114, NPC_MECHANOLIFT = 33214, NPC_LIQUID = 33189, NPC_CONTAINER = 33218, NPC_THORIM_BEACON = 33365, NPC_MIMIRON_BEACON = 33370, NPC_HODIR_BEACON = 33212, NPC_FREYA_BEACON = 33367, NPC_THORIM_TARGET_BEACON = 33364, NPC_MIMIRON_TARGET_BEACON = 33369, NPC_HODIR_TARGET_BEACON = 33108, NPC_FREYA_TARGET_BEACON = 33366, NPC_LOREKEEPER = 33686, // Hard mode starter NPC_BRANZ_BRONZBEARD = 33579, NPC_DELORAH = 33701, NPC_ULDUAR_GAUNTLET_GENERATOR = 33571, // Trigger tied to towers }; enum Towers { GO_TOWER_OF_STORMS = 194377, GO_TOWER_OF_FLAMES = 194371, GO_TOWER_OF_FROST = 194370, GO_TOWER_OF_LIFE = 194375, }; enum Events { EVENT_PURSUE = 1, EVENT_MISSILE = 2, EVENT_VENT = 3, EVENT_SPEED = 4, EVENT_SUMMON = 5, EVENT_SHUTDOWN = 6, EVENT_REPAIR = 7, EVENT_THORIM_S_HAMMER = 8, // Tower of Storms EVENT_MIMIRON_S_INFERNO = 9, // Tower of Flames EVENT_HODIR_S_FURY = 10, // Tower of Frost EVENT_FREYA_S_WARD = 11, // Tower of Nature }; enum Seats { SEAT_PLAYER = 0, SEAT_TURRET = 1, SEAT_DEVICE = 2, SEAT_CANNON = 7, }; enum Vehicles { VEHICLE_SIEGE = 33060, VEHICLE_CHOPPER = 33062, VEHICLE_DEMOLISHER = 33109, }; #define EMOTE_PURSUE "Flame Leviathan pursues $N." #define EMOTE_OVERLOAD "Flame Leviathan's circuits overloaded." #define EMOTE_REPAIR "Automatic repair sequence initiated." #define DATA_SHUTOUT 29112912 // 2911, 2912 are achievement IDs #define DATA_ORBIT_ACHIEVEMENTS 1 #define VEHICLE_SPAWNS 5 #define FREYA_SPAWNS 4 enum Yells { SAY_AGGRO = -1603060, SAY_SLAY = -1603061, SAY_DEATH = -1603062, SAY_TARGET_1 = -1603063, SAY_TARGET_2 = -1603064, SAY_TARGET_3 = -1603065, SAY_HARDMODE = -1603066, SAY_TOWER_NONE = -1603067, SAY_TOWER_FROST = -1603068, SAY_TOWER_FLAME = -1603069, SAY_TOWER_NATURE = -1603070, SAY_TOWER_STORM = -1603071, SAY_PLAYER_RIDING = -1603072, SAY_OVERLOAD_1 = -1603073, SAY_OVERLOAD_2 = -1603074, SAY_OVERLOAD_3 = -1603075, }; enum MiscellanousData { // Other Actions are in Ulduar.h ACTION_START_HARD_MODE = 5, ACTION_SPAWN_VEHICLES = 6, // Amount of seats depending on Raid mode TWO_SEATS = 2, FOUR_SEATS = 4, }; Position const Center[]= { {354.8771f, -12.90240f, 409.803650f, 0.0f}, }; Position const InfernoStart[]= { {390.93f, -13.91f, 409.81f, 0.0f}, }; Position const PosSiege[VEHICLE_SPAWNS] = { {-814.59f, -64.54f, 429.92f, 5.969f}, {-784.37f, -33.31f, 429.92f, 5.096f}, {-808.99f, -52.10f, 429.92f, 5.668f}, {-798.59f, -44.00f, 429.92f, 5.663f}, {-812.83f, -77.71f, 429.92f, 0.046f}, }; Position const PosChopper[VEHICLE_SPAWNS] = { {-717.83f, -106.56f, 430.02f, 0.122f}, {-717.83f, -114.23f, 430.44f, 0.122f}, {-717.83f, -109.70f, 430.22f, 0.122f}, {-718.45f, -118.24f, 430.26f, 0.052f}, {-718.45f, -123.58f, 430.41f, 0.085f}, }; Position const PosDemolisher[VEHICLE_SPAWNS] = { {-724.12f, -176.64f, 430.03f, 2.543f}, {-766.70f, -225.03f, 430.50f, 1.710f}, {-729.54f, -186.26f, 430.12f, 1.902f}, {-756.01f, -219.23f, 430.50f, 2.369f}, {-798.01f, -227.24f, 429.84f, 1.446f}, }; Position const FreyaBeacons[FREYA_SPAWNS] = { {377.02f, -119.10f, 409.81f, 0.0f}, {185.62f, -119.10f, 409.81f, 0.0f}, {377.02f, 54.78f, 409.81f, 0.0f}, {185.62f, 54.78f, 409.81f, 0.0f}, }; class boss_flame_leviathan : public CreatureScript { public: boss_flame_leviathan() : CreatureScript("boss_flame_leviathan") { } struct boss_flame_leviathanAI : public BossAI { boss_flame_leviathanAI(Creature* creature) : BossAI(creature, BOSS_LEVIATHAN), vehicle(creature->GetVehicleKit()) { } void InitializeAI() { ASSERT(vehicle); if (!me->isDead()) Reset(); ActiveTowersCount = 4; Shutdown = 0; ActiveTowers = false; towerOfStorms = false; towerOfLife = false; towerOfFlames = false; towerOfFrost = false; Shutout = true; Unbroken = true; DoCast(SPELL_INVIS_AND_STEALTH_DETECT); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED); me->SetReactState(REACT_PASSIVE); } Vehicle* vehicle; uint8 ActiveTowersCount; uint8 Shutdown; bool ActiveTowers; bool towerOfStorms; bool towerOfLife; bool towerOfFlames; bool towerOfFrost; bool Shutout; bool Unbroken; void Reset() { _Reset(); //resets shutdown counter to 0. 2 or 4 depending on raid mode Shutdown = 0; _pursueTarget = 0; me->SetReactState(REACT_DEFENSIVE); } void EnterCombat(Unit* /*who*/) { _EnterCombat(); me->SetReactState(REACT_PASSIVE); events.ScheduleEvent(EVENT_PURSUE, 1); events.ScheduleEvent(EVENT_MISSILE, urand(1500, 4*IN_MILLISECONDS)); events.ScheduleEvent(EVENT_VENT, 20*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SHUTDOWN, 150*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SPEED, 15*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SUMMON, 1*IN_MILLISECONDS); ActiveTower(); //void ActiveTower } void ActiveTower() { if (ActiveTowers) { if (towerOfStorms) { me->AddAura(SPELL_BUFF_TOWER_OF_STORMS, me); events.ScheduleEvent(EVENT_THORIM_S_HAMMER, 35*IN_MILLISECONDS); } if (towerOfFlames) { me->AddAura(SPELL_BUFF_TOWER_OF_FLAMES, me); events.ScheduleEvent(EVENT_MIMIRON_S_INFERNO, 70*IN_MILLISECONDS); } if (towerOfFrost) { me->AddAura(SPELL_BUFF_TOWER_OF_FR0ST, me); events.ScheduleEvent(EVENT_HODIR_S_FURY, 105*IN_MILLISECONDS); } if (towerOfLife) { me->AddAura(SPELL_BUFF_TOWER_OF_LIFE, me); events.ScheduleEvent(EVENT_FREYA_S_WARD, 140*IN_MILLISECONDS); } if (!towerOfLife && !towerOfFrost && !towerOfFlames && !towerOfStorms) DoScriptText(SAY_TOWER_NONE, me); else DoScriptText(SAY_HARDMODE, me); } else DoScriptText(SAY_AGGRO, me); } void JustDied(Unit* /*killer*/) { _JustDied(); // Set Field Flags 67108928 = 64 | 67108864 = UNIT_FLAG_UNK_6 | UNIT_FLAG_SKINNABLE // Set DynFlags 12 // Set NPCFlags 0 DoScriptText(SAY_DEATH, me); } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) { if (spell->Id == SPELL_START_THE_ENGINE) vehicle->InstallAllAccessories(false); if (spell->Id == SPELL_ELECTROSHOCK) me->InterruptSpell(CURRENT_CHANNELED_SPELL); if (spell->Id == SPELL_OVERLOAD_CIRCUIT) ++Shutdown; } uint32 GetData(uint32 type) { switch (type) { case DATA_SHUTOUT: return Shutout ? 1 : 0; case DATA_UNBROKEN: return Unbroken ? 1 : 0; case DATA_ORBIT_ACHIEVEMENTS: if (ActiveTowers) // Only on HardMode return ActiveTowersCount; default: break; } return 0; } void SetData(uint32 id, uint32 data) { if (id == DATA_UNBROKEN) Unbroken = data ? true : false; } void UpdateAI(uint32 const diff) { if (!UpdateVictim() || !CheckInRoom()) return; events.Update(diff); if (Shutdown == RAID_MODE(TWO_SEATS, FOUR_SEATS)) { Shutdown = 0; events.ScheduleEvent(EVENT_SHUTDOWN, 4000); me->RemoveAurasDueToSpell(SPELL_OVERLOAD_CIRCUIT); me->InterruptNonMeleeSpells(true); return; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_PURSUE: DoScriptText(RAND(SAY_TARGET_1, SAY_TARGET_2, SAY_TARGET_3), me); DoCast(SPELL_PURSUED); // Will select target in spellscript events.ScheduleEvent(EVENT_PURSUE, 35*IN_MILLISECONDS); break; case EVENT_MISSILE: DoCast(me, SPELL_MISSILE_BARRAGE, true); events.ScheduleEvent(EVENT_MISSILE, 2*IN_MILLISECONDS); break; case EVENT_VENT: DoCastAOE(SPELL_FLAME_VENTS); events.ScheduleEvent(EVENT_VENT, 20*IN_MILLISECONDS); break; case EVENT_SPEED: DoCastAOE(SPELL_GATHERING_SPEED); events.ScheduleEvent(EVENT_SPEED, 15*IN_MILLISECONDS); break; case EVENT_SUMMON: if (summons.size() < 15) if (Creature* lift = DoSummonFlyer(NPC_MECHANOLIFT, me, 30.0f, 50.0f, 0)) lift->GetMotionMaster()->MoveRandom(100); events.ScheduleEvent(EVENT_SUMMON, 2*IN_MILLISECONDS); break; case EVENT_SHUTDOWN: DoScriptText(RAND(SAY_OVERLOAD_1, SAY_OVERLOAD_2, SAY_OVERLOAD_3), me); me->MonsterTextEmote(EMOTE_OVERLOAD, 0, true); me->CastSpell(me, SPELL_SYSTEMS_SHUTDOWN, true); if (Shutout) Shutout = false; events.ScheduleEvent(EVENT_REPAIR, 4000); events.DelayEvents(20 * IN_MILLISECONDS, 0); break; case EVENT_REPAIR: me->MonsterTextEmote(EMOTE_REPAIR, 0, true); me->ClearUnitState(UNIT_STATE_STUNNED | UNIT_STATE_ROOT); events.ScheduleEvent(EVENT_SHUTDOWN, 150*IN_MILLISECONDS); events.CancelEvent(EVENT_REPAIR); break; case EVENT_THORIM_S_HAMMER: // Tower of Storms for (uint8 i = 0; i < 7; ++i) { if (Creature* thorim = DoSummon(NPC_THORIM_BEACON, me, float(urand(20, 60)), 20000, TEMPSUMMON_TIMED_DESPAWN)) thorim->GetMotionMaster()->MoveRandom(100); } DoScriptText(SAY_TOWER_STORM, me); events.CancelEvent(EVENT_THORIM_S_HAMMER); break; case EVENT_MIMIRON_S_INFERNO: // Tower of Flames me->SummonCreature(NPC_MIMIRON_BEACON, InfernoStart->GetPositionX(), InfernoStart->GetPositionY(), InfernoStart->GetPositionZ()); DoScriptText(SAY_TOWER_FLAME, me); events.CancelEvent(EVENT_MIMIRON_S_INFERNO); break; case EVENT_HODIR_S_FURY: // Tower of Frost for (uint8 i = 0; i < 7; ++i) { if (Creature* hodir = DoSummon(NPC_HODIR_BEACON, me, 50, 0)) hodir->GetMotionMaster()->MoveRandom(100); } DoScriptText(SAY_TOWER_FROST, me); events.CancelEvent(EVENT_HODIR_S_FURY); break; case EVENT_FREYA_S_WARD: // Tower of Nature DoScriptText(SAY_TOWER_NATURE, me); for (int32 i = 0; i < 4; ++i) me->SummonCreature(NPC_FREYA_BEACON, FreyaBeacons[i]); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_FREYA_S_WARD); events.CancelEvent(EVENT_FREYA_S_WARD); break; } } DoBatteringRamIfReady(); } void SpellHitTarget(Unit* target, SpellInfo const* spell) { if (spell->Id == SPELL_PURSUED) _pursueTarget = target->GetGUID(); } void DoAction(int32 const action) { if (action && action <= 4) // Tower destruction, debuff leviathan loot and reduce active tower count { if (me->HasLootMode(LOOT_MODE_DEFAULT | LOOT_MODE_HARD_MODE_1 | LOOT_MODE_HARD_MODE_2 | LOOT_MODE_HARD_MODE_3 | LOOT_MODE_HARD_MODE_4) && ActiveTowersCount == 4) { me->RemoveLootMode(LOOT_MODE_HARD_MODE_4); --ActiveTowersCount; } if (me->HasLootMode(LOOT_MODE_DEFAULT | LOOT_MODE_HARD_MODE_1 | LOOT_MODE_HARD_MODE_2 | LOOT_MODE_HARD_MODE_3) && ActiveTowersCount == 3) { me->RemoveLootMode(LOOT_MODE_HARD_MODE_3); --ActiveTowersCount; } if (me->HasLootMode(LOOT_MODE_DEFAULT | LOOT_MODE_HARD_MODE_1 | LOOT_MODE_HARD_MODE_2) && ActiveTowersCount == 2) { me->RemoveLootMode(LOOT_MODE_HARD_MODE_2); --ActiveTowersCount; } if (me->HasLootMode(LOOT_MODE_DEFAULT | LOOT_MODE_HARD_MODE_1) && ActiveTowersCount == 1) { me->RemoveLootMode(LOOT_MODE_HARD_MODE_1); --ActiveTowersCount; } } switch (action) { case ACTION_TOWER_OF_STORM_DESTROYED: towerOfStorms = false; break; case ACTION_TOWER_OF_FROST_DESTROYED: towerOfFrost = false; break; case ACTION_TOWER_OF_FLAMES_DESTROYED: towerOfFlames = false; break; case ACTION_TOWER_OF_LIFE_DESTROYED: towerOfLife = false; break; case ACTION_START_HARD_MODE: // Activate hard-mode enable all towers, apply buffs on leviathan ActiveTowers = true; towerOfStorms = true; towerOfLife = true; towerOfFlames = true; towerOfFrost = true; me->SetLootMode(LOOT_MODE_DEFAULT | LOOT_MODE_HARD_MODE_1 | LOOT_MODE_HARD_MODE_2 | LOOT_MODE_HARD_MODE_3 | LOOT_MODE_HARD_MODE_4); break; case ACTION_MOVE_TO_CENTER_POSITION: // Triggered by 2 Collossus near door if (!me->isDead()) { me->SetHomePosition(Center->GetPositionX(), Center->GetPositionY(), Center->GetPositionZ(), 0); me->GetMotionMaster()->MoveCharge(Center->GetPositionX(), Center->GetPositionY(), Center->GetPositionZ()); //position center me->SetReactState(REACT_AGGRESSIVE); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED); return; } break; default: break; } } private: //! Copypasta from DoSpellAttackIfReady, only difference is the target - it cannot be selected trough getVictim this way - //! I also removed the spellInfo check void DoBatteringRamIfReady() { if (me->isAttackReady()) { Unit* target = ObjectAccessor::GetUnit(*me, _pursueTarget); if (me->IsWithinCombatRange(target, 30.0f)) { DoCast(target, SPELL_BATTERING_RAM); me->resetAttackTimer(); } } } uint64 _pursueTarget; }; CreatureAI* GetAI(Creature* creature) const { return GetUlduarAI<boss_flame_leviathanAI>(creature); } }; class boss_flame_leviathan_seat : public CreatureScript { public: boss_flame_leviathan_seat() : CreatureScript("boss_flame_leviathan_seat") { } struct boss_flame_leviathan_seatAI : public ScriptedAI { boss_flame_leviathan_seatAI(Creature* creature) : ScriptedAI(creature), vehicle(creature->GetVehicleKit()) { ASSERT(vehicle); me->SetReactState(REACT_PASSIVE); me->SetDisplayId(me->GetCreatureTemplate()->Modelid2); instance = creature->GetInstanceScript(); } InstanceScript* instance; Vehicle* vehicle; void PassengerBoarded(Unit* who, int8 seatId, bool apply) { if (!me->GetVehicle()) return; if (seatId == SEAT_PLAYER) { if (!apply) return; else DoScriptText(SAY_PLAYER_RIDING, me); if (Creature* turret = me->GetVehicleKit()->GetPassenger(SEAT_TURRET)->ToCreature()) { turret->setFaction(me->GetVehicleBase()->getFaction()); turret->SetUInt32Value(UNIT_FIELD_FLAGS, 0); // unselectable turret->AI()->AttackStart(who); } if (Creature* device = me->GetVehicleKit()->GetPassenger(SEAT_DEVICE)->ToCreature()) { device->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK); device->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } else if (seatId == SEAT_TURRET) { if (apply) return; if (Unit* device = vehicle->GetPassenger(SEAT_DEVICE)) { device->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK); device->SetUInt32Value(UNIT_FIELD_FLAGS, 0); // unselectable } } } }; CreatureAI* GetAI(Creature* creature) const { return new boss_flame_leviathan_seatAI(creature); } }; class boss_flame_leviathan_defense_cannon : public CreatureScript { public: boss_flame_leviathan_defense_cannon() : CreatureScript("boss_flame_leviathan_defense_cannon") { } struct boss_flame_leviathan_defense_cannonAI : public ScriptedAI { boss_flame_leviathan_defense_cannonAI(Creature* creature) : ScriptedAI(creature) { } uint32 NapalmTimer; void Reset() { NapalmTimer = 5*IN_MILLISECONDS; DoCast(me, AURA_STEALTH_DETECTION); } void UpdateAI(uint32 const diff) { if (!UpdateVictim()) return; if (NapalmTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) if (CanAIAttack(target)) DoCast(target, SPELL_NAPALM, true); NapalmTimer = 5000; } else NapalmTimer -= diff; } bool CanAIAttack(Unit const* who) const { if (who->GetTypeId() != TYPEID_PLAYER || !who->GetVehicle() || who->GetVehicleBase()->GetEntry() == NPC_SEAT) return false; return true; } }; CreatureAI* GetAI(Creature* creature) const { return new boss_flame_leviathan_defense_cannonAI(creature); } }; class boss_flame_leviathan_defense_turret : public CreatureScript { public: boss_flame_leviathan_defense_turret() : CreatureScript("boss_flame_leviathan_defense_turret") { } struct boss_flame_leviathan_defense_turretAI : public TurretAI { boss_flame_leviathan_defense_turretAI(Creature* creature) : TurretAI(creature) {} void DamageTaken(Unit* who, uint32 &damage) { if (!CanAIAttack(who)) damage = 0; } bool CanAIAttack(Unit const* who) const { if (who->GetTypeId() != TYPEID_PLAYER || !who->GetVehicle() || who->GetVehicleBase()->GetEntry() != NPC_SEAT) return false; return true; } }; CreatureAI* GetAI(Creature* creature) const { return new boss_flame_leviathan_defense_turretAI(creature); } }; class boss_flame_leviathan_overload_device : public CreatureScript { public: boss_flame_leviathan_overload_device() : CreatureScript("boss_flame_leviathan_overload_device") { } struct boss_flame_leviathan_overload_deviceAI : public PassiveAI { boss_flame_leviathan_overload_deviceAI(Creature* creature) : PassiveAI(creature) { } void OnSpellClick(Unit* /*clicker*/) { if (me->GetVehicle()) { me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Unit* player = me->GetVehicle()->GetPassenger(SEAT_PLAYER)) { me->GetVehicleBase()->CastSpell(player, SPELL_SMOKE_TRAIL, true); player->GetMotionMaster()->MoveKnockbackFrom(me->GetVehicleBase()->GetPositionX(), me->GetVehicleBase()->GetPositionY(), 30, 30); player->ExitVehicle(); } } } }; CreatureAI* GetAI(Creature* creature) const { return new boss_flame_leviathan_overload_deviceAI(creature); } }; class boss_flame_leviathan_safety_container : public CreatureScript { public: boss_flame_leviathan_safety_container() : CreatureScript("boss_flame_leviathan_safety_container") { } struct boss_flame_leviathan_safety_containerAI : public PassiveAI { boss_flame_leviathan_safety_containerAI(Creature* creature) : PassiveAI(creature) { } void JustDied(Unit* /*killer*/) { float x, y, z; me->GetPosition(x, y, z); z = me->GetMap()->GetHeight(me->GetPhaseMask(), x, y, z); me->GetMotionMaster()->MovePoint(0, x, y, z); me->SetPosition(x, y, z, 0); } void UpdateAI(uint32 const /*diff*/) { } }; CreatureAI* GetAI(Creature* creature) const { return new boss_flame_leviathan_safety_containerAI(creature); } }; class npc_mechanolift : public CreatureScript { public: npc_mechanolift() : CreatureScript("npc_mechanolift") { } struct npc_mechanoliftAI : public PassiveAI { npc_mechanoliftAI(Creature* creature) : PassiveAI(creature) { ASSERT(me->GetVehicleKit()); } uint32 MoveTimer; void Reset() { MoveTimer = 0; me->GetMotionMaster()->MoveRandom(50); } void JustDied(Unit* /*killer*/) { me->GetMotionMaster()->MoveTargetedHome(); DoCast(SPELL_DUSTY_EXPLOSION); Creature* liquid = DoSummon(NPC_LIQUID, me, 0); if (liquid) { liquid->CastSpell(liquid, SPELL_LIQUID_PYRITE, true); liquid->CastSpell(liquid, SPELL_DUST_CLOUD_IMPACT, true); } } void MovementInform(uint32 type, uint32 id) { if (type == POINT_MOTION_TYPE && id == 1) if (Creature* container = me->FindNearestCreature(NPC_CONTAINER, 5, true)) container->EnterVehicle(me); } void UpdateAI(const uint32 diff) { if (MoveTimer <= diff) { if (me->GetVehicleKit()->HasEmptySeat(-1)) { Creature* container = me->FindNearestCreature(NPC_CONTAINER, 50, true); if (container && !container->GetVehicle()) me->GetMotionMaster()->MovePoint(1, container->GetPositionX(), container->GetPositionY(), container->GetPositionZ()); } MoveTimer = 30000; //check next 30 seconds } else MoveTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_mechanoliftAI(creature); } }; class npc_pool_of_tar : public CreatureScript { public: npc_pool_of_tar() : CreatureScript("npc_pool_of_tar") { } struct npc_pool_of_tarAI : public ScriptedAI { npc_pool_of_tarAI(Creature* creature) : ScriptedAI(creature) { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); me->CastSpell(me, SPELL_TAR_PASSIVE, true); } void DamageTaken(Unit* /*who*/, uint32& damage) { damage = 0; } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) { if (spell->SchoolMask & SPELL_SCHOOL_MASK_FIRE && !me->HasAura(SPELL_BLAZE)) me->CastSpell(me, SPELL_BLAZE, true); } void UpdateAI(uint32 const /*diff*/) {} }; CreatureAI* GetAI(Creature* creature) const { return new npc_pool_of_tarAI(creature); } }; class npc_colossus : public CreatureScript { public: npc_colossus() : CreatureScript("npc_colossus") { } struct npc_colossusAI : public ScriptedAI { npc_colossusAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; void JustDied(Unit* /*killer*/) { if (me->GetHomePosition().IsInDist(Center, 50.f)) instance->SetData(DATA_COLOSSUS, instance->GetData(DATA_COLOSSUS)+1); } void UpdateAI(uint32 const /*diff*/) { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_colossusAI(creature); } }; class npc_thorims_hammer : public CreatureScript { public: npc_thorims_hammer() : CreatureScript("npc_thorims_hammer") { } struct npc_thorims_hammerAI : public ScriptedAI { npc_thorims_hammerAI(Creature* creature) : ScriptedAI(creature) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->CastSpell(me, AURA_DUMMY_BLUE, true); } void MoveInLineOfSight(Unit* who) { if (who->GetTypeId() == TYPEID_PLAYER && who->IsVehicle() && me->IsInRange(who, 0, 10, false)) { if (Creature* trigger = DoSummonFlyer(NPC_THORIM_TARGET_BEACON, me, 20, 0, 1000, TEMPSUMMON_TIMED_DESPAWN)) trigger->CastSpell(who, SPELL_THORIM_S_HAMMER, true); } } void UpdateAI(uint32 const /*diff*/) { if (!me->HasAura(AURA_DUMMY_BLUE)) me->CastSpell(me, AURA_DUMMY_BLUE, true); UpdateVictim(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_thorims_hammerAI(creature); } }; class npc_mimirons_inferno : public CreatureScript { public: npc_mimirons_inferno() : CreatureScript("npc_mimirons_inferno") { } CreatureAI* GetAI(Creature* creature) const { return new npc_mimirons_infernoAI(creature); } struct npc_mimirons_infernoAI : public npc_escortAI { npc_mimirons_infernoAI(Creature* creature) : npc_escortAI(creature) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->CastSpell(me, AURA_DUMMY_YELLOW, true); me->SetReactState(REACT_PASSIVE); } void WaypointReached(uint32 /*waypointId*/) { } void Reset() { infernoTimer = 2000; } uint32 infernoTimer; void UpdateAI(uint32 const diff) { npc_escortAI::UpdateAI(diff); if (!HasEscortState(STATE_ESCORT_ESCORTING)) Start(false, true, 0, NULL, false, true); else { if (infernoTimer <= diff) { if (Creature* trigger = DoSummonFlyer(NPC_MIMIRON_TARGET_BEACON, me, 20, 0, 1000, TEMPSUMMON_TIMED_DESPAWN)) { trigger->CastSpell(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), SPELL_MIMIRON_S_INFERNO, true); infernoTimer = 2000; } } else infernoTimer -= diff; if (!me->HasAura(AURA_DUMMY_YELLOW)) me->CastSpell(me, AURA_DUMMY_YELLOW, true); } } }; }; class npc_hodirs_fury : public CreatureScript { public: npc_hodirs_fury() : CreatureScript("npc_hodirs_fury") { } struct npc_hodirs_furyAI : public ScriptedAI { npc_hodirs_furyAI(Creature* creature) : ScriptedAI(creature) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->CastSpell(me, AURA_DUMMY_GREEN, true); } void MoveInLineOfSight(Unit* who) { if (who->GetTypeId() == TYPEID_PLAYER && who->IsVehicle() && me->IsInRange(who, 0, 5, false)) { if (Creature* trigger = DoSummonFlyer(NPC_HODIR_TARGET_BEACON, me, 20, 0, 1000, TEMPSUMMON_TIMED_DESPAWN)) trigger->CastSpell(who, SPELL_HODIR_S_FURY, true); } } void UpdateAI(uint32 const /*diff*/) { if (!me->HasAura(AURA_DUMMY_GREEN)) me->CastSpell(me, AURA_DUMMY_GREEN, true); UpdateVictim(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_hodirs_furyAI(creature); } }; class npc_freyas_ward : public CreatureScript { public: npc_freyas_ward() : CreatureScript("npc_freyas_ward") { } struct npc_freyas_wardAI : public ScriptedAI { npc_freyas_wardAI(Creature* creature) : ScriptedAI(creature) { me->CastSpell(me, AURA_DUMMY_GREEN, true); } uint32 summonTimer; void Reset() { summonTimer = 5000; } void UpdateAI(uint32 const diff) { if (summonTimer <= diff) { DoCast(SPELL_FREYA_S_WARD_EFFECT_1); DoCast(SPELL_FREYA_S_WARD_EFFECT_2); summonTimer = 20000; } else summonTimer -= diff; if (!me->HasAura(AURA_DUMMY_GREEN)) me->CastSpell(me, AURA_DUMMY_GREEN, true); UpdateVictim(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_freyas_wardAI(creature); } }; class npc_freya_ward_summon : public CreatureScript { public: npc_freya_ward_summon() : CreatureScript("npc_freya_ward_summon") { } struct npc_freya_ward_summonAI : public ScriptedAI { npc_freya_ward_summonAI(Creature* creature) : ScriptedAI(creature) { creature->GetMotionMaster()->MoveRandom(100); } uint32 lashTimer; void Reset() { lashTimer = 5000; } void UpdateAI(uint32 const diff) { if (!UpdateVictim()) return; if (lashTimer <= diff) { DoCast(SPELL_LASH); lashTimer = 20000; } else lashTimer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_freya_ward_summonAI(creature); } }; //npc lore keeper #define GOSSIP_ITEM_1 "Activate secondary defensive systems" #define GOSSIP_ITEM_2 "Confirmed" class npc_lorekeeper : public CreatureScript { public: npc_lorekeeper() : CreatureScript("npc_lorekeeper") { } struct npc_lorekeeperAI : public ScriptedAI { npc_lorekeeperAI(Creature* creature) : ScriptedAI(creature) { } void DoAction(int32 const action) { // Start encounter if (action == ACTION_SPAWN_VEHICLES) { for (int32 i = 0; i < RAID_MODE(2, 5); ++i) DoSummon(VEHICLE_SIEGE, PosSiege[i], 3000, TEMPSUMMON_CORPSE_TIMED_DESPAWN); for (int32 i = 0; i < RAID_MODE(2, 5); ++i) DoSummon(VEHICLE_CHOPPER, PosChopper[i], 3000, TEMPSUMMON_CORPSE_TIMED_DESPAWN); for (int32 i = 0; i < RAID_MODE(2, 5); ++i) DoSummon(VEHICLE_DEMOLISHER, PosDemolisher[i], 3000, TEMPSUMMON_CORPSE_TIMED_DESPAWN); return; } } }; bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); InstanceScript* instance = creature->GetInstanceScript(); if (!instance) return true; switch (action) { case GOSSIP_ACTION_INFO_DEF+1: if (player) { player->PrepareGossipMenu(creature); instance->instance->LoadGrid(364, -16); //make sure leviathan is loaded player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); } break; case GOSSIP_ACTION_INFO_DEF+2: if (player) player->CLOSE_GOSSIP_MENU(); if (Creature* leviathan = instance->instance->GetCreature(instance->GetData64(BOSS_LEVIATHAN))) { leviathan->AI()->DoAction(ACTION_START_HARD_MODE); creature->SetVisible(false); creature->AI()->DoAction(ACTION_SPAWN_VEHICLES); // spawn the vehicles if (Creature* Delorah = creature->FindNearestCreature(NPC_DELORAH, 1000, true)) { if (Creature* Branz = creature->FindNearestCreature(NPC_BRANZ_BRONZBEARD, 1000, true)) { Delorah->GetMotionMaster()->MovePoint(0, Branz->GetPositionX()-4, Branz->GetPositionY(), Branz->GetPositionZ()); //TODO DoScriptText(xxxx, Delorah, Branz); when reached at branz } } } break; } return true; } bool OnGossipHello(Player* player, Creature* creature) { InstanceScript* instance = creature->GetInstanceScript(); if (instance && instance->GetData(BOSS_LEVIATHAN) !=DONE && player) { player->PrepareGossipMenu(creature); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); } return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_lorekeeperAI(creature); } }; //enable hardmode ////npc_brann_bronzebeard this requires more work involving area triggers. if reached this guy speaks through his radio.. //#define GOSSIP_ITEM_1 "xxxxx" //#define GOSSIP_ITEM_2 "xxxxx" // /* class npc_brann_bronzebeard : public CreatureScript { public: npc_brann_bronzebeard() : CreatureScript("npc_brann_bronzebeard") { } //bool OnGossipSelect(Player* player, Creature* creature, uint32 sender, uint32 action) //{ // player->PlayerTalkClass->ClearMenus(); // switch (action) // { // case GOSSIP_ACTION_INFO_DEF+1: // if (player) // { // player->PrepareGossipMenu(creature); // // player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); // player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); // } // break; // case GOSSIP_ACTION_INFO_DEF+2: // if (player) // player->CLOSE_GOSSIP_MENU(); // if (Creature* Lorekeeper = creature->FindNearestCreature(NPC_LOREKEEPER, 1000, true)) //lore keeper of lorgannon // Lorekeeper->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); // break; // } // return true; //} //bool OnGossipHello(Player* player, Creature* creature) //{ // InstanceScript* instance = creature->GetInstanceScript(); // if (instance && instance->GetData(BOSS_LEVIATHAN) !=DONE) // { // player->PrepareGossipMenu(creature); // // player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); // player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); // } // return true; //} // } */ class go_ulduar_tower : public GameObjectScript { public: go_ulduar_tower() : GameObjectScript("go_ulduar_tower") { } void OnDestroyed(GameObject* go, Player* /*player*/) { InstanceScript* instance = go->GetInstanceScript(); if (!instance) return; switch (go->GetEntry()) { case GO_TOWER_OF_STORMS: instance->ProcessEvent(go, EVENT_TOWER_OF_STORM_DESTROYED); break; case GO_TOWER_OF_FLAMES: instance->ProcessEvent(go, EVENT_TOWER_OF_FLAMES_DESTROYED); break; case GO_TOWER_OF_FROST: instance->ProcessEvent(go, EVENT_TOWER_OF_FROST_DESTROYED); break; case GO_TOWER_OF_LIFE: instance->ProcessEvent(go, EVENT_TOWER_OF_LIFE_DESTROYED); break; } Creature* trigger = go->FindNearestCreature(NPC_ULDUAR_GAUNTLET_GENERATOR, 15.0f, true); if (trigger) trigger->DisappearAndDie(); } }; class achievement_three_car_garage_demolisher : public AchievementCriteriaScript { public: achievement_three_car_garage_demolisher() : AchievementCriteriaScript("achievement_three_car_garage_demolisher") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == VEHICLE_DEMOLISHER) return true; } return false; } }; class achievement_three_car_garage_chopper : public AchievementCriteriaScript { public: achievement_three_car_garage_chopper() : AchievementCriteriaScript("achievement_three_car_garage_chopper") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == VEHICLE_CHOPPER) return true; } return false; } }; class achievement_three_car_garage_siege : public AchievementCriteriaScript { public: achievement_three_car_garage_siege() : AchievementCriteriaScript("achievement_three_car_garage_siege") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == VEHICLE_SIEGE) return true; } return false; } }; class achievement_shutout : public AchievementCriteriaScript { public: achievement_shutout() : AchievementCriteriaScript("achievement_shutout") { } bool OnCheck(Player* /*source*/, Unit* target) { if (target) if (Creature* leviathan = target->ToCreature()) if (leviathan->AI()->GetData(DATA_SHUTOUT)) return true; return false; } }; class achievement_unbroken : public AchievementCriteriaScript { public: achievement_unbroken() : AchievementCriteriaScript("achievement_unbroken") { } bool OnCheck(Player* /*source*/, Unit* target) { if (target) if (InstanceScript* instance = target->GetInstanceScript()) return instance->GetData(DATA_UNBROKEN); return false; } }; class achievement_orbital_bombardment : public AchievementCriteriaScript { public: achievement_orbital_bombardment() : AchievementCriteriaScript("achievement_orbital_bombardment") { } bool OnCheck(Player* /*source*/, Unit* target) { if (!target) return false; if (Creature* Leviathan = target->ToCreature()) if (Leviathan->AI()->GetData(DATA_ORBIT_ACHIEVEMENTS) >= 1) return true; return false; } }; class achievement_orbital_devastation : public AchievementCriteriaScript { public: achievement_orbital_devastation() : AchievementCriteriaScript("achievement_orbital_devastation") { } bool OnCheck(Player* /*source*/, Unit* target) { if (!target) return false; if (Creature* Leviathan = target->ToCreature()) if (Leviathan->AI()->GetData(DATA_ORBIT_ACHIEVEMENTS) >= 2) return true; return false; } }; class achievement_nuked_from_orbit : public AchievementCriteriaScript { public: achievement_nuked_from_orbit() : AchievementCriteriaScript("achievement_nuked_from_orbit") { } bool OnCheck(Player* /*source*/, Unit* target) { if (!target) return false; if (Creature* Leviathan = target->ToCreature()) if (Leviathan->AI()->GetData(DATA_ORBIT_ACHIEVEMENTS) >= 3) return true; return false; } }; class achievement_orbit_uary : public AchievementCriteriaScript { public: achievement_orbit_uary() : AchievementCriteriaScript("achievement_orbit_uary") { } bool OnCheck(Player* /*source*/, Unit* target) { if (!target) return false; if (Creature* Leviathan = target->ToCreature()) if (Leviathan->AI()->GetData(DATA_ORBIT_ACHIEVEMENTS) == 4) return true; return false; } }; class spell_load_into_catapult : public SpellScriptLoader { enum Spells { SPELL_PASSENGER_LOADED = 62340, }; public: spell_load_into_catapult() : SpellScriptLoader("spell_load_into_catapult") { } class spell_load_into_catapult_AuraScript : public AuraScript { PrepareAuraScript(spell_load_into_catapult_AuraScript); void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* owner = GetOwner()->ToUnit(); if (!owner) return; owner->CastSpell(owner, SPELL_PASSENGER_LOADED, true); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* owner = GetOwner()->ToUnit(); if (!owner) return; owner->RemoveAurasDueToSpell(SPELL_PASSENGER_LOADED); } void Register() { OnEffectApply += AuraEffectApplyFn(spell_load_into_catapult_AuraScript::OnApply, EFFECT_0, SPELL_AURA_CONTROL_VEHICLE, AURA_EFFECT_HANDLE_REAL); OnEffectRemove += AuraEffectRemoveFn(spell_load_into_catapult_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_CONTROL_VEHICLE, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } }; AuraScript* GetAuraScript() const { return new spell_load_into_catapult_AuraScript(); } }; class spell_auto_repair : public SpellScriptLoader { enum Spells { SPELL_AUTO_REPAIR = 62705, }; public: spell_auto_repair() : SpellScriptLoader("spell_auto_repair") {} class spell_auto_repair_SpellScript : public SpellScript { PrepareSpellScript(spell_auto_repair_SpellScript); void CheckCooldownForTarget() { if (GetHitUnit()->HasAuraEffect(SPELL_AUTO_REPAIR, EFFECT_2)) // Check presence of dummy aura indicating cooldown { PreventHitEffect(EFFECT_0); PreventHitDefaultEffect(EFFECT_1); PreventHitDefaultEffect(EFFECT_2); //! Currently this doesn't work: if we call PreventHitAura(), the existing aura will be removed //! because of recent aura refreshing changes. Since removing the existing aura negates the idea //! of a cooldown marker, we just let the dummy aura refresh itself without executing the other spelleffects. //! The spelleffects can be executed by letting the dummy aura expire naturally. //! This is a temporary solution only. //PreventHitAura(); } } void HandleScript(SpellEffIndex /*eff*/) { Vehicle* vehicle = GetHitUnit()->GetVehicleKit(); if (!vehicle) return; Player* driver = vehicle->GetPassenger(0) ? vehicle->GetPassenger(0)->ToPlayer() : NULL; if (!driver) return; driver->MonsterTextEmote(EMOTE_REPAIR, driver->GetGUID(), true); InstanceScript* instance = driver->GetInstanceScript(); if (!instance) return; // Actually should/could use basepoints (100) for this spell effect as percentage of health, but oh well. vehicle->GetBase()->SetFullHealth(); // For achievement instance->SetData(DATA_UNBROKEN, 0); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_auto_repair_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); BeforeHit += SpellHitFn(spell_auto_repair_SpellScript::CheckCooldownForTarget); } }; SpellScript* GetSpellScript() const { return new spell_auto_repair_SpellScript(); } }; class spell_systems_shutdown : public SpellScriptLoader { public: spell_systems_shutdown() : SpellScriptLoader("spell_systems_shutdown") { } class spell_systems_shutdown_AuraScript : public AuraScript { PrepareAuraScript(spell_systems_shutdown_AuraScript); void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Creature* owner = GetOwner()->ToCreature(); if (!owner) return; //! This could probably in the SPELL_EFFECT_SEND_EVENT handler too: owner->AddUnitState(UNIT_STATE_STUNNED | UNIT_STATE_ROOT); owner->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); owner->RemoveAurasDueToSpell(SPELL_GATHERING_SPEED); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Creature* owner = GetOwner()->ToCreature(); if (!owner) return; owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } void Register() { OnEffectApply += AuraEffectApplyFn(spell_systems_shutdown_AuraScript::OnApply, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, AURA_EFFECT_HANDLE_REAL); OnEffectRemove += AuraEffectRemoveFn(spell_systems_shutdown_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_systems_shutdown_AuraScript(); } }; class FlameLeviathanPursuedTargetSelector { enum Area { AREA_FORMATION_GROUNDS = 4652, }; public: explicit FlameLeviathanPursuedTargetSelector(Unit* unit) : _me(unit) {}; bool operator()(WorldObject* target) const { //! No players, only vehicles (todo: check if blizzlike) Creature* creatureTarget = target->ToCreature(); if (!creatureTarget) return true; //! NPC entries must match if (creatureTarget->GetEntry() != NPC_SALVAGED_DEMOLISHER && creatureTarget->GetEntry() != NPC_SALVAGED_SIEGE_ENGINE) return true; //! NPC must be a valid vehicle installation Vehicle* vehicle = creatureTarget->GetVehicleKit(); if (!vehicle) return true; //! Entity needs to be in appropriate area if (target->GetAreaId() != AREA_FORMATION_GROUNDS) return true; //! Vehicle must be in use by player bool playerFound = false; for (SeatMap::const_iterator itr = vehicle->Seats.begin(); itr != vehicle->Seats.end() && !playerFound; ++itr) if (IS_PLAYER_GUID(itr->second.Passenger)) playerFound = true; return !playerFound; } private: Unit const* _me; }; class spell_pursue : public SpellScriptLoader { public: spell_pursue() : SpellScriptLoader("spell_pursue") {} class spell_pursue_SpellScript : public SpellScript { PrepareSpellScript(spell_pursue_SpellScript); bool Load() { _target = NULL; return true; } void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if(FlameLeviathanPursuedTargetSelector(GetCaster())); if (targets.empty()) { if (Creature* caster = GetCaster()->ToCreature()) caster->AI()->EnterEvadeMode(); } else { //! In the end, only one target should be selected _target = Trinity::Containers::SelectRandomContainerElement(targets); FilterTargetsSubsequently(targets); } } void FilterTargetsSubsequently(std::list<WorldObject*>& targets) { targets.clear(); if (_target) targets.push_back(_target); } void HandleScript(SpellEffIndex /*eff*/) { Creature* caster = GetCaster()->ToCreature(); if (!caster) return; caster->AI()->AttackStart(GetHitUnit()); // Chase target for (SeatMap::const_iterator itr = caster->GetVehicleKit()->Seats.begin(); itr != caster->GetVehicleKit()->Seats.end(); ++itr) { if (IS_PLAYER_GUID(itr->second.Passenger)) { caster->MonsterTextEmote(EMOTE_PURSUE, itr->second.Passenger, true); return; } } } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_pursue_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_pursue_SpellScript::FilterTargetsSubsequently, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_pursue_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_APPLY_AURA); } WorldObject* _target; }; SpellScript* GetSpellScript() const { return new spell_pursue_SpellScript(); } }; class spell_vehicle_throw_passenger : public SpellScriptLoader { public: spell_vehicle_throw_passenger() : SpellScriptLoader("spell_vehicle_throw_passenger") {} class spell_vehicle_throw_passenger_SpellScript : public SpellScript { PrepareSpellScript(spell_vehicle_throw_passenger_SpellScript); void HandleScript(SpellEffIndex effIndex) { Spell* baseSpell = GetSpell(); SpellCastTargets targets = baseSpell->m_targets; int32 damage = GetEffectValue(); if (targets.HasTraj()) if (Vehicle* vehicle = GetCaster()->GetVehicleKit()) if (Unit* passenger = vehicle->GetPassenger(damage - 1)) { // use 99 because it is 3d search std::list<WorldObject*> targetList; Trinity::WorldObjectSpellAreaTargetCheck check(99, GetExplTargetDest(), GetCaster(), GetCaster(), GetSpellInfo(), TARGET_CHECK_DEFAULT, NULL); Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> searcher(GetCaster(), targetList, check); GetCaster()->GetMap()->VisitAll(GetCaster()->m_positionX, GetCaster()->m_positionY, 99, searcher); float minDist = 99 * 99; Unit* target = NULL; for (std::list<WorldObject*>::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) if (unit->GetEntry() == NPC_SEAT) if (Vehicle* seat = unit->GetVehicleKit()) if (!seat->GetPassenger(0)) if (Unit* device = seat->GetPassenger(2)) if (!device->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) { float dist = unit->GetExactDistSq(targets.GetDstPos()); if (dist < minDist) { minDist = dist; target = unit; } } } if (target && target->IsWithinDist2d(targets.GetDstPos(), GetSpellInfo()->Effects[effIndex].CalcRadius() * 2)) // now we use *2 because the location of the seat is not correct passenger->EnterVehicle(target, 0); else { passenger->ExitVehicle(); float x, y, z; targets.GetDstPos()->GetPosition(x, y, z); passenger->GetMotionMaster()->MoveJump(x, y, z, targets.GetSpeedXY(), targets.GetSpeedZ()); } } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_vehicle_throw_passenger_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_vehicle_throw_passenger_SpellScript(); } }; void AddSC_boss_flame_leviathan() { new boss_flame_leviathan(); new boss_flame_leviathan_seat(); new boss_flame_leviathan_defense_turret(); new boss_flame_leviathan_defense_cannon(); new boss_flame_leviathan_overload_device(); new boss_flame_leviathan_safety_container(); new npc_mechanolift(); new npc_pool_of_tar(); new npc_colossus(); new npc_thorims_hammer(); new npc_mimirons_inferno(); new npc_hodirs_fury(); new npc_freyas_ward(); new npc_freya_ward_summon(); new npc_lorekeeper(); // new npc_brann_bronzebeard(); new go_ulduar_tower(); new achievement_three_car_garage_demolisher(); new achievement_three_car_garage_chopper(); new achievement_three_car_garage_siege(); new achievement_shutout(); new achievement_unbroken(); new achievement_orbital_bombardment(); new achievement_orbital_devastation(); new achievement_nuked_from_orbit(); new achievement_orbit_uary(); new spell_load_into_catapult(); new spell_auto_repair(); new spell_systems_shutdown(); new spell_pursue(); new spell_vehicle_throw_passenger(); }
35.934283
203
0.528972
499453466
9d5d89620bce4e93bc107119991bc9b3eef7a9e0
7,546
hpp
C++
include/codegen/include/UnityEngine/Networking/PlayerConnection/PlayerConnection.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/Networking/PlayerConnection/PlayerConnection.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/Networking/PlayerConnection/PlayerConnection.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:31 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: UnityEngine.ScriptableObject #include "UnityEngine/ScriptableObject.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::Networking::PlayerConnection namespace UnityEngine::Networking::PlayerConnection { // Forward declaring type: PlayerEditorConnectionEvents class PlayerEditorConnectionEvents; // Forward declaring type: MessageEventArgs class MessageEventArgs; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: IPlayerEditorConnectionNative class IPlayerEditorConnectionNative; } // Forward declaring namespace: System namespace System { // Forward declaring type: Guid struct Guid; // Skipping declaration: IntPtr because it is already included! } // Forward declaring namespace: UnityEngine::Events namespace UnityEngine::Events { // Forward declaring type: UnityAction`1<T0> template<typename T0> class UnityAction_1; // Forward declaring type: UnityAction`1<T0> template<typename T0> class UnityAction_1; } // Completed forward declares // Type namespace: UnityEngine.Networking.PlayerConnection namespace UnityEngine::Networking::PlayerConnection { // Autogenerated type: UnityEngine.Networking.PlayerConnection.PlayerConnection class PlayerConnection : public UnityEngine::ScriptableObject { public: // Nested type: UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass12_0 class $$c__DisplayClass12_0; // Nested type: UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass13_0 class $$c__DisplayClass13_0; // Nested type: UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass20_0 class $$c__DisplayClass20_0; // Get static field: static UnityEngine.IPlayerEditorConnectionNative connectionNative static UnityEngine::IPlayerEditorConnectionNative* _get_connectionNative(); // Set static field: static UnityEngine.IPlayerEditorConnectionNative connectionNative static void _set_connectionNative(UnityEngine::IPlayerEditorConnectionNative* value); // private UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents m_PlayerEditorConnectionEvents // Offset: 0x18 UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents* m_PlayerEditorConnectionEvents; // private System.Collections.Generic.List`1<System.Int32> m_connectedPlayers // Offset: 0x20 System::Collections::Generic::List_1<int>* m_connectedPlayers; // private System.Boolean m_IsInitilized // Offset: 0x28 bool m_IsInitilized; // Get static field: static private UnityEngine.Networking.PlayerConnection.PlayerConnection s_Instance static UnityEngine::Networking::PlayerConnection::PlayerConnection* _get_s_Instance(); // Set static field: static private UnityEngine.Networking.PlayerConnection.PlayerConnection s_Instance static void _set_s_Instance(UnityEngine::Networking::PlayerConnection::PlayerConnection* value); // static public UnityEngine.Networking.PlayerConnection.PlayerConnection get_instance() // Offset: 0x13FCA50 static UnityEngine::Networking::PlayerConnection::PlayerConnection* get_instance(); // public System.Boolean get_isConnected() // Offset: 0x13FCC1C bool get_isConnected(); // static private UnityEngine.Networking.PlayerConnection.PlayerConnection CreateInstance() // Offset: 0x13FCB5C static UnityEngine::Networking::PlayerConnection::PlayerConnection* CreateInstance(); // public System.Void OnEnable() // Offset: 0x13FCD94 void OnEnable(); // private UnityEngine.IPlayerEditorConnectionNative GetConnectionNativeApi() // Offset: 0x13FCCD0 UnityEngine::IPlayerEditorConnectionNative* GetConnectionNativeApi(); // public System.Void Register(System.Guid messageId, UnityEngine.Events.UnityAction`1<UnityEngine.Networking.PlayerConnection.MessageEventArgs> callback) // Offset: 0x13FCE6C void Register(System::Guid messageId, UnityEngine::Events::UnityAction_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>* callback); // public System.Void Unregister(System.Guid messageId, UnityEngine.Events.UnityAction`1<UnityEngine.Networking.PlayerConnection.MessageEventArgs> callback) // Offset: 0x13FD1F8 void Unregister(System::Guid messageId, UnityEngine::Events::UnityAction_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>* callback); // public System.Void RegisterConnection(UnityEngine.Events.UnityAction`1<System.Int32> callback) // Offset: 0x13FD4C8 void RegisterConnection(UnityEngine::Events::UnityAction_1<int>* callback); // public System.Void RegisterDisconnection(UnityEngine.Events.UnityAction`1<System.Int32> callback) // Offset: 0x13FD60C void RegisterDisconnection(UnityEngine::Events::UnityAction_1<int>* callback); // public System.Void UnregisterConnection(UnityEngine.Events.UnityAction`1<System.Int32> callback) // Offset: 0x13FD67C void UnregisterConnection(UnityEngine::Events::UnityAction_1<int>* callback); // public System.Void UnregisterDisconnection(UnityEngine.Events.UnityAction`1<System.Int32> callback) // Offset: 0x13FD6EC void UnregisterDisconnection(UnityEngine::Events::UnityAction_1<int>* callback); // public System.Void Send(System.Guid messageId, System.Byte[] data) // Offset: 0x13FD75C void Send(System::Guid messageId, ::Array<uint8_t>* data); // public System.Boolean TrySend(System.Guid messageId, System.Byte[] data) // Offset: 0x13FD8BC bool TrySend(System::Guid messageId, ::Array<uint8_t>* data); // public System.Boolean BlockUntilRecvMsg(System.Guid messageId, System.Int32 timeout) // Offset: 0x13FDA1C bool BlockUntilRecvMsg(System::Guid messageId, int timeout); // public System.Void DisconnectAll() // Offset: 0x13FDC28 void DisconnectAll(); // static private System.Void MessageCallbackInternal(System.IntPtr data, System.UInt64 size, System.UInt64 guid, System.String messageId) // Offset: 0x13FDCDC static void MessageCallbackInternal(System::IntPtr data, uint64_t size, uint64_t guid, ::Il2CppString* messageId); // static private System.Void ConnectedCallbackInternal(System.Int32 playerId) // Offset: 0x13FE1CC static void ConnectedCallbackInternal(int playerId); // static private System.Void DisconnectedCallback(System.Int32 playerId) // Offset: 0x13FE25C static void DisconnectedCallback(int playerId); // public System.Void .ctor() // Offset: 0x13FE2EC // Implemented from: UnityEngine.ScriptableObject // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static PlayerConnection* New_ctor(); }; // UnityEngine.Networking.PlayerConnection.PlayerConnection } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Networking::PlayerConnection::PlayerConnection*, "UnityEngine.Networking.PlayerConnection", "PlayerConnection"); #pragma pack(pop)
53.9
160
0.771005
Futuremappermydud
9d6431cc10d616873a4d6c2d27c0df8ea78ccc82
2,729
hpp
C++
src/input/keyboard/keyboard_plugin.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/input/keyboard/keyboard_plugin.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/input/keyboard/keyboard_plugin.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #ifndef ZEN_INPUT_KEYBOARD_PLUGIN_HPP #define ZEN_INPUT_KEYBOARD_PLUGIN_HPP #include <SDL2/SDL_keycode.h> #include "../../event/event_emitter.hpp" #include "../../scene/scene.fwd.hpp" #include "types/cursor_keys.hpp" #include "types/key_combo_config.hpp" #include "keys/key.hpp" #include "combo/key_combo.hpp" #include <memory> #include <deque> namespace Zen { /** * The KeyboardPlugin is an input plugin that belongs to the Scene-owned * InputPlugin. * * Its role is to listen for native Keyboard Events and then process them. * * You do not need to create this class directly, the InputPlugin will create an * instance of it automatically. * * You can access it from within a Scene using `input.keyboard`. For example, you * can do: * * ```cpp * input.keyboard.on("keydown", callback, context); * ``` * * You can also create Key objects, which you can then poll in your game loop: * * ```cpp * Key* spaceBar = input.keyboard.addKey(SDLK_SPACE); * ``` * * @class KeyboardPlugin * @since 0.0.0 * * @param sceneInputPlugin A pointer to the Scene InputPlugin that the * KeyboardPlugin belongs to. */ class KeyboardPlugin : public EventEmitter { public: KeyboardPlugin (Scene* scene); ~KeyboardPlugin (); void start (); bool isActive (); CursorKeys createCursorKeys (); Key* addKey (SDL_Keycode keys_, bool emitOnRepeat_ = false); Key* addKey (std::string keys_, bool emitOnRepeat_ = false); Key* addKey (char keys_, bool emitOnRepeat_ = false); void removeKey (Key* key_); void removeKey (SDL_Keycode key_); void removeKey (std::string key_); void removeKey (char key_); void removeAllKeys (); KeyCombo* createCombo (const char * keys_, KeyComboConfig config_ = {}); KeyCombo* createCombo (std::vector<const char *> keys_, KeyComboConfig config_ = {}); KeyCombo* createCombo (std::vector<SDL_Keycode> keys_, KeyComboConfig config_ = {}); void processKeyDown (const SDL_Event * const event_); void processKeyUp (const SDL_Event * const event_); Key* getKeyFromKeycode (SDL_Keycode keycode_); void resetKeys (); Scene* scene; bool enabled = true; std::deque<Key> keys; std::deque<KeyCombo> combos; /** * Internal repeat key flag. * * @since 0.0.0 */ SDL_KeyCode prevCode = SDLK_UNKNOWN; /** * Internal repeat key flag. * * @since 0.0.0 */ Uint32 prevTime = 0; ListenerBase* lKeyUp = nullptr; ListenerBase* lKeyDown = nullptr; ListenerBase* lBlur = nullptr; ListenerBase* lPause = nullptr; ListenerBase* lSleep = nullptr; }; } // namespace Zen #endif
20.992308
86
0.70502
hexoctal
9d64641b396b97b97cdc059303cd70199e68217e
1,351
hpp
C++
src/q_1301_1350/q1306_unittest.hpp
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
2
2021-09-28T18:41:03.000Z
2021-09-28T18:42:57.000Z
src/q_1301_1350/q1306_unittest.hpp
vNaonLu/Daily_LeetCode
30024b561611d390931cef1b22afd6a5060cf586
[ "MIT" ]
16
2021-09-26T11:44:20.000Z
2021-11-28T06:44:02.000Z
src/q_1301_1350/q1306_unittest.hpp
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
1
2021-11-22T09:11:36.000Z
2021-11-22T09:11:36.000Z
#ifndef Q1306_UNITTEST_H__ #define Q1306_UNITTEST_H__ #include <gtest/gtest.h> #include "q1306.hpp" using namespace std; /** * This file is generated by leetcode_add.py * * 1306. * Jump Game III * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * Given an array of non-negative integers ‘arr’ , you are initially * positioned at ‘start’ index of the array. When you are at index ‘i’ , * you can jumpto ‘i + arr[i]’ or ‘i - arr[i]’ , check if you can reach * to “any” index with value * Notice that you can not jump outside of the array at any time. * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * • ‘1 ≤ arr.length ≤ 5 × 10⁴’ * • ‘0 ≤ arr[i] <arr.length’ * • ‘0 ≤ start < arr.length’ * */ TEST(q1306, sample_input01) { l1306::Solution solver; vector<int> arr = {4, 2, 3, 0, 3, 1, 2}; int start = 5; bool exp = true; EXPECT_EQ(solver.canReach(arr, start), exp); } TEST(q1306, sample_input02) { l1306::Solution solver; vector<int> arr = {4, 2, 3, 0, 3, 1, 2}; int start = 0; bool exp = true; EXPECT_EQ(solver.canReach(arr, start), exp); } TEST(q1306, sample_input03) { l1306::Solution solver; vector<int> arr = {3, 0, 2, 1, 2}; int start = 2; bool exp = false; EXPECT_EQ(solver.canReach(arr, start), exp); } #endif
24.563636
74
0.572169
vNaonLu
9d6b2a591021f1b9d8cc970db08a7dfe0ac25735
820
hpp
C++
core/include/Score.hpp
Brukols/Epitech-Arcade
5443d28169e9494f0c77abac23f4139e60b46365
[ "MIT" ]
null
null
null
core/include/Score.hpp
Brukols/Epitech-Arcade
5443d28169e9494f0c77abac23f4139e60b46365
[ "MIT" ]
null
null
null
core/include/Score.hpp
Brukols/Epitech-Arcade
5443d28169e9494f0c77abac23f4139e60b46365
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2020 ** OOP_arcade_2019 ** File description: ** Score */ #ifndef SCORE_HPP_ #define SCORE_HPP_ #include <string> #include <vector> using vector = std::vector<std::pair<std::string, std::string>>; namespace arc { class Score { public: Score(const std::string &path); ~Score(); const vector getScores() const; void insertScore(const std::string &name, const std::string &score) const; private: void writeFile(const std::string &path, vector &score_vector) const; void sortScoreVector(vector &scoreVector) const; std::string getNextData(const std::string &line, size_t &i, int cpt) const; private: std::string _path; }; } // namespace arc #endif /* !SCORE_HPP_ */
22.162162
87
0.609756
Brukols
9d6bbb0afadb0ec42d2868e197e62fe43032003f
2,569
cpp
C++
src/use_brpc/server/use_brpc_server.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
src/use_brpc/server/use_brpc_server.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
src/use_brpc/server/use_brpc_server.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author:liu.hao(33852613@163.com) Time:2021-3 info: ***************************************************************************************************/ #include <markcore.h> #include <gtest/gtest.h> #include <butil/logging.h> #include <butil/string_printf.h> #include <brpc/server.h> #include "use_brpc.pb.h" class ServiceImpl : public use_brpc::Service { public: ServiceImpl() {} ~ServiceImpl() {}; virtual void Read(google::protobuf::RpcController* controller, const use_brpc::ReadRequest* request, use_brpc::ReadResponse* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); // Echo request and its attachment try { //MK_PRINT("request::value = %d", request->value()); //MK_PRINT("request::atta = %s", cntl->request_attachment().to_string().c_str()); } catch(std::exception& e) { MK_PRINT("e = %s", e.what()); sleep(1); } response->set_value(request->value()); if (1) { cntl->response_attachment().append(cntl->request_attachment()); } } }; TEST(use_brpc, default) { brpc::Server server; ServiceImpl service; if (server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0) { LOG(ERROR) << "Fail to add service"; return; } // Start the server. brpc::ServerOptions options; options.idle_timeout_sec = 60; options.max_concurrency = 60; if(server.Start(9999, &options) != 0) { LOG(ERROR) << "Fail to start EchoServer"; return; } // Wait until Ctrl-C is pressed, then Stop() and Join() the server. server.RunUntilAskedToQuit(); }
32.518987
102
0.568315
unihykes
9d6d911eeac10f5ec3ceb71f86b3da9ffd818e53
234
cpp
C++
QtGuitest1/QtGuitest1/main.cpp
lvzl20/QtTest1
b5df4f93530763b3aeada3499b1b4695c49c0c04
[ "MIT" ]
null
null
null
QtGuitest1/QtGuitest1/main.cpp
lvzl20/QtTest1
b5df4f93530763b3aeada3499b1b4695c49c0c04
[ "MIT" ]
null
null
null
QtGuitest1/QtGuitest1/main.cpp
lvzl20/QtTest1
b5df4f93530763b3aeada3499b1b4695c49c0c04
[ "MIT" ]
null
null
null
#include "QtGuitest1.h" #include <QtWidgets/QApplication> #include <QPushButton> #include <QWidget> #include "ParWidget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); ParWidget w; w.show(); return a.exec(); }
15.6
33
0.700855
lvzl20
9d7049e70dbe8edcdcb957dd318ef3a845677704
4,416
hpp
C++
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_StoreOp.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_StoreOp.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_StoreOp.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: GenProtoS_StoreOp.hpp // // AUTHOR: Dean Roddey // // CREATED: 11/24/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header file for the GenProtoS_StoreOp.cpp file, which // defines the TGenProtoStoreOp class, which is used in a number of places // where setting of fields or variables are allowed. In those cases, we // need to store a field or variable info object and the expression that // will be evaluated to get the value. // // CAVEATS/GOTCHAS: // // LOG: // #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TGenProtoStoreOp // PREFIX: sop // --------------------------------------------------------------------------- class TGenProtoStoreOp : public TObject, public MDuplicable { public : // ------------------------------------------------------------------- // Constructors and Destructors // ------------------------------------------------------------------- TGenProtoStoreOp() = delete; TGenProtoStoreOp ( TGenProtoFldInfo* const pfldiTarget , TGenProtoExprNode* const pnodeValue ); TGenProtoStoreOp ( TGenProtoVarInfo* const pvariTarget , TGenProtoExprNode* const pnodeValue , const tCIDLib::TBoolean bDeref ); TGenProtoStoreOp ( const TGenProtoStoreOp& sopToCopy ); ~TGenProtoStoreOp(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- tCIDLib::TVoid operator= ( const TGenProtoStoreOp& sopToAssign ); // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bIsDeref() const; tCIDLib::TBoolean bDoStore ( TGenProtoCtx& ctxThis ); const TString& strTarget() const; const TString& strVarValue ( TGenProtoCtx& ctxThis ); tCIDLib::TVoid SetField ( TGenProtoFldInfo* const pfldiTarget ); private : // ------------------------------------------------------------------- // Private class types // ------------------------------------------------------------------- enum class EStoreTypes { Field , Variable }; // ------------------------------------------------------------------- // Private data members // // m_bDeref // Indicates whether our variable/const target is the actual // target, or whether we should dereferenced it and treat it as // the actual name of the target field. This allows for dynamic // targeting of reply blocks. // // m_eType // Indicates whether the field or variable info object is the // target of the store. // // m_pfldiTarget // This is a pointer to the field info object that we are to // store to. // // m_pnodeValue // The top level expression node that we evaluate to create the // value to store. // ------------------------------------------------------------------- tCIDLib::TBoolean m_bDeref; EStoreTypes m_eType; TGenProtoFldInfo* m_pfldiTarget; TGenProtoExprNode* m_pnodeValue; TGenProtoVarInfo* m_pvariTarget; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TGenProtoStoreOp, TObject) DefPolyDup(TGenProtoStoreOp) }; #pragma CIDLIB_POPPACK
30.246575
78
0.42663
MarkStega
9d7547a71c3123aaa2ce3ccf3cce099f2a764bf8
5,580
cpp
C++
src/world/actor.cpp
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
2
2015-11-05T03:47:29.000Z
2020-01-24T18:48:09.000Z
src/world/actor.cpp
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
null
null
null
src/world/actor.cpp
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
null
null
null
#include "apsis/world/actor.h" #include "apsis/world/collision_object.h" #include "apsis/primitive/fragment_shader.h" #include "apsis/primitive/vertex_shader.h" #include "apsis/primitive/unlinked_program.h" #include "apsis/primitive/program.h" #include <fstream> #include <string> #include <json/json.h> // glm::vec3, glm::vec4, glm::ivec4, glm::mat4 #include <glm/glm.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective #include <glm/gtc/matrix_transform.hpp> // glm::value_ptr #include <glm/gtc/type_ptr.hpp> Apsis::World::Actor::Actor(const Apsis::Sprite::Thing& thing, unsigned int x, unsigned int y) : _thing(thing), _sheet(thing.sheet()), _position(0.0f, 0.0f, 0.0f, 0.0f) { // Copy over object properties _object = thing.object(); const Apsis::Sprite::Animation& animation = _thing.animationById(0); _animation = &animation; _frame = &_animation->frame(0); _currentFrame = 0; _currentTime = 0; const Apsis::World::RuleSet& rules = thing.rules(); for (unsigned int i = 0; i < rules.count(); i++) { _ruleSet.addRule(rules.rule(i)); } _position.x = (float)x; _position.y = (float)y; _position.width = (float)_object.get("width").asDouble(); _position.height = (float)_object.get("height").asDouble(); } const Apsis::Sprite::Sheet& Apsis::World::Actor::sheet() const { return _sheet; } const Apsis::Geometry::Rectangle& Apsis::World::Actor::position() const { return _position; } void Apsis::World::Actor::animate(const char* animationName) { _animation = &_thing.animation(animationName); } void Apsis::World::Actor::nextFrame() { _currentFrame += 1; if (_animation->count() == 0) { _currentFrame = 0; } else { _currentFrame %= _animation->count(); } _frame = &_animation->frame(_currentFrame); _currentTime = 0; } void Apsis::World::Actor::attachRule(const Apsis::Registry::Rule& rule) { _ruleSet.addRule(rule); } void Apsis::World::Actor::act(Apsis::World::Scene& scene, unsigned int action_id, bool held) { _ruleSet.act(action_id, held, _object, scene); } void Apsis::World::Actor::update(Apsis::World::Scene& scene, float elapsed) { _currentTime += elapsed; if (_currentTime > 0.08f) { nextFrame(); } _object.set("x", _position.x); _object.set("y", _position.y); _ruleSet.update(elapsed, _object, scene); } void Apsis::World::Actor::collide(Apsis::World::Scene& scene) { Apsis::Geometry::Point to; to.x = (float)_object.get("x").asDouble(); to.y = (float)_object.get("y").asDouble(); if (to.x == _position.x && to.y == _position.y) { return; } Apsis::Geometry::Line trajectory; trajectory.points[0] = _position.center(); trajectory.points[1] = to; bool checkCollisions = true; while (checkCollisions) { // Optimistically assume we won't do another collision pass. checkCollisions = false; // Generate a list of collisions. _ruleSet.collide(scene, _object, _position, to); // Collisions are iterated in the order they occur as one moves. for (unsigned int i = 0; i < _object.collisionCount(); i++) { const Apsis::World::CollisionObject& collisionObject = _object.collisionObject(i); unsigned int event_id = collisionObject.collideEvent(); if (_object.respondsTo(event_id)) { _object.enqueueEvent(event_id); } if (collisionObject.collisionType() == Apsis::World::CollisionObject::CollisionType::Impeded) { // Ok, clip the movement to this and stop. to = trajectory.at(_object.collisionPeriod(i)); break; } else if (collisionObject.collisionType() == Apsis::World::CollisionObject::CollisionType::Redirected) { // Ok, clip our movement and then spawn a new trajectory from the // redirection vector. We still break to form a new list of // collisions. float t = _object.collisionPeriod(i); to = collisionObject.repositionPoint(); _position.x = (float)to.x; _position.y = (float)to.y; trajectory = collisionObject.redirection(); to = trajectory.points[1]; // We have to continue checking collisions on this new path // if there is a path to check if (!(to.x == _position.x && to.y == _position.y)) { checkCollisions = true; } // We are done with this collision list break; } } // TODO: We need to trigger an event for the object we collided with? // Event type: "collided_with_#{this->name()}" // Or do we have that object create a collision rule and then just // add a hint that this was already compared? } _position.x = (float)to.x; _position.y = (float)to.y; } void Apsis::World::Actor::respond(Apsis::World::Scene& scene) { while (_object.hasEvents()) { unsigned int event_id = _object.dequeueEvent(); _ruleSet.respond(event_id, _object, scene); } } void Apsis::World::Actor::draw(const Primitive::Matrix& projection, const World::Camera& camera) const { glm::mat4 model = glm::translate(glm::mat4(1.0), glm::vec3(_position.x, 0.0, _position.y)); const Primitive::Matrix& model_matrix = *(const Primitive::Matrix*)glm::value_ptr(model); _sheet.draw(_frame->spriteIndex, projection, camera, model_matrix); } const char* Apsis::World::Actor::name() const { return _thing.name(); } const Apsis::World::Object& Apsis::World::Actor::object() const { return _object; }
29.0625
109
0.650179
wilkie
9d794579955ef61b727da98c14ff6807f5c18baf
2,401
cpp
C++
src/solver/linear/conjugate_gradient_ocl.cpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
9
2018-07-12T17:06:33.000Z
2021-11-20T23:13:26.000Z
src/solver/linear/conjugate_gradient_ocl.cpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
119
2016-06-22T07:36:04.000Z
2019-03-10T19:38:12.000Z
src/solver/linear/conjugate_gradient_ocl.cpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
9
2017-10-08T16:51:38.000Z
2021-03-15T08:08:04.000Z
#include "conjugate_gradient_ocl.hpp" #ifdef ENABLE_OPENCL #include "exceptions.hpp" #include "dmatrix_vector_product.hpp" #include "numeric/float_compare.hpp" #define VIENNACL_HAVE_EIGEN #define VIENNACL_WITH_OPENCL #include <viennacl/vector.hpp> #include <viennacl/compressed_matrix.hpp> #include <viennacl/linalg/jacobi_precond.hpp> #include <viennacl/linalg/cg.hpp> #include <cmath> #include <iostream> namespace neon { conjugate_gradient_ocl::conjugate_gradient_ocl() : iterative_linear_solver() { viennacl::ocl::set_context_device_type(0, viennacl::ocl::cpu_tag()); } conjugate_gradient_ocl::conjugate_gradient_ocl(double const residual_tolerance) : conjugate_gradient_ocl() { this->residual_tolerance = residual_tolerance; } conjugate_gradient_ocl::conjugate_gradient_ocl(int const max_iterations) : conjugate_gradient_ocl() { this->max_iterations = max_iterations; } conjugate_gradient_ocl::conjugate_gradient_ocl(double const residual_tolerance, int const max_iterations) : conjugate_gradient_ocl() { this->residual_tolerance = residual_tolerance; this->max_iterations = max_iterations; } conjugate_gradient_ocl::~conjugate_gradient_ocl() = default; void conjugate_gradient_ocl::solve(sparse_matrix const& A, vector& x, vector const& b) { using vcl_sparse_matrix = viennacl::compressed_matrix<double>; using vcl_vector = viennacl::vector<double>; viennacl::linalg::cg_tag solver_tag(residual_tolerance, max_iterations); vcl_sparse_matrix vcl_A(A.rows(), A.cols()); vcl_vector vcl_b(b.rows()); // Copy from Eigen objects to ViennaCL objects viennacl::copy(A, vcl_A); viennacl::copy(b, vcl_b); viennacl::linalg::jacobi_precond<vcl_sparse_matrix> vcl_jacobi(vcl_A, viennacl::linalg::jacobi_tag()); // Conjugate gradient solver with preconditioner on GPU vcl_vector const vcl_x = viennacl::linalg::solve(vcl_A, vcl_b, solver_tag, vcl_jacobi); // Copy back to host viennacl::copy(vcl_x, x); viennacl::backend::finish(); std::cout << std::string(6, ' ') << "Conjugate Gradient iterations: " << solver_tag.iters() << " (max. " << max_iterations << "), estimated error: " << solver_tag.error() << " (min. " << residual_tolerance << ")\n"; } } #endif
30.0125
99
0.703457
dbeurle
9d7968f3b06aceca03617592f48437cd5d54ab86
46
cpp
C++
src/core/geometry.cpp
peng00bo00/PBRender
393ef8d80877e26ef7fc405fac7e734637e64580
[ "MIT" ]
null
null
null
src/core/geometry.cpp
peng00bo00/PBRender
393ef8d80877e26ef7fc405fac7e734637e64580
[ "MIT" ]
null
null
null
src/core/geometry.cpp
peng00bo00/PBRender
393ef8d80877e26ef7fc405fac7e734637e64580
[ "MIT" ]
null
null
null
#include "geometry.h" namespace PBRender { }
9.2
21
0.717391
peng00bo00
9d7bafe8c7ceb03037e6034ee45b2dee7665f2df
4,157
cpp
C++
Common/SystemRemote/Document/xServerClient.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/SystemRemote/Document/xServerClient.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/SystemRemote/Document/xServerClient.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
//================================================================================ // Copyright (c) 2013 ~ 2019. HyungKi Jeong(clonextop@gmail.com) // All rights reserved. // // The 3-Clause BSD License (https://opensource.org/licenses/BSD-3-Clause) // // Redistribution and use in source and binary forms, // with or without modification, are permitted provided // that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. // // Title : System remote // Rev. : 10/31/2019 Thu (clonextop@gmail.com) //================================================================================ #include<iostream> #include "xServerClient.h" boost::asio::io_service xNetService::m_Service; xSession::xSession(tcp::socket& sock) : m_Socket(sock){ start(); } void xSession::start(void){ try{ while(1){ boost::system::error_code error; size_t length = m_Socket.read_some(boost::asio::buffer(m_Buffer), error); if(error == boost::asio::error::eof){ // connection closed. exit out break; }else if(error){ throw boost::system::system_error(error); } cout << "Message from client: " << m_Buffer << endl; boost::asio::write(m_Socket, boost::asio::buffer((void*)m_Buffer, length)); } }catch(exception& e){ cerr << "Exception in server: " << e.what() << endl; } } xServer::xServer(short port) : m_Acceptor(m_Service, tcp::endpoint(tcp::v4(), port)) { while(1){ tcp::socket sock(m_Service); //wait for client m_Acceptor.accept(sock); // connection complete new xSession(sock); } } xClient::xClient(const string& host, const string& port) : m_Socket(m_Service) { tcp::resolver resolver(m_Service); //try to connect to server boost::asio::connect(m_Socket, resolver.resolve({host, port})); string msg = "Hello, world!"; size_t msg_length = msg.length(); //send data boost::asio::write(m_Socket, boost::asio::buffer(msg, msg_length)); char reply[MAX_TRANS_SIZE]; //get data size_t reply_length = boost::asio::read(m_Socket, boost::asio::buffer(reply, msg_length)); cout << "Reply is: " << reply << endl; } xClient::~xClient(void) { } int main_server(int argc, char* argv[]){ try{ if(argc != 2){ cerr << "Usage: server <port>" << endl; return 1; } xServer s(atoi(argv[1])); }catch(exception& e){ cerr << "Exception: " << e.what() << endl; } return 0; } int main_client(int argc, char* argv[]){ try{ if(argc != 3){ cerr << "Usage: client <host> <port>" << endl; return 1; } xClient c(argv[1], argv[2]); }catch(exception& e){ cerr<<"Exception: " << e.what() << endl; } return 0; }
32.224806
91
0.629541
testdrive-profiling-master
9d7d3bd11be5d3992f6721a21f5561c3a996c60a
14,584
cpp
C++
src/io/readerwriter.cpp
cmdc0de/libwss
58c1bd1ad79e345bbd5f7af155dbfe1d96c9b91d
[ "MIT" ]
null
null
null
src/io/readerwriter.cpp
cmdc0de/libwss
58c1bd1ad79e345bbd5f7af155dbfe1d96c9b91d
[ "MIT" ]
null
null
null
src/io/readerwriter.cpp
cmdc0de/libwss
58c1bd1ad79e345bbd5f7af155dbfe1d96c9b91d
[ "MIT" ]
null
null
null
#include "readerwriter.h" #include <algorithm> #include "../buffer/segmented_reader_writer_impl.h" using namespace wss; IReaderWriter * ReaderWriter::Create_Default_Interface() { return SegmentedReaderWriterImpl::Create(); } ReaderWriter::ReaderWriter( IReaderWriter* stream_interface ) : ReadCursor(0) ,WriteCursor(0) ,Impl(stream_interface) { WriteCursor = stream_interface->size(); } ReaderWriter::ReaderWriter( const ReaderWriter& other ) : ReadCursor(0) ,WriteCursor(0) ,Impl(other.Impl) { WriteCursor = Impl->size(); } ReaderWriter::~ReaderWriter() { } /********************************************************************************************** * ReaderWriter::Read -- Read from the stream * * In: dst - Buffer data will be written to. * length - Amount of data (in bytes) to read. * * Returns: Number of bytes read, -1 on error. * *********************************************************************************************/ size_t ReaderWriter::read( void * dst, size_t length ) { //Adjust length here. Never pass length to Impl that would read more than is available if(length > 0) { size_t real_len = length; if(real_len + ReadCursor > Impl->size()) { real_len = Impl->size() - ReadCursor; } size_t read_len = Impl->read(ReadCursor, dst, real_len); ReadCursor += read_len; return read_len; } return STREAM_ERROR; //error } size_t ReaderWriter::readUntilDelim(void * dst, size_t length, char delim, bool &wasDelimHit) { //Adjust length here. Never pass length to Impl that would read more than is available if(length > 0) { size_t real_len = length; if(real_len + ReadCursor > Impl->size()) { real_len = Impl->size() - ReadCursor; } size_t read_len = Impl->readUntilDelim(ReadCursor, dst, real_len, delim, wasDelimHit); ReadCursor += read_len; return read_len; } return STREAM_ERROR; //error } /********************************************************************************************** * ReaderWriter::Write -- Write data to the stream * * In: src - Data to be written to stream * length - Number of bytes to write to stream * * Returns: The number of bytes actually written or -1 on error. * *********************************************************************************************/ size_t ReaderWriter::write( const void * src, size_t length ) { if(length > 0) { //If fixed size then adjust length of data if needed. size_t real_length = length; if(real_length + WriteCursor > Impl->capacity()) { if(Impl->fixedCapacity()) { //Can't resize the buffer real_length = (Impl->capacity() - WriteCursor); } } size_t written = Impl->write(WriteCursor, src, real_length); WriteCursor += written; return written; } return STREAM_ERROR; //error } /********************************************************************************************** * ReaderWriter::Erase -- Erase data from the stream * * In: idx - Index to begin erasing at * length - Number of bytes to erase * * Returns: Number of bytes actually erased. * *********************************************************************************************/ size_t ReaderWriter::erase( size_t idx, size_t length ) { //get actual amount erased size_t erased_length = Impl->erase(idx, length); //Move read and write cursors //If // Cursor is before erased data - Do nothing. // Cursor is inside erased data - Place cursor on first un-erased byte // Cursor is after erased data - Subtract amount erased so that cursor points to the same data //Cursor is inside erased data if(ReadCursor >= idx && ReadCursor < idx+erased_length) { ReadCursor = idx; } //cursor is past erased data else if(ReadCursor >= idx+erased_length) { ReadCursor -= erased_length; } //Cursor is inside erased data if(WriteCursor >= idx && WriteCursor < idx+erased_length) { WriteCursor = idx; } //cursor is past erased data else if(WriteCursor >= idx+erased_length) { WriteCursor -= erased_length; } return erased_length; } /********************************************************************************************** * ReaderWriter::TellRead -- Returns the current read posision of the stream * *********************************************************************************************/ size_t ReaderWriter::tellRead() const { return ReadCursor; } /********************************************************************************************** * ReaderWriter::SeekRead -- Move the read cursor to the specified location * * In: distance - Distance from the specified start point. Can be negative. * seek_type - Starting position to seek from (BEGIN, CUR, END). * * Returns: new location of read cursor. -1 on error. * *********************************************************************************************/ size_t ReaderWriter::seekRead( pos_type distance, StreamSeekType seek_type ) { size_t new_cursor = 0; switch(seek_type) { case BEGIN: new_cursor = distance; break; case CUR: new_cursor = ReadCursor + distance; break; case END: new_cursor = Impl->size() + distance; break; } if(new_cursor >= 0 && new_cursor <= Impl->size()) { ReadCursor = new_cursor; return ReadCursor; } return STREAM_ERROR; //error } /********************************************************************************************** * ReaderWriter::UnreadSize -- Number of bytes left to read in the stream * *********************************************************************************************/ size_t ReaderWriter::unreadSize() const { return size() - tellRead(); } /********************************************************************************************** * ReaderWriter::TellWrite -- Returns the current position of the write cursor. * *********************************************************************************************/ size_t ReaderWriter::tellWrite() const { return WriteCursor; } /********************************************************************************************** * ReaderWriter::SeekWrite -- Move the write cursor to the specified location * * In: distance - Distance from the specified start point. Can be negative. * seek_type - Starting position to seek from (BEGIN, CUR, END). * * Returns: new location of write cursor. -1 on error. * *********************************************************************************************/ size_t ReaderWriter::seekWrite( pos_type distance, StreamSeekType seek_type ) { size_t new_cursor = 0; switch(seek_type) { case BEGIN: new_cursor = distance; break; case CUR: new_cursor = ReadCursor + distance; break; case END: new_cursor = Impl->size() + distance; break; } if(new_cursor >= 0 && new_cursor <= Impl->size()) { WriteCursor = new_cursor; return WriteCursor; } return STREAM_ERROR; //error } /********************************************************************************************** * ReaderWriter::Empty -- Returns true if the buffer has no data. * *********************************************************************************************/ bool ReaderWriter::empty() const { return size() == 0; } /********************************************************************************************** * ReaderWriter::Size -- Returns the current size of the stream. * *********************************************************************************************/ size_t ReaderWriter::size() const { return Impl->size(); } /********************************************************************************************** * ReaderWriter::Raw -- Fetch a raw pointer to the data at a given index * * In: idx - Index of the requested data * * Out: out_length - Amount of data that can be read from the returned pointer. This may not * be the whole buffer in the case of a segmented buffer. Multiple may be * needed to read all of the data. * * Returns: pointer to data that at least out_length bytes can be read from * *********************************************************************************************/ const void * ReaderWriter::raw( size_t idx, size_t& out_length ) const { return Impl->raw(idx, out_length); } /********************************************************************************************** * ReaderWriter::Get_Preferred_Block_Size -- returns preferred blocksize for this buffer * *********************************************************************************************/ size_t ReaderWriter::getPreferredBlockSize() const { return Impl->getPreferredBlockSize(); } /********************************************************************************************** * * ReaderWriter::readVarUInt32 -- Read an Unsigned VarInt into a 32 bit value * *********************************************************************************************/ size_t ReaderWriter::readVarUInt32(uint32_t& val) { uint32_t result = 0; int count = 0; uint8_t b; do { if (static_cast<uint32_t>(count) >= MaxVarInt32) { return STREAM_ERROR; } if(readFixed8(b) == STREAM_ERROR) { return STREAM_ERROR; } result |= static_cast<uint32_t>(b & 0x7F) << (7 * count); count++; } while(b & 0x80); val = result; return count; } /********************************************************************************************** * * ReaderWriter::ReadVarUInt32 -- Read an Signed VarInt into a 32 bit value * *********************************************************************************************/ size_t ReaderWriter::readVarSInt32(int32_t& val) { uint32_t number; size_t ret = readVarUInt32(number); if (ret != STREAM_ERROR) { val = zigZagDecode32(number); } return ret; } /********************************************************************************************** * * ReaderWriter::ReadVarUInt64 -- Read an Unsigned VarInt into a 64 bit value * *********************************************************************************************/ size_t ReaderWriter::readVarUInt64(uint64_t& val) { uint64_t result = 0; int count = 0; uint8_t b; do { if (static_cast<uint32_t>(count) >= MaxVarInt64) { return STREAM_ERROR; } if(readFixed8(b) == STREAM_ERROR) { return STREAM_ERROR; } result |= static_cast<uint64_t>(b & 0x7F) << (7 * count); count++; } while(b & 0x80); val = result; return count; } /********************************************************************************************** * * ReaderWriter::ReadVarSInt64 -- Read a Signed VarInt into a 64 bit value * *********************************************************************************************/ size_t ReaderWriter::readVarSInt64(int64_t& val) { uint64_t number; size_t ret = readVarUInt64(number); if (ret != STREAM_ERROR) { val = zigZagDecode64(number); } return ret; } /********************************************************************************************** * * ReaderWriter::WriteVarInt32Helper -- Helper for writing 32-bit VarInts * from the Google Protocol Buffer code base * *********************************************************************************************/ size_t ReaderWriter::WriteVarInt32Helper(uint32_t value, uint8_t* target) { target[0] = static_cast<uint8_t>(value | 0x80); if (value >= (1 << 7)) { target[1] = static_cast<uint8_t>((value >> 7) | 0x80); if (value >= (1 << 14)) { target[2] = static_cast<uint8_t>((value >> 14) | 0x80); if (value >= (1 << 21)) { target[3] = static_cast<uint8_t>((value >> 21) | 0x80); if (value >= (1 << 28)) { target[4] = static_cast<uint8_t>(value >> 28); return 5; } else { target[3] &= 0x7F; return 4; } } else { target[2] &= 0x7F; return 3; } } else { target[1] &= 0x7F; return 2; } } else { target[0] &= 0x7F; return 1; } } /********************************************************************************************** * * ReaderWriter::WriteVarInt64Helper -- Helper for writing 64-bit VarInts * from the Google Protocol Buffer code base * *********************************************************************************************/ size_t ReaderWriter::WriteVarInt64Helper(uint64_t value, uint8_t* target) { // Splitting into 32-bit pieces gives better performance on 32-bit // processors. uint32_t part0 = static_cast<uint32_t>(value ); uint32_t part1 = static_cast<uint32_t>(value >> 28); uint32_t part2 = static_cast<uint32_t>(value >> 56); int size; // Here we can't really optimize for small numbers, since the value is // split into three parts. Cheking for numbers < 128, for instance, // would require three comparisons, since you'd have to make sure part1 // and part2 are zero. However, if the caller is using 64-bit integers, // it is likely that they expect the numbers to often be very large, so // we probably don't want to optimize for small numbers anyway. Thus, // we end up with a hardcoded binary search tree... if (part2 == 0) { if (part1 == 0) { if (part0 < (1 << 14)) { if (part0 < (1 << 7)) { size = 1; target[0] = static_cast<uint8_t>((part0 ) | 0x80); } else { size = 2; target[1] = static_cast<uint8_t>((part0 >> 7) | 0x80); } } else { if (part0 < (1 << 21)) { size = 3; target[2] = static_cast<uint8_t>((part0 >> 14) | 0x80); } else { size = 4; target[3] = static_cast<uint8_t>((part0 >> 21) | 0x80); } } } else { if (part1 < (1 << 14)) { if (part1 < (1 << 7)) { size = 5; target[4] = static_cast<uint8_t>((part1 ) | 0x80); } else { size = 6; target[5] = static_cast<uint8_t>((part1 >> 7) | 0x80); } } else { if (part1 < (1 << 21)) { size = 7; target[6] = static_cast<uint8_t>((part1 >> 14) | 0x80); } else { size = 8; target[7] = static_cast<uint8_t>((part1 >> 21) | 0x80); } } } } else { if (part2 < (1 << 7)) { size = 9; target[8] = static_cast<uint8_t>((part2 ) | 0x80); } else { size = 10; target[9] = static_cast<uint8_t>((part2 >> 7) | 0x80); } } target[size-1] &= 0x7F; return size; }
30.832981
97
0.489578
cmdc0de
9d8484afe946078a7759d756051f6734b3185b74
432
hpp
C++
Include/Utils/GBSpecs.hpp
ShannonHG/Modest-GB
f39851cd36bf0c752ce56c60783035e2bf2fd19c
[ "MIT" ]
6
2022-01-25T06:55:00.000Z
2022-01-25T18:39:25.000Z
Include/Utils/GBSpecs.hpp
ShannonHG/Modest-GB
f39851cd36bf0c752ce56c60783035e2bf2fd19c
[ "MIT" ]
null
null
null
Include/Utils/GBSpecs.hpp
ShannonHG/Modest-GB
f39851cd36bf0c752ce56c60783035e2bf2fd19c
[ "MIT" ]
1
2022-01-25T08:09:54.000Z
2022-01-25T08:09:54.000Z
#pragma once #include <cstdint> namespace ModestGB { const uint32_t GB_CLOCK_SPEED = 4194304; const double GB_FRAMES_PER_SECOND = 59.7; const double GB_SECONDS_PER_FRAME = 1 / GB_FRAMES_PER_SECOND; const double GB_CYCLES_PER_FRAME = GB_CLOCK_SPEED / GB_FRAMES_PER_SECOND; const uint8_t GB_SCREEN_WIDTH = 160; const uint8_t GB_SCREEN_HEIGHT = 144; const uint16_t GB_HSYNC_TIME = 9198; const uint16_t GB_VSYNC_TIME = 59730; }
30.857143
74
0.803241
ShannonHG
9d877756a1088c1933f93f3ba432863274a26d90
7,298
hxx
C++
src/interfaces/python/opengm/inference/pyVisitor.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
src/interfaces/python/opengm/inference/pyVisitor.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
src/interfaces/python/opengm/inference/pyVisitor.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef OPENGM_PYTHON_VISITOR #define OPENGM_PYTHON_VISITOR #include <boost/python.hpp> #include <boost/python/wrapper.hpp> #include <vector> #include <opengm/python/opengmpython.hxx> #include <opengm/python/converter.hxx> #include <opengm/python/numpyview.hxx> #include <opengm/python/pythonfunction.hxx> //#include <opengm/inference/new_visitors/new_visitors.hxx> template<class INF> class PythonVisitor{ public: typedef INF & PassedInfTye; typedef typename INF::GraphicalModelType GraphicalModelType; typedef typename INF::ValueType ValueType; typedef typename INF::IndexType IndexType; typedef typename INF::LabelType LabelType; void setGilEnsure(const bool gilEnsure){ gilEnsure_=gilEnsure; } PythonVisitor( boost::python::object obj, const size_t visitNth, const bool gilEnsure=true ) : obj_(obj), visitNth_(visitNth), visitNr_(0), gilEnsure_(gilEnsure) { } void begin_impl(PassedInfTye inf){ if(gilEnsure_){ PyGILState_STATE gstate; gstate = PyGILState_Ensure (); // CALL BACK TO PYTHON obj_.attr("begin")(inf); PyGILState_Release (gstate); } else{ obj_.attr("begin")(inf); } } void end_impl(PassedInfTye inf){ if(gilEnsure_){ PyGILState_STATE gstate; gstate = PyGILState_Ensure (); // CALL BACK TO PYTHON obj_.attr("end")(inf); PyGILState_Release (gstate); } else{ obj_.attr("end")(inf); } } size_t visit_impl(PassedInfTye inf){ ++visitNr_; if(visitNr_%visitNth_==0){ if(gilEnsure_){ PyGILState_STATE gstate; gstate = PyGILState_Ensure (); obj_.attr("visit")(inf); PyGILState_Release (gstate); } else{ obj_.attr("visit")(inf); } } return 0;//static_cast<size_t>(opengm::visitors::VisitorReturnFlag::continueInf); } void addLog(const std::string & log){ } void log(const std::string & log, const double ){ } void begin(PassedInfTye inf){return begin_impl(inf);} template<class A> void begin(PassedInfTye inf,const A & a){return begin_impl(inf);} template<class I,class A,class B> void begin(I & inf,const A & a,const B & b){return begin_impl(inf);} template<class A,class B,class C> void begin(PassedInfTye inf,const A & a,const B & b,const C & c){return begin_impl(inf);} template<class A,class B,class C,class D> void begin(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d){return begin_impl(inf);} template<class A,class B,class C,class D,class E> void begin(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e){return begin_impl(inf);} template<class A,class B,class C,class D,class E,class F> void begin(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f){return begin_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G> void begin(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g){return begin_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G,class H> void begin(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g,const H & h){return begin_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G,class H,class I> void begin(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g,const H & h,const I & i){return begin_impl(inf);} void end(PassedInfTye inf){return end_impl(inf);} template<class A> void end(PassedInfTye inf,const A & a){return end_impl(inf);} template<class A,class B> void end(PassedInfTye inf,const A & a,const B & b){return end_impl(inf);} template<class A,class B,class C> void end(PassedInfTye inf,const A & a,const B & b,const C & c){return end_impl(inf);} template<class A,class B,class C,class D> void end(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d){return end_impl(inf);} template<class A,class B,class C,class D,class E> void end(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e){return end_impl(inf);} template<class A,class B,class C,class D,class E,class F> void end(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f){return end_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G> void end(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g){return end_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G,class H> void end(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g,const H & h){return end_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G,class H,class I> void end(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g,const H & h,const I & i){return end_impl(inf);} template<class I> size_t operator()(I & inf){return visit_impl(inf);} template<class A> size_t operator()(PassedInfTye inf,const A & a){return visit_impl(inf);} template<class A,class B> size_t operator()(PassedInfTye inf,const A & a,const B & b){return visit_impl(inf);} template<class A,class B,class C> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c){return visit_impl(inf);} template<class A,class B,class C,class D> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d){return visit_impl(inf);} template<class A,class B,class C,class D,class E> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e){return visit_impl(inf);} template<class A,class B,class C,class D,class E,class F> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f){return visit_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g){return visit_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G,class H> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g,const H & h){return visit_impl(inf);} template<class A,class B,class C,class D,class E,class F,class G,class H,class I> size_t operator()(PassedInfTye inf,const A & a,const B & b,const C & c,const D & d,const E & e,const F & f,const G & g,const H & h,const I & i){return visit_impl(inf);} // Interface private: boost::python::object obj_; size_t visitNth_; size_t visitNr_; bool gilEnsure_; //std::vector<LabelType> labeling_; }; #endif
41.942529
172
0.644423
jasjuang
9d91ab3556d97b93bf1666fe1c9d77c733a5dd19
1,777
cpp
C++
src/concentric_histogram.cpp
BetaRavener/ZPO-Histogram
2ac39cf9a891190ea48f4413548426ade98c9ead
[ "MIT" ]
null
null
null
src/concentric_histogram.cpp
BetaRavener/ZPO-Histogram
2ac39cf9a891190ea48f4413548426ade98c9ead
[ "MIT" ]
null
null
null
src/concentric_histogram.cpp
BetaRavener/ZPO-Histogram
2ac39cf9a891190ea48f4413548426ade98c9ead
[ "MIT" ]
null
null
null
#include "concentric_histogram.h" using namespace std; ConcentricHistogram::ConcentricHistogram(int step) : _step(step) { } void ConcentricHistogram::compute(const GrayscaleImage& img, GrayscaleImage* mark_img) { clear_data(); int x1 = 0; int y1 = 0; int i; int j; int x2 = img.width() -1; int y2 = img.height() -1; if(_step >= 1) { while(x1 <= x2 && y1 <= y2) { //--------------------------------- for(i = x1; i <= x2; i++) { _data[img.pixel(i, y1)]++; _data[img.pixel(i, y2)]++; _used_samples = _used_samples + 2; if(mark_img != nullptr) { mark_img->pixel(i, y1, 255); mark_img->pixel(i, y2, 255); } } for(j = y1; j <= y2; j++) { _data[img.pixel(x1,j)]++; _data[img.pixel(x2,j)]++; _used_samples = _used_samples + 2; if(mark_img != nullptr) { mark_img->pixel(x1, j, 255); mark_img->pixel(x2, j, 255); } } //--------------------------------- x1 += _step; y1 += _step; x2 -= _step; y2 -= _step; } } // Normalize histogram for (int i = 0; i < size; i++) { _data[i] /= _used_samples; } } std::string ConcentricHistogram::to_string(bool with_params) const { return "Concentric Histogram" + (with_params ? (" (" + std::to_string(_step) + ")") : ""); }
25.385714
86
0.388295
BetaRavener
9d9247d61e0daa710c32723a13a01708d922fc33
1,494
cpp
C++
srcs/AModule.cpp
quentin-litzler/Hydrodynamic-Simulation
9924b71108aca2a443f9e5852bd44b0cf7319731
[ "MIT" ]
null
null
null
srcs/AModule.cpp
quentin-litzler/Hydrodynamic-Simulation
9924b71108aca2a443f9e5852bd44b0cf7319731
[ "MIT" ]
null
null
null
srcs/AModule.cpp
quentin-litzler/Hydrodynamic-Simulation
9924b71108aca2a443f9e5852bd44b0cf7319731
[ "MIT" ]
null
null
null
#include <Model.hpp> #include <AModule.hpp> /******************************************* Constructors *******************************************/ AModule::AModule(Model & model) : _model(model), _vertices(nullptr), _elements(nullptr) { return; } /******************************************* Destructor *******************************************/ AModule::~AModule(void) { return ; } /******************************************* Accessors - getters *******************************************/ GLfloat * AModule::getVertices(void) const { return this->_vertices; } GLfloat * AModule::getColors(void) const { return this->_colors; } GLfloat * AModule::getNormals(void) const { return this->_normals; } GLuint * AModule::getElements(void) const { return this->_elements; } GLuint AModule::getVerticesSize(void) const { return this->_verticesSize; } GLuint AModule::getColorsSize(void) const { return this->_colorsSize; } GLuint AModule::getNormalsSize(void) const { return this->_normalsSize; } GLuint AModule::getElementsSize(void) const { return this->_elementsSize; } GLuint AModule::getInstances(void) const { return this->_instances; } GLuint AModule::getMaxInstances(void) const { return this->_maxInstances; } GLfloat * AModule::getPositions(void) const { return this->_positions; } GLuint AModule::getPositionsSize(void) const { return this->_positionsSize; } GLuint AModule::getBatchSize(void) const { return this->_batchSize; }
16.6
87
0.596386
quentin-litzler
9d96a0b5931bfa23a8beec7081c3078cd50533d4
1,546
cpp
C++
src/unicode/tests/test_libaeon_unicode/test_encoding.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
7
2017-02-19T16:22:16.000Z
2021-03-02T05:47:39.000Z
src/unicode/tests/test_libaeon_unicode/test_encoding.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
61
2017-05-29T06:11:17.000Z
2021-03-28T21:51:44.000Z
src/unicode/tests/test_libaeon_unicode/test_encoding.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
2
2017-05-28T17:17:40.000Z
2017-07-14T21:45:16.000Z
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen #include <aeon/unicode/encoding.h> #include <aeon/common/bom.h> #include <gtest/gtest.h> #include <array> using namespace aeon; TEST(test_encoding, test_encoding_convert) { const auto str = u8"I like Π, and らき☆すた, Raki☆Suta "; const auto converted = unicode::utf8::to_utf16(str); const auto converted2 = unicode::utf16::to_utf8(converted); // TODO: Fix for C++20 migration. const auto converted2_u8 = std::u8string{std::begin(converted2), std::end(converted2)}; EXPECT_TRUE(str == converted2_u8); } TEST(test_encoding, test_encoding_convert_with_bom) { const auto str = common::bom::utf8::u8string() + u8"I like Π, and らき☆すた, Raki☆Suta "; const auto converted = unicode::utf8::to_utf16(str); const auto converted2 = unicode::utf16::to_utf8(converted); // TODO: Fix for C++20 migration. const auto converted2_u8 = std::u8string{std::begin(converted2), std::end(converted2)}; EXPECT_TRUE(str == converted2_u8); } TEST(test_encoding, test_encoding_utf32) { const auto str1 = unicode::utf32::to_utf8('A'); EXPECT_EQ(1u, std::size(str1)); const auto str2 = unicode::utf32::to_utf8(U"ę"); EXPECT_EQ(2u, std::size(str2)); const auto str3 = unicode::utf32::to_utf8(U"ら"); EXPECT_EQ(3u, std::size(str3)); const auto str4 = unicode::utf32::to_utf8(U"𠜎"); EXPECT_EQ(4u, std::size(str4)); const auto banana = unicode::utf32::to_utf8(U"🍌"); EXPECT_EQ(4u, std::size(banana)); }
30.313725
91
0.684994
aeon-engine
9da0b24cdf10f28da460f1632103c0a474e1ac33
5,324
hpp
C++
include/codegen/include/System/Reflection/MonoEvent.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Reflection/MonoEvent.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Reflection/MonoEvent.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:43 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Reflection.RuntimeEventInfo #include "System/Reflection/RuntimeEventInfo.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Reflection namespace System::Reflection { // Forward declaring type: MethodInfo class MethodInfo; // Forward declaring type: CustomAttributeData class CustomAttributeData; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IList`1<T> template<typename T> class IList_1; } // Completed forward declares // Type namespace: System.Reflection namespace System::Reflection { // Autogenerated type: System.Reflection.MonoEvent class MonoEvent : public System::Reflection::RuntimeEventInfo { public: // private System.IntPtr klass // Offset: 0x18 System::IntPtr klass; // private System.IntPtr handle // Offset: 0x20 System::IntPtr handle; // public override System.Reflection.MethodInfo GetAddMethod(System.Boolean nonPublic) // Offset: 0x113BB90 // Implemented from: System.Reflection.EventInfo // Base method: System.Reflection.MethodInfo EventInfo::GetAddMethod(System.Boolean nonPublic) System::Reflection::MethodInfo* GetAddMethod(bool nonPublic); // public override System.Reflection.MethodInfo GetRaiseMethod(System.Boolean nonPublic) // Offset: 0x113BC5C // Implemented from: System.Reflection.EventInfo // Base method: System.Reflection.MethodInfo EventInfo::GetRaiseMethod(System.Boolean nonPublic) System::Reflection::MethodInfo* GetRaiseMethod(bool nonPublic); // public override System.Reflection.MethodInfo GetRemoveMethod(System.Boolean nonPublic) // Offset: 0x113BCE0 // Implemented from: System.Reflection.EventInfo // Base method: System.Reflection.MethodInfo EventInfo::GetRemoveMethod(System.Boolean nonPublic) System::Reflection::MethodInfo* GetRemoveMethod(bool nonPublic); // public override System.Type get_DeclaringType() // Offset: 0x113BD64 // Implemented from: System.Reflection.MemberInfo // Base method: System.Type MemberInfo::get_DeclaringType() System::Type* get_DeclaringType(); // public override System.Type get_ReflectedType() // Offset: 0x113BD94 // Implemented from: System.Reflection.MemberInfo // Base method: System.Type MemberInfo::get_ReflectedType() System::Type* get_ReflectedType(); // public override System.String get_Name() // Offset: 0x113BDC4 // Implemented from: System.Reflection.MemberInfo // Base method: System.String MemberInfo::get_Name() ::Il2CppString* get_Name(); // public override System.String ToString() // Offset: 0x113BDF4 // Implemented from: System.Object // Base method: System.String Object::ToString() ::Il2CppString* ToString(); // public override System.Boolean IsDefined(System.Type attributeType, System.Boolean inherit) // Offset: 0x113BE74 // Implemented from: System.Reflection.MemberInfo // Base method: System.Boolean MemberInfo::IsDefined(System.Type attributeType, System.Boolean inherit) bool IsDefined(System::Type* attributeType, bool inherit); // public override System.Object[] GetCustomAttributes(System.Boolean inherit) // Offset: 0x113BEF4 // Implemented from: System.Reflection.MemberInfo // Base method: System.Object[] MemberInfo::GetCustomAttributes(System.Boolean inherit) ::Array<::Il2CppObject*>* GetCustomAttributes(bool inherit); // public override System.Object[] GetCustomAttributes(System.Type attributeType, System.Boolean inherit) // Offset: 0x113BF6C // Implemented from: System.Reflection.MemberInfo // Base method: System.Object[] MemberInfo::GetCustomAttributes(System.Type attributeType, System.Boolean inherit) ::Array<::Il2CppObject*>* GetCustomAttributes(System::Type* attributeType, bool inherit); // public override System.Collections.Generic.IList`1<System.Reflection.CustomAttributeData> GetCustomAttributesData() // Offset: 0x113BFEC // Implemented from: System.Reflection.MemberInfo // Base method: System.Collections.Generic.IList`1<System.Reflection.CustomAttributeData> MemberInfo::GetCustomAttributesData() System::Collections::Generic::IList_1<System::Reflection::CustomAttributeData*>* GetCustomAttributesData(); // public System.Void .ctor() // Offset: 0x113BFF4 // Implemented from: System.Reflection.RuntimeEventInfo // Base method: System.Void RuntimeEventInfo::.ctor() // Base method: System.Void EventInfo::.ctor() // Base method: System.Void MemberInfo::.ctor() // Base method: System.Void Object::.ctor() static MonoEvent* New_ctor(); }; // System.Reflection.MonoEvent } DEFINE_IL2CPP_ARG_TYPE(System::Reflection::MonoEvent*, "System.Reflection", "MonoEvent"); #pragma pack(pop)
47.535714
131
0.737979
Futuremappermydud
9da3164473305d69ce932562dccda848c548127b
2,257
cpp
C++
examples/timeclient/main.cpp
katreniak/cppwamp
b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9
[ "BSL-1.0" ]
39
2015-04-04T00:29:47.000Z
2021-06-27T11:25:38.000Z
examples/timeclient/main.cpp
katreniak/cppwamp
b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9
[ "BSL-1.0" ]
115
2015-04-04T01:59:32.000Z
2020-12-04T09:23:09.000Z
examples/timeclient/main.cpp
katreniak/cppwamp
b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9
[ "BSL-1.0" ]
8
2015-05-04T06:24:55.000Z
2020-11-11T12:38:46.000Z
/*------------------------------------------------------------------------------ Copyright Butterfly Energy Systems 2014-2015. 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) ------------------------------------------------------------------------------*/ #include <ctime> #include <iostream> #include <cppwamp/conversion.hpp> #include <cppwamp/corosession.hpp> #include <cppwamp/json.hpp> #include <cppwamp/tcp.hpp> #include <cppwamp/unpacker.hpp> const std::string realm = "cppwamp.demo.time"; const std::string address = "localhost"; const short port = 12345; //------------------------------------------------------------------------------ namespace wamp { // Convert a std::tm to/from an object variant. template <typename TConverter> void convert(TConverter& conv, std::tm& t) { conv ("sec", t.tm_sec) ("min", t.tm_min) ("hour", t.tm_hour) ("mday", t.tm_mday) ("mon", t.tm_mon) ("year", t.tm_year) ("wday", t.tm_wday) ("yday", t.tm_yday) ("isdst", t.tm_isdst); } } //------------------------------------------------------------------------------ void onTimeTick(std::tm time) { std::cout << "The current time is: " << std::asctime(&time) << "\n"; } //------------------------------------------------------------------------------ int main() { using namespace wamp; AsioService iosvc; auto tcp = connector<Json>(iosvc, TcpHost(address, port)); auto session = CoroSession<>::create(iosvc, tcp); boost::asio::spawn(iosvc, [&](boost::asio::yield_context yield) { session->connect(yield); session->join(Realm(realm), yield); auto result = session->call(Rpc("get_time"), yield); auto time = result[0].to<std::tm>(); std::cout << "The current time is: " << std::asctime(&time) << "\n"; session->subscribe(Topic("time_tick"), wamp::basicEvent<std::tm>(&onTimeTick), yield); }); iosvc.run(); return 0; }
31.347222
80
0.464333
katreniak
9da6da40cf9dd8ffb28ba785db0f753a1044fe51
705
hpp
C++
android-28/android/hardware/Camera_Face.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/hardware/Camera_Face.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/hardware/Camera_Face.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" namespace android::graphics { class Point; } namespace android::graphics { class Rect; } namespace android::hardware { class Camera_Face : public JObject { public: // Fields jint id(); android::graphics::Point leftEye(); android::graphics::Point mouth(); android::graphics::Rect rect(); android::graphics::Point rightEye(); jint score(); // QJniObject forward template<typename ...Ts> explicit Camera_Face(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} Camera_Face(QJniObject obj); // Constructors Camera_Face(); // Methods }; } // namespace android::hardware
18.552632
152
0.678014
YJBeetle
9da881ed814c4b32819b7c8327d3e2fefb82a7de
1,426
hh
C++
Mu2eUtilities/inc/MedianCalculator.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
Mu2eUtilities/inc/MedianCalculator.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Mu2eUtilities/inc/MedianCalculator.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
#ifndef Mu2eUtilities_MedianCalculator_hh #define Mu2eUtilities_MedianCalculator_hh // // Original author G. Pezzullo // // this class is intended to be used for evaluaitng the median // from a set of elements that are stored internally in a vector // #include <vector> //#include <utility> #include <numeric> #include <functional> namespace mu2e { class MedianCalculator{ struct MedianData { MedianData(float Val, float Wg): val(Val), wg(Wg){} float val; float wg; }; struct MedianDatacomp : public std::binary_function<MedianData,MedianData,bool> { bool operator()(MedianData const& p1, MedianData const& p2) { return p1.val < p2.val; } }; public: MedianCalculator(size_t nToReserve=0){ _vec.reserve(nToReserve); } float weightedMedian(); float unweightedMedian(); inline void push(float value, float weight=1){ _vec.emplace_back(MedianData(value, weight)); _needsSorting = true; _totalWeight += weight; } inline size_t size(){ return _vec.size(); } private: std::vector<MedianData> _vec; bool _needsSorting = true; float _weightedMedian = 0; float _unweightedMedian = 0; float _totalWeight = 0; }; } // namespace mu2e #endif /* Mu2eUtilities_MedianCalculator_hh */
27.423077
93
0.624123
bonventre
9db6a56b0657dcd0b119e4a3432787a1841df0c1
714
hpp
C++
OfferReview/OfferReview/01_38/17_Print1ToMaxOfNDigits/Print1ToMaxOfNDigits_1.hpp
chm994483868/HMDailyLearningRecord
95ff0a5347927ce4527bcdd70374e5be22bfc60d
[ "MIT" ]
2
2021-06-26T08:07:04.000Z
2021-08-03T06:05:40.000Z
OfferReview/OfferReview/01_38/17_Print1ToMaxOfNDigits/Print1ToMaxOfNDigits_1.hpp
chm994483868/HMDailyLearningRecord
95ff0a5347927ce4527bcdd70374e5be22bfc60d
[ "MIT" ]
null
null
null
OfferReview/OfferReview/01_38/17_Print1ToMaxOfNDigits/Print1ToMaxOfNDigits_1.hpp
chm994483868/HMDailyLearningRecord
95ff0a5347927ce4527bcdd70374e5be22bfc60d
[ "MIT" ]
null
null
null
// // Print1ToMaxOfNDigits_1.hpp // OfferReview // // Created by CHM on 2020/11/3. // Copyright © 2020 CHM. All rights reserved. // #ifndef Print1ToMaxOfNDigits_1_hpp #define Print1ToMaxOfNDigits_1_hpp #include <stdio.h> #include <memory> #include <vector> using namespace std; namespace Print1ToMaxOfNDigits_1 { // 17:打印 1 到最大的 n 位数 // 题目:输入数字 n,按顺序打印出从 1 最大的 n 位十进制数。比如输入 3,则 // 打印出 1、2、3 一直到最大的 3 位数即 999。 void printNumber(char* number); bool increment(char* number); void print1ToMaxOfNDigits_1(int n); void print1ToMaxOfNDigitsRecursively(char* number, int length, int index); void print1ToMaxOfNDigits_2(int n); // 测试代码 void Test(int n); void Test(); } #endif /* Print1ToMaxOfNDigits_1_hpp */
18.307692
74
0.738095
chm994483868
9db9d69a28ac2392dc1afce1133a0f1abd1270e7
5,834
cpp
C++
super-knowledge-platform/skpClient/skpClient/trunk/src/main/skp_mainwindow.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
super-knowledge-platform/skpClient/skpClient/trunk/src/main/skp_mainwindow.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
super-knowledge-platform/skpClient/skpClient/trunk/src/main/skp_mainwindow.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
#include "skp_mainwindow.h" #include "ui_skp_mainwindow.h" #include "NcFramelessHelper.h" #include "skp_socket_test_widget.h" #include "skp_skin_themed_widget.h" #include "skp_file_widget.h" #include "MOption.h" #ifdef Q_OS_WIN #include <qwinfunctions.h> #endif #include <QSystemTrayIcon> #include <QMenu> #include <QLabel> #include <QPainter> SkpMainWindow::SkpMainWindow(QWidget *parent) : QMainWindow(parent), SkpChangeWidget(this), SkpThemedBase(this), ui(new Ui::SkpMainWindow), m_framelessHelper(NULL), m_socketTestWidget(NULL) { ui->setupUi(this); m_framelessHelper = new NcFramelessHelper; m_framelessHelper->setWidgetMovable(true); m_framelessHelper->setWidgetResizable(true); m_framelessHelper->activateOn(this); skp_set_move(m_framelessHelper); ui->centralWidget->setContentsMargins(5,5,5,5); #ifdef Q_OS_WIN //QtWin::enableBlurBehindWindow(this); #endif setWindowTitle(tr("SKP")); ui->titleWidget->setTitle(tr("SKP")); ui->titleWidget->setFixedHeight(30); ui->titleWidget->setShowButton(skin_button | min_button | max_button | close_button); connect(ui->titleWidget, SIGNAL(skp_sig_skin()), this, SLOT(skp_on_skin())); connect(ui->titleWidget, SIGNAL(skp_sig_min()), this, SLOT(skp_on_min())); connect(ui->titleWidget, SIGNAL(skp_sig_max()), this, SLOT(skp_on_max())); connect(ui->titleWidget, SIGNAL(skp_sig_close()), this, SLOT(skp_on_close())); connect(ui->tabBar, SIGNAL(currentChanged(int)), ui->stackedWidget, SLOT(setCurrentIndex(int))); m_fileWidget = new SkpFileWidget(this); addTabWidget(m_fileWidget, QPixmap(":/ble_live.png"), tr("File")); //m_socketTestWidget = new SkpSocketTestWidget(this); //addTabWidget(m_socketTestWidget, QPixmap(":/ble_live.png"), tr("Test")); //m_socketTestWidget_2 = new SkpSocketTestWidget(this); //addTabWidget(m_socketTestWidget_2, QPixmap(":/ble_live.png"), tr("test_2")); //setWindowIcon(QIcon(":/logo.png")); m_systemTrayIcon = new QSystemTrayIcon(QIcon(":/logo.png"), this); connect(m_systemTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(skp_on_activated(QSystemTrayIcon::ActivationReason))); QString versionStr = QString(" version: %1").arg("skp test"); m_statusLabel = new QLabel(versionStr, this); m_statusLabel->setFrameStyle(QFrame::NoFrame); ui->statusBar->addWidget(m_statusLabel); ui->statusBar->setStyleSheet(QString("QStatusBar::item{border: 0px}")); } SkpMainWindow::~SkpMainWindow() { delete ui; } void SkpMainWindow::skp_show() { m_systemTrayIcon->show(); show(); } void SkpMainWindow::mouseDoubleClickEvent(QMouseEvent *mouseEvent) { QMainWindow::mouseDoubleClickEvent(mouseEvent); skp_change_doubleClick(); } void SkpMainWindow::paintEvent(QPaintEvent *paintEvent) { m_titleHeight = ui->titleWidget->height() + ui->tabBar->height() + 10; m_linearHeight = 0; m_statusHeight = ui->statusBar->height(); //QMainWindow::paintEvent(paintEvent); //QPainter p(this); //QMainWindow::paintEvent(paintEvent); skp_draw_themed(); #ifdef Q_OS_LINUX ///处理在linux下状态栏不能透明 QColor cachedColor; QString themeType = MOption::instance()->option("WindowBGPixmapType", "theme").toString(); if(themeType == "bitmap") { cachedColor = MOption::instance()->option(OPTION_AVERAGE_COLOR, OPTION_GROUP_Theme).value<QColor>(); } else { cachedColor = MOption::instance()->option("WindowBGColor", "theme").value<QColor>(); } int aeroTransparent = MOption::instance()->option("AeroTransparent", "theme").toInt(); cachedColor.setAlpha(aeroTransparent); QPalette palette; palette.setColor(QPalette::Background, cachedColor); //palette.setBrush(QPalette::Background, QBrush(QPixmap(":/background.png"))); ui->statusBar->setPalette(palette); #endif } void SkpMainWindow::showEvent(QShowEvent *showEvent) { if(isVisible()) repaint(); //repaint(); QMainWindow::showEvent(showEvent); } void SkpMainWindow::resizeEvent(QResizeEvent *resizeEvent) { if(isVisible()) repaint(); //repaint(); QMainWindow::resizeEvent(resizeEvent); } void SkpMainWindow::changeEvent(QEvent *event) { //if(isVisible()) repaint(); //repaint(); QMainWindow::changeEvent(event); } void SkpMainWindow::skp_on_skin() { SkpSkinThemedWidget *skinThemed = new SkpSkinThemedWidget(); skinThemed->show(); } void SkpMainWindow::skp_on_min() { skp_change_min(true); } void SkpMainWindow::skp_on_max() { skp_change_max(); } void SkpMainWindow::skp_on_close() { skp_change_close(SKP::Type_Quit); } void SkpMainWindow::skp_on_doubleClick() { skp_change_doubleClick(); } void SkpMainWindow::addTabWidget(QWidget *widget, const QPixmap &pixmap, const QString &text) { ui->stackedWidget->addWidget(widget); ui->tabBar->addTab(pixmap, text); } void SkpMainWindow::skp_on_Show() { skp_change_show(); } void SkpMainWindow::skp_on_activated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Context: { QMenu menu; menu.addAction(tr("show"), this, SLOT(skp_on_Show())); menu.addAction(tr("hide"), this, SLOT(skp_on_min())); menu.addAction(tr("quit"), this, SLOT(skp_on_close())); QPoint globalPoint = QCursor::pos(); menu.exec(globalPoint); } break; case QSystemTrayIcon::DoubleClick: case QSystemTrayIcon::Trigger: default: skp_on_Show(); break; } }
28.458537
109
0.671752
yefy
9dbb29a715b3eb20d80a66ea066c72623c884d7c
41,912
cc
C++
test/src/test_hirescamera.cc
tim-schoenmackers/hippo
ce381551898b4eba7ca73fc64bf138b6ba93a66c
[ "MIT" ]
5
2020-08-28T02:43:00.000Z
2020-09-23T15:03:13.000Z
test/src/test_hirescamera.cc
tim-schoenmackers/hippo
ce381551898b4eba7ca73fc64bf138b6ba93a66c
[ "MIT" ]
1
2021-07-16T01:08:56.000Z
2021-09-17T17:41:33.000Z
test/src/test_hirescamera.cc
tim-schoenmackers/hippo
ce381551898b4eba7ca73fc64bf138b6ba93a66c
[ "MIT" ]
5
2019-11-01T23:48:04.000Z
2022-02-18T07:24:49.000Z
// Copyright 2019 HP Development Company, L.P. // SPDX-License-Identifier: MIT #include <windows.h> // for Sleep() #include <cstdio> #include <cstring> #include <cstdlib> #include "include/hirescamera.h" extern const char wsAddress[]; extern const uint32_t wsPort; extern void print_error(uint64_t err); extern void print_error(uint64_t err, const char *msg); extern void print_device_info(const hippo::DeviceInfo &info); void printAutoOrFixed(const hippo::AutoOrFixed &param); void printCameraSettings(const hippo::CameraSettings &cs); void printCameraKeystone(const hippo::CameraKeystone &ks); void printCameraKeystoneTable(const hippo::CameraKeystoneTable &ks); void printKeystoneTableEntries(const hippo::CameraKeystoneTableEntries &entries, const uint32_t &num_entries); void printCameraStatus(const hippo::CameraDeviceStatus &camera_status); void printCameraLEDState(const hippo::CameraLedState *state); void printCameraResolution(const hippo::CameraResolution &res); void printPowerLineFrequency(const hippo::PowerLineFrequency &param); void hirescamera_notification(const hippo::HiResCameraNotificationParam &param, void *data); extern uint64_t TestCameraStreams(hippo::HippoCamera *cam, hippo::CameraStreams st); uint64_t TestHiResCamera(hippo::HiResCamera *hirescamera) { uint64_t err; fprintf(stderr, "##################################\n"); fprintf(stderr, " Now Testing HiRes Camera\n"); fprintf(stderr, "##################################\n"); ADD_FILE_TO_MAP(); // will add this file to the file/error map // subscribe uint32_t num_subscribe = 0; if (err = hirescamera->subscribe(&hirescamera_notification, reinterpret_cast<void*>(hirescamera), &num_subscribe)) { print_error(err); } else { fprintf(stderr, "hirescamera.subscribe: count: %d\n", num_subscribe); } bool bConnected; if (err = hirescamera->is_device_connected(&bConnected)) { return err; } if (bConnected) { fprintf(stderr, "Hirescamera is connected\n"); } else { fprintf(stderr, "No hirescamera is connected -- not running test\n"); return MAKE_HIPPO_ERROR(hippo::HIPPO_DEVICE, hippo::HIPPO_DEV_NOT_FOUND); } // open uint32_t open_count = 0; if (err = hirescamera->open(&open_count)) { return err; } fprintf(stderr, "hirescamera.open(): open_count: %d\n", open_count); // test all streams combinations hippo::CameraStreams st = { 1 }; if (err = TestCameraStreams(hirescamera, st)) { print_error(err); } // camera_settings hippo::CameraSettings cs_1, cs_2; if (err = hirescamera->camera_settings(&cs_1)) { print_error(err, "hirescamera.camera_settings get"); } else { printCameraSettings(cs_1); } bool bCameraSupportsTest = true; // Camera LED State hippo::CameraLedState state1, state2; // get current state if (err = hirescamera->led_state(&state1)) { print_error(err); // sprout camera doesn't support this function - don't error out if (hippo::HippoErrorCode(err) == hippo::HIPPO_FUNC_NOT_AVAILABLE) { bCameraSupportsTest = false; } else { return err; } } else { printCameraLEDState(&state1); } if (bCameraSupportsTest) { // turn the states to off state2.capture = hippo::CameraLedStateEnum::off; state2.streaming = hippo::CameraLedStateEnum::off; if (err = hirescamera->led_state(state2)) { print_error(err); } else { printCameraLEDState(&state2); } // now re-set the states if (err = hirescamera->led_state(state1, &state2)) { print_error(err); } else { printCameraLEDState(&state2); } } hippo::CameraDeviceStatus camera_status; if (err = hirescamera->device_status(&camera_status)) { print_error(err); } else { printCameraStatus(camera_status); } bCameraSupportsTest = true; // Camera Keystone Table hippo::CameraKeystoneTable kst1, kst2; // get current PLF if (err = hirescamera->keystone_table(&kst1)) { print_error(err); // sprout camera doesn't support this function - don't error out if (hippo::HippoErrorCode(err) == hippo::HIPPO_FUNC_NOT_AVAILABLE) { bCameraSupportsTest = false; } else { return err; } } else { printCameraKeystoneTable(kst1); } if (bCameraSupportsTest) { // change the table if (static_cast<uint32_t>(kst1) < 4) { kst2 = hippo::CameraKeystoneTable::RAM; } else { kst2 = hippo::CameraKeystoneTable::DEFAULT; } if (err = hirescamera->keystone_table(kst2)) { print_error(err); } else { printCameraKeystoneTable(kst2); } // now re-set the states if (err = hirescamera->keystone_table(kst1, &kst2)) { print_error(err); } else { printCameraKeystoneTable(kst2); } } bCameraSupportsTest = true; // Camera Power Line Frequency hippo::PowerLineFrequency p1, p2; // get current PLF if (err = hirescamera->power_line_frequency(&p1)) { print_error(err); // sprout camera doesn't support this function - don't error out if (hippo::HippoErrorCode(err) == hippo::HIPPO_FUNC_NOT_AVAILABLE) { bCameraSupportsTest = false; } else { return err; } } else { printPowerLineFrequency(p1); } if (bCameraSupportsTest) { // change the frequency if (p1 == hippo::PowerLineFrequency::disabled) { p2 = hippo::PowerLineFrequency::hz_60; } else { p2 = hippo::PowerLineFrequency::disabled; } if (err = hirescamera->power_line_frequency(p2)) { print_error(err); } else { printPowerLineFrequency(p2); } // now re-set the states if (err = hirescamera->power_line_frequency(p1, &p2)) { print_error(err); } else { printPowerLineFrequency(p2); } } hippo::CameraResolution res, parent; if (err = hirescamera->streaming_resolution(&res)) { print_error(err); } else { fprintf(stderr, "Current Streaming "); printCameraResolution(res); } if (err = hirescamera->parent_resolution(&res)) { print_error(err); } else { fprintf(stderr, "Parent Resolution of Current "); printCameraResolution(res); } res.width = 2176; res.height = 1448; res.fps = 25; if (err = hirescamera->parent_resolution(res, &parent)) { print_error(err); } else { fprintf(stderr, "Parent Resolution of 2176 x 1448 @25hz is: "); printCameraResolution(parent); } bCameraSupportsTest = true; // keystone table entries hippo::CameraKeystoneTable kstable; hippo::CameraKeystoneTableEntries ksTableEntries, ksTableEntries2; uint32_t num_entries1 = 0, num_entries2 = 0; memset(&ksTableEntries, 0, sizeof(hippo::CameraKeystoneTableEntries)); memset(&ksTableEntries2, 0, sizeof(hippo::CameraKeystoneTableEntries)); // lets get the items in the ram keystone table kstable = hippo::CameraKeystoneTable::RAM; if (err = hirescamera->keystone_table_entries(kstable, &ksTableEntries, &num_entries1)) { print_error(err); // sprout camera doesn't support this function - don't error out if (hippo::HippoErrorCode(err) == hippo::HIPPO_FUNC_NOT_AVAILABLE) { bCameraSupportsTest = false; } else { return err; } } else { printKeystoneTableEntries(ksTableEntries, num_entries1); } if (bCameraSupportsTest) { hippo::CameraResolution resolutions[2]; resolutions[0].width = 640; resolutions[0].height = 480; resolutions[0].fps = 60; resolutions[1].width = 4352; resolutions[1].height = 3264; resolutions[1].fps = 6; fprintf(stderr, "Keystone_table_entries with resolution parameters:\n"); if (err = hirescamera->keystone_table_entries(kstable, resolutions, 2, &ksTableEntries2, &num_entries2)) { print_error(err); } else { printKeystoneTableEntries(ksTableEntries2, num_entries2); } // get a backup if (err = hirescamera->keystone_table_entries(kstable, &ksTableEntries2, &num_entries2)) { print_error(err); } else { printKeystoneTableEntries(ksTableEntries, num_entries1); } // now change the values of the first copy and set if (num_entries1 > 0) { for (uint32_t i = 0; i < num_entries1; i++) { ksTableEntries.entries[i].value.bottom_left.x = 101; ksTableEntries.entries[i].value.bottom_right.y = 101; ksTableEntries.entries[i].value.top_left.x = 415; ksTableEntries.entries[i].value.top_left.y = 415; ksTableEntries.entries[i].value.bottom_right.x = -101; ksTableEntries.entries[i].value.bottom_right.y = -101; ksTableEntries.entries[i].value.top_right.x = -415; ksTableEntries.entries[i].value.top_right.y = 415; } } // set the new values if (err = hirescamera->keystone_table_entries(ksTableEntries, num_entries1)) { print_error(err); } else { // free the allocated memory from the get above hirescamera->free_keystone_table_entries(&ksTableEntries, num_entries1); // get the current (hopefully new) values if (err = hirescamera->keystone_table_entries(kstable, &ksTableEntries, &num_entries1)) { print_error(err); } else { // wait for notification to print first Sleep(1000); // print the new values fprintf(stderr, "Got keystone entries:\n"); printKeystoneTableEntries(ksTableEntries, num_entries1); } } // free the items gotten above hirescamera->free_keystone_table_entries(&ksTableEntries, num_entries1); // set the old values back, and get the current values at the same time if (err = hirescamera->keystone_table_entries(ksTableEntries2, num_entries2, &ksTableEntries, &num_entries1)) { print_error(err); } else { // wait for notification to print first Sleep(1000); // print the newly gotten values printKeystoneTableEntries(ksTableEntries, num_entries1); } // and finally free all the memory hirescamera->free_keystone_table_entries(&ksTableEntries2, num_entries2); } hirescamera->free_keystone_table_entries(&ksTableEntries, num_entries1); // we can avoid sending exposure, gain and wb by setting them to TYPE_NONE // but so far we can not do the same with the bool types. // SR: Is this even useful??? cs_1.exposure.type = hippo::AutoOrFixedType::TYPE_NONE; if (err = hirescamera->camera_settings(cs_1)) { print_error(err, "hirescamera.camera_settings set"); } else { fprintf(stderr, "hirescamera.camera_settings set\n"); } cs_1.exposure.type = hippo::AutoOrFixedType::TYPE_AUTO; if (err = hirescamera->camera_settings(cs_1, &cs_2)) { print_error(err, "hirescamera.camera_settings set get"); } else { printCameraSettings(cs_2); } bool bool_set, bool_get; // auto_exposure if (err = hirescamera->auto_exposure(&bool_get)) { print_error(err, "hirescamera.auto_exposure"); } else { fprintf(stderr, "hirescamera.auto_exposure(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->auto_exposure(bool_set)) { print_error(err, "hirescamera.auto_exposure"); } else { fprintf(stderr, "hirescamera.auto_exposure(%d)\n", bool_set); } if (err = hirescamera->auto_exposure(&bool_get)) { print_error(err, "hirescamera.auto_exposure"); } else { fprintf(stderr, "hirescamera.auto_exposure(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->auto_exposure(bool_set, &bool_get)) { print_error(err, "hirescamera.auto_exposure"); } else { fprintf(stderr, "hirescamera.auto_exposure(%d): %d\n", bool_set, bool_get); } // auto_gain if (err = hirescamera->auto_gain(&bool_get)) { print_error(err, "hirescamera.auto_gain"); } else { fprintf(stderr, "hirescamera.auto_gain(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->auto_gain(bool_set)) { print_error(err, "hirescamera.auto_gain"); } else { fprintf(stderr, "hirescamera.auto_gain(%d)\n", bool_set); } if (err = hirescamera->auto_gain(&bool_get)) { print_error(err, "hirescamera.auto_gain"); } else { fprintf(stderr, "hirescamera.auto_gain(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->auto_gain(bool_set, &bool_get)) { print_error(err, "hirescamera.auto_gain"); } else { fprintf(stderr, "hirescamera.auto_gain(%d): %d\n", bool_set, bool_get); } // auto_white_balance if (err = hirescamera->auto_white_balance(&bool_get)) { print_error(err, "hirescamera.auto_white_balance"); } else { fprintf(stderr, "hirescamera.auto_white_balance(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->auto_white_balance(bool_set)) { print_error(err, "hirescamera.auto_white_balance"); } else { fprintf(stderr, "hirescamera.auto_white_balance(%d)\n", bool_set); } if (err = hirescamera->auto_white_balance(&bool_get)) { print_error(err, "hirescamera.auto_white_balance"); } else { fprintf(stderr, "hirescamera.auto_white_balance(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->auto_white_balance(bool_set, &bool_get)) { print_error(err, "hirescamera.auto_white_balance"); } else { fprintf(stderr, "hirescamera.auto_white_balance(%d): %d\n", bool_set, bool_get); } // camera_index uint32_t index; if (err = hirescamera->camera_index(&index)) { print_error(err, "hirescamera.camera_index"); } else { fprintf(stderr, "hirescamera.camera_index(): %d\n", index); } // defaultConfig hippo::CameraConfig cf; hippo::CameraMode mode = hippo::CameraMode::MODE_4416x3312; if (err = hirescamera->default_config(mode, &cf)) { print_error(err, "default_config"); } else { fprintf(stderr, "hirescamera.default_config(): exposure: %d, fps: %d, gain: %d, " "mode: %d, RGB: [%d, %d, %d]\n", cf.exposure, cf.fps, cf.gain, static_cast<uint32_t>(cf.mode), cf.white_balance.red, cf.white_balance.green, cf.white_balance.blue); } // exposure uint16_t set_exp, get_exp; if (err = hirescamera->exposure(&get_exp)) { print_error(err, "hirescamera.exposure"); } else { fprintf(stderr, "hirescamera.exposure(): %d\n", get_exp); } set_exp = get_exp + 1; if (err = hirescamera->exposure(set_exp)) { print_error(err, "hirescamera.exposure"); } else { fprintf(stderr, "hirescamera.exposure(%d)\n", set_exp); } if (err = hirescamera->exposure(&get_exp)) { print_error(err, "hirescamera.exposure"); } else { fprintf(stderr, "hirescamera.exposure(): %d\n", get_exp); } set_exp = get_exp - 1; if (err = hirescamera->exposure(set_exp, &get_exp)) { print_error(err, "hirescamera.exposure"); } else { fprintf(stderr, "hirescamera.exposure(%d): %d\n", set_exp, get_exp); } if (err = hirescamera->auto_exposure(true)) { print_error(err, "hirescamera.auto_exposure"); } else { fprintf(stderr, "hirescamera.auto_exposure(%d)\n", true); } // factory_default if (err = hirescamera->factory_default()) { print_error(err, "hirescamera.factory_default"); } // flip_frame if (err = hirescamera->flip_frame(&bool_get)) { print_error(err, "hirescamera.flip_frame"); } else { fprintf(stderr, "hirescamera.flip_frame(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->flip_frame(bool_set)) { print_error(err, "hirescamera.flip_frame"); } else { fprintf(stderr, "hirescamera.flip_frame(%d)\n", bool_set); } if (err = hirescamera->flip_frame(&bool_get)) { print_error(err, "hirescamera.flip_frame"); } else { fprintf(stderr, "hirescamera.flip_frame(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->flip_frame(bool_set, &bool_get)) { print_error(err, "hirescamera.flip_frame"); } else { fprintf(stderr, "hirescamera.flip_frame(%d): %d\n", bool_set, bool_get); } // gain uint16_t set_gain, get_gain; if (err = hirescamera->gain(&get_gain)) { print_error(err, "hirescamera.gain"); } else { fprintf(stderr, "hirescamera.gain(): %d\n", get_gain); } set_gain = get_gain - 1; if (err = hirescamera->gain(set_gain)) { print_error(err, "hirescamera.gain"); } else { fprintf(stderr, "hirescamera.gain(%d)\n", set_gain); } if (err = hirescamera->gain(&get_gain)) { print_error(err, "hirescamera.gain"); } else { fprintf(stderr, "hirescamera.gain(): %d\n", get_gain); } set_gain = get_gain + 1; if (err = hirescamera->gain(set_gain, &get_gain)) { print_error(err, "hirescamera.gain"); } else { fprintf(stderr, "hirescamera.gain(%d): %d\n", set_gain, get_gain); } if (err = hirescamera->auto_gain(true)) { print_error(err, "hirescamera.auto_gain"); } else { fprintf(stderr, "hirescamera.auto_gain(%d)\n", true); } // gamma_correction if (err = hirescamera->gamma_correction(&bool_get)) { print_error(err, "hirescamera.gamma_correction"); } else { fprintf(stderr, "hirescamera.gamma_correction(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->gamma_correction(bool_set)) { print_error(err, "hirescamera.gamma_correction"); } else { fprintf(stderr, "hirescamera.gamma_correction(%d)\n", bool_set); } if (err = hirescamera->gamma_correction(&bool_get)) { print_error(err, "hirescamera.gamma_correction"); } else { fprintf(stderr, "hirescamera.gamma_correction(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->gamma_correction(bool_set, &bool_get)) { print_error(err, "hirescamera.gamma_correction"); } else { fprintf(stderr, "hirescamera.gamma_correction(%d): %d\n", bool_set, bool_get); } // info hippo::DeviceInfo info; if (err = hirescamera->info(&info)) { print_error(err, "hirescamera.info"); } else { print_device_info(info); } // lens_color_shading if (err = hirescamera->lens_color_shading(&bool_get)) { print_error(err, "hirescamera.lens_color_shading"); } else { fprintf(stderr, "hirescamera.lens_color_shading(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->lens_color_shading(bool_set)) { print_error(err, "hirescamera.lens_color_shading"); } else { fprintf(stderr, "hirescamera.lens_color_shading(%d)\n", bool_set); } if (err = hirescamera->lens_color_shading(&bool_get)) { print_error(err, "hirescamera.lens_color_shading"); } else { fprintf(stderr, "hirescamera.lens_color_shading(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->lens_color_shading(bool_set, &bool_get)) { print_error(err, "hirescamera.lens_color_shading"); } else { fprintf(stderr, "hirescamera.lens_color_shading(%d): %d\n", bool_set, bool_get); } // lens_shading if (err = hirescamera->lens_shading(&bool_get)) { print_error(err, "hirescamera.lens_shading"); } else { fprintf(stderr, "hirescamera.lens_shading(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->lens_shading(bool_set)) { print_error(err, "hirescamera.lens_shading"); } else { fprintf(stderr, "hirescamera.lens_shading(%d)\n", bool_set); } if (err = hirescamera->lens_shading(&bool_get)) { print_error(err, "hirescamera.lens_shading"); } else { fprintf(stderr, "hirescamera.lens_shading(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->lens_shading(bool_set, &bool_get)) { print_error(err, "hirescamera.lens_shading"); } else { fprintf(stderr, "hirescamera.lens_shading(%d): %d\n", bool_set, bool_get); } // mirror_frame if (err = hirescamera->mirror_frame(&bool_get)) { print_error(err, "hirescamera.mirror_frame"); } else { fprintf(stderr, "hirescamera.mirror_frame(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->mirror_frame(bool_set)) { print_error(err, "hirescamera.mirror_frame"); } else { fprintf(stderr, "hirescamera.mirror_frame(%d)\n", bool_set); } if (err = hirescamera->mirror_frame(&bool_get)) { print_error(err, "hirescamera.mirror_frame"); } else { fprintf(stderr, "hirescamera.mirror_frame(): %d\n", bool_get); } bool_set = bool_get ? false : true; if (err = hirescamera->mirror_frame(bool_set, &bool_get)) { print_error(err, "hirescamera.mirror_frame"); } else { fprintf(stderr, "hirescamera.mirror_frame(%d): %d\n", bool_set, bool_get); } //// strobe // hippo::Strobe str; // str.exposure = 166; // str.frames = 10; // str.gain = 0; // if (err = hirescamera->strobe(str)) { // print_error(err); // } // fprintf(stderr, "hirescamera.strobe(166,1,0)\n"); // white_balance hippo::Rgb wb_get, wb_set; if (err = hirescamera->white_balance(&wb_get)) { print_error(err, "hirescamera.mirror_frame"); } else { fprintf(stderr, "hirescamera.white_balance(): r:%d, g:%d, b:%d\n", wb_get.red, wb_get.green, wb_get.blue); } wb_set.red = 2020; wb_set.green = 2020; wb_set.blue = 2020; if (err = hirescamera->white_balance(wb_set)) { print_error(err, "hirescamera.white_balance"); } else { fprintf(stderr, "hirescamera.white_balance(r:%d, g:%d, b:%d)\n", wb_set.red, wb_set.green, wb_set.blue); } if (err = hirescamera->white_balance(&wb_get)) { print_error(err, "hirescamera.white_balance"); } else { fprintf(stderr, "hirescamera.white_balance(): r:%d, g:%d, b:%d\n", wb_get.red, wb_get.green, wb_get.blue); } wb_set.red = 1024; wb_set.green = 1025; wb_set.blue = 1026; if (err = hirescamera->white_balance(wb_set, &wb_get)) { print_error(err, "hirescamera.white_balance"); } else { fprintf(stderr, "hirescamera.white_balance(r:%d, g:%d, b:%d): " "r:%d, g:%d, b:%d\n", wb_set.red, wb_set.green, wb_set.blue, wb_get.red, wb_get.green, wb_get.blue); } if (err = hirescamera->auto_white_balance(true)) { print_error(err, "hirescamera.auto_white_balance"); } else { fprintf(stderr, "hirescamera.auto_white_balance(true)\n"); } // keystone (flick only) hippo::CameraKeystone ks_1, ks_2; if (err = hirescamera->keystone(&ks_1)) { print_error(err, "hirescamera.keystone get"); } else { printCameraKeystone(ks_1); } ks_1.value.top_left.x += 300; ks_1.value.top_left.y += 300; ks_1.enabled = true; if (err = hirescamera->keystone(ks_1)) { print_error(err, "hirescamera.keystone set"); } Sleep(500); // now get keystone to validate if (err = hirescamera->keystone(&ks_2)) { print_error(err, "hirescamera.keystone get"); } else { printCameraKeystone(ks_2); } Sleep(500); ks_1.value.top_left.x -= 300; ks_1.value.top_left.y -= 300; if (err = hirescamera->keystone(ks_1, &ks_2)) { print_error(err, "hirescamera.keystone set"); } else { printCameraKeystone(ks_2); } // brightness uint16_t set_brightness, get_brightness; if (err = hirescamera->brightness(&get_brightness)) { print_error(err, "hirescamera.brightness"); } else { fprintf(stderr, "hirescamera.brightness(): %d\n", get_brightness); } set_brightness = get_brightness - 1; if (err = hirescamera->brightness(set_brightness)) { print_error(err, "hirescamera.brightness"); } else { fprintf(stderr, "hirescamera.brightness(%d)\n", set_brightness); } if (err = hirescamera->brightness(&get_brightness)) { print_error(err, "hirescamera.brightness"); } else { fprintf(stderr, "hirescamera.brightness(): %d\n", get_brightness); } set_brightness = get_brightness + 1; if (err = hirescamera->brightness(set_brightness, &get_brightness)) { print_error(err, "hirescamera.brightness"); } else { fprintf(stderr, "hirescamera.brightness(%d): %d\n", set_brightness, get_brightness); } // contrast uint16_t set_contrast, get_contrast; if (err = hirescamera->contrast(&get_contrast)) { print_error(err, "hirescamera.contrast"); } else { fprintf(stderr, "hirescamera.contrast(): %d\n", get_contrast); } set_contrast = get_contrast - 1; if (err = hirescamera->contrast(set_contrast)) { print_error(err, "hirescamera.contrast"); } else { fprintf(stderr, "hirescamera.contrast(%d)\n", set_contrast); } if (err = hirescamera->contrast(&get_contrast)) { print_error(err, "hirescamera.contrast"); } else { fprintf(stderr, "hirescamera.contrast(): %d\n", get_contrast); } set_contrast = get_contrast + 1; if (err = hirescamera->contrast(set_contrast, &get_contrast)) { print_error(err, "hirescamera.contrast"); } else { fprintf(stderr, "hirescamera.contrast(%d): %d\n", set_contrast, get_contrast); } // saturation uint16_t set_saturation, get_saturation; if (err = hirescamera->saturation(&get_saturation)) { print_error(err, "hirescamera.saturation"); } else { fprintf(stderr, "hirescamera.saturation(): %d\n", get_saturation); } set_saturation = get_saturation - 1; if (err = hirescamera->saturation(set_saturation)) { print_error(err, "hirescamera.saturation"); } else { fprintf(stderr, "hirescamera.saturation(%d)\n", set_saturation); } if (err = hirescamera->saturation(&get_saturation)) { print_error(err, "hirescamera.saturation"); } else { fprintf(stderr, "hirescamera.saturation(): %d\n", get_saturation); } set_saturation = get_saturation + 1; if (err = hirescamera->saturation(set_saturation, &get_saturation)) { print_error(err, "hirescamera.saturation"); } else { fprintf(stderr, "hirescamera.saturation(%d): %d\n", set_saturation, get_saturation); } // sharpness uint16_t set_sharpness, get_sharpness; if (err = hirescamera->sharpness(&get_sharpness)) { print_error(err, "hirescamera.sharpness"); } else { fprintf(stderr, "hirescamera.sharpness(): %d\n", get_sharpness); } set_sharpness = get_sharpness - 1; if (err = hirescamera->sharpness(set_sharpness)) { print_error(err, "hirescamera.sharpness"); } else { fprintf(stderr, "hirescamera.sharpness(%d)\n", set_sharpness); } if (err = hirescamera->sharpness(&get_sharpness)) { print_error(err, "hirescamera.sharpness"); } else { fprintf(stderr, "hirescamera.sharpness(): %d\n", get_sharpness); } set_sharpness = get_sharpness + 1; if (err = hirescamera->sharpness(set_sharpness, &get_sharpness)) { print_error(err, "hirescamera.sharpness"); } else { fprintf(stderr, "hirescamera.sharpness(%d): %d\n", set_sharpness, get_sharpness); } // white_balance_temperature uint16_t set_white_balance_temperature, get_white_balance_temperature; if (err = hirescamera->white_balance_temperature(&get_white_balance_temperature)) { print_error(err, "hirescamera.white_balance_temperature"); } else { fprintf(stderr, "hirescamera.white_balance_temperature(): %d\n", get_white_balance_temperature); } set_white_balance_temperature = get_white_balance_temperature - 1; if (err = hirescamera->white_balance_temperature(set_white_balance_temperature)) { print_error(err, "hirescamera.white_balance_temperature"); } else { fprintf(stderr, "hirescamera.white_balance_temperature(%d)\n", set_white_balance_temperature); } if (err = hirescamera->white_balance_temperature(&get_white_balance_temperature)) { print_error(err, "hirescamera.white_balance_temperature"); } else { fprintf(stderr, "hirescamera.white_balance_temperature(): %d\n", get_white_balance_temperature); } set_white_balance_temperature = get_white_balance_temperature + 1; if (err = hirescamera->white_balance_temperature(set_white_balance_temperature, &get_white_balance_temperature)) { print_error(err, "hirescamera.white_balance_temperature"); } else { fprintf(stderr, "hirescamera.white_balance_temperature(%d): %d\n", set_white_balance_temperature, get_white_balance_temperature); } // reset if (err = hirescamera->reset()) { print_error(err, "hirescamera.reset"); } Sleep(5000); // close if (err = hirescamera->close(&open_count)) { return err; } else { fprintf(stderr, "hirescamera.close(): open_count: %d\n", open_count); } // unsubscribe if (err = hirescamera->unsubscribe(&num_subscribe)) { print_error(err); } else { fprintf(stderr, "hirescamera.unsubscribe(): count: %d\n", num_subscribe); } return 0LL; } void printAutoOrFixed(const hippo::AutoOrFixed &param) { switch (param.type) { case hippo::AutoOrFixedType::TYPE_AUTO: fprintf(stderr, "auto\n"); break; case hippo::AutoOrFixedType::TYPE_UINT: fprintf(stderr, "%d\n", param.value.value); break; case hippo::AutoOrFixedType::TYPE_RGB: fprintf(stderr, "r:%d, g:%d, b:%d\n", param.value.rgb.red, param.value.rgb.green, param.value.rgb.blue); break; case hippo::AutoOrFixedType::TYPE_MODE: fprintf(stderr, "OPS! we should not get notifications with TYPE_MODE\n"); break; default: fprintf(stderr, "OPS! Unknown type %d\n", param.type); } } void printPowerLineFrequency(const hippo::PowerLineFrequency &param) { switch (param) { case hippo::PowerLineFrequency::disabled: fprintf(stderr, "PowerLineFrequency: disabled\n"); break; case hippo::PowerLineFrequency::hz_50: fprintf(stderr, "PowerLineFrequency: 50 Hz\n"); break; case hippo::PowerLineFrequency::hz_60: fprintf(stderr, "PowerLineFrequency: 60 Hz\n"); break; default: fprintf(stderr, "OPS! Unknown PowerLineFrequency\n"); } } void printCameraSettings(const hippo::CameraSettings &cs) { fprintf(stderr, "-> CameraSettings\n"); fprintf(stderr, " \\-> exposure "); printAutoOrFixed(cs.exposure); fprintf(stderr, " \\-> gain "); printAutoOrFixed(cs.gain); fprintf(stderr, " \\-> white_balance "); printAutoOrFixed(cs.white_balance); fprintf(stderr, " \\-> flip_frame %d\n", cs.flip_frame); fprintf(stderr, " \\-> gamma_correction %d\n", cs.gamma_correction); fprintf(stderr, " \\-> lens_color_shading %d\n", cs.lens_color_shading); fprintf(stderr, " \\-> lens_shading %d\n", cs.lens_shading); fprintf(stderr, " \\-> mirror_frame %d\n", cs.mirror_frame); } void printCameraStatus(const hippo::CameraDeviceStatus &camera_status) { const char *CameraStatusEnum_str[ static_cast<uint32_t>(hippo::CameraStatus::error) + 1] = { "ok", "busy", "error", }; fprintf(stderr, "Camera Device Status:\n"); fprintf(stderr, " generic_get : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.generic_get)]); fprintf(stderr, " generic_set : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.generic_set)]); fprintf(stderr, " isp_colorbar : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.isp_colorbar)]); fprintf(stderr, " isp_function : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.isp_function)]); fprintf(stderr, " isp_fw_boot : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.isp_fw_boot)]); fprintf(stderr, " isp_reset : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.isp_reset)]); fprintf(stderr, " isp_restore : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.isp_restore)]); fprintf(stderr, " isp_videostream : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.isp_videostream)]); fprintf(stderr, " load_lenc_calibration : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.load_lenc_calibration)]); fprintf(stderr, " load_white_balance_calibration : %s\n", CameraStatusEnum_str[static_cast<uint32_t>( camera_status.load_white_balance_calibration)]); fprintf(stderr, " special_get : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.special_get)]); fprintf(stderr, " special_set : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.special_set)]); fprintf(stderr, " thermal_sensor_error : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.thermal_sensor_error)]); fprintf(stderr, " thermal_shutdown : %s\n", CameraStatusEnum_str[ static_cast<uint32_t>(camera_status.thermal_shutdown)]); } void printCameraLEDState(const hippo::CameraLedState *state) { const char *CameraLedStateEnum_str[ static_cast<uint32_t>(hippo::CameraLedStateEnum::automatic) + 1] = { "off", "low", "high", "auto", }; fprintf(stderr, "Camera LED State:\n"); fprintf(stderr, " Capture: %s\n", CameraLedStateEnum_str[static_cast<uint32_t>(state->capture)]); fprintf(stderr, " Streaming: %s\n", CameraLedStateEnum_str[static_cast<uint32_t>(state->streaming)]); } void printCameraKeystone(const hippo::CameraKeystone &ks) { fprintf(stderr, "-> Camera Keystone\n"); fprintf(stderr, " \\ -> Enabled: %i\n", ks.enabled); fprintf(stderr, " \\ -> Value\n"); fprintf(stderr, " \\ -> Bottom Left: (%i, %i)\n", ks.value.bottom_left.x, ks.value.bottom_left.y); fprintf(stderr, " \\ -> Bottom Right: (%i, %i)\n", ks.value.bottom_right.x, ks.value.bottom_right.y); fprintf(stderr, " \\ -> Top Left: (%i, %i)\n", ks.value.top_left.x, ks.value.top_left.y); fprintf(stderr, " \\ -> Top Right: (%i, %i)\n", ks.value.top_right.x, ks.value.top_right.y); } const char *keystoneTable_str[] = { "ram", "default", "flash_max_fov", "flash_fit_to_mat", }; void printCameraKeystoneTable(const hippo::CameraKeystoneTable &ks) { fprintf(stderr, "-> Camera Keystone Table\n"); fprintf(stderr, " \\ -> type: %s\n", keystoneTable_str[static_cast<uint32_t>(ks)]); } void printCameraKeystoneTableEntry(const hippo::CameraKeystoneTableEntry &ks) { fprintf(stderr, "-> Camera Keystone\n"); fprintf(stderr, " \\ -> Enabled: %i\n", ks.enabled); fprintf(stderr, " \\ -> Value\n"); fprintf(stderr, " \\ -> Bottom Left: (%i, %i)\n", ks.value.bottom_left.x, ks.value.bottom_left.y); fprintf(stderr, " \\ -> Bottom Right: (%i, %i)\n", ks.value.bottom_right.x, ks.value.bottom_right.y); fprintf(stderr, " \\ -> Top Left: (%i, %i)\n", ks.value.top_left.x, ks.value.top_left.y); fprintf(stderr, " \\ -> Top Right: (%i, %i)\n", ks.value.top_right.x, ks.value.top_right.y); fprintf(stderr, " \\ -> Resolution\n"); fprintf(stderr, " \\ -> (Width, Height, Fps): (%i, %i, %i)\n", ks.resolution.width, ks.resolution.height, ks.resolution.fps); } void printKeystoneTableEntries(const hippo::CameraKeystoneTableEntries &entries, const uint32_t &num_entries) { fprintf(stderr, "-> Camera Keystone Table: %s\n", keystoneTable_str[static_cast<uint32_t>(entries.type)]); for (uint32_t i = 0; i < num_entries; i++) { printCameraKeystoneTableEntry(entries.entries[i]); } } void printCameraResolution(const hippo::CameraResolution &res) { fprintf(stderr, "Resolution: (Width, Height, Fps): (%i, %i, %i)\n", res.width, res.height, res.fps); } void hirescamera_notification(const hippo::HiResCameraNotificationParam &param, void *data) { // and print the notification switch (param.type) { case hippo::HiResCameraNotification::on_close: fprintf(stderr, "[SIGNAL]: hirescamera.on_close\n"); break; case hippo::HiResCameraNotification::on_device_connected: fprintf(stderr, "[SIGNAL]: hirescamera.on_device_connected\n"); break; case hippo::HiResCameraNotification::on_device_disconnected: fprintf(stderr, "[SIGNAL]: hirescamera.on_device_disconnected\n"); break; case hippo::HiResCameraNotification::on_factory_default: fprintf(stderr, "[SIGNAL]: hirescamera.on_factory_default\n"); break; case hippo::HiResCameraNotification::on_open: fprintf(stderr, "[SIGNAL]: hirescamera.on_open\n"); break; case hippo::HiResCameraNotification::on_open_count: fprintf(stderr, "[SIGNAL]: hirescamera.on_open_count: %d\n", param.on_open_count); break; case hippo::HiResCameraNotification::on_resume: fprintf(stderr, "[SIGNAL]: hirescamera.on_resume\n"); break; case hippo::HiResCameraNotification::on_suspend: fprintf(stderr, "[SIGNAL]: hirescamera.on_suspend\n"); break; case hippo::HiResCameraNotification::on_sohal_disconnected: fprintf(stderr, "[SIGNAL]: hirescamera.on_sohal_disconnected\n"); break; case hippo::HiResCameraNotification::on_sohal_connected: fprintf(stderr, "[SIGNAL]: hirescamera.on_sohal_connected\n"); break; case hippo::HiResCameraNotification::on_exposure: fprintf(stderr, "[SIGNAL]: hirescamera.on_exposure: "); printAutoOrFixed(param.on_exposure); break; case hippo::HiResCameraNotification::on_brightness: fprintf(stderr, "[SIGNAL]: hirescamera.on_brightness: %d\n", param.on_brightness); break; case hippo::HiResCameraNotification::on_contrast: fprintf(stderr, "[SIGNAL]: hirescamera.on_contrast: %d\n", param.on_contrast); break; case hippo::HiResCameraNotification::on_flip_frame: fprintf(stderr, "[SIGNAL]: hirescamera.on_flip_frame: %d\n", param.on_flip_frame); break; case hippo::HiResCameraNotification::on_gain: fprintf(stderr, "[SIGNAL]: hirescamera.on_gain: "); printAutoOrFixed(param.on_gain); break; case hippo::HiResCameraNotification::on_gamma_correction: fprintf(stderr, "[SIGNAL]: hirescamera.on_gamma_correction: %d\n", param.on_gamma_correction); break; case hippo::HiResCameraNotification::on_keystone: fprintf(stderr, "[SIGNAL]: hirescamera.on_keystone\n"); printCameraKeystone(param.on_keystone); break; case hippo::HiResCameraNotification::on_keystone_table: fprintf(stderr, "[SIGNAL]: hirescamera.on_keystone_table\n"); printCameraKeystoneTable(param.on_keystone_table); break; case hippo::HiResCameraNotification::on_keystone_table_entries: fprintf(stderr, "[SIGNAL]: hirescamera.on_keystone_table_entries\n"); printKeystoneTableEntries(param.on_keystone_table_entries, param.num_keystone_table_entries); break; case hippo::HiResCameraNotification::on_led_state: fprintf(stderr, "[SIGNAL]: hirescamera.on_led_state:\n"); printCameraLEDState(&param.on_led_state); break; case hippo::HiResCameraNotification::on_lens_color_shading: fprintf(stderr, "[SIGNAL]: hirescamera.on_lens_color_shading: %d\n", param.on_lens_color_shading); break; case hippo::HiResCameraNotification::on_lens_shading: fprintf(stderr, "[SIGNAL]: hirescamera.on_lens_shading: %d\n", param.on_lens_shading); break; case hippo::HiResCameraNotification::on_mirror_frame: fprintf(stderr, "[SIGNAL]: hirescamera.on_mirror_frame: %d\n", param.on_mirror_frame); break; case hippo::HiResCameraNotification::on_power_line_frequency: fprintf(stderr, "[SIGNAL]: hirescamera.on_power_line_frequency\n"); printPowerLineFrequency(param.on_power_line_frequency); break; case hippo::HiResCameraNotification::on_strobe: fprintf(stderr, "[SIGNAL]: hirescamera.on_strobe\n"); break; case hippo::HiResCameraNotification::on_white_balance: fprintf(stderr, "[SIGNAL]: hirescamera.on_white_balance: "); printAutoOrFixed(param.on_white_balance); break; case hippo::HiResCameraNotification::on_saturation: fprintf(stderr, "[SIGNAL]: hirescamera.on_saturation: %d\n", param.on_saturation); break; case hippo::HiResCameraNotification::on_white_balance_temperature: fprintf(stderr, "[SIGNAL]: hirescamera.on_white_balance_temperature: %d\n", param.on_white_balance_temperature); break; case hippo::HiResCameraNotification::on_reset: fprintf(stderr, "[SIGNAL]: hirescamera.on_reset\n"); break; case hippo::HiResCameraNotification::on_sharpness: fprintf(stderr, "[SIGNAL]: hirescamera.on_sharpness: %d\n", param.on_sharpness); break; default: break; } #if 0 // sample on how to use the void *data parameter to pass objects (the // this pointer in this case) to the callback function uint64_t err = 0LL; hippo::HiResCamera *hirescamera = (hippo::HiResCamera*)data; bool bool_get; // in this case we just get auto_exposure if (err = hirescamera->auto_exposure(&bool_get)) { print_error(err); } fprintf(stderr, "[SIGNAL+] hirescamera.auto_exposure(): %d\n", bool_get); #endif }
36.540541
80
0.664511
tim-schoenmackers
9dbbac82cb859d9fb39899ec7224e1a4da3afc86
1,622
cpp
C++
Juez/FAL1/source.cpp
Yule1223/FAL
de7aef53ca3af5e01e65228290ada14512f46850
[ "MIT" ]
null
null
null
Juez/FAL1/source.cpp
Yule1223/FAL
de7aef53ca3af5e01e65228290ada14512f46850
[ "MIT" ]
null
null
null
Juez/FAL1/source.cpp
Yule1223/FAL
de7aef53ca3af5e01e65228290ada14512f46850
[ "MIT" ]
null
null
null
// Yule Zhang // E81 #include <iostream> #include <iomanip> #include <fstream> #include <vector> using namespace std; //T(n) = C1 (Si n == 1); //T(n) = 2T(n/2) + C2 (Si n > 1); //Se obtiene un coste O(n) siendo n el numero de elementos del vector. // Funcion que resuelve el problema // v.size() es potencia de dos bool sufDisperso(vector<int> const& v, int ini, int fin, int K) { if (ini + 1 == fin)// Un elemento return true; else { // Vector de 2 o mas elementos int m = (ini + fin) / 2; bool sIz = sufDisperso(v, ini, m, K); bool sDr = sufDisperso(v, m, fin, K); return sIz && sDr && K <= abs(v[ini] - v[fin - 1]); } } // Resuelve un caso de prueba, leyendo de la entrada la // configuracion, y escribiendo la respuesta bool resuelveCaso() { int num; cin >> num; if (!cin) return false; int K; cin >> K; vector<int> v(num); for (int& n : v) cin >> n; if (sufDisperso(v, 0, v.size(), K)) cout << "SI" << endl; else cout << "NO" <<endl; return true; } int main() { // Para la entrada por fichero. // Comentar para acepta el reto #ifndef DOMJUDGE std::ifstream in("datos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt #endif while (resuelveCaso()); // Para restablecer entrada. Comentar para acepta el reto #ifndef DOMJUDGE // para dejar todo como estaba al principio std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
24.575758
96
0.561652
Yule1223
e38383648b3baf4d7477ebf6fedf3f9bf4b85aad
1,994
cc
C++
Source/BladeDevice/source/graphics/Texture.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeDevice/source/graphics/Texture.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeDevice/source/graphics/Texture.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2010/04/15 filename: Texture.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <graphics/Texture.h> namespace Blade { //////////////////////////////////////////////////////////////////////////// Texture::Texture(ETextureType type,IMG_ORIENT layout) :mViewTop(0) ,mViewLeft(0) ,mViewWidth(0) ,mViewHeight(0) ,mLockedMip(-1) ,mLockedFace(-1) ,mIsLocked(false) ,mSharedSampler(false) { mDesc.mTextureType = type; mDesc.mLayout = layout; } ////////////////////////////////////////////////////////////////////////// Texture::Texture(ETextureType type,IMG_ORIENT layout, size_t width,size_t height,PixelFormat format, IGraphicsBuffer::USAGE usage,IGraphicsBuffer::ACCESS GpuAccess,size_t depth/* = 1*/,size_t mipmap/* = 0*/) :mLockedMip(-1) ,mLockedFace(-1) ,mIsLocked(false) ,mSharedSampler(false) { mDesc.mTextureType = type; mDesc.mLayout = layout; mDesc.mWidth = width; mDesc.mHeight = height; mDesc.mDepth = depth; mDesc.mPixelFormat = format; mDesc.mMipmapCount = mipmap; mDesc.mUsage = usage; mDesc.mGpuAccess = GpuAccess; } ////////////////////////////////////////////////////////////////////////// /*static */const HSAMPLER& Texture::DEFAULT_RTT_SAMPLER() { #if BLADE_COMPILER == BLADE_COMPILER_MSVC #pragma warning(disable:4640) #endif static HSAMPLER sampler; if(sampler == NULL) { sampler.bind(BLADE_NEW Sampler(Sampler::DEFAULT_RTT)); } return sampler; } ////////////////////////////////////////////////////////////////////////// /*static */const HSAMPLER& Texture::DEFAULT_DEPTH_RTT_SAMPLER() { #if BLADE_COMPILER == BLADE_COMPILER_MSVC #pragma warning(disable:4640) #endif static HSAMPLER sampler; if (sampler == NULL) { sampler.bind(BLADE_NEW Sampler(Sampler::DEFAULT_RTT_DEPTH)); } return sampler; } }//namespace Blade
26.236842
108
0.557673
OscarGame
e3851ef7f234d9c884c54264a4b45b6b17187593
1,901
cc
C++
modules/planning/lattice/trajectory1d/piecewise_jerk_trajectory1d.cc
idaohang/apollo
2f35a68bcd915f571afbd8ef2604aa3289a5a0cc
[ "Apache-2.0" ]
1
2018-07-22T08:09:08.000Z
2018-07-22T08:09:08.000Z
modules/planning/lattice/trajectory1d/piecewise_jerk_trajectory1d.cc
ouyangle8794/apollo
2f35a68bcd915f571afbd8ef2604aa3289a5a0cc
[ "Apache-2.0" ]
null
null
null
modules/planning/lattice/trajectory1d/piecewise_jerk_trajectory1d.cc
ouyangle8794/apollo
2f35a68bcd915f571afbd8ef2604aa3289a5a0cc
[ "Apache-2.0" ]
1
2021-11-01T02:48:42.000Z
2021-11-01T02:48:42.000Z
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/trajectory1d/piecewise_jerk_trajectory1d.h" #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { void PiecewiseJerkTrajectory1d::AppendSegment( const double jerk, const double param) { CHECK(!segments_.empty()); const auto& last_segment = segments_.back(); double last_p = last_segment.GetEndState(); double last_v = last_segment.GetEndVelocity(); double last_a = last_segment.GetEndAcceleration(); segments_.emplace_back(last_p, last_v, last_a, jerk, param); } void PiecewiseJerkTrajectory1d::AppendSegment( const double p1, const double v1, const double a1, const double param) { CHECK_GT(param, FLAGS_lattice_epsilon); const auto& last_segment = segments_.back(); double last_p = last_segment.GetEndState(); double last_v = last_segment.GetEndVelocity(); double last_a = last_segment.GetEndAcceleration(); double jerk = (a1 - last_a) / param; segments_.emplace_back(last_p, last_v, last_a, jerk, param); } } // namespace planning } // namespace apollo
35.203704
79
0.687533
idaohang
e38543517438ea869409b2aa9d337d5b915dcfa2
1,307
cpp
C++
toolbox/sys/Time.cpp
Shivix/toolbox-cpp
84f397a2503edd029a9dbf32f6500c00617aeb3a
[ "Apache-2.0" ]
null
null
null
toolbox/sys/Time.cpp
Shivix/toolbox-cpp
84f397a2503edd029a9dbf32f6500c00617aeb3a
[ "Apache-2.0" ]
null
null
null
toolbox/sys/Time.cpp
Shivix/toolbox-cpp
84f397a2503edd029a9dbf32f6500c00617aeb3a
[ "Apache-2.0" ]
null
null
null
// The Reactive C++ Toolbox. // Copyright (C) 2013-2019 Swirly Cloud Limited // Copyright (C) 2021 Reactive Markets Limited // // 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 "Time.hpp" namespace toolbox { inline namespace sys { using namespace std; TOOLBOX_WEAK Nanos get_time(clockid_t clock_id) noexcept; NanoTime get_time(clockid_t clock_id) noexcept { timespec ts; clock_gettime(clock_id, &ts); // Long-long literal is required here for ARM32. return NanoTime{ts.tv_sec * 1'000'000'000LL + ts.tv_nsec}; } ostream& operator<<(ostream& os, MonoTime t) { return os << ns_since_epoch(t); } ostream& operator<<(ostream& os, WallTime t) { return os << ns_since_epoch(t); } thread_local CyclTime::Time CyclTime::time_; } // namespace sys } // namespace toolbox
27.808511
75
0.729151
Shivix
e3891f10370ac55e47cf17c67c36f7249b2965bc
8,797
cpp
C++
view.cpp
kaitokidi/WakomExercice
bf0135db68a4300382e41a947b7a327b145a3056
[ "MIT" ]
null
null
null
view.cpp
kaitokidi/WakomExercice
bf0135db68a4300382e41a947b7a327b145a3056
[ "MIT" ]
null
null
null
view.cpp
kaitokidi/WakomExercice
bf0135db68a4300382e41a947b7a327b145a3056
[ "MIT" ]
null
null
null
#include <string> #include <sstream> #include <iostream> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> int main(){ //VARIABLES CONSTANTS i ENUMERATIONS int speed = 180; float pantalla = 1; float time_to_next_sprite = 0.09; enum direction { down, left, right, up , none}; const int mx[5] = {0, -1, 1, 0, 0}; const int my[5] = {1, 0, 0, -1, 0}; //VECTOR2 sf::Vector2u size(1100,700); sf::Vector2f spriteSize(32,48); sf::Vector2i spriteSource(0,down); sf::Vector2f originalSpriteSize(0,0); sf::Vector2u newsize(size.x, size.y); sf::Vector2f oldMousePosition(sf::Vector2f(0,0)); sf::Vector2f playerPosition(spriteSize.x,spriteSize.y); //OBJECTES DE SFML //DECLAREM LA VIEW sf::View view; sf::Image image; sf::Event event; sf::Clock deltaClock; sf::Sprite player, background; sf::Texture pTexture, tbackground; //LOAD THE IMAGES AND TEXTURES if(!image.loadFromFile("ground.png")) std::cout << "ground Image Not Loaded " << std::endl; if(!tbackground.loadFromImage(image)) std::cout << "background texture Not Loaded " << std::endl; if(!pTexture.loadFromFile("sprites.png")) std::cout << "personatge Not Loaded " << std::endl; spriteSize.x = originalSpriteSize.x = pTexture.getSize().x/4; spriteSize.y = originalSpriteSize.y = pTexture.getSize().y/4; //VARIABLES direction d = none; double escalat = 1; float distx = spriteSize.x/3, disty = spriteSize.y/4; float deltatime = 0, movx = 0.0, movy = 0.0, scont = 0.0; //Set player's properties player.setTexture(pTexture); player.setPosition(playerPosition); //Set Background's properties background.setTexture(tbackground); //CREATE THE WINDOW sf::RenderWindow window(/*sf::VideoMode(size.x,size.y)*/sf::VideoMode::getDesktopMode(), "Penguins <3", sf::Style::Resize|sf::Style::Close); //GAME LOOP while(window.isOpen()){ speed = 180*((window.getSize().x - playerPosition.x)/window.getSize().x)+20; //Loop for handling events while(window.pollEvent(event)){ switch (event.type){ //Close event case sf::Event::Closed: window.close(); break; //KeyPressed event case sf::Event::KeyPressed: //Close key if (event.key.code == sf::Keyboard::Escape) { window.close(); } if (event.key.code == sf::Keyboard::K) { sf::Mouse::setPosition(sf::Vector2i(2000,100)); } break; //Default default: //Do nothing break; } } //Deltatime deltatime = deltaClock.restart().asSeconds(); scont += deltatime; //Updating if a key is pressed in a direction 'd' d = none; if(sf::Mouse::getPosition().x > oldMousePosition.x) d = right; if(sf::Mouse::getPosition().x < oldMousePosition.x) d = left; if(sf::Mouse::getPosition().y > oldMousePosition.y) d = down; if(sf::Mouse::getPosition().y < oldMousePosition.y) d = up; oldMousePosition.x = sf::Mouse::getPosition().x; oldMousePosition.y = sf::Mouse::getPosition().y; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) d = up; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) d = down; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) d = right; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) d = left; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && sf::Keyboard::isKeyPressed(sf::Keyboard::E)) sf::Mouse::setPosition(sf::Vector2i(window.getSize().x-3, playerPosition.y), window); //If some key is pressed if(d != none){ //Set value to movement variables and update spritesource if(spriteSource.y == d){ // movx += mx[d]*speed*deltatime; // movy += my[d]*speed*deltatime; } else spriteSource.y = d; if (scont >= time_to_next_sprite){ scont = 0; ++spriteSource.x; } } //Calcula el desti del player float destix = playerPosition.x; if(sf::Mouse::getPosition().x > playerPosition.x) destix += movx; if(sf::Mouse::getPosition().x < playerPosition.x) destix -= movx; float destiy = playerPosition.y+movy; destix = sf::Mouse::getPosition().x; destiy = sf::Mouse::getPosition().y-spriteSize.y/2; //Calcula l'equivalent del punt de la pantalla on esta el player en la imatge de background float px, py; if(destix > 0 && destiy > 0) { px = image.getSize().x*destix/tbackground.getSize().x/background.getScale().x; py = image.getSize().y*destiy/tbackground.getSize().y/background.getScale().y; if(image.getPixel(px,py) != sf::Color::Black) { playerPosition.x = destix; playerPosition.y = destiy; } else { playerPosition.x = 1; playerPosition.y = 1; sf::Mouse::setPosition(sf::Vector2i(playerPosition.x, playerPosition.y), window); } } else { playerPosition.x = 1; playerPosition.y = 1; sf::Mouse::setPosition(sf::Vector2i(playerPosition.x, playerPosition.y), window); } //Setting movement variables to 0 movx = movy = 0; //Checking the sprite sources and position to be ok if(spriteSource.x >= 4) spriteSource.x = 0; float aux = background.getTexture()->getSize().y * background.getScale().y; if(playerPosition.x < 0) playerPosition.x = 0; else if (playerPosition.x >= window.getSize().x-3) { ++pantalla; //if(!image.loadFromFile("ground2.png")) std::cout << "ground Image Not Loaded " << std::endl; //if(!tbackground.loadFromImage(image)) std::cout << "background texture Not Loaded " << std::endl; int t = pantalla + 1; std::stringstream d; d << "ground" << t; std::string b = d.str(); if(!image.loadFromFile(b+".png")) if(!pTexture.loadFromFile("sprites3.png")) { std::cout << "personatge Not Loaded " << std::endl; exit(1);} std::stringstream s; s << "ground" << pantalla; std::string board = s.str(); if(!image.loadFromFile(board+".png")) { std::cout << "I CAN'T LOAD BOARD IMAGE" << std::endl; exit(1);} if(!tbackground.loadFromFile(board+".png")) { std::cout << "I CAN'T LOAD BOARD texture" << std::endl; exit(1);} playerPosition.x = 5; playerPosition.y = 5; sf::Mouse::setPosition(sf::Vector2i(playerPosition.x, playerPosition.y), window); } else if (playerPosition.y < 0) playerPosition.y = 0; else if (playerPosition.y > aux) { playerPosition.x = 5; playerPosition.y = 5; sf::Mouse::setPosition(sf::Vector2i(playerPosition.x, playerPosition.y), window); } //Set player properties player.setOrigin(spriteSize.x/2, spriteSize.y); player.setPosition(playerPosition.x, playerPosition.y); player.setTextureRect(sf::IntRect(spriteSource.x*spriteSize.x, spriteSource.y*spriteSize.y, spriteSize.x, spriteSize.y)); // player.setScale(window.getSize().x/600.0, window.getSize().x/600.0); player.setScale((window.getSize().x - playerPosition.x)/window.getSize().x , (window.getSize().x - playerPosition.x)/window.getSize().x); player.scale(originalSpriteSize.x/spriteSize.x, originalSpriteSize.y/spriteSize.y); //Set background scale escalat = (double)(window.getSize().x) / (double)(tbackground.getSize().x); background.setScale(escalat, escalat); //Set VIEW values view.reset(sf::FloatRect(playerPosition.x,playerPosition.y, window.getSize().x, window.getSize().y)); //Definim on volem centrar la VIEW view.setCenter(playerPosition); sf::CircleShape c; c.setRadius(1); c.setOutlineThickness(2); c.setFillColor(sf::Color::Red); c.setPosition(playerPosition.x-0.5, playerPosition.y-0.5); // view.setRotation(playerPosition.y+playerPosition.x); // view.zoom((view.getSize().y/2) / playerPosition.y); view.zoom(0.4); //view.setViewport(sf::FloatRect(0,0,1,1)); //Clear the window window.clear(); //Set window view, draw and display window.draw(background); window.draw(player); window.draw(c); // window.setView(view); window.display(); } }
40.16895
294
0.588837
kaitokidi
e38e4b9fa409eb06d4f5cc4ca6c915569d676adc
381
cpp
C++
RealNumber.cpp
lwjpig/number
562013f04fdd2e1af350e67c726f4ad87956602c
[ "MIT" ]
null
null
null
RealNumber.cpp
lwjpig/number
562013f04fdd2e1af350e67c726f4ad87956602c
[ "MIT" ]
null
null
null
RealNumber.cpp
lwjpig/number
562013f04fdd2e1af350e67c726f4ad87956602c
[ "MIT" ]
null
null
null
#include"Number.h" #include"RealNumber.h" #include<iostream> using namespace std; RealNumber::RealNumber(double a) { Rn=a; } RealNumber RealNumber::add(const RealNumber& other) { RealNumber B(Rn+other.Rn); return B; } RealNumber RealNumber::mul(const RealNumber& other) { RealNumber B(Rn*other.Rn); return B; } void RealNumber::print() { cout<<"RealNumber : "<<Rn<<endl; }
12.290323
51
0.716535
lwjpig
e391e59033ada28146926d0ed73db28b34d4c724
1,050
hpp
C++
arm/settings.hpp
fyhertz/epilepsia
16adc539e26c0e5bea06f768caaf08172b405a00
[ "Apache-2.0" ]
16
2018-03-12T23:44:58.000Z
2021-06-15T11:45:46.000Z
arm/settings.hpp
fyhertz/epilepsia
16adc539e26c0e5bea06f768caaf08172b405a00
[ "Apache-2.0" ]
null
null
null
arm/settings.hpp
fyhertz/epilepsia
16adc539e26c0e5bea06f768caaf08172b405a00
[ "Apache-2.0" ]
1
2019-05-23T08:12:29.000Z
2019-05-23T08:12:29.000Z
/* * Copyright (C) 2018-2019 Simon Guigui * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EPILEPSIASETTINGS_H #define EPILEPSIASETTINGS_H #include "leddriver.hpp" #include <string> #include <vector> namespace epilepsia { class settings { public: explicit settings(const std::string& file = "/etc/epilepsia/epilepsia.json"); void load_settings(); void dump_settings(); std::vector<uint16_t> server_ports; led_driver_settings driver; private: std::string file_; }; } // namespace epilepsia #endif
25
81
0.731429
fyhertz
e394a41912c016c6cafa87b744e9a26158953600
4,998
cpp
C++
xaiPatch.cpp
Coxxs/YsVIII-tools
4da809c90693f492e67ccb31b3150fb9a3269559
[ "Apache-2.0" ]
15
2017-10-06T08:55:19.000Z
2022-01-11T22:03:34.000Z
xaiPatch.cpp
Coxxs/YsVIII-tools
4da809c90693f492e67ccb31b3150fb9a3269559
[ "Apache-2.0" ]
9
2017-09-25T12:21:31.000Z
2018-08-03T04:29:55.000Z
xaiPatch.cpp
Coxxs/YsVIII-tools
4da809c90693f492e67ccb31b3150fb9a3269559
[ "Apache-2.0" ]
7
2017-09-27T21:43:38.000Z
2020-06-10T03:16:53.000Z
// XAST Patcher by yosh778 #include <string> #include <iostream> #include <algorithm> #include <sstream> #include <fstream> #include <cinttypes> #define RBUF_SIZE 0x1000000 uint32_t read32(std::fstream& input) { uint32_t data; input.read((char*)&data, (int)sizeof(data)); return data; } uint64_t read64(std::fstream& input) { uint64_t data; input.read((char*)&data, (int)sizeof(data)); return data; } void write32(std::fstream& output, uint32_t data) { output.write((char*)&data, (int)sizeof(data)); } // Checksum reverse by weaknespase uint32_t checksum(const char* in, const uint32_t length, int last = 0){ const char* end = in + length; int acc = last; while (in < end) acc = (acc * 33) ^ (unsigned char) *in++; return acc; } int main(int argc, char *argv[]) { if ( argc < 4 ) { std::cerr << "Usage : " << argv[0] << " <inputXai> <inputFile> <filename>" << std::endl; return -1; } std::string iXai = argv[1]; std::string iFile = argv[2]; std::string iFileName = argv[3]; uint32_t fHash = checksum( iFileName.c_str(), iFileName.size() ); std::fstream file( iXai.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary ); if ( !file.is_open() ) { std::cerr << "ERROR : input XAST not found" << std::endl; return -2; } uint32_t data; // XAST header uint32_t magic = read32(file); // Version : 1.01 uint32_t version = read32(file); uint32_t nbEntries = read32(file); // nbEntries uint32_t maxEntries = read32(file); // maxEntries uint32_t pathsCount = read32(file); uint32_t dataOffset = read32(file); uint32_t headerChecksum = read32(file); uint32_t headersCount = read32(file); uint32_t xaiSize = read32(file); uint32_t pathsOffset = 0x30 + headersCount; file.seekg(0x30); uint64_t fileSize; uint64_t fileOffset; uint32_t pathOffset; uint32_t pathHash; uint32_t fileChecksum; uint32_t nbActualEntries = 0; uint32_t i = 0; std::stringstream ss; bool found = false; for (i = 0; i < maxEntries; i++) { pathHash = read32(file); pathOffset = read32(file); fileChecksum = read32(file); uint32_t isXai = read32(file); found = (pathHash == fHash); ss << std::hex << pathHash << " | " << pathOffset << " | " << fileChecksum << " | " << isXai << std::endl; if ( isXai > 1 ) { std::cerr << "WARNING : unsupported value found for isXai : " << isXai << std::endl; } fileSize = read64(file); ss << fileSize << std::endl; if ( uint64_t padding = read64(file) ) { std::cerr << "WARNING : unsupported value found for padding : " << padding << std::endl; // return -3; } fileOffset = read64(file); uint64_t aSize = read64(file); ss << fileOffset << " | " << aSize << std::endl << std::endl; if ( found || file.tellg() >= pathsOffset ) { // std::cout << "break" << std::endl; // std::cout << std::hex << file.tellg() << std::endl; break; } } // std::cerr << ss.str(); if ( !found ) { file.close(); std::cerr << "File " << iFileName << " not found in this XAST" << std::endl; return -1; } const uint32_t headerOffset = (i+1) * 0x30; std::ifstream input( iFile.c_str(), std::ios_base::binary ); if ( !input.is_open() ) { file.close(); std::cerr << "Failed to open " << iFile << std::endl; return -2; } std::cout << "Writing " << iFileName << " at offset 0x" << std::hex << fileOffset << std::dec << std::endl << std::endl; file.seekg(fileOffset); uint32_t last = 0; uint64_t read = 0; uint64_t totalRead = 0; uint8_t *buf = new uint8_t[RBUF_SIZE]; while ( input && file ) { input.read( (char*)buf, RBUF_SIZE ); if ( input ) read = RBUF_SIZE; else read = input.gcount(); totalRead += read; uint64_t wSize = read; if ( totalRead > fileSize ) { wSize -= totalRead - fileSize; std::cerr << "ERROR : Input file size differs ! Expected size : " << fileSize << std::endl; } if ( wSize > 0 ) { last = checksum( (const char*)buf, wSize, last ); file.write( (const char*)buf, wSize ); } if ( totalRead >= fileSize ) break; } input.close(); file.seekp(headerOffset + 8); write32(file, last); // File checksum std::cout << "Header offset : 0x" << std::hex << headerOffset << std::dec << std::endl; std::cout << "Old file checksum : 0x" << std::hex << fileChecksum << std::dec << std::endl; std::cout << "New file checksum : 0x" << std::hex << last << std::dec << std::endl; file.seekp(0x30); uint32_t headerSize = 0x30 * maxEntries; if ( RBUF_SIZE < headerSize ) { delete buf; buf = new uint8_t[ headerSize ]; } file.read( (char*)buf, headerSize ); uint32_t headerCheck = checksum( (const char*)buf, headerSize); file.seekp(0x18); write32(file, headerCheck); std::cout << "Old header checksum : 0x" << std::hex << headerChecksum << std::dec << std::endl; std::cout << "New header checksum : 0x" << std::hex << headerCheck << std::dec << std::endl; std::cout << std::endl << "XAST file patched with success" << std::endl; return 0; }
23.464789
121
0.622049
Coxxs
e3a23466dc97c4953ce2b2d0b44392757e18510b
1,843
cpp
C++
3Tree/987. Vertical Order Traversal of a Binary Tree.cpp
lingqtan/myLeetcode
54cc538b640660c0d64420442466af4df2ed0225
[ "Apache-2.0" ]
null
null
null
3Tree/987. Vertical Order Traversal of a Binary Tree.cpp
lingqtan/myLeetcode
54cc538b640660c0d64420442466af4df2ed0225
[ "Apache-2.0" ]
null
null
null
3Tree/987. Vertical Order Traversal of a Binary Tree.cpp
lingqtan/myLeetcode
54cc538b640660c0d64420442466af4df2ed0225
[ "Apache-2.0" ]
null
null
null
/** * 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 { vector<vector<int> > ans; map<TreeNode*, pair<int, int> > m; typedef pair<int, pair<int, int> > TRIPLE; vector<TRIPLE> v; static bool cmp(const TRIPLE& t1, const TRIPLE& t2) { if (t1.second.first < t2.second.first) return true; if (t1.second.first > t2.second.first) return false; if (t1.second.second < t2.second.second) return true; if (t1.second.second > t2.second.second) return false; return t1.first < t2.first; } void traverse(TreeNode* root) { if (root == NULL) return; int x = m[root].first; int y = m[root].second; if (root->left) { m[root->left] = pair(x-1, y+1); traverse(root->left); } if (root->right) { m[root->right] = pair(x+1, y+1); traverse(root->right); } } void map2vec() { for (auto elem: m) { v.push_back(pair(elem.first->val, elem.second)); } sort(v.begin(), v.end(), cmp); } void solve() { int x = -1000; vector<int> req; for (auto elem: v) { int x1 = elem.second.first; if (x != x1) { if (req.size() != 0) ans.push_back(req); x = x1; req.clear(); } req.push_back(elem.first); } ans.push_back(req); } public: vector<vector<int>> verticalTraversal(TreeNode* root) { if (root == NULL) return ans; m[root] = pair(0, 0); traverse(root); map2vec(); solve(); return ans; } };
27.102941
62
0.490505
lingqtan
e3a339bf9b2d7c390267649b7edbf4249b0f4c53
1,390
cpp
C++
src/prod/src/Hosting2/ConfigureSecurityPrincipalReply.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Hosting2/ConfigureSecurityPrincipalReply.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Hosting2/ConfigureSecurityPrincipalReply.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Hosting2; ConfigureSecurityPrincipalReply::ConfigureSecurityPrincipalReply() : error_(ErrorCodeValue::Success), principalsInformation_() { } ConfigureSecurityPrincipalReply::ConfigureSecurityPrincipalReply( vector<SecurityPrincipalInformationSPtr> const & principalsInformation, ErrorCode const & error) : error_(error), principalsInformation_() { if(error_.IsSuccess()) { for(auto iter=principalsInformation.begin(); iter != principalsInformation.end(); ++iter) { principalsInformation_.push_back(*(*iter)); } } } void ConfigureSecurityPrincipalReply::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("ConfigureSecurityPrincipalReply { "); w.Write("ErrorCode = {0}", error_); w.Write("User : Sid"); for(auto iter = principalsInformation_.begin(); iter != principalsInformation_.end(); ++iter) { w.Write(" PrincipalInformation = {0}", *iter); } w.Write("}"); }
30.217391
98
0.638849
AnthonyM
e3a67380e84d48f0cec7dcac3476d157f5bebfe8
1,404
cpp
C++
Visual Studio 2010/Projects/bjarneStroustrupC++PartII/bjarneStroustrupCFLTK/Chapter16Exercise1.cpp
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
9
2018-10-24T15:16:47.000Z
2021-12-14T13:53:50.000Z
Visual Studio 2010/Projects/bjarneStroustrupC++PartII/bjarneStroustrupCFLTK/Chapter16Exercise1.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
null
null
null
Visual Studio 2010/Projects/bjarneStroustrupC++PartII/bjarneStroustrupCFLTK/Chapter16Exercise1.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
7
2018-10-29T15:30:37.000Z
2021-01-18T15:15:09.000Z
/* TITLE My window Chapter16Exercise1.cpp "Bjarne Stroustrup "Programming Principles and Practices Using C++"" COMMENT Objective: Define class based on Window with two buttons: quit, next. Input: - Output: - Author: 18.10.2015 Date: Chris B. Kirov */ #include <iostream> #include "GUI.h" #include "Graph.h" #include "Simple_window.h" struct My_window: Window { My_window(Point o, int w, int h, std::string& t) : Window(o, w, h, t), quit_button(Point(x_max() - 80, 0), 70, 20, "Quit" , cb_quit), next_button(Point(x_max() - 80, 30), 70, 20, "Next" , cb_next) { attach(quit_button); attach(next_button); } private: // widget Graph_lib::Button quit_button; Graph_lib::Button next_button; // callback static void cb_quit(Address, Address pw) { reference_to<My_window>(pw).quit_pressed(); } static void cb_next(Address, Address pw) { reference_to<My_window>(pw).next_pressed(); } // action void quit_pressed() { hide(); } void next_pressed() { redraw(); } }; //------------------------------------------------------------------------------------------------------- int main() { try { const int width = 600; const int height = width; std::string title = "Chapter 16 Exercise 1"; My_window sw(Point(500, 0), width, height, title); return gui_main(); } catch (std::exception& e) { std::cerr << e.what() <<'\n'; getchar(); } }
23.4
105
0.605413
Ziezi
e3a9321e16f9758527f3bbede21df8df6e501e7a
3,525
cpp
C++
src/Mario.cpp
KenReneris/PacManClock
39a304bce1514dbd9770d4048748a2e5eaed3c23
[ "MIT" ]
null
null
null
src/Mario.cpp
KenReneris/PacManClock
39a304bce1514dbd9770d4048748a2e5eaed3c23
[ "MIT" ]
null
null
null
src/Mario.cpp
KenReneris/PacManClock
39a304bce1514dbd9770d4048748a2e5eaed3c23
[ "MIT" ]
null
null
null
/* * Mario.cpp * Mario animations * * Author: Ken Reneris <https://github.com/KenReneris> * MIT License * ---------------------------------------------------------- */ #include "platform.h" #include "Mario.h" const uint8 PROGMEM k_mario0[] = { 2, 0,0,0, 3, 0, 15, 16, 0x00,0x00,0xff, 0xf1,0xd0,0xb1, 0xff,0x00,0x00, 0xc0, 0x3f, 0x00, 0x00, 0xf0, 0xff, 0x0f, 0x00, 0x50, 0xa5, 0x00, 0x00, 0xa4, 0x69, 0x2a, 0x00, 0xa4, 0xa5, 0xa9, 0x00, 0x95, 0x6a, 0x15, 0x00, 0x80, 0xaa, 0x0a, 0x00, 0x50, 0x55, 0x00, 0x00, 0x54, 0x7d, 0x01, 0x00, 0x54, 0xef, 0x03, 0x00, 0x54, 0xfd, 0x0f, 0x00, 0x9c, 0xfa, 0x0f, 0x00, 0xbc, 0xfe, 0x0f, 0x00, 0xfc, 0xf3, 0x03, 0x00, 0x54, 0x50, 0x01, 0x00, 0x54, 0x51, 0x05, 0x00 }; const uint8 PROGMEM k_mario1[] = { 2, 0,0,0, 3, 0, 15, 16, 0x00,0x00,0xff, 0xf1,0xd0,0xb1, 0xff,0x00,0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0xf0, 0x0f, 0xc0, 0x00, 0xfc, 0xff, 0xc3, 0x00, 0x54, 0x29, 0xc0, 0x00, 0x69, 0x9a, 0xca, 0x00, 0x69, 0x69, 0xea, 0x40, 0xa5, 0x5a, 0xc5, 0x00, 0xa0, 0xaa, 0xc2, 0x00, 0x55, 0x8d, 0xc0, 0x80, 0x55, 0xa5, 0xc2, 0xa0, 0x5f, 0xa5, 0xc0, 0xf5, 0xff, 0xff, 0xc0, 0xf5, 0xff, 0x3f, 0xc0, 0xf5, 0x0f, 0x0f, 0xc0, 0x01, 0x40, 0x05, 0xc0, 0x00, 0x40, 0x15, 0xc0 }; const uint8 PROGMEM k_mario2[] = { 2, 0,0,0, 3, 0, 15, 16, 0x00,0x00,0xff, 0xf1,0xd0,0xb1, 0xff,0x00,0x00, 0x00, 0xfc, 0x03, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x55, 0x0a, 0x00, 0x40, 0x9a, 0xa6, 0x02, 0x40, 0x5a, 0x9a, 0x0a, 0x50, 0xa9, 0x56, 0x01, 0x00, 0xa8, 0xaa, 0x00, 0x50, 0xf5, 0x05, 0x28, 0x5a, 0xf5, 0x57, 0x2a, 0x2a, 0xb5, 0x7f, 0x29, 0x0a, 0xff, 0x3f, 0x04, 0xc0, 0xff, 0xff, 0x05, 0xf0, 0xff, 0xff, 0x05, 0x54, 0x0f, 0xfc, 0x05, 0x54, 0x00, 0x00, 0x00, 0x50, 0x01, 0x00, 0x00 }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Mario::RunBy::RunBy() { BitmapBase *mario[] = { snew<Bitmap<2>>( 40, k_mario0 ), snew<Bitmap<2>>( 40, k_mario2 ), snew<Bitmap<2>>( 40, k_mario1 ) }; _mario.InitSprite( mario, countof(mario) ); } IStoryboard::StartResult Mario::RunBy::Start() { _mario.Start( Point(-30, 0), Point(1,0) ); return StartResult( Start_ClockOffTop | Start_DimClock2 ); } void Mario::RunBy::Loop() { if ( _mario.SpriteMode() == SpriteBase::Mode::Disabled ) { g_animationManager.ContinueTo( Animation::MarioRunBack, 400 ); } } //////////////////////////////////////// Mario::RunBack::RunBack() { BitmapBase *mario[] = { snew<Bitmap<2>>( 40, k_mario0, true ), snew<Bitmap<2>>( 40, k_mario2, true ), snew<Bitmap<2>>( 40, k_mario1, true ) }; _mario.InitSprite( mario, countof(mario) ); } IStoryboard::StartResult Mario::RunBack::Start() { _mario.Start( Point(PANEL_WIDTH+40, 0), Point(-1,0) ); return Start_ClockOffBottom; } void Mario::RunBack::Loop() { if ( _mario.SpriteMode() == SpriteBase::Mode::Disabled ) { g_animationManager.Done(); } }
23.817568
109
0.49844
KenReneris
e3b214a435b68786aa2611250e56534788d20e26
6,114
cpp
C++
src/predict.cpp
seandobs/psvn-suite
aa6fbb5a6c0f062f10216efd7596018ef4b7c325
[ "MIT" ]
1
2020-06-16T17:49:02.000Z
2020-06-16T17:49:02.000Z
src/predict.cpp
seandobs/psvn-suite
aa6fbb5a6c0f062f10216efd7596018ef4b7c325
[ "MIT" ]
null
null
null
src/predict.cpp
seandobs/psvn-suite
aa6fbb5a6c0f062f10216efd7596018ef4b7c325
[ "MIT" ]
null
null
null
// Performs SSDP to predict the number of problems // that an A* search will expand. #include <iostream> #include <string> #include <sstream> #include <chrono> #include <thread> #include <random> #include <functional> #include "../include/probabilitypredictor.hpp" #include "../include/ss.hpp" #include "../include/state.hpp" #include "../include/abstraction.hpp" #include "../include/heuristic.hpp" #include "../include/domain.hpp" #include "../include/ezOptionParser.hpp" #include "../include/statetyper.hpp" #include "../include/searchstat.hpp" #include "../include/astar.hpp" using namespace ez; void Usage(ezOptionParser& opt) { std::string usage; opt.getUsage(usage); std::cout << usage; }; int main( int argc, const char **argv ) { ezOptionParser opt; opt.overview = "Performs Stratified Sampling with Duplicate Detection on the given inputs."; opt.syntax = "sd --domain --start <file>,<file>,... " "[--pdb <file> --abstraction <file> --probes <num> --walks <num> --f-max <num> --num-abstractions <num> --level-abstractions <num> --rngseed <num>]"; opt.example = "sd --domain pancake15.so --pdb a1.pdb --abstraction a1.abst " "--probes 1 --walks 100 --f-max 10 --start s1,s2,s3\n\n"; opt.footer = ""; opt.add("", // Default. 0, // Required? 0, // Number of args expected. 0, // Delimiter if expecting multiple args. "Display usage instructions.", // Help description. "-h", // Flag token. "--help" // Flag token. ); opt.add("",1,1,0,"PSVN Domain file","-d","--domain"); opt.add("",0,1,0,"PSVN PDB file","-p","--pdb"); opt.add("",0,1,0,"PSVN Abstraction file","-a","--abstraction"); opt.add("1",0,1,0,"Number of SS probes.","-m","--probes"); opt.add("0",0,1,0,"Number of SDD walks.","-k","--walks"); opt.add("0",0,1,0,"Number of Abstractions to use when predicting duplicate probabilities.","-n","--num-abstractions"); opt.add("0",0,1,0,"Level of Abstraction to use when predicting duplicate probabilities.","-l","--level-abstractions"); opt.add("",1,1,0,"Maximum f-level for SS.","-f","--f-max"); opt.add("",1,-1,';',"PSVN Start files","-s","--start"); opt.add("",0,1,0,"Output SS statistics","-ps","--pred-stats"); opt.add("",0,1,0,"Output SS statistics","-as","--abstract-stats"); opt.add("0",0,1,0,"RNG Seed","-r","--rng-seed"); opt.add("",0,0,0, "Ignore Goal","-i","--ignore-goal"); opt.parse(argc, argv); if (opt.isSet("-h")) { Usage(opt); return 1; } std::vector<std::string> badOptions; int i; if(!opt.gotRequired(badOptions)) { for(i=0; i < badOptions.size(); ++i) std::cerr << "ERROR: Missing required option " << badOptions[i] << ".\n"; Usage(opt); return 1; } if(!opt.gotExpected(badOptions)) { for(i=0; i < badOptions.size(); ++i) std::cerr << "ERROR: Got unexpected number of arguments for option " << badOptions[i] << ".\n\n"; Usage(opt); return 1; } cout.precision(10); string domain_file_name; opt.get("-d")->getString(domain_file_name); int seed; opt.get("-r")->getInt(seed); int m; opt.get("-m")->getInt(m); int k; opt.get("-k")->getInt(k); int f_max; opt.get("-f")->getInt(f_max); int n; opt.get("-n")->getInt(n); int l; opt.get("-l")->getInt(l); vector<vector<string>> starts; opt.get("-s")->getMultiStrings(starts); bool is_ignore_goal = opt.isSet("-i"); ofstream pred_stats_file; if(opt.isSet("-ps")){ string pred_stats_file_name; opt.get("-ps")->getString(pred_stats_file_name); pred_stats_file = ofstream(pred_stats_file_name); pred_stats_file << "start,g,t,generated,duplicated,expanded" << endl; } ofstream abstract_stats_file; if(opt.isSet("-as")){ string abstract_stats_file_name; opt.get("-as")->getString(abstract_stats_file_name); abstract_stats_file = ofstream(abstract_stats_file_name); abstract_stats_file << "start,g,t,generated,duplicated,expanded" << endl; } mt19937 rng(seed); PSVNDomain domain(domain_file_name); Abstraction abs(&domain); StateMap pdb(&domain); if(opt.isSet("-p")) { string pdb_file_name; opt.get("-p")->getString(pdb_file_name); pdb.from_file(pdb_file_name); } if(opt.isSet("-a")){ string abs_file_name; opt.get("-a")->getString(abs_file_name); abs.from_file(abs_file_name); } PDBHeuristic h(pdb, abs); StateTyper T; cout << "start,pred_generated,pred_duplicated,pred_expanded,ssdp_expanded" << endl; for(int j = 0; j < starts.size(); j++) { State start(&domain); start.from_file(starts[j][0]); start.set_h(h(start)); ProbabilityPredictor P_pred(start, h, T, l, n, f_max, rng, is_ignore_goal); std::vector<SearchStat> abstract_stats = P_pred.get_abstract_stats(); if(abstract_stats_file) { ostringstream os; os << i; for(auto& abstract_stat : abstract_stats) { abstract_stats_file << abstract_stat.to_string(os.str(), abstract_stat.get_f_max() - 1); } } double pred_generated = 0; double pred_expanded = 0; double pred_duplicated = 0; double ss_expanded = 0; for(int i = 0; i < m; i++) { StratifiedSampler ssdd(start, k, f_max, T, h, P_pred, rng); SearchStat stats = ssdd.get_stats(); SearchStat pred_stats = ssdd.get_pred_stats(); pred_generated += pred_stats.total_generated_up_to(pred_stats.get_f_max() -1); pred_expanded += pred_stats.total_expanded_up_to(pred_stats.get_f_max() -1); pred_duplicated += pred_stats.total_duplicated_up_to(pred_stats.get_f_max() -1); ss_expanded += stats.total_expanded_up_to(stats.get_f_max()); if(pred_stats_file) { ostringstream os; os << i; pred_stats_file << pred_stats.to_string(os.str(), pred_stats.get_f_max() - 1); } } pred_generated /= m; pred_expanded /= m; pred_duplicated /= m; cout << j << "," << pred_generated << "," << pred_duplicated << "," << pred_expanded << "," << ss_expanded + P_pred.total_expanded() << endl; } return 0; }
27.917808
153
0.63052
seandobs
e3b46a094909090f2a73cabbd6d5fe22d9fc8c7c
1,743
cpp
C++
QEncryptionKit/src/qencryptionkit.cpp
daodaoliang/QDaodaoliang
bc404934fe6d694c5a3904112414a434ca86f953
[ "MIT" ]
2
2017-10-24T02:50:51.000Z
2021-06-18T16:13:18.000Z
QEncryptionKit/src/qencryptionkit.cpp
daodaoliang/QDaodaoliang
bc404934fe6d694c5a3904112414a434ca86f953
[ "MIT" ]
null
null
null
QEncryptionKit/src/qencryptionkit.cpp
daodaoliang/QDaodaoliang
bc404934fe6d694c5a3904112414a434ca86f953
[ "MIT" ]
4
2017-07-20T07:17:47.000Z
2021-08-12T09:47:44.000Z
#include "qencryptionkit.h" #include <QDebug> QEncryptionKit::QEncryptionKit(QObject *parent): QObject(parent) { } QString QEncryptionKit::getMD5Harsh(const QString &param_data) { return QString(QCryptographicHash::hash(param_data.toLocal8Bit(),QCryptographicHash::Md5).toHex()); } QString QEncryptionKit::getSHA1Harsh(const QString &param_data) { return QString(QCryptographicHash::hash(param_data.toLocal8Bit(),QCryptographicHash::Sha1).toHex()); } bool QEncryptionKit::stringByKaiser(QString &param_data, qint8 param_key) { if(param_data.isEmpty()){ return false; } for(int temp_index = 0; temp_index != param_data.size();++temp_index){ char tempChar = param_data.at(temp_index).toAscii(); int tempValue = 0; if(tempChar >= 0x30 && tempChar <= 0x39){ tempValue = (tempChar - '0' + param_key); tempChar = (tempValue >= 0) ? (tempValue % 10 + '0') : (tempValue % 10 + 0x3a); } else if (tempChar >= 0x41 && tempChar <= 0x5a) { tempValue = (tempChar - 'A' + param_key); tempChar = (tempValue >= 0) ? (tempValue % 26 + 'A') : (tempValue % 26 + 0x5b); } else if (tempChar >= 0x61 && tempChar <= 0x7a) { tempValue = (tempChar - 'a' + param_key); tempChar = (tempValue >= 0) ? (tempValue % 26 + 'a') : (tempValue % 26 + 0x7b); } param_data[temp_index] = QChar(tempChar); } return true; } QString QEncryptionKit::stringDESEncode(const QString &param_data, const QString &param_key) { return EncodeMain(param_data,param_key); } QString QEncryptionKit::stringDESDecode(const QString &param_data, const QString &param_key) { return DecodeMain(param_data,param_key);; }
34.176471
104
0.650602
daodaoliang
e3b60a34d025a386385abb7aa61b853ed6dc6ec6
1,560
ipp
C++
ThirdParty/oglplus-develop/implement/oglplus/enums/program_pipeline_stage_names.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
24
2015-01-31T15:30:49.000Z
2022-01-29T08:36:42.000Z
ThirdParty/oglplus-develop/implement/oglplus/enums/program_pipeline_stage_names.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
4
2015-08-21T02:29:15.000Z
2020-05-02T13:50:36.000Z
ThirdParty/oglplus-develop/implement/oglplus/enums/program_pipeline_stage_names.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
9
2015-06-08T22:04:15.000Z
2021-08-16T03:52:11.000Z
/* * .file oglplus/enums/program_pipeline_stage_names.ipp * * Automatically generated header file. DO NOT modify manually, * edit 'source/enums/oglplus/program_pipeline_stage.txt' instead. * * Copyright 2010-2013 Matus Chochlik. 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) */ namespace enums { OGLPLUS_LIB_FUNC StrLit ValueName_( ProgramPipelineStage*, GLbitfield value ) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVN_PROGRAMPIPELINESTAGE) #define OGLPLUS_IMPL_EVN_PROGRAMPIPELINESTAGE { switch(value) { #if defined GL_VERTEX_SHADER_BIT case GL_VERTEX_SHADER_BIT: return StrLit("VERTEX_SHADER_BIT"); #endif #if defined GL_TESS_CONTROL_SHADER_BIT case GL_TESS_CONTROL_SHADER_BIT: return StrLit("TESS_CONTROL_SHADER_BIT"); #endif #if defined GL_TESS_EVALUATION_SHADER_BIT case GL_TESS_EVALUATION_SHADER_BIT: return StrLit("TESS_EVALUATION_SHADER_BIT"); #endif #if defined GL_GEOMETRY_SHADER_BIT case GL_GEOMETRY_SHADER_BIT: return StrLit("GEOMETRY_SHADER_BIT"); #endif #if defined GL_FRAGMENT_SHADER_BIT case GL_FRAGMENT_SHADER_BIT: return StrLit("FRAGMENT_SHADER_BIT"); #endif #if defined GL_COMPUTE_SHADER_BIT case GL_COMPUTE_SHADER_BIT: return StrLit("COMPUTE_SHADER_BIT"); #endif #if defined GL_ALL_SHADER_BITS case GL_ALL_SHADER_BITS: return StrLit("ALL_SHADER_BITS"); #endif default:; } OGLPLUS_FAKE_USE(value); return StrLit(); } #else ; #endif } // namespace enums
28.888889
81
0.808974
vif
e3b6c312f8af454ff35451af8df355258f1a1ed7
2,892
cpp
C++
LifeBrush/Source/LifeBrush/SurfaceMovementComponent.cpp
timdecode/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
33
2019-04-23T23:00:09.000Z
2021-11-09T11:44:09.000Z
LifeBrush/Source/LifeBrush/SurfaceMovementComponent.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
1
2019-10-09T15:57:56.000Z
2020-03-05T20:01:01.000Z
LifeBrush/Source/LifeBrush/SurfaceMovementComponent.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
6
2019-04-25T00:10:55.000Z
2021-04-12T05:16:28.000Z
// Copyright 2015, Timothy Davison. All rights reserved. #include "LifeBrush.h" #include "tcodsMeshInterface.h" #include "SurfaceMovementComponent.h" // Sets default values for this component's properties USurfaceMovementComponent::USurfaceMovementComponent() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void USurfaceMovementComponent::BeginPlay() { Super::BeginPlay(); // ... auto root = Cast<UPrimitiveComponent>(GetOwner()->GetRootComponent()); FRotator rot = GetOwner()->GetActorRotation(); hackStartRotation = rot.Quaternion(); } // Called every frame void USurfaceMovementComponent::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) { Super::TickComponent( DeltaTime, TickType, ThisTickFunction ); // ... URegionGrowingComponent * regionGrower = _regionGrowingComponent(); if( !regionGrower ) return; if( !regionGrower->isMeshInterfaceReady() ) return; auto meshInterface = regionGrower->meshInterface(); FVector position = GetOwner()->GetActorLocation(); tcodsMeshInterface::SurfacePoint nearest = meshInterface->nearestPointOnMesh(position); auto rotationAndNormal = meshInterface->rotationAndNormalAtIndex(nearest.surfaceIndex); auto frame = meshInterface->frameAtNearest(nearest); auto root = Cast<UPrimitiveComponent>(GetOwner()->GetRootComponent()); if( !root ) return; // Linear acceleration FVector normal = rotationAndNormal.second; FVector offset = nearest.point - position; FVector velocity = root->GetPhysicsLinearVelocity(TEXT("None")); FVector offset_ = offset.ProjectOnTo(normal); FVector velocity_ = velocity.ProjectOnTo(normal); FVector force = offset_ * 4.0f - velocity_ * 2.0f; root->AddForce(force, TEXT("None"), true); // Angular acceleration // FVector up = root->GetUpVector(); // FVector angularOffset = -normal - up; // // root->AddTorque(-angularOffset, TEXT("None"), true); FQuat rotation = rotationAndNormal.first * hackStartRotation; rotation = rotation.Inverse(); root->SetWorldRotation(rotation); // random walk t -= DeltaTime; if( t < 0.0f ) { r1 = FMath::FRandRange(-maxAcceleration, maxAcceleration); r2 = FMath::FRandRange(-maxAcceleration, maxAcceleration); t = FMath::FRandRange(0.0f, maxWalkTime); } FVector e1 = frame.first; FVector e2 = frame.second; force = e1 * r1 + e2 * r2; root->AddForce(force, TEXT("None"), true); // align to surface }
27.283019
132
0.677732
timdecode
e3be72f379864534f93ce93d1b9da6ad2886583d
8,450
cxx
C++
src/mod/pub/tst/test-kube-sphere/icosphere.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
1
2017-12-26T14:29:37.000Z
2017-12-26T14:29:37.000Z
src/mod/pub/tst/test-kube-sphere/icosphere.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
src/mod/pub/tst/test-kube-sphere/icosphere.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
#include "stdafx.hxx" #include "mod-test-kube-sphere.hxx" #include "icosphere.hxx" #include "pfm.hxx" #include "gfx-camera.hxx" #include "rng/rng.hxx" #include <unordered_map> static uint64_t get_key(glm::vec3& pos) { float k1 = pos.x * 1.23f + pos.y * 4.56f + pos.z * 7.89f; float k2 = pos.x * 9.87f + pos.y * 6.54f + pos.z * 3.21f; int* x = (int*)&k1; int* y = (int*)&k2; uint64_t x64 = *x & 0xffffffff; uint64_t y64 = *y & 0xffffffff; uint64_t r = (x64 << 32) | y64; return r; } icosphere_face::icosphere_face() : gfx_vxo(vx_info("a_v3_position, a_iv4_color, a_v3_normal, a_v2_tex_coord"), true) { subdiv_count = -1; check_numbers.push_back(6); check_numbers.push_back(15); check_numbers.push_back(45); check_numbers.push_back(153); check_numbers.push_back(561); check_numbers.push_back(2145); check_numbers.push_back(8385); check_ind.push_back(3); check_ind.push_back(12); check_ind.push_back(48); check_ind.push_back(192); check_ind.push_back(768); check_ind.push_back(3072); check_ind.push_back(12288); } int icosphere_face::get_subdiv_count(){return subdiv_count;} void icosphere_face::gen_geometry(int isubdiv_count) { if(subdiv_count == isubdiv_count) { return; } std::vector<vx_fmt_p3f_c4b_n3f_t2f> vx_data; std::vector<gfx_indices_type> ind_data; std::vector<gfx_indices_type> ind_data_new; std::unordered_map<uint64_t, uint32_t> vertex_map; gfx_color& c = face_color; gfx_color clr = {c.r, c.g, c.b, c.a}; subdiv_count = isubdiv_count; for (int idx = 0; idx < 3; idx++) { glm::vec3& v = corners[idx]; vx_fmt_p3f_c4b_n3f_t2f vx = {{v.x, v.y, v.z}, clr, {}, {0, 0,}}; vx_data.push_back(vx); ind_data.push_back(idx); vertex_map[get_key(vx_data[idx].pos)] = idx; } for(int i = 0; i < subdiv_count; i++) { ind_data_new.clear(); for(int j = 0; j < ind_data.size(); j += 3) { glm::vec3 va = vx_data[ind_data[j + 0]].pos; glm::vec3 vb = vx_data[ind_data[j + 1]].pos; glm::vec3 vc = vx_data[ind_data[j + 2]].pos; int va_idx = vertex_map[get_key(va)]; int vb_idx = vertex_map[get_key(vb)]; int vc_idx = vertex_map[get_key(vc)]; //mws_print("va (%f, %f, %f) ", va.x, va.y, va.z); //mws_print("vb (%f, %f, %f) ", vb.x, vb.y, vb.z); //mws_print("vc (%f, %f, %f)\n", vc.x, vc.y, vc.z); glm::vec3 ab = glm::vec3(va.x + vb.x, va.y + vb.y, va.z + vb.z) * 0.5f; glm::vec3 cb = glm::vec3(vc.x + vb.x, vc.y + vb.y, vc.z + vb.z) * 0.5f; glm::vec3 ac = glm::vec3(va.x + vc.x, va.y + vc.y, va.z + vc.z) * 0.5f; ab = glm::normalize(ab) * radius; cb = glm::normalize(cb) * radius; ac = glm::normalize(ac) * radius; vx_fmt_p3f_c4b_n3f_t2f vab = {{ab.x, ab.y, ab.z}, clr, {}, {0, 0,}}; vx_fmt_p3f_c4b_n3f_t2f vcb = {{cb.x, cb.y, cb.z}, clr, {}, {0, 0,}}; vx_fmt_p3f_c4b_n3f_t2f vac = {{ac.x, ac.y, ac.z}, clr, {}, {0, 0,}}; uint64_t r1 = get_key(vab.pos); uint64_t r2 = get_key(vcb.pos); uint64_t r3 = get_key(vac.pos); int vab_idx = -1; int vcb_idx = -1; int vac_idx = -1; mws_assert(r1 != r2); mws_assert(r1 != r3); mws_assert(r2 != r3); if (vertex_map.find(r1) == vertex_map.end()) { vx_data.push_back(vab); vab_idx = vx_data.size() - 1; vertex_map[r1] = vab_idx; } else { vab_idx = vertex_map[r1]; } if (vertex_map.find(r2) == vertex_map.end()) { vx_data.push_back(vcb); vcb_idx = vx_data.size() - 1; vertex_map[r2] = vcb_idx; } else { vcb_idx = vertex_map[r2]; } if (vertex_map.find(r3) == vertex_map.end()) { vx_data.push_back(vac); vac_idx = vx_data.size() - 1; vertex_map[r3] = vac_idx; } else { vac_idx = vertex_map[r3]; } ind_data_new.push_back(va_idx); ind_data_new.push_back(vab_idx); ind_data_new.push_back(vac_idx); ind_data_new.push_back(vab_idx); ind_data_new.push_back(vb_idx); ind_data_new.push_back(vcb_idx); ind_data_new.push_back(vab_idx); ind_data_new.push_back(vcb_idx); ind_data_new.push_back(vac_idx); ind_data_new.push_back(vac_idx); ind_data_new.push_back(vcb_idx); ind_data_new.push_back(vc_idx); } int limit = check_numbers[i]; mws_assert(vertex_map.size() == limit); mws_assert(vx_data.size() == limit); ind_data = ind_data_new; } int vdata_size = vx_data.size() * sizeof(vx_fmt_p3f_c4b_n3f_t2f); int idata_size = ind_data.size() * sizeof(gfx_indices_type); gfx_vxo_util::set_mesh_data((const uint8_t*)vx_data.data(), vdata_size, ind_data.data(), idata_size, static_pointer_cast<gfx_vxo>(get_mws_sp())); } icosphere::icosphere() : gfx_vxo(vx_info("a_v3_position, a_iv4_color, a_v3_normal, a_v2_tex_coord")) { } void icosphere::update() { std::vector<mws_sp<gfx_node> >::iterator it = children.begin(); mws_sp<gfx_node> n = get_root()->find_node_by_name("defcam"); mws_sp<gfx_camera> camera; if(n) { camera = static_pointer_cast<gfx_camera>(n); } for (; it != children.end(); it++) { //(*it)->update_recursive(); if(camera) { mws_sp<icosphere_face> face = static_pointer_cast<icosphere_face>(*it); camera->draw_line(position, face->face_normal * radius * 1.5f, glm::vec4(1, 0, 0.f, 1.f), 1.f); //for (int k = 0; k < 3; k++) //{ // camera->draw_line(position, face->corner_normals[k] * radius * 1.5f, ia_color::colors::cyan.to_vec4(), 1.f); //} } } } int icosphere::get_face_count() { return children.size(); } mws_sp<icosphere_face> icosphere::get_face_at(int iidx) { mws_sp<gfx_node> n = children[iidx]; return static_pointer_cast<icosphere_face>(n); } void icosphere::set_dimensions(float iradius, int isubdiv_count) { float size = 1.f; float t = (1.f + glm::sqrt(5.f)) / 2.f; radius = iradius; glm::vec3 tvertices_data[] = { glm::vec3(-size, t*size, 0), glm::vec3(size, t*size, 0), glm::vec3(-size, -t*size, 0), glm::vec3(size, -t*size, 0), glm::vec3(0, -size, t*size), glm::vec3(0, size, t*size), glm::vec3(0, -size, -t*size), glm::vec3(0, size, -t*size), glm::vec3(t*size, 0, -size), glm::vec3(t*size, 0, size), glm::vec3(-t*size, 0, -size), glm::vec3(-t*size, 0, size), }; glm::vec3 vertices_normals[12]; const gfx_indices_type tindices_data[] = { // 5 faces around point 0 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, // 5 adjacent faces 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, // 5 faces around point 3 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, // 5 adjacent faces 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1, }; face_colors.clear(); face_colors.push_back(gfx_color::colors::blue); face_colors.push_back(gfx_color::colors::blue_violet); face_colors.push_back(gfx_color::colors::cyan); face_colors.push_back(gfx_color::colors::dark_orange); face_colors.push_back(gfx_color::colors::yellow); face_colors.push_back(gfx_color::colors::dark_red); face_colors.push_back(gfx_color::colors::deep_pink); face_colors.push_back(gfx_color::colors::dodger_blue); face_colors.push_back(gfx_color::colors::gold); face_colors.push_back(gfx_color::colors::gray); face_colors.push_back(gfx_color::colors::green); face_colors.push_back(gfx_color::colors::indigo); face_colors.push_back(gfx_color::colors::lavender); face_colors.push_back(gfx_color::colors::magenta); face_colors.push_back(gfx_color::colors::orange); face_colors.push_back(gfx_color::colors::orchid); face_colors.push_back(gfx_color::colors::papaya_whip); face_colors.push_back(gfx_color::colors::pink); face_colors.push_back(gfx_color::colors::plum); face_colors.push_back(gfx_color::colors::red); for (int k = 0; k < 12; k++) { glm::vec3& p = tvertices_data[k]; p = glm::normalize(p); vertices_normals[k] = p; p *= iradius; } RNG rng; for (int k = 0; k < 20; k++) { mws_sp<icosphere_face> face(new icosphere_face()); face->middle_point = face->face_normal = glm::vec3(0.f); for (int idx = 0; idx < 3; idx++) { int v_idx = tindices_data[3 * k + idx]; glm::vec3 v = tvertices_data[v_idx]; face->corners[idx] = v; face->corner_normals[idx] = vertices_normals[v_idx]; face->face_normal += face->corner_normals[idx]; face->middle_point += face->corners[idx]; } isubdiv_count = 0;//rng.range(2, 7); face->radius = iradius; face->face_color = face_colors[k]; face->face_normal = glm::normalize(face->face_normal / 3.f); face->middle_point = face->face_normal * iradius; face->gen_geometry(isubdiv_count); attach(face); } }
25.375375
146
0.653846
indigoabstract
e3c6d5bcb6f2f518f533ed7d75e634e36de180dc
214
cpp
C++
source/Phase1/main.cpp
MoaazZaki/coolGameEngine
2324c62c5c7ad6860b3a8b817cd24ca80b1b18ae
[ "MIT" ]
2
2021-01-18T20:51:54.000Z
2021-11-01T08:41:38.000Z
source/Phase1/main.cpp
MoaazZaki/coolGameEngine
2324c62c5c7ad6860b3a8b817cd24ca80b1b18ae
[ "MIT" ]
null
null
null
source/Phase1/main.cpp
MoaazZaki/coolGameEngine
2324c62c5c7ad6860b3a8b817cd24ca80b1b18ae
[ "MIT" ]
null
null
null
#include <game-state/GameStateManager.hpp> #include <iostream> int main(int argc, char** argv) { famm::GameStateManager pleaseWork; pleaseWork.onInitilaize(); pleaseWork.onDraw(); return 0; }
19.454545
42
0.686916
MoaazZaki
e3cfa36fb65536193e5e1e295e217584eada7e27
2,476
hxx
C++
tropical_convolution.hxx
pawelswoboda/tropical-convolution
e4de71fec95390ef8878d5b504a0b26eb11ead38
[ "MIT" ]
null
null
null
tropical_convolution.hxx
pawelswoboda/tropical-convolution
e4de71fec95390ef8878d5b504a0b26eb11ead38
[ "MIT" ]
null
null
null
tropical_convolution.hxx
pawelswoboda/tropical-convolution
e4de71fec95390ef8878d5b504a0b26eb11ead38
[ "MIT" ]
null
null
null
#ifndef TROPICAL_CONVOLUTION_HXX #define TROPICAL_CONVOLUTION_HXX #include <tuple> #include <cassert> #include "tropical_convolution_naive.hxx" #include "tropical_convolution_bussieck.hxx" #include "min_sum.hxx" // perform min convolution. Choose automatically betweeen the naive version which is fast on small inputs and the method by Bussieck et al tends to be faster for larger input namespace tropical_convolution{ // automatically choose between naive and efficient version of min convolution // when more elements than indicated by threshold need to be computed, use heuristic, otherwise use naive implementation. // a good value can be gleaned from the results of the benchmark program. static const std::size_t min_conv_threshold = 160; // break even value of the two implementations gleaned from running tropical_convolution_benchmark template<typename INPUT_ITERATOR_1, typename INPUT_ITERATOR_2, typename OUTPUT_ITERATOR> void min_conv(INPUT_ITERATOR_1 a_begin, INPUT_ITERATOR_1 a_end, INPUT_ITERATOR_2 b_begin, INPUT_ITERATOR_2 b_end, OUTPUT_ITERATOR result_begin, OUTPUT_ITERATOR result_end) { const auto result_size = std::distance(result_begin, result_end); if(result_size < min_conv_threshold) { return min_conv_naive(a_begin, a_end, b_begin, b_end, result_begin, result_end); } else { return min_conv_Bussieck_et_al(a_begin, a_end, b_begin, b_end, result_begin, result_end); } } // additionally return the index coming from the first vector for the optimum convolution. template<typename INPUT_ITERATOR_1, typename INPUT_ITERATOR_2, typename OUTPUT_ITERATOR_VAL, typename OUTPUT_ITERATOR_INDEX> void min_conv( INPUT_ITERATOR_1 a_begin, INPUT_ITERATOR_1 a_end, INPUT_ITERATOR_2 b_begin, INPUT_ITERATOR_2 b_end, OUTPUT_ITERATOR_VAL result_begin, OUTPUT_ITERATOR_VAL result_end, OUTPUT_ITERATOR_INDEX result_index_a_begin) { const auto result_size = std::distance(result_begin, result_end); if(result_size < min_conv_threshold) { return min_conv_naive(a_begin, a_end, b_begin, b_end, result_begin, result_end, result_index_a_begin); } else { return min_conv_Bussieck_et_al(a_begin, a_end, b_begin, b_end, result_begin, result_end, result_index_a_begin); } } } // end namespace tropical_convolution #endif // TROPICAL_CONVOLUTION_HXX
52.680851
177
0.756866
pawelswoboda
e3d4aba1556d3d66b8ea41e6050ddc66ee5178fa
3,998
cpp
C++
tests/approval_tests/cdv/elem/swatch_legend.cpp
cpp-niel/cdv
9aa310c6fe66dbc7f224ace3a3d4212ca6f0ed4a
[ "MIT" ]
1
2020-08-09T01:05:30.000Z
2020-08-09T01:05:30.000Z
tests/approval_tests/cdv/elem/swatch_legend.cpp
cpp-niel/cdv
9aa310c6fe66dbc7f224ace3a3d4212ca6f0ed4a
[ "MIT" ]
null
null
null
tests/approval_tests/cdv/elem/swatch_legend.cpp
cpp-niel/cdv
9aa310c6fe66dbc7f224ace3a3d4212ca6f0ed4a
[ "MIT" ]
null
null
null
#include <framework/approval_tests.hpp> #include <cdv/core/color/categorical_schemes.hpp> #include <cdv/elem/swatch_legend.hpp> #include <cdv/fig/frame.hpp> #include <cdv/fig/render_svg.hpp> #include <cdv/stdx/date_io.hpp> #include <array> namespace cdv::elem { namespace { using namespace units_literals; using namespace std::string_literals; using namespace date::literals; namespace rv = ::ranges::views; } TEST_SUITE("swatch legend") { TEST_CASE("swatches in columns") { const auto frame = fig::frame(480_px, 240_px); // mdinject-begin: swatch-legend-with-columns auto scale = scl::ordinal_scale(std::array{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, scheme::accent); const auto legend = elem::swatch_legend{.scale = scale, .pos = {30_px, 210_px}, .columns = {100_px, 100_px, 100_px}}; // mdinject-end test::approve_svg(fig::render_to_svg_string(frame.dimensions(), legend)); } TEST_CASE("simple swatches") { const auto scale0 = scl::ordinal_scale(std::array{"dogs", "cats", "hamsters"}, scheme::accent); const auto legend0 = elem::swatch_legend{.scale = scale0, .pos = {50_px, 450_px}}; const auto scale1 = scl::ordinal_scale( std::array{"very long text followed by very", "short", "text as swatch labels"}, scheme::dark2); const auto legend1 = elem::swatch_legend{.scale = scale1, .pos = {50_px, 400_px}}; const auto scale2 = scl::ordinal_scale( std::array{2020_y / date::August / 10, 2025_y / date::October / 16, 2030_y / date::May / 01}, scheme::set1); const auto legend2 = elem::swatch_legend{.scale = scale2, .pos = {50_px, 350_px}, .label_format_specifier = "%d-%b-%Y"}; const auto scale3 = scl::ordinal_scale(std::array{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, scheme::pastel1); const auto legend3 = elem::swatch_legend{.scale = scale3, .pos = {50_px, 300_px}}; const auto scale4 = scl::ordinal_scale(std::array{"10K", "Half Marathon", "Marathon"}, scheme::pastel2); const auto legend4 = elem::swatch_legend{ .scale = scale4, .pos = {50_px, 250_px}, .block_width = 30_px, .block_height = 10_px, .title = "Races"}; const auto scale5 = scl::ordinal_scale(std::array{"10K", "Half Marathon", "Marathon"}, scheme::tableau10); const auto legend5 = elem::swatch_legend{.scale = scale5, .pos = {50_px, 200_px}, .block_width = 30_px, .block_height = 10_px, .title = "Races", .title_properties = text_properties{.color = css4::darkred, .font_size = 12_pt}, // TODO is this a bug in CTAD for aggregates? can't deduce const char* from the scale when fint size is specified!?!? unless text_properties is explicitly given .title_offset = {20_px, 6_px}, .label_properties = {.color = css4::darkgreen}}; const auto scale6 = scl::ordinal_scale(std::array{"More", "than", "three", "entries", "which", "allows", "columns", "to", "be", "demonstrated"}, scheme::paired); const auto legend6 = elem::swatch_legend{ .scale = scale6, .pos = {50_px, 150_px}, .block_height = 24_px, .columns = {160_px, 160_px, 160_px}}; test::approve_svg( fig::render_to_svg_string({}, legend0, legend1, legend2, legend3, legend4, legend5, legend6)); } } }
51.25641
294
0.537269
cpp-niel
e3dd9824aa4d09efb272bffde134c9ee0b23fd63
770
cpp
C++
Lab_exercise/lab2/ex2/sizeof.cpp
Aries-Dawn/Cpp-Program-Design
9d4fc9a902fff2f76e41314f5d6c52871d30a511
[ "MIT" ]
null
null
null
Lab_exercise/lab2/ex2/sizeof.cpp
Aries-Dawn/Cpp-Program-Design
9d4fc9a902fff2f76e41314f5d6c52871d30a511
[ "MIT" ]
null
null
null
Lab_exercise/lab2/ex2/sizeof.cpp
Aries-Dawn/Cpp-Program-Design
9d4fc9a902fff2f76e41314f5d6c52871d30a511
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdbool.h> int main() { printf("\nPrint size of the fundamental types:\n"); printf("-----------------------------------------\n"); printf("The sizeof(char) is:%ld bytes.\n", sizeof(char)); printf("The sizeof(short) is:%ld bytes.\n", sizeof(short)); printf("The sizeof(int) is:%ld bytes.\n",sizeof(int)); printf("The sizeof(long) is:%ld bytes.\n", sizeof(long)); printf("The sizeof(long long) is:%ld bytes.\n", sizeof(long long)); printf("The sizeof(float) is:%ld bytes.\n", sizeof(float)); printf("The sizeof(double) is:%ld bytes.\n", sizeof(double)); printf("The sizeof(long double) is:%ld bytes.\n",sizeof(long double)); printf("The sizeof(bool) is:%ld byte.\n", sizeof(bool)); return 0; }
42.777778
74
0.601299
Aries-Dawn
e3df424b6433eb1f55bb5c615ce6326bb65c501a
8,298
cpp
C++
sdk/physx/2.8.3/Samples/SampleParticleFluid/src/SamplePacketData.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
1
2018-09-20T10:01:30.000Z
2018-09-20T10:01:30.000Z
sdk/physx/2.8.3/Samples/SampleParticleFluid/src/SamplePacketData.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
sdk/physx/2.8.3/Samples/SampleParticleFluid/src/SamplePacketData.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
#include "SampleParticleFluid.h" #include "MyFluid.h" #include "ParticleFactory.h" extern NxActor *gGroundPlane; extern bool gHardwareSimulation; extern NxScene* gScene; extern NxPhysicsSDK* gPhysicsSDK; extern NxArray<MyFluid*> gMyFluids; extern NxVec3 gCameraPos; extern NxVec3 gCameraForward; extern bool gWireframeMode; extern bool gShadows; #ifdef __PPCGEKKO__ #define MAX_PARTICLES 1000 #else #define MAX_PARTICLES 10000 #endif NxFluidPacketData gFluidPacketData; NxU32 gNumPackets; static unsigned gNewParticlesMax = MAX_PARTICLES; static unsigned gNewParticlesNum = 0; static ParticleSDK* gNewParticles = NULL; static NxParticleData gNewParticleData; static NxActor* gSphere = 0; static float gSphereRadius = 3.0f; static float gDistance = 0.2f; static float gLifetime = 0.0f; void SamplePacketData::setup() { SetTitleString(getName()); #ifdef __PPCGEKKO__ SetHelpString(" a: throw scoop"); #else SetHelpString(" b: throw scoop"); #endif gNewParticles = new ParticleSDK[gNewParticlesMax]; gFluidPacketData.bufferFluidPackets = new NxFluidPacket[(NxU32)gPhysicsSDK->getParameter(NX_CONSTANT_FLUID_MAX_PACKETS)]; gFluidPacketData.numFluidPacketsPtr = &gNumPackets; //Setup structure which wraps the buffers for particle creation. gNewParticleData.numParticlesPtr = &gNewParticlesNum; gNewParticleData.bufferPos = &gNewParticles[0].position.x; gNewParticleData.bufferPosByteStride = sizeof(ParticleSDK); gNewParticleData.bufferVel = &gNewParticles[0].velocity.x; gNewParticleData.bufferVelByteStride = sizeof(ParticleSDK); gNewParticleData.bufferLife = &gNewParticles[0].lifetime; gNewParticleData.bufferLifeByteStride = sizeof(ParticleSDK); gPhysicsSDK->setParameter(NX_VISUALIZE_FLUID_PACKET_DATA, 1.0f); //gPhysicsSDK->setParameter(NX_VISUALIZE_FLUID_PACKETS, 1.0f); NxVec3 fluidPos(0,1,0); // Create actors in the scene CreateGroundPlane(-3.0f)->getShapes()[0]->setGroup(1); gGroundPlane = CreateGroundPlane(); #ifdef __PPCGEKKO1__ CreateBox(NxVec3( 0, 0, 4), NxVec3(4.3,0.5,0.3), 0)->getShapes()[0]->setGroup(2); CreateBox(NxVec3( 0, 0,-4), NxVec3(4.3,0.5,0.3), 0)->getShapes()[0]->setGroup(2); CreateBox(NxVec3( 4, 0, 0), NxVec3(0.3,0.5,4.3), 0)->getShapes()[0]->setGroup(2); CreateBox(NxVec3(-4, 0, 0), NxVec3(0.3,0.5,4.3), 0)->getShapes()[0]->setGroup(2); #else CreateBox(NxVec3( 0, 0, 11), NxVec3(11.3,2.5,0.3), 0)->getShapes()[0]->setGroup(2); CreateBox(NxVec3( 0, 0,-11), NxVec3(11.3,2.5,0.3), 0)->getShapes()[0]->setGroup(2); CreateBox(NxVec3( 11, 0, 0), NxVec3(0.3,2.5,11.3), 0)->getShapes()[0]->setGroup(2); CreateBox(NxVec3(-11, 0, 0), NxVec3(0.3,2.5,11.3), 0)->getShapes()[0]->setGroup(2); #endif gSphere = CreateSphere(NxVec3( 0, -gSphereRadius, 0), gSphereRadius, 1.0f); gSphere->raiseActorFlag(NX_AF_FLUID_DISABLE_COLLISION); gSphere->getShapes()[0]->setGroup(1); // disable collision for sphere and upper plane gScene->setGroupCollisionFlag(0, 1, false); //Setup fluid descriptor NxFluidDesc fluidDesc; fluidDesc.maxParticles = MAX_PARTICLES; fluidDesc.kernelRadiusMultiplier = 2.0f; #ifdef __PPCGEKKO1__ fluidDesc.restParticlesPerMeter = 0.9f/gDistance; fluidDesc.packetSizeMultiplier = 4; fluidDesc.stiffness = 80.0f; fluidDesc.viscosity = 80.0f; fluidDesc.motionLimitMultiplier = 3.0f; fluidDesc.collisionDistanceMultiplier = 0.1; #else fluidDesc.restParticlesPerMeter = 1.0f/gDistance; fluidDesc.motionLimitMultiplier = 3.0f; fluidDesc.packetSizeMultiplier = 8; fluidDesc.collisionDistanceMultiplier = 0.1; fluidDesc.stiffness = 50.0f; fluidDesc.viscosity = 40.0f; #endif fluidDesc.restDensity = 1000.0f; fluidDesc.damping = 0.0f; fluidDesc.restitutionForStaticShapes = 0.3f; fluidDesc.dynamicFrictionForStaticShapes= 0.05f; fluidDesc.simulationMethod = NX_F_SPH; fluidDesc.fluidPacketData = gFluidPacketData; if (!gHardwareSimulation) fluidDesc.flags &= ~NX_FF_HARDWARE; NxVec3 fluidVel; fluidPos.set(0,4,0); fluidVel.set(0,0,0); NxBounds3 aabb; #ifdef __PPCGEKKO1__ aabb.set(NxVec3(-2.8,0,-2.8), NxVec3(2.8,0,2.8)); CreateParticleAABB(gNewParticleData, gNewParticlesMax, gNewParticlesMax, false, aabb, fluidVel, gLifetime, gDistance); #else aabb.set(NxVec3(-6.8,0,-6.8), NxVec3(6.8,0,6.8)); CreateParticleAABB(gNewParticleData, gNewParticlesMax, gNewParticlesMax, false, aabb, fluidVel, gLifetime, gDistance); aabb.set(NxVec3(5,0,5), NxVec3(10,0,10)); CreateParticleAABB(gNewParticleData, gNewParticlesMax, gNewParticlesMax, true, aabb, fluidVel, gLifetime, gDistance); #endif fluidDesc.initialParticleData = gNewParticleData; //Create user fluid. //- create NxFluid in NxScene //- setup the buffers to read from data from the SDK //- set NxFluid::userData field to MyFluid instance bool trackUserData = true; bool provideCollisionNormals = false; MyFluid* fluid = new MyFluid(gScene, fluidDesc, trackUserData, provideCollisionNormals, NxVec3(0.3f,0.4f,0.7f), 0.03f); assert(fluid); gMyFluids.pushBack(fluid); #ifdef __PPCGEKKO1__ gCameraPos.set(6.51f,13.40f,10.43f); #else gCameraPos.set(1.43f,10.96f,17.9f); #endif gCameraForward = fluidPos - gCameraPos; gCameraForward.normalize(); gShadows = false; gWireframeMode = true; } void SamplePacketData::cleanup() { //MyFluid cleaned up by ReleaseNx() delete[] gFluidPacketData.bufferFluidPackets; delete[] gNewParticles; gFluidPacketData.bufferFluidPackets = NULL; } void SamplePacketData::update() { if (!gMyFluids.size()) return; MyFluid* fluid = gMyFluids[0]; // walk over packets and color fluid particles depending on their position relative to the big sphere. for(NxU32 p = 0; p < *gFluidPacketData.numFluidPacketsPtr; p++) { NxVec3 center, extents; NxFluidPacket& packet = gFluidPacketData.bufferFluidPackets[p]; packet.aabb.fatten(gSphereRadius); bool insideAABB = packet.aabb.contain(gSphere->getShapes()[0]->getGlobalPosition()); for(NxU32 i = packet.firstParticleIndex; i < packet.firstParticleIndex + packet.numParticles; i++) { const ParticleSDK& particle = fluid->getParticles()[i]; MyParticle& myParticle = fluid->getMyParticles()[particle.id]; if(insideAABB) { if(particle.position.distance(gSphere->getShapes()[0]->getGlobalPosition()) <= gSphereRadius) { myParticle.rgba[0] = 1.0f; myParticle.rgba[1] = 0.0f; myParticle.rgba[2] = 0.0f; myParticle.rgba[3] = 1.0f; } else { myParticle.rgba[0] = 1.0f; myParticle.rgba[1] = 1.0f; myParticle.rgba[2] = 0.0f; myParticle.rgba[3] = 1.0f; } } else { myParticle.rgba[0] = 0.0f; myParticle.rgba[1] = 0.0f; myParticle.rgba[2] = 1.0f; myParticle.rgba[3] = 1.0f; } } } } void SamplePacketData::onKeyPress(unsigned char key, int x, int y) { if(!gMyFluids.size()) return; MyFluid* fluid = gMyFluids[0]; switch(key) { case 'b': { //Throw a small scoop of random color. //Note: if to many particles are added (exceeding of per frame limitation or hitting NxFluid::getMaxParticles()). //a warning appears in the console. NxVec3 baseColor(NxMath::rand(0.2f,0.8f), NxMath::rand(0.2f,0.8f), NxMath::rand(0.2f,0.8f)); NxVec3 fluidPos = gCameraPos + NxVec3(0,-2,0); #ifdef __PPCGEKKO1__ NxVec3 fluidVel = gCameraForward + NxVec3(0,0.65f,0); fluidVel.setMagnitude(8); CreateParticleSphere(gNewParticleData, gNewParticlesMax, false, fluidPos, fluidVel, 5.0, gDistance, 6); #else NxVec3 fluidVel = gCameraForward + NxVec3(0,0.5f,0); fluidVel.setMagnitude(15); CreateParticleSphere(gNewParticleData, gNewParticlesMax, false, fluidPos, fluidVel, 5.0, gDistance, 8); #endif fluid->getNxFluid()->addParticles(gNewParticleData); for(unsigned i=0; i<fluid->getCreatedIdsNum(); i++) { unsigned id = fluid->getCreatedIds()[i]; MyParticle& myParticle = fluid->getMyParticles()[id]; myParticle.rgba[0] = NxMath::rand(baseColor.x - 0.2f, baseColor.x + 0.2f); myParticle.rgba[1] = NxMath::rand(baseColor.y - 0.2f, baseColor.y + 0.2f); myParticle.rgba[2] = NxMath::rand(baseColor.z - 0.2f, baseColor.z + 0.2f); myParticle.rgba[3] = 1.0f; } } break; default: break; } }
33.325301
122
0.716558
daher-alfawares
e3e3e13df41a9f4f63e828f4b20ac05e94b6ded7
10,290
cpp
C++
tests/pingpair_test/pingpair_test.cpp
zzuummaa/Arduino_rf24
f4c27f311b9756eba44feef7ed1bbe3940fd823a
[ "BSD-3-Clause" ]
null
null
null
tests/pingpair_test/pingpair_test.cpp
zzuummaa/Arduino_rf24
f4c27f311b9756eba44feef7ed1bbe3940fd823a
[ "BSD-3-Clause" ]
null
null
null
tests/pingpair_test/pingpair_test.cpp
zzuummaa/Arduino_rf24
f4c27f311b9756eba44feef7ed1bbe3940fd823a
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2011 James Coliz, Jr. <maniacbug@ymail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. */ /** * Full test on single RF pair * * This sketches uses as many RF24 methods as possible in a single test. * * To operate: * Upload this sketch on two nodes, each with IRQ -> pin 2 * One node needs pin 7 -> GND, the other NC. That's the receiving node * Monitor the sending node's serial output * Look for "+OK PASS" or "+OK FAIL" */ #include <Arduino.h> #include <SPI.h> #include "nRF24L01.h" #include "RF24.h" #include "printf.h" // // Hardware configuration // // Set up nRF24L01 radio on SPI bus plus pins 8 & 9 RF24 radio(7,8); // sets the role of this unit in hardware. Connect to GND to be the 'pong' receiver // Leave open to be the 'ping' transmitter const short role_pin = 5; // // Topology // // Single radio pipe address for the 2 nodes to communicate. const uint64_t pipe = 0xE8E8F0F0E1LL; // // Role management // // Set up role. This sketch uses the same software for all the nodes in this // system. Doing so greatly simplifies testing. The hardware itself specifies // which node it is. // // This is done through the role_pin // // The various roles supported by this sketch typedef enum { role_sender = 1, role_receiver } role_e; // The debug-friendly names of those roles const char* role_friendly_name[] = { "invalid", "Sender", "Receiver"}; // The role of the current running sketch role_e role; // Interrupt handler, check the radio because we got an IRQ void check_radio(void); // // Payload // const int min_payload_size = 4; const int max_payload_size = 32; int payload_size_increments_by = 2; int next_payload_size = min_payload_size; char receive_payload[max_payload_size+1]; // +1 to allow room for a terminating NULL char // // Test state // bool done; //*< Are we done with the test? */ bool passed; //*< Have we passed the test? */ bool notified; //*< Have we notified the user we're done? */ const int num_needed = 10; //*< How many success/failures until we're done? */ int receives_remaining = num_needed; //*< How many ack packets until we declare victory? */ int failures_remaining = num_needed; //*< How many more failed sends until we declare failure? */ const int interval = 100; //*< ms to wait between sends */ char configuration = '1'; //*< Configuration key, one char sent in by the test framework to tell us how to configure, this is the default */ uint8_t pipe_number = 1; // Which pipe to send on. void one_ok(void) { // Have we received enough yet? if ( ! --receives_remaining ) { done = true; passed = true; } } void one_failed(void) { // Have we failed enough yet? if ( ! --failures_remaining ) { done = true; passed = false; } } // // Setup // void setup(void) { // // Role // // set up the role pin pinMode(role_pin, INPUT); digitalWrite(role_pin,HIGH); delay(20); // Just to get a solid reading on the role pin // read the address pin, establish our role if ( digitalRead(role_pin) ) role = role_sender; else role = role_receiver; // // Print preamble // Serial.begin(115200); printf_begin(); printf("\n\rRF24/tests/pingpair_test/\n\r"); printf("ROLE: %s\n\r",role_friendly_name[role]); // // Read configuration from serial // // It would be a much better test if this program could accept configuration // from the serial port. Then it would be possible to run the same test under // lots of different circumstances. // // The idea is that we will print "+READY" at this point. The python script // will wait for it, and then send down a configuration script that we // execute here and then run with. // // The test controller will need to configure the receiver first, then go run // the test on the sender. // printf("+READY press any key to start\n\r\n\r"); while (! Serial.available() ) {} configuration = Serial.read(); printf("Configuration\t = %c\n\r",configuration); // // Setup and configure rf radio // radio.begin(); // We will be using the Ack Payload feature, so please enable it radio.enableAckPayload(); // Config 2 is special radio config if (configuration=='2') { radio.setCRCLength(RF24_CRC_8); radio.setDataRate(RF24_250KBPS); radio.setChannel(10); } else { //Otherwise, default radio config // Optional: Increase CRC length for improved reliability radio.setCRCLength(RF24_CRC_16); // Optional: Decrease data rate for improved reliability radio.setDataRate(RF24_1MBPS); // Optional: Pick a high channel radio.setChannel(90); } // Config 3 is static payloads only if (configuration == '3') { next_payload_size = 16; payload_size_increments_by = 0; radio.setPayloadSize(next_payload_size); } else { // enable dynamic payloads radio.enableDynamicPayloads(); } // Config 4 tests out a higher pipe ## if (configuration == '4' && role == role_sender) { // Set top 4 bytes of the address in pipe 1 radio.openReadingPipe(1,pipe & 0xFFFFFFFF00ULL); // indicate the pipe to use pipe_number = 5; } else if ( role == role_sender ) { radio.openReadingPipe(5,0); } // // Open pipes to other nodes for communication // // This simple sketch opens a single pipe for these two nodes to communicate // back and forth. One listens on it, the other talks to it. if ( role == role_sender ) { radio.openWritingPipe(pipe); } else { radio.openReadingPipe(pipe_number,pipe); } // // Start listening // if ( role == role_receiver ) radio.startListening(); // // Dump the configuration of the rf unit for debugging // radio.printDetails(); // // Attach interrupt handler to interrupt #0 (using pin 2) // on BOTH the sender and receiver // attachInterrupt(0, check_radio, FALLING); delay(50); if ( role == role_receiver ) printf("\n\r+OK "); } // // Print buffer // // Printing from the interrupt handler is a bad idea, so we print from there // to this intermediate buffer // char prbuf[1000]; char *prbuf_end = prbuf + sizeof(prbuf); char *prbuf_in = prbuf; char *prbuf_out = prbuf; // // Loop // static uint32_t message_count = 0; static uint32_t last_message_count = 0; void loop(void) { // // Sender role. Repeatedly send the current time // if (role == role_sender && !done) { // The payload will always be the same, what will change is how much of it we send. static char send_payload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ789012"; // First, stop listening so we can talk. radio.stopListening(); // Send it. This will block until complete printf("\n\rNow sending length %i...",next_payload_size); radio.startWrite( send_payload, next_payload_size,0 ); // Update size for next time. next_payload_size += payload_size_increments_by; if ( next_payload_size > max_payload_size ) next_payload_size = min_payload_size; // Try again soon delay(interval); // Timeout if we have not received anything back ever if ( ! last_message_count && millis() > interval * 100 ) { printf("No responses received. Are interrupts connected??\n\r"); done = true; } } // // Receiver role: Does nothing! All the work is in IRQ // // // Spew print buffer // size_t write_length = prbuf_in - prbuf_out; if ( write_length ) { Serial.write(reinterpret_cast<uint8_t*>(prbuf_out),write_length); prbuf_out += write_length; } // // Stop the test if we're done and report results // if ( done && ! notified ) { notified = true; printf("\n\r+OK "); if ( passed ) printf("PASS\n\r\n\r"); else printf("FAIL\n\r\n\r"); } } void check_radio(void) { // What happened? bool tx,fail,rx; radio.whatHappened(tx,fail,rx); // Have we successfully transmitted? if ( tx ) { if ( role == role_sender ) prbuf_in += sprintf(prbuf_in,"Send:OK "); if ( role == role_receiver ) prbuf_in += sprintf(prbuf_in,"Ack Payload:Sent\n\r"); } // Have we failed to transmit? if ( fail ) { if ( role == role_sender ) { prbuf_in += sprintf(prbuf_in,"Send:Failed "); // log status of this line one_failed(); } if ( role == role_receiver ) prbuf_in += sprintf(prbuf_in,"Ack Payload:Failed\n\r"); } // Not powering down since radio is in standby mode //if ( ( tx || fail ) && ( role == role_sender ) ) //radio.powerDown(); // Did we receive a message? if ( rx ) { // If we're the sender, we've received an ack payload if ( role == role_sender ) { radio.read(&message_count,sizeof(message_count)); prbuf_in += sprintf(prbuf_in,"Ack:%lu ",message_count); // is this ack what we were expecting? to account // for failures, we simply want to make sure we get a // DIFFERENT ack every time. if ( ( message_count != last_message_count ) || ( configuration=='3' && message_count == 16 ) ) { prbuf_in += sprintf(prbuf_in,"OK "); one_ok(); } else { prbuf_in += sprintf(prbuf_in,"FAILED "); one_failed(); } last_message_count = message_count; } // If we're the receiver, we've received a time message if ( role == role_receiver ) { // Get this payload and dump it size_t len = max_payload_size; memset(receive_payload,0,max_payload_size); if ( configuration == '3' ){ len = next_payload_size; }else{ len = radio.getDynamicPayloadSize(); } radio.read( receive_payload, len ); // Put a zero at the end for easy printing receive_payload[len] = 0; // Spew it prbuf_in += sprintf(prbuf_in,"Recv size=%i val=%s len=%u\n\r",len,receive_payload,strlen(receive_payload)); // Add an ack packet for the next time around. // Here we will report back how many bytes we got this time. radio.writeAckPayload( pipe_number, &len, sizeof(len) ); ++message_count; } } }
23.493151
140
0.651312
zzuummaa
e3e5e7665694515653114ea1ca640e65ad799912
4,594
cpp
C++
src/TurtleBot.cpp
sukoonsarin/fetch-it
d05518aa922e58737daa9a03957ec90e8505587e
[ "BSD-3-Clause" ]
null
null
null
src/TurtleBot.cpp
sukoonsarin/fetch-it
d05518aa922e58737daa9a03957ec90e8505587e
[ "BSD-3-Clause" ]
null
null
null
src/TurtleBot.cpp
sukoonsarin/fetch-it
d05518aa922e58737daa9a03957ec90e8505587e
[ "BSD-3-Clause" ]
10
2020-12-01T18:09:41.000Z
2021-01-13T17:38:43.000Z
/** * @file turtlebot.cpp * @brief Source file to implement turtlebot class * @date 12/07/2020 * @author Nidhi Bhojak * @author Nalin Das * * @section LICENSE * * @copyright (c) 2020, Nalin Das, Sukoon Sarin, Nidhi Bhojak * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * Controls motion of the turtlebot * */ // Add ROS headers #include <std_msgs/Int8.h> #include "ros/ros.h" #include "../include/TurtleBot.h" #include "geometry_msgs/Twist.h" #include "../include/ObstacleAvoidance.h" // Implement Turtlebot Class /** * @brief Laser Callback function * @param data from LaserScan node * @return void * **/ TurtleBot::TurtleBot() { // Initialize to all zeros velocity.linear.x = 0.0; velocity.linear.y = 0.0; velocity.linear.z = 0.0; velocity.angular.x = 0.0; velocity.angular.y = 0.0; velocity.angular.z = 0.0; // Publsh the velocities to /cmd_vel topic velocity_pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 10); // ROS Subscriber for ball_present topic detect_sub = nh.subscribe<std_msgs::Int8>("ball_present", 1000, &TurtleBot::detectCallback, this); } TurtleBot::~TurtleBot() { ROS_INFO_STREAM("Turtlebot will stop now."); } void TurtleBot::moveAhead(float linear_vel) { velocity.linear.x = linear_vel; velocity.angular.z = 0.0; } void TurtleBot::turn(float angular_vel) { velocity.linear.x = 0.0; velocity.angular.z = angular_vel; } // void TurtleBot::collect() { // } void TurtleBot::moveTurtle() { // Looprate of 4 Hz ros::Rate rate(4); while (ros::ok()) { // Define twist msg geometry_msgs::Twist twist; // True if obstacle present obstacle_present = obstacle_avoidance.checkObstacle(); ROS_WARN_STREAM("obstacle_present: " << obstacle_present << "ball_present:" << getBallPresent()); // Start moving the robot if no obstacle detected if (!obstacle_present && getBallPresent()) { ROS_WARN_STREAM("Moving forward ..."); moveAhead(-0.12); // Start turning the robot to avoid obstacle } else { ROS_WARN_STREAM("Rotating ..."); turn(0.8); } // Publish the velocties velocity_pub.publish(velocity); ros::spinOnce(); // Pause to maintain loop rate rate.sleep(); } } // void TurtleBot::reset() { // } void TurtleBot::setBallPresent(bool ball_present_) { ball_present = ball_present_; } bool TurtleBot::getBallPresent() { return ball_present; } geometry_msgs::Twist TurtleBot::getVelocity() { return velocity; } void TurtleBot::setObstaclePresent(bool present) { obstacle_present = present; } bool TurtleBot::getObstaclePresent() { return obstacle_present; } void TurtleBot::detectCallback(const std_msgs::Int8::ConstPtr& msg) { // ROS_WARN_STREAM("I heard: [%s]" << msg->data); (msg->data == 1) ? setBallPresent(true) : setBallPresent(false); // ROS_WARN_STREAM("ball_present inside callback:" << getBallPresent()); }
31.465753
81
0.686983
sukoonsarin
e3ec91ade9b49171f86d12d9eb2d074982229da2
9,966
cpp
C++
lib/PhasarLLVM/Utils/DOTGraph.cpp
n-junge/phasar
baa80e78bf67b80f030db4d1eedfb97755d407fc
[ "MIT" ]
null
null
null
lib/PhasarLLVM/Utils/DOTGraph.cpp
n-junge/phasar
baa80e78bf67b80f030db4d1eedfb97755d407fc
[ "MIT" ]
null
null
null
lib/PhasarLLVM/Utils/DOTGraph.cpp
n-junge/phasar
baa80e78bf67b80f030db4d1eedfb97755d407fc
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright (c) 2017 Philipp Schubert. * All rights reserved. This program and the accompanying materials are made * available under the terms of LICENSE.txt. * * Contributors: * Philipp Schubert and others *****************************************************************************/ /* * DOTGraph.cpp * * Created on: 31.08.2019 * Author: rleer */ #include <algorithm> #include <iterator> #include <ostream> #include "boost/filesystem.hpp" #include "nlohmann/json.hpp" #include "phasar/Config/Configuration.h" #include "phasar/PhasarLLVM/Utils/DOTGraph.h" namespace psr { DOTNode::DOTNode(std::string fName, std::string l, std::string sId, unsigned fId, bool isStmt, bool isv) : funcName(fName), label(l), stmtId(sId), factId(fId), isVisible(isv) { if (isStmt) { id = funcName + '_' + stmtId; } else { id = funcName + '_' + std::to_string(factId) + '_' + stmtId; } } std::string DOTNode::str(std::string indent) const { std::string str = indent + id + " [label=\"" + label; if (factId) { str += " | SID: " + stmtId; } str += "\""; if (!isVisible) { str += ", style=invis"; } return str + ']'; } DOTEdge::DOTEdge(DOTNode src, DOTNode tar, bool isv, std::string efl, std::string vl) : source(src), target(tar), isVisible(isv), edgeFnLabel(efl), valueLabel(vl) {} std::string DOTEdge::str(std::string indent) const { std::string str = indent + source.id + " -> " + target.id; if (isVisible) { if (!edgeFnLabel.empty() && !valueLabel.empty()) { str += " [headlabel=\"\\r" + edgeFnLabel + "\", taillabel=\"" + valueLabel + "\"]"; } else if (!edgeFnLabel.empty()) { str += " [headlabel=\"\\r" + edgeFnLabel + "\"]"; } else if (!valueLabel.empty()) { str += " [taillabel=\"" + valueLabel + "\"]"; } } else if (!isVisible) { str += " [style=invis]"; } return str; } std::string DOTFactSubGraph::str(std::string indent) const { std::string innerIndent = indent + " "; std::string str = indent + "subgraph cluster_" + id + " {\n" + innerIndent + "style=invis\n" + innerIndent + "label=\"" + label + "\"\n\n" + innerIndent + "// Fact nodes in the ESG\n" + innerIndent + DOTConfig::FactNodeAttr() + '\n'; // Print fact nodes for (auto n : nodes) { str += n.second.str(innerIndent) + '\n'; } // Print id edges str += '\n' + innerIndent + "// Identity edges for this fact\n" + innerIndent + DOTConfig::FactIDEdgeAttr() + '\n'; for (DOTEdge e : edges) { str += e.str(innerIndent) + '\n'; } return str + indent + '}'; } std::string DOTFunctionSubGraph::str(std::string indent) const { std::string innerIndent = indent + " "; std::string str = indent + "subgraph cluster_" + id + " {\n" + innerIndent + "label=\"" + id + "\""; // Print control flow nodes str += "\n\n" + innerIndent + "// Control flow nodes\n" + innerIndent + DOTConfig::CFNodeAttr() + '\n'; for (DOTNode stmt : stmts) { str += stmt.str(innerIndent) + '\n'; } // Print fact subgraphs str += '\n' + innerIndent + "// Fact subgraphs\n"; for (auto factSG : facts) { str += factSG.second.str(innerIndent) + "\n\n"; } // Print lambda subgraph str += generateLambdaSG(innerIndent); // Print intra control flow edges str += "\n\n" + innerIndent + "// Intra-procedural control flow edges\n" + innerIndent + DOTConfig::CFIntraEdgeAttr() + '\n'; for (DOTEdge e : intraCFEdges) { str += e.str(innerIndent) + '\n'; } // Print intra cross fact edges str += '\n' + innerIndent + "// Intra-procedural cross fact edges\n" + innerIndent + DOTConfig::FactCrossEdgeAttr() + '\n'; for (DOTEdge e : crossFactEdges) { str += e.str(innerIndent) + '\n'; } return str + indent + '}'; } DOTFactSubGraph *DOTFunctionSubGraph::getOrCreateFactSG(unsigned factID, std::string &label) { DOTFactSubGraph *FuncSG = &facts[factID]; if (FuncSG->id.empty()) { FuncSG->id = id + '_' + std::to_string(factID); FuncSG->factId = factID; FuncSG->label = label; } return FuncSG; } std::string DOTFunctionSubGraph::generateLambdaSG(std::string indent) const { std::string innerIndent = indent + " "; std::string str = indent + "// Auto-generated lambda nodes and edges\n" + indent + "subgraph cluster_" + id + "_lambda {\n" + innerIndent + "style=invis\n" + innerIndent + "label=\"Λ\"\n" + innerIndent + DOTConfig::LambdaNodeAttr() + '\n'; // Print lambda nodes for (DOTNode stmt : stmts) { str += innerIndent + id + "_0_" + stmt.stmtId + " [label=\"Λ|SID: " + stmt.stmtId + "\"]\n"; } // Print lambda edges str += '\n' + innerIndent + DOTConfig::LambdaIDEdgeAttr() + '\n'; for (DOTEdge e : intraCFEdges) { str += innerIndent + id + "_0_" + e.source.stmtId + " -> " + id + "_0_" + e.target.stmtId; if (e.isVisible) { str += " [headlabel=\"\\rAllBottom\", taillabel=\"BOT\"]\n"; } else { str += " [style=invis]\n"; } } return str + indent + '}'; } void DOTFunctionSubGraph::createLayoutCFNodes() { auto last = stmts.empty() ? stmts.end() : std::prev(stmts.end()); for (auto firstIt = stmts.begin(); firstIt != last; ++firstIt) { auto secondIt = std::next(firstIt); DOTNode n1 = *firstIt; DOTNode n2 = *secondIt; intraCFEdges.emplace(n1, n2, false); } } void DOTFunctionSubGraph::createLayoutFactNodes() { for (auto &[key, factSG] : facts) { for (auto stmt : stmts) { if (factSG.nodes.find(stmt.stmtId) == factSG.nodes.end()) { DOTNode factNode(stmt.funcName, factSG.label, stmt.stmtId, factSG.factId, false, false); factSG.nodes[stmt.stmtId] = factNode; } } } } void DOTFunctionSubGraph::createLayoutFactEdges() { for (auto &[key, factSG] : facts) { for (auto iCFE : intraCFEdges) { DOTNode d1 = {iCFE.source.funcName, factSG.label, iCFE.source.stmtId, factSG.factId, false}; DOTNode d2 = {iCFE.target.funcName, factSG.label, iCFE.target.stmtId, factSG.factId, false}; factSG.edges.emplace(d1, d2, false); } } } bool operator<(const DOTNode &lhs, const DOTNode &rhs) { stringIDLess strLess; // comparing control flow nodes if (lhs.factId == 0 && rhs.factId == 0) { return strLess(lhs.stmtId, rhs.stmtId); } else { // comparing fact nodes if (lhs.factId == rhs.factId) { return strLess(lhs.stmtId, rhs.stmtId); } else { return lhs.factId < rhs.factId; } } } bool operator==(const DOTNode &lhs, const DOTNode &rhs) { return !(lhs < rhs) && !(rhs < lhs); } std::ostream &operator<<(std::ostream &os, const DOTNode &node) { return os << node.str(); } bool operator<(const DOTEdge &lhs, const DOTEdge &rhs) { if (lhs.source == rhs.source) { return lhs.target < rhs.target; } return lhs.source < rhs.source; } std::ostream &operator<<(std::ostream &os, const DOTEdge &edge) { return os << edge.str(); } std::ostream &operator<<(std::ostream &os, const DOTFactSubGraph &factSG) { return os << factSG.str(); } std::ostream &operator<<(std::ostream &os, const DOTFunctionSubGraph &functionSG) { return os << functionSG.str(); } DOTConfig &DOTConfig::getDOTConfig() { static DOTConfig DC; return DC; } void DOTConfig::importDOTConfig() { boost::filesystem::path FilePath(PhasarConfig::PhasarDirectory()); FilePath /= boost::filesystem::path("config/DOTGraphConfig.json"); if (boost::filesystem::exists(FilePath) && !boost::filesystem::is_directory(FilePath)) { std::ifstream ifs(FilePath.string()); if (ifs.is_open()) { std::stringstream iss; iss << ifs.rdbuf(); ifs.close(); nlohmann::json jDOTConfig; iss >> jDOTConfig; for (auto &el : jDOTConfig.items()) { std::stringstream attr_str; if (el.key().find("Node") != std::string::npos) { attr_str << "node ["; } else { attr_str << "edge ["; } for (nlohmann::json::iterator it = el.value().begin(); it != el.value().end(); ++it) { // using it.value() directly with the << operator adds unnecessary // quotes std::string val = it.value(); attr_str << it.key() << "=" << val; if (std::next(it) != el.value().end()) { attr_str << ", "; } } attr_str << ']'; if (el.key() == "CFNode") { DOTConfig::CFNode = attr_str.str(); } else if (el.key() == "CFIntraEdge") { DOTConfig::CFIntraEdge = attr_str.str(); } else if (el.key() == "CFInterEdge") { DOTConfig::CFInterEdge = attr_str.str(); } else if (el.key() == "FactNode") { DOTConfig::FactNode = attr_str.str(); } else if (el.key() == "FactIDEdge") { DOTConfig::FactIDEdge = attr_str.str(); } else if (el.key() == "FactCrossEdge") { DOTConfig::FactCrossEdge = attr_str.str(); } else if (el.key() == "FactInterEdge") { DOTConfig::FactInterEdge = attr_str.str(); } else if (el.key() == "LambdaNode") { DOTConfig::LambdaNode = attr_str.str(); } else if (el.key() == "LambdaIDEdge") { DOTConfig::LambdaIDEdge = attr_str.str(); } else if (el.key() == "LambdaInterEdge") { DOTConfig::LambdaInterEdge = attr_str.str(); } } } else { throw std::ios_base::failure("Could not open file"); } } else { throw std::ios_base::failure(FilePath.string() + " is not a valid path"); } } } // namespace psr
32.357143
79
0.564921
n-junge
e3ee99a8280f603efe5928321aec707c37d87bf7
7,243
cpp
C++
src/lepage/input/SourceLocationProvider.test.cpp
jaydee-io/lepage
30ec14fa809e4e60de64ac7e5bf1f06ee71c93cf
[ "BSD-3-Clause" ]
null
null
null
src/lepage/input/SourceLocationProvider.test.cpp
jaydee-io/lepage
30ec14fa809e4e60de64ac7e5bf1f06ee71c93cf
[ "BSD-3-Clause" ]
null
null
null
src/lepage/input/SourceLocationProvider.test.cpp
jaydee-io/lepage
30ec14fa809e4e60de64ac7e5bf1f06ee71c93cf
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // lepage // // This file is distributed under the 3-clause Berkeley Software Distribution // License. See LICENSE for details. //////////////////////////////////////////////////////////////////////////////// #include "SourceLocationProvider.h" #include <gtest/gtest.h> using namespace lepage::input; TEST(SourceLocationProvider, DefaultLocation) { SourceLocationProvider sourceProvider; EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); } TEST(SourceLocationProvider, Forward_AnyCharacter) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 2); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); sourceProvider.forward('e'); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 3); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); } TEST(SourceLocationProvider, Forward_LineFeed) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\n'); EXPECT_EQ(sourceProvider.currentLocation().line, 2); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); } TEST(SourceLocationProvider, Forward_CarriageReturn) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\r'); EXPECT_EQ(sourceProvider.currentLocation().line, 2); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); } TEST(SourceLocationProvider, Forward_CarriageReturnLineFeed) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\r'); EXPECT_EQ(sourceProvider.currentLocation().line, 2); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); sourceProvider.forward('\n'); EXPECT_EQ(sourceProvider.currentLocation().line, 2); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); // CRLF occupies just one column } TEST(SourceLocationProvider, Forward_SuccessiveLineFeed) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\n'); sourceProvider.forward('\n'); sourceProvider.forward('\r'); sourceProvider.forward('\r'); EXPECT_EQ(sourceProvider.currentLocation().line, 5); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 4); EXPECT_EQ(sourceProvider.previousLocation().column, 1); } TEST(SourceLocationProvider, Backward_AnyCharacter) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('e'); sourceProvider.forward('s'); sourceProvider.forward('t'); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 4); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 3); } TEST(SourceLocationProvider, Backward_BeforeBegin) { SourceLocationProvider sourceProvider; sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); sourceProvider.forward('T'); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); } TEST(SourceLocationProvider, Backward_LineFeed) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\n'); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 2); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); } TEST(SourceLocationProvider, Backward_CarriageReturn) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\r'); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 2); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); } TEST(SourceLocationProvider, Backward_CarriageReturnLineFeed) { SourceLocationProvider sourceProvider; sourceProvider.forward('T'); sourceProvider.forward('\r'); EXPECT_EQ(sourceProvider.currentLocation().line, 2); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); sourceProvider.backward(); EXPECT_EQ(sourceProvider.currentLocation().line, 1); EXPECT_EQ(sourceProvider.currentLocation().column, 2); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 1); sourceProvider.forward('\r'); sourceProvider.forward('\n'); EXPECT_EQ(sourceProvider.currentLocation().line, 2); EXPECT_EQ(sourceProvider.currentLocation().column, 1); EXPECT_EQ(sourceProvider.previousLocation().line, 1); EXPECT_EQ(sourceProvider.previousLocation().column, 2); // CRLF occupies just one column }
36.580808
92
0.734088
jaydee-io
e3f4342df9ba193f40933fd4f7369d8c82b2e34c
2,555
cpp
C++
src/eos/general/eos_table.cpp
charge72002/Athena_Radiation-master
a192aeab0c3cd258853fe43468a4a1d8c2a9279d
[ "BSD-3-Clause" ]
null
null
null
src/eos/general/eos_table.cpp
charge72002/Athena_Radiation-master
a192aeab0c3cd258853fe43468a4a1d8c2a9279d
[ "BSD-3-Clause" ]
null
null
null
src/eos/general/eos_table.cpp
charge72002/Athena_Radiation-master
a192aeab0c3cd258853fe43468a4a1d8c2a9279d
[ "BSD-3-Clause" ]
1
2021-07-15T19:06:10.000Z
2021-07-15T19:06:10.000Z
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //====================================================================================== //! \file eos_table_hydro.cpp // \brief implements functions in class EquationOfState for an EOS lookup table //====================================================================================== // C headers // C++ headers #include <cmath> // sqrt() #include <fstream> #include <iostream> // ifstream #include <sstream> #include <stdexcept> // std::invalid_argument #include <string> // Athena++ headers #include "../../athena.hpp" #include "../../athena_arrays.hpp" #include "../../coordinates/coordinates.hpp" #include "../../field/field.hpp" #include "../../parameter_input.hpp" #include "../../utils/interp_table.hpp" #include "../eos.hpp" void EosTestLoop(EquationOfState *peos); //---------------------------------------------------------------------------------------- //! \fn Real EquationOfState::PresFromRhoEg(Real rho, Real egas) // \brief Return interpolated gas pressure Real EquationOfState::PresFromRhoEg(Real rho, Real egas) { return ptable->GetEosData(0, egas, rho) * egas; } //---------------------------------------------------------------------------------------- //! \fn Real EquationOfState::EgasFromRhoP(Real rho, Real pres) // \brief Return interpolated internal energy density Real EquationOfState::EgasFromRhoP(Real rho, Real pres) { return ptable->GetEosData(1, pres, rho) * pres; } //---------------------------------------------------------------------------------------- //! \fn Real EquationOfState::AsqFromRhoP(Real rho, Real pres) // \brief Return interpolated adiabatic sound speed squared Real EquationOfState::AsqFromRhoP(Real rho, Real pres) { return ptable->GetEosData(2, pres, rho) * pres / rho; } //---------------------------------------------------------------------------------------- //! \fn Real EquationOfState::RiemannAsq(Real rho, Real hint) // \brief Return interpolated adiabatic sound speed squared for use in // Riemann solver. Real EquationOfState::RiemannAsq(Real rho, Real hint) { return std::pow(static_cast<Real>(10.0), ptable->table.interpolate(3, std::log10(hint*ptable->hUnit), std::log10(rho*ptable->rhoUnit))) * hint; }
41.885246
90
0.528376
charge72002
e3f751e16023ed1b2a437a88cc8e4b8dec19175c
4,722
cpp
C++
tests/automata_generator/test.cpp
Xazax-hun/CppQuery
e1b505351abbe1b770dc15b5173b2a9fa06f9866
[ "BSD-2-Clause" ]
7
2015-05-17T02:31:54.000Z
2018-05-26T16:15:16.000Z
tests/automata_generator/test.cpp
Xazax-hun/CppQuery
e1b505351abbe1b770dc15b5173b2a9fa06f9866
[ "BSD-2-Clause" ]
null
null
null
tests/automata_generator/test.cpp
Xazax-hun/CppQuery
e1b505351abbe1b770dc15b5173b2a9fa06f9866
[ "BSD-2-Clause" ]
null
null
null
#include <string> #include <set> #include <gtest/gtest.h> #include "automata_generator/matcher_traits.hpp" #include "automata_generator/automata_generator.hpp" namespace { // --- Test interface --- struct A {}; struct B : A {}; struct C {}; struct E : B {}; A *func1(A *) { return 0; } B *func2(A *, B *) { return 0; } C *func3(A *) { return 0; } struct D { E *operator()(A *) { return 0; } }; // For Instantiation test struct F { A *operator()(A *) { return 0; } virtual int getTypeID() { return 1; } virtual ~F() {} }; struct G : F { A *operator()(A *) { return 0; } virtual int getTypeID() { return 2; } }; struct GetInstancePolicy { typedef F *ResultType; template <typename T> static ResultType Create() { return new T; } }; // --- Test interface --- TEST(SimpleFunctionInterface, First) { typedef typename Automata<FUNCTION(func1), FUNCTION(func2), FUNCTION(func3)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "func1", "func2" }; auto tmp = automata.GetComposables("func1"); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } TEST(SimpleFunctionInterfaceWithFunctors, First) { typedef typename Automata<FUNCTION(func1), FUNCTION(func2), FUNCTION(func3), FUNCTOR(D)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "func1", "func2", "D" }; auto tmp = automata.GetComposables("func1"); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } TEST(OptimizedMetaString, First) { std::string s1 = MetaString<_S("csiga biga")>::GetRuntimeString(); std::string s2 = MetaString<_S("csiga biga\0\0\0")>::GetRuntimeString(); EXPECT_EQ(s1, s2); } TEST(SimpleFunctionInterfaceWithMultipleParams, First) { typedef typename Automata<FUNCTION(func1), FUNCTION(func2), FUNCTION(func3), FUNCTOR(D)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{}; auto tmp = automata.GetComposables("func1", 1); std::set<std::string> result(tmp.begin(), tmp.end()); // Func1 has no second parameter... expect empty result EXPECT_EQ(expected, result); } TEST(SimpleFunctionInterfaceWithMultipleParams, Second) { typedef typename Automata<FUNCTION(func1), FUNCTION(func2), FUNCTION(func3), FUNCTOR(D)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "func2", "D" }; auto tmp = automata.GetComposables("func2", 1); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } // Matcher related tests using namespace clang::ast_matchers; TEST(SimpleMatcherInterfaceTest, First) { typedef typename Automata<MATCHER(methodDecl), MATCHER(hasName), MATCHER(namedDecl), MATCHER(qualType)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "hasName", "namedDecl", "methodDecl" }; auto tmp = automata.GetComposables("namedDecl"); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } TEST(SimpleMatcherInterfaceTest, Second) { typedef typename Automata<MATCHER(recordDecl), MATCHER(hasName), MATCHER(ifStmt), MATCHER(hasCondition)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "recordDecl", "hasName" }; auto tmp = automata.GetComposables("recordDecl"); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } TEST(SimpleMatcherInterfaceTest, Third) { typedef typename Automata<MATCHER(stmt), MATCHER(ifStmt), MATCHER(hasCondition)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "ifStmt", "hasCondition", "stmt" }; auto tmp = automata.GetComposables("ifStmt"); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } TEST(SimpleMatcherInterfaceTest, Fourth) { typedef typename Automata<MATCHER(stmt), MATCHER(ifStmt), MATCHER(hasCondition)>::result GeneratedAutomata; GeneratedAutomata automata; std::set<std::string> expected{ "ifStmt", "stmt" }; auto tmp = automata.GetComposables("stmt"); std::set<std::string> result(tmp.begin(), tmp.end()); EXPECT_EQ(expected, result); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
27.453488
78
0.656925
Xazax-hun
e3f958eba90da1ed7a0a49f1380373510fe3fc21
1,232
cpp
C++
util.cpp
artm/mirror
dbaedebcde84a5a4eb66ddb5c25c3b8f7ccf6283
[ "MIT" ]
1
2018-10-31T17:18:34.000Z
2018-10-31T17:18:34.000Z
util.cpp
artm/mirror
dbaedebcde84a5a4eb66ddb5c25c3b8f7ccf6283
[ "MIT" ]
null
null
null
util.cpp
artm/mirror
dbaedebcde84a5a4eb66ddb5c25c3b8f7ccf6283
[ "MIT" ]
null
null
null
#include "util.h" #include <QVector> #include <QRgb> #include <QtDebug> #include <QCoreApplication> namespace Mirror { static bool s_greyTableInit = false; static QVector<QRgb> s_greyTable; QImage CvMat2QImage(const cv::Mat& cvmat) { int height = cvmat.rows; int width = cvmat.cols; if (cvmat.depth() == CV_8U && cvmat.channels() == 3) { QImage img((const uchar*)cvmat.data, width, height, cvmat.step.p[0], QImage::Format_RGB888); return img.rgbSwapped(); } else if (cvmat.depth() == CV_8U && cvmat.channels() == 1) { if (!s_greyTableInit) { for (int i = 0; i < 256; i++){ s_greyTable.push_back(qRgb(i, i, i)); } } QImage img((const uchar*)cvmat.data, width, height, cvmat.step.p[0], QImage::Format_Indexed8); img.setColorTable(s_greyTable); return img; } else { qWarning() << "Image cannot be converted."; return QImage(); } } QString findResourceFile(const QString& relPath) { // FIXME this is osx specific. // TODO make it actually search in some defined places. return QCoreApplication::applicationDirPath () + "/../../../Resources/" + relPath; } }
26.782609
102
0.602273
artm
e3f99d57e302f365c82ebebc32194eee192a896b
5,952
cpp
C++
femm/ActiveFEMM.cpp
ResonanceGroup/FEMM
227f1cb46fc18b298e2da48d732692c206d0539f
[ "MIT" ]
1
2020-05-18T00:57:57.000Z
2020-05-18T00:57:57.000Z
femm/ActiveFEMM.cpp
ResonanceGroup/FEMM
227f1cb46fc18b298e2da48d732692c206d0539f
[ "MIT" ]
1
2018-05-02T13:43:31.000Z
2018-05-02T13:43:31.000Z
femm/ActiveFEMM.cpp
ResonanceGroup/FEMM
227f1cb46fc18b298e2da48d732692c206d0539f
[ "MIT" ]
3
2018-05-02T13:38:43.000Z
2021-05-19T10:48:49.000Z
// ActiveFEMM.cpp : implementation file // #include "stdafx.h" #include "femm.h" #include "lua.h" #include "luadebug.h" #include "luaconsoledlg.h" #include "ActiveFEMM.h" #include "mainfrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern lua_State *lua; extern BOOL bLinehook; extern BOOL lua_byebye; extern HANDLE hProc; extern int m_luaWindowStatus; extern CFemmApp theApp; CString LuaResult; ///////////////////////////////////////////////////////////////////////////// // ActiveFEMM IMPLEMENT_DYNCREATE(ActiveFEMM, CCmdTarget) ActiveFEMM::ActiveFEMM() { EnableAutomation(); EnableTypeLib(); // To keep the application running as long as an OLE automation // object is active, the constructor calls AfxOleLockApp. AfxOleLockApp(); lua_register(lua,"actxprint", lua_to_string); lua_register(lua,"lua2matlab",lua_to_matlab); } ActiveFEMM::~ActiveFEMM() { // To terminate the application when all objects created with // with OLE automation, the destructor calls AfxOleUnlockApp. AfxOleUnlockApp(); } void ActiveFEMM::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. // We have to close things in a funny way so that FEMM shuts down // the way that it expects to. First, the call to AfxOleSetUserCtrl // makes it so that the the application won't get closed when the // base class version of OnFinalRelease gets called. AfxOleSetUserCtrl(TRUE); // Then, post a message to the main window requesting a shutdown. // This is the way that FEMM likes to shut down. Since the message // has been posted rather than sent, it will be acted upon after // ActiveFEMM has shut itself down. AfxGetMainWnd()->PostMessage(WM_CLOSE); // Then, call the base class to shut down ActiveFEMM CCmdTarget::OnFinalRelease(); } BEGIN_MESSAGE_MAP(ActiveFEMM, CCmdTarget) //{{AFX_MSG_MAP(ActiveFEMM) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(ActiveFEMM, CCmdTarget) //{{AFX_DISPATCH_MAP(ActiveFEMM) DISP_FUNCTION(ActiveFEMM, "call2femm", call2femm, VT_BSTR, VTS_BSTR) DISP_FUNCTION(ActiveFEMM, "mlab2femm", mlab2femm, VT_BSTR, VTS_BSTR) //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() ///////////////////////////////////////////////////////////////////////////// // Type library ID and version // {04EF434A-1A91-495A-85AA-C625602B4AF4} static const GUID _tlid = { 0x04EF434A, 0x1A91, 0x495A, { 0x85, 0xAA, 0xC6, 0x25, 0x60, 0x2B, 0x4A, 0xF4 } }; const WORD _wVerMajor = 1; const WORD _wVerMinor = 0; IMPLEMENT_OLETYPELIB(ActiveFEMM, _tlid, _wVerMajor, _wVerMinor) // Note: we add support for IID_IActiveFEMM to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .ODL file. // {E08185B4-FEDF-4B1B-A88D-D40C97625060} static const IID IID_IActiveFEMM = { 0xe08185b4, 0xfedf, 0x4b1b, { 0xa8, 0x8d, 0xd4, 0xc, 0x97, 0x62, 0x50, 0x60 } }; BEGIN_INTERFACE_MAP(ActiveFEMM, CCmdTarget) INTERFACE_PART(ActiveFEMM, IID_IActiveFEMM, Dispatch) END_INTERFACE_MAP() // {0A35D5BD-DCA9-4C39-9512-1D89A1A37047} IMPLEMENT_OLECREATE2(ActiveFEMM, "femm.ActiveFEMM", 0xa35d5bd, 0xdca9, 0x4c39, 0x95, 0x12, 0x1d, 0x89, 0xa1, 0xa3, 0x70, 0x47) BOOL ActiveFEMM::GetDispatchIID(IID* pIID) { *pIID = IID_IActiveFEMM; return TRUE; } ///////////////////////////////////////////////////////////////////////////// // ActiveFEMM message handlers BSTR ActiveFEMM::call2femm(LPCTSTR luacmd) { // executes the line contained in luacmd // and returns a string containing the results // of the command with the results separated // by newline characters. CString strToLua; theApp.MatlabLoveNote.Empty(); strToLua=luacmd; strToLua="actxprint(" + strToLua +")"; DoLuaCmd(strToLua); // Returns the result of errors that are trapped // via message boxes during a normal UI session if(theApp.MatlabLoveNote.GetLength()>0) { LuaResult.Format("error: %s",theApp.MatlabLoveNote); } return LuaResult.AllocSysString(); } BSTR ActiveFEMM::mlab2femm(LPCTSTR luacmd) { // executes the line contained in luacmd // and returns a string containing the results // of the command formatted in matlab format. // One would expect that all the results are // real numbers, in which case we can eval() // the result in matlab to get a vector of numbers. CString strToLua; theApp.MatlabLoveNote.Empty(); strToLua=luacmd; strToLua="lua2matlab(" + strToLua +")"; DoLuaCmd(strToLua); // Returns the result of errors that are trapped // via message boxes during a normal UI session if(theApp.MatlabLoveNote.GetLength()>0) { LuaResult.Format("error: %s",theApp.MatlabLoveNote); } return LuaResult.AllocSysString(); } void ActiveFEMM::DoLuaCmd(CString strToLua) { LuaResult.Empty(); if(m_luaWindowStatus==SW_SHOW) bLinehook=NormalLua; else bLinehook=HiddenLua; theApp.bActiveX=TRUE; if (lua_dostring(lua,strToLua)!=0) LuaResult=theApp.LuaErrmsg; theApp.bActiveX=FALSE; lua_byebye=FALSE; bLinehook=FALSE; } int ActiveFEMM::lua_to_string(lua_State *L) { CString s; int n = lua_gettop(L); LuaResult=""; for(int k=1;k<=n;k++) { s=lua_tostring(L,k); LuaResult = LuaResult + s +"\n"; } return 0; } int ActiveFEMM::lua_to_matlab(lua_State *L) { CString s; int n = lua_gettop(L); if(n>0){ LuaResult="[ "; for(int k=1;k<=n;k++) { s=lua_tostring(L,k); LuaResult = LuaResult + s + " "; } LuaResult += "]"; } else LuaResult.Empty(); return 0; }
26.690583
127
0.680444
ResonanceGroup
e3fa2704de46b83734eb4e216dbf546f0833f36e
2,127
cpp
C++
Classes/SetupVolumeEx.cpp
lfeng1420/BrickGame
e4961a7454ae1adece6845c64a6ba8ac59856d68
[ "MIT" ]
39
2016-05-07T06:39:54.000Z
2021-04-13T15:00:52.000Z
Classes/SetupVolumeEx.cpp
lfeng1420/BrickGame
e4961a7454ae1adece6845c64a6ba8ac59856d68
[ "MIT" ]
8
2016-07-17T06:39:54.000Z
2021-07-06T15:14:19.000Z
Classes/SetupVolumeEx.cpp
lfeng1420/BrickGame
e4961a7454ae1adece6845c64a6ba8ac59856d68
[ "MIT" ]
13
2016-03-11T11:46:19.000Z
2018-08-10T16:34:33.000Z
#include "stdafx.h" #include "SetupVolumeEx.h" #include "BarrierLayer.h" void CSetupVolumeEx::InitUI() { Size visibleSize1 = GET_VISIBLESIZE(); Size visibleSize(visibleSize1.height, visibleSize1.width); Size bgSprSize = GET_CONTENTSIZE(m_pBGSprite); Size closeSize = GET_CONTENTSIZE(m_pCloseMenuItem); Size bgmLabelSize = GET_CONTENTSIZE(m_pBGMLabel); Size bgmVolumeSize = GET_CONTENTSIZE(m_pBGMVolume); Size bgmSliderSize = GET_CONTENTSIZE(m_pBGMSlider); Size effectLabelSize = GET_CONTENTSIZE(m_pEffectLabel); Size effectVolumeSize = GET_CONTENTSIZE(m_pEffetVolume); Size effectSliderSize = GET_CONTENTSIZE(m_pEffectSlider); float fMaxHeight = max(effectLabelSize.height, effectSliderSize.height); float fLabelMaxWidth = max(bgmLabelSize.width, effectLabelSize.width); float fTotalWidth = fLabelMaxWidth + X_PADDING + bgmSliderSize.width + X_PADDING + bgmVolumeSize.width; float fYPadding = (bgSprSize.height - fMaxHeight * 2) / 8; float fXPadding = (visibleSize.width - fTotalWidth) * 0.5f; float fBGMY = visibleSize.height * 0.5f + fYPadding + fMaxHeight * 0.5f; float fEffectY = visibleSize.height * 0.5f - fYPadding - fMaxHeight * 0.5f; float fLabelX = fXPadding + fLabelMaxWidth * 0.5f; float fSliderX = fXPadding + fLabelMaxWidth + X_PADDING + bgmSliderSize.width * 0.5f; float fVolumeX = fXPadding + fLabelMaxWidth + X_PADDING * 2 + bgmSliderSize.width + bgmVolumeSize.width * 0.5f; // Barrier layer m_pBarrierLayer->setContentSize(visibleSize); m_pBarrierLayer->setPosition(Vec2::ZERO); // Background m_pBGSprite->setPosition(visibleSize.width * 0.5f, visibleSize.height * 0.5f); // Close button m_pCloseMenuItem->setPosition(visibleSize.width * 0.5f + bgSprSize.width * 0.5f - closeSize.width * 0.5f, visibleSize.height * 0.5f + bgSprSize.height * 0.5f - closeSize.height * 0.5f); //BGM m_pBGMLabel->setPosition(fLabelX, fBGMY); m_pBGMSlider->setPosition(fSliderX, fBGMY); m_pBGMVolume->setPosition(fVolumeX, fBGMY); //Effect m_pEffectLabel->setPosition(fLabelX, fEffectY); m_pEffectSlider->setPosition(fSliderX, fEffectY); m_pEffetVolume->setPosition(fVolumeX, fEffectY); }
45.255319
112
0.77433
lfeng1420
e3fb10e7d28870ed12fce54b4ff47c76c39f928e
281
cpp
C++
source/layout/style.cpp
zhiayang/sap
f8d1d48b02c6df075bc59b5228fbd339d3923a4d
[ "Apache-2.0" ]
13
2021-08-06T20:20:05.000Z
2022-03-29T10:46:00.000Z
source/layout/style.cpp
zhiayang/sap
f8d1d48b02c6df075bc59b5228fbd339d3923a4d
[ "Apache-2.0" ]
1
2021-08-07T17:42:59.000Z
2021-09-19T00:34:30.000Z
source/layout/style.cpp
zhiayang/sap
f8d1d48b02c6df075bc59b5228fbd339d3923a4d
[ "Apache-2.0" ]
null
null
null
// style.cpp // Copyright (c) 2022, zhiayang // SPDX-License-Identifier: Apache-2.0 #include "sap/style.h" namespace sap { static Style g_defaultStyle {}; const Style& defaultStyle() { return g_defaultStyle; } void setDefaultStyle(Style s) { g_defaultStyle = s; } }
13.380952
38
0.690391
zhiayang