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
6b91940f5e4de26027991a0e6671bceb3c08b61c
3,735
cc
C++
firestore/src/common/listener_registration.cc
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
[ "Apache-2.0" ]
null
null
null
firestore/src/common/listener_registration.cc
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
[ "Apache-2.0" ]
null
null
null
firestore/src/common/listener_registration.cc
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
[ "Apache-2.0" ]
null
null
null
#include "firestore/src/include/firebase/firestore/listener_registration.h" #include <utility> #include "firestore/src/common/cleanup.h" #if defined(__ANDROID__) #include "firestore/src/android/listener_registration_android.h" #elif defined(FIRESTORE_STUB_BUILD) #include "firestore/src/stub/listener_registration_stub.h" #else #include "firestore/src/ios/listener_registration_ios.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { // ListenerRegistration specific fact: // ListenerRegistration does NOT own the ListenerRegistrationInternal object, // which is different from other wrapper types. FirestoreInternal owns all // ListenerRegistrationInternal objects instead. So FirestoreInternal can // remove all listeners upon destruction. using CleanupFnListenerRegistration = CleanupFn<ListenerRegistration, ListenerRegistrationInternal>; ListenerRegistration::ListenerRegistration() : ListenerRegistration(nullptr) {} ListenerRegistration::ListenerRegistration( const ListenerRegistration& registration) : firestore_(registration.firestore_) { internal_ = registration.internal_; CleanupFnListenerRegistration::Register(this, firestore_); } ListenerRegistration::ListenerRegistration(ListenerRegistration&& registration) : firestore_(registration.firestore_) { CleanupFnListenerRegistration::Unregister(&registration, registration.firestore_); std::swap(internal_, registration.internal_); CleanupFnListenerRegistration::Register(this, firestore_); } ListenerRegistration::ListenerRegistration( ListenerRegistrationInternal* internal) : firestore_(internal == nullptr ? nullptr : internal->firestore_internal()), internal_(internal) { CleanupFnListenerRegistration::Register(this, firestore_); } ListenerRegistration::~ListenerRegistration() { CleanupFnListenerRegistration::Unregister(this, firestore_); internal_ = nullptr; } ListenerRegistration& ListenerRegistration::operator=( const ListenerRegistration& registration) { if (this == &registration) { return *this; } firestore_ = registration.firestore_; CleanupFnListenerRegistration::Unregister(this, firestore_); internal_ = registration.internal_; CleanupFnListenerRegistration::Register(this, firestore_); return *this; } ListenerRegistration& ListenerRegistration::operator=( ListenerRegistration&& registration) { if (this == &registration) { return *this; } firestore_ = registration.firestore_; CleanupFnListenerRegistration::Unregister(&registration, registration.firestore_); CleanupFnListenerRegistration::Unregister(this, firestore_); internal_ = registration.internal_; CleanupFnListenerRegistration::Register(this, firestore_); return *this; } void ListenerRegistration::Remove() { // The check for firestore_ is required. User can hold a ListenerRegistration // instance indefinitely even after Firestore is destructed, in which case // firestore_ will be reset to nullptr by the Cleanup function. // The check for internal_ is optional. Actually internal_ can be of following // cases: // * nullptr if already called Remove() on the same instance; // * not nullptr but invalid if Remove() is called on a copy of this; // * not nullptr and valid. // Unregister a nullptr or invalid ListenerRegistration is a no-op. if (internal_ && firestore_) { firestore_->UnregisterListenerRegistration(internal_); internal_ = nullptr; } } void ListenerRegistration::Cleanup() { Remove(); firestore_ = nullptr; } } // namespace firestore } // namespace firebase
34.583333
80
0.754752
NetsoftHoldings
6b944121c76ab19157aa731af2fbefcb3ec68d43
3,362
cpp
C++
wpimath/src/test/native/cpp/filter/LinearFilterOutputTest.cpp
liorsagy/allwpilib
3838cc4ec48d4bf38815565fab016f0c4f746585
[ "BSD-3-Clause" ]
null
null
null
wpimath/src/test/native/cpp/filter/LinearFilterOutputTest.cpp
liorsagy/allwpilib
3838cc4ec48d4bf38815565fab016f0c4f746585
[ "BSD-3-Clause" ]
null
null
null
wpimath/src/test/native/cpp/filter/LinearFilterOutputTest.cpp
liorsagy/allwpilib
3838cc4ec48d4bf38815565fab016f0c4f746585
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "frc/filter/LinearFilter.h" // NOLINT(build/include_order) #include <cmath> #include <functional> #include <memory> #include <random> #include <wpi/numbers> #include "gtest/gtest.h" #include "units/time.h" // Filter constants static constexpr auto kFilterStep = 5_ms; static constexpr auto kFilterTime = 2_s; static constexpr double kSinglePoleIIRTimeConstant = 0.015915; static constexpr double kSinglePoleIIRExpectedOutput = -3.2172003; static constexpr double kHighPassTimeConstant = 0.006631; static constexpr double kHighPassExpectedOutput = 10.074717; static constexpr int32_t kMovAvgTaps = 6; static constexpr double kMovAvgExpectedOutput = -10.191644; enum LinearFilterOutputTestType { kTestSinglePoleIIR, kTestHighPass, kTestMovAvg, kTestPulse }; static double GetData(double t) { return 100.0 * std::sin(2.0 * wpi::numbers::pi * t) + 20.0 * std::cos(50.0 * wpi::numbers::pi * t); } static double GetPulseData(double t) { if (std::abs(t - 1.0) < 0.001) { return 1.0; } else { return 0.0; } } /** * A fixture that includes a consistent data source wrapped in a filter */ class LinearFilterOutputTest : public testing::TestWithParam<LinearFilterOutputTestType> { protected: frc::LinearFilter<double> m_filter = [=] { switch (GetParam()) { case kTestSinglePoleIIR: return frc::LinearFilter<double>::SinglePoleIIR( kSinglePoleIIRTimeConstant, kFilterStep); break; case kTestHighPass: return frc::LinearFilter<double>::HighPass(kHighPassTimeConstant, kFilterStep); break; case kTestMovAvg: return frc::LinearFilter<double>::MovingAverage(kMovAvgTaps); break; default: return frc::LinearFilter<double>::MovingAverage(kMovAvgTaps); break; } }(); std::function<double(double)> m_data; double m_expectedOutput = 0.0; LinearFilterOutputTest() { switch (GetParam()) { case kTestSinglePoleIIR: { m_data = GetData; m_expectedOutput = kSinglePoleIIRExpectedOutput; break; } case kTestHighPass: { m_data = GetData; m_expectedOutput = kHighPassExpectedOutput; break; } case kTestMovAvg: { m_data = GetData; m_expectedOutput = kMovAvgExpectedOutput; break; } case kTestPulse: { m_data = GetPulseData; m_expectedOutput = 0.0; break; } } } }; /** * Test if the linear filters produce consistent output for a given data set. */ TEST_P(LinearFilterOutputTest, Output) { double filterOutput = 0.0; for (auto t = 0_s; t < kFilterTime; t += kFilterStep) { filterOutput = m_filter.Calculate(m_data(t.to<double>())); } RecordProperty("LinearFilterOutput", filterOutput); EXPECT_FLOAT_EQ(m_expectedOutput, filterOutput) << "Filter output didn't match expected value"; } INSTANTIATE_TEST_SUITE_P(Test, LinearFilterOutputTest, testing::Values(kTestSinglePoleIIR, kTestHighPass, kTestMovAvg, kTestPulse));
27.785124
77
0.665675
liorsagy
6b95e79e995335c6323e9e09400bd830da835586
3,751
hpp
C++
include/motion_manager/scenario.hpp
JoaoQPereira/motion_manager
de853e9341c482a0c13e0ba7b78429c019890507
[ "MIT" ]
null
null
null
include/motion_manager/scenario.hpp
JoaoQPereira/motion_manager
de853e9341c482a0c13e0ba7b78429c019890507
[ "MIT" ]
null
null
null
include/motion_manager/scenario.hpp
JoaoQPereira/motion_manager
de853e9341c482a0c13e0ba7b78429c019890507
[ "MIT" ]
null
null
null
#ifndef SCENARIO_HPP #define SCENARIO_HPP #include "robot.hpp" #include "object.hpp" #include "pose.hpp" #include "waypoint.hpp" namespace motion_manager { typedef boost::shared_ptr<Robot> robotPtr; /**< shared pointer to a robot */ typedef boost::shared_ptr<Object> objectPtr; /**< shared pointer to an object*/ typedef boost::shared_ptr<Pose> posePtr; /**< shared pointer to a pose*/ typedef boost::shared_ptr<Waypoint> waypointPtr; /**< shared pointer to a waypoint*/ class Scenario { public: /** * @brief Scenario, a constructor * @param name * @param id */ Scenario(string name, int id); /** * @brief Scenario, a copy constructor * @param scene */ Scenario(const Scenario& scene); /** * @brief ~Scenario, a destructor. */ ~Scenario(); /** * @brief This method sets the name of the scenario * @param name */ void setName(string& name); /** * @brief This method sets the ID of the scenario * @param id */ void setID(int id); /** * @brief This method insert an object in the vector of objects at the position pos * @param pos * @param obj */ void setObject(int pos, objectPtr obj); /** * @brief This method insert a pose in the vector of poses at the position pos * @param pos * @param pt */ void setPose(int pos, posePtr pt); /** * @brief This method gets the name of the scenario * @return */ string getName(); /** * @brief This method gets the ID of the scenario * @return */ int getID(); /** * @brief This method gets a pointer to the robot in the scenario * @return */ robotPtr getRobot(); /** * @brief This method get the list of the objects in the scenario * @param objs * @return */ bool getObjects(vector<objectPtr>& objs); /** * @brief This method get the list of the poses in the scenario * @param pts * @return */ bool getPoses(vector<posePtr>& pts); /** * @brief getWaypoints * @param wps * @return */ bool getWaypoints(vector<waypointPtr> &wps); /** * @brief This method adds a new object to the scenario * @param obj_ptr */ void addObject(objectPtr obj_ptr); /** * @brief addPose * @param pose_ptr */ void addPose(posePtr pose_ptr); /** * @brief addWaypoint * @param wp_Ptr */ void addWaypoint(waypointPtr wp_ptr); //void addWaypoint(Waypoint &wp_ptr); /** * @brief This method gets the object at the position pos in the vector of objects * @param pos * @return */ objectPtr getObject(int pos); /** * @brief getPose * @param pos * @return */ posePtr getPose(int pos); /** * @brief This method gets the object named "obj_name" * @param obj_name * @return */ objectPtr getObject(string obj_name); /** * @brief getPose * @param pose_name * @return */ posePtr getPose(string pose_name); waypointPtr getWaypoint_traj(string traj_name); /** * @brief This method adds the robot to the scenario * @param hh_ptr */ void addRobot(robotPtr hh_ptr); private: string m_name; /**< the name of the scenario*/ int m_scenarioID; /**< the ID of the scenario*/ vector<objectPtr> objs_list; /**< the objects in the scenario */ vector<posePtr> poses_list; /**< the poses in the scenario */ robotPtr rPtr; /**< the robot in the scenario */ vector<waypointPtr> wps_list; /** the waypoints in the scenario **/ }; } // namespace motion_manager #endif // SCENARIO_HPP
22.195266
87
0.597174
JoaoQPereira
6ba7c527633cf9a4f1de6d4670ab5afbd46e649e
1,472
cpp
C++
Source/OpenExrWrapper/OpenExrWrapper.cpp
TQwan/ExrMedia
3934b82b85c4f0c00987c535fb0a2fb2d1602034
[ "MIT" ]
null
null
null
Source/OpenExrWrapper/OpenExrWrapper.cpp
TQwan/ExrMedia
3934b82b85c4f0c00987c535fb0a2fb2d1602034
[ "MIT" ]
null
null
null
Source/OpenExrWrapper/OpenExrWrapper.cpp
TQwan/ExrMedia
3934b82b85c4f0c00987c535fb0a2fb2d1602034
[ "MIT" ]
null
null
null
#pragma warning(push) #pragma warning(disable:28251) #include "OpenExrWrapper.h" #include "ImathBox.h" #include "ImfHeader.h" #include "ImfRgbaFile.h" #include "ImfStandardAttributes.h" #include "Modules/ModuleManager.h" FRgbaInputFile::FRgbaInputFile(const FString& FilePath) { InputFile = new Imf::RgbaInputFile(TCHAR_TO_ANSI(*FilePath)); } FRgbaInputFile::~FRgbaInputFile() { delete (Imf::RgbaInputFile*)InputFile; } FIntPoint FRgbaInputFile::GetDataWindow() const { Imath::Box2i Win = ((Imf::RgbaInputFile*)InputFile)->dataWindow(); return FIntPoint( Win.max.x - Win.min.x + 1, Win.max.y - Win.min.y + 1 ); } double FRgbaInputFile::GetFramesPerSecond(double DefaultValue) const { auto Attribute = ((Imf::RgbaInputFile*)InputFile)->header().findTypedAttribute<Imf::RationalAttribute>("framesPerSecond"); if (Attribute == nullptr) { return DefaultValue; } return Attribute->value(); } void FRgbaInputFile::ReadPixels(int32 StartY, int32 EndY) { Imath::Box2i Win = ((Imf::RgbaInputFile*)InputFile)->dataWindow(); ((Imf::RgbaInputFile*)InputFile)->readPixels(Win.min.y, Win.max.y); } void FRgbaInputFile::SetFrameBuffer(void* Buffer, const FIntPoint& BufferDim) { Imath::Box2i Win = ((Imf::RgbaInputFile*)InputFile)->dataWindow(); ((Imf::RgbaInputFile*)InputFile)->setFrameBuffer((Imf::Rgba*)Buffer - Win.min.x - Win.min.y * BufferDim.X, 1, BufferDim.X); } IMPLEMENT_MODULE(FDefaultModuleImpl, OpenExrWrapper); #pragma warning(pop)
22.30303
124
0.737772
TQwan
6ba92bcc7a6c613243d8ed0b8e0389b6bb8563f7
4,491
hpp
C++
include/estd/tuple/for_each.hpp
fizyr/estd
6562e7d3d21972f9eee7f4b36dfd381b4ae9d2bf
[ "BSD-3-Clause" ]
9
2018-07-28T21:37:28.000Z
2021-12-20T22:24:14.000Z
include/estd/tuple/for_each.hpp
fizyr/estd
6562e7d3d21972f9eee7f4b36dfd381b4ae9d2bf
[ "BSD-3-Clause" ]
8
2019-05-17T18:40:19.000Z
2021-10-11T09:35:08.000Z
include/estd/tuple/for_each.hpp
fizyr/estd
6562e7d3d21972f9eee7f4b36dfd381b4ae9d2bf
[ "BSD-3-Clause" ]
4
2019-02-23T13:39:26.000Z
2021-12-20T22:24:19.000Z
/* Copyright 2017-2018 Fizyr B.V. - https://fizyr.com * * 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. */ #pragma once #include "../traits/is_tuple.hpp" #include <cstddef> #include <functional> #include <tuple> #include <type_traits> #include <utility> namespace estd { namespace detail { template<std::size_t I, typename F, typename Tuple> constexpr std::size_t tuple_for_each_impl(Tuple && tuple, F && f) { if constexpr (I == std::tuple_size_v<std::decay_t<Tuple>>) { return I; } else { using std::get; using R = decltype(std::invoke(f, get<I>(std::forward<Tuple>(tuple)))); if constexpr(std::is_same_v<R, void>) { std::invoke(f, get<I>(std::forward<Tuple>(tuple))); } else { if (!std::invoke(f, get<I>(std::forward<Tuple>(tuple)))) return I; } return tuple_for_each_impl<I + 1>(std::forward<Tuple>(tuple), std::forward<F>(f)); } } template<std::size_t I, typename F, typename Tuple> constexpr std::size_t tuple_for_each_i_impl(Tuple && tuple, F && f) { if constexpr (I == std::tuple_size_v<std::decay_t<Tuple>>) { return I; } else { using std::get; using R = decltype(std::invoke(f, I, get<I>(std::forward<Tuple>(tuple)))); if constexpr(std::is_same_v<R, void>) { std::invoke(f, I, get<I>(std::forward<Tuple>(tuple))); } else { if (!std::invoke(f, I, get<I>(std::forward<Tuple>(tuple)))) return I; } return tuple_for_each_i_impl<I + 1>(std::forward<Tuple>(tuple), std::forward<F>(f)); } } } /// Execute a functor for each tuple element in order. /** * The functor willed be called as func(elem) where elem is the value of the element. * * The functor may optionally return a value to abort the loop before all elements are processed. * If the functor returns a value it is tested in boolean context. * If the value compares as false, the loop is stopped. * * Returns the index of the element that caused the loop to halt, * or the size of the tuple if no element caused the loop to stop. */ template<typename F, typename Tuple, typename = std::enable_if_t<estd::is_tuple<Tuple>>> constexpr std::size_t for_each(Tuple && tuple, F && func) { return detail::tuple_for_each_impl<0>(std::forward<Tuple>(tuple), std::forward<F>(func)); } /// Execute a functor for each tuple element in order. /** * The functor willed be called as func(i, elem) where i is the index in the tuple, * and elem is the value of the element. * * The functor may optionally return a value to abort the loop before all elements are processed. * If the functor returns a value it is tested in boolean context. * If the value compares as false, the loop is stopped. * * Returns the index of the element that caused the loop to halt, * or the size of the tuple if no element caused the loop to stop. */ template<typename F, typename Tuple, typename = std::enable_if_t<estd::is_tuple<Tuple>>> constexpr std::size_t for_each_i(Tuple && tuple, F && func) { return detail::tuple_for_each_i_impl<0>(std::forward<Tuple>(tuple), std::forward<F>(func)); } }
41.583333
97
0.717435
fizyr
6baa61169badd91f1029ae2817562f354457a866
1,103
cpp
C++
linear-list/array/median_of_two_sorted_arrays.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
1
2015-07-15T07:31:42.000Z
2015-07-15T07:31:42.000Z
linear-list/array/median_of_two_sorted_arrays.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
linear-list/array/median_of_two_sorted_arrays.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /** * There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. * The overall run time complexity should be O(log(m + n)). * */ class Solution { public: double findMedian(int A[], int m, int B[], int n) { int total = m + n; if(total % 2 != 0) return find_kth(A, m, B, n, total / 2 + 1); else return (find_kth(A, m, B, n, total / 2) + find_kth(A, m, B, n, total / 2 + 1)) / 2.0; } private: static int find_kth(int A[], int m, int B[], int n, int k) { if(m > n) return find_kth(B, n, A, m, k); if(m == 0) return B[k - 1]; if(k == 1) return min(A[0], B[0]); int idx_a = min(k / 2, m), idx_b = k - idx_a; if(A[idx_a - 1] < B[idx_b - 1]) return find_kth(A + idx_a, m - idx_a, B, n, k - idx_a); else if(A[idx_a - 1] > B[idx_b -1]) return find_kth(A, m, B + idx_b, n - idx_b, k - idx_b); else return A[idx_a - 1]; } };
29.026316
110
0.4932
zhangxin23
6bb02840355fc14356f0266998b0c1ed3b7128db
25,634
hpp
C++
include/virt_wrap/Domain.hpp
AeroStun/virthttp
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
[ "Apache-2.0" ]
7
2019-08-22T20:48:15.000Z
2021-12-31T16:08:59.000Z
include/virt_wrap/Domain.hpp
AeroStun/virthttp
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
[ "Apache-2.0" ]
10
2019-08-22T21:40:43.000Z
2020-09-03T14:21:21.000Z
include/virt_wrap/Domain.hpp
AeroStun/virthttp
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
[ "Apache-2.0" ]
2
2019-08-22T21:08:28.000Z
2019-08-23T21:31:56.000Z
// // Created by _as on 2019-01-31. // #ifndef VIRTPP_DOMAIN_HPP #define VIRTPP_DOMAIN_HPP #include <filesystem> #include <stdexcept> #include <variant> #include <vector> #include <gsl/gsl> #include "../cexpr_algs.hpp" #include "enums/Connection/Decls.hpp" #include "enums/Domain/Decls.hpp" #include "enums/Domain/Domain.hpp" #include "enums/GFlags.hpp" #include "CpuMap.hpp" #include "fwd.hpp" #include "tfe.hpp" #include "utility.hpp" namespace tmp { /* using virConnectDomainEventAgentLifecycleCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int state, int reason, void* opaque); using virConnectDomainEventBalloonChangeCallback = void (*)(virConnectPtr conn, virDomainPtr dom, unsigned long long actual, void* opaque); using virConnectDomainEventBlockJobCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* disk, int type, int status, void* opaque); using virConnectDomainEventBlockThresholdCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* dev, const char* path, unsigned long long threshold, unsigned long long excess, void* opaque); using virConnectDomainEventCallback = int (*)(virConnectPtr conn, virDomainPtr dom, int event, int detail, void* opaque); int virConnectDomainEventDeregister(virConnectPtr conn, virConnectDomainEventCallback cb); int virConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID); using virConnectDomainEventDeviceAddedCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* devAlias, void* opaque); using virConnectDomainEventDeviceRemovalFailedCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* devAlias, void* opaque); using virConnectDomainEventDeviceRemovedCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* devAlias, void* opaque); using virConnectDomainEventDiskChangeCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* oldSrcPath, const char* newSrcPath, const char* devAlias, int reason, void* opaque); using virConnectDomainEventGenericCallback = void (*)(virConnectPtr conn, virDomainPtr dom, void* opaque); using virConnectDomainEventGraphicsCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int phase, const virDomainEventGraphicsAddress* local, const virDomainEventGraphicsAddress* remote, const char* authScheme, const virDomainEventGraphicsSubject* subject, void* opaque); using virConnectDomainEventIOErrorCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* srcPath, const char* devAlias, int action, void* opaque); using virConnectDomainEventIOErrorReasonCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* srcPath, const char* devAlias, int action, const char* reason, void* opaque); using virConnectDomainEventJobCompletedCallback = void (*)(virConnectPtr conn, virDomainPtr dom, virTypedParameterPtr params, int nparams, void* opaque); using virConnectDomainEventMetadataChangeCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int type, const char* nsuri, void* opaque); using virConnectDomainEventMigrationIterationCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int iteration, void* opaque); using virConnectDomainEventPMSuspendCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int reason, void* opaque); using virConnectDomainEventPMSuspendDiskCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int reason, void* opaque); using virConnectDomainEventPMWakeupCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int reason, void* opaque); using virConnectDomainEventRTCChangeCallback = void (*)(virConnectPtr conn, virDomainPtr dom, long long utcoffset, void* opaque); int virConnectDomainEventRegister(virConnectPtr conn, virConnectDomainEventCallback cb, void* opaque, virFreeCallback freecb); int virConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID, virConnectDomainEventGenericCallback cb, void* opaque, virFreeCallback freecb); using virConnectDomainEventTrayChangeCallback = void (*)(virConnectPtr conn, virDomainPtr dom, const char* devAlias, int reason, void* opaque); using virConnectDomainEventTunableCallback = void (*)(virConnectPtr conn, virDomainPtr dom, virTypedParameterPtr params, int nparams, void* opaque); using virConnectDomainEventWatchdogCallback = void (*)(virConnectPtr conn, virDomainPtr dom, int action, void* opaque); char* virConnectDomainXMLFromNative(virConnectPtr conn, const char* nativeFormat, const char* nativeConfig, unsigned int flags); char* virConnectDomainXMLToNative(virConnectPtr conn, const char* nativeFormat, const char* domainXml, unsigned int flags); char* virConnectGetDomainCapabilities(virConnectPtr conn, const char* emulatorbin, const char* arch, const char* machine, const char* virttype, unsigned int flags); */ /* * ((?:[A-Z]+_)+([A-Z]+)(?!_))\s*=.*,(.*) * $2 = $1, $3 * */ } // namespace tmp namespace virt { class Domain { friend Connection; virDomainPtr underlying = nullptr; public: using Info = virDomainInfo; class StatsRecord; struct StateReason {}; struct StateWReason; struct DiskError; struct FSInfo; struct Interface; struct InterfaceView; struct IPAddress; struct IPAddressView; struct JobInfo; struct light { struct IOThreadInfo; }; struct heavy { struct IOThreadInfo; }; using BlockStats = virDomainBlockStatsStruct; constexpr inline explicit Domain(virDomainPtr ptr = nullptr) noexcept; Domain(const Domain&) = delete; constexpr inline Domain(Domain&&) noexcept; Domain& operator=(const Domain&) = delete; inline Domain& operator=(Domain&&) noexcept; inline ~Domain() noexcept; constexpr inline explicit operator bool() const noexcept; bool abortJob() noexcept; bool addIOThread(unsigned int iothread_id, enums::domain::ModificationImpactFlag flags) noexcept; bool attachDevice(gsl::czstring<> xml) noexcept; bool attachDevice(gsl::czstring<> xml, enums::domain::DeviceModifyFlag flags) noexcept; bool blockCommit(gsl::czstring<> disk, gsl::czstring<> base, gsl::czstring<> top, unsigned long bandwidth, enums::domain::BlockCommitFlag flags) noexcept; bool blockCopy(gsl::czstring<> disk, gsl::czstring<> destxml, const TypedParams& params, enums::domain::BlockCopyFlag flags) noexcept; bool blockJobAbort(gsl::czstring<> disk, enums::domain::BlockJobAbortFlag flags) noexcept; bool blockJobSetSpeed(gsl::czstring<> disk, unsigned long bandwidth, enums::domain::BlockJobSetSpeedFlag flags) noexcept; bool blockPeek(gsl::czstring<> disk, unsigned long long offset, gsl::span<std::byte> buffer) const noexcept; bool blockPull(gsl::czstring<> disk, unsigned long bandwidth, enums::domain::BlockPullFlag flags) noexcept; bool blockRebase(gsl::czstring<> disk, gsl::czstring<> base, unsigned long bandwidth, enums::domain::BlockRebaseFlag flags); bool blockResize(gsl::czstring<> disk, unsigned long long size, enums::domain::BlockResizeFlag flags) noexcept; auto blockStats(gsl::czstring<> disk, size_t size) const noexcept; auto blockStatsFlags(gsl::czstring<> disk, enums::TypedParameterFlag flags) const noexcept; bool create() noexcept; bool create(enums::domain::CreateFlag flag) noexcept; // createWithFiles() // Left out bool coreDump(std::filesystem::path to, enums::domain::core_dump::Flag flags) const noexcept; bool coreDump(std::filesystem::path to, enums::domain::core_dump::Format format, enums::domain::core_dump::Flag flags) const noexcept; bool delIOThread(unsigned int iothread_id, enums::domain::ModificationImpactFlag flags) noexcept; bool destroy() noexcept; bool destroy(enums::domain::DestroyFlag flag) noexcept; bool detachDevice(gsl::czstring<> xml) noexcept; bool detachDevice(gsl::czstring<> xml, enums::domain::DeviceModifyFlag flag) noexcept; bool detachDeviceAlias(gsl::czstring<> alias, enums::domain::DeviceModifyFlag flag) noexcept; int fsFreeze(gsl::span<gsl::czstring<>> mountpoints) noexcept; int fsThaw(gsl::span<gsl::czstring<>> mountpoints) noexcept; bool fsTrim(gsl::czstring<> mountpoint, unsigned long long minimum) noexcept; [[nodiscard]] bool getAutostart() const noexcept; [[nodiscard]] auto getBlkioParameters(enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] auto getBlockInfo(gsl::czstring<> disk) const noexcept -> std::optional<virDomainBlockInfo>; [[nodiscard]] auto getBlockIoTune(gsl::czstring<> disk, enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] auto getBlockJobInfo(gsl::czstring<> disk, enums::domain::BlockJobInfoFlag flags) const noexcept; [[nodiscard]] Connection getConnect() const noexcept; [[nodiscard]] std::optional<virDomainControlInfo> getControlInfo() const noexcept; [[nodiscard]] auto getTotalCPUStats() const noexcept; [[nodiscard]] auto getCPUStats(unsigned start_cpu, unsigned ncpus) const noexcept; [[nodiscard]] auto getDiskErrors() const noexcept; [[nodiscard]] std::vector<DiskError> extractDiskErrors() const; //[[nodiscard]] CpuMap getEmulatorPinInfo(std::size_t maplen, ModificationImpactFlag flags) const noexcept; [[nodiscard]] auto getFSInfo() const noexcept; [[nodiscard]] std::vector<FSInfo> extractFSInfo() const; [[nodiscard]] auto getJobStats(enums::domain::GetJobStatsFlag flags) const noexcept; [[nodiscard]] std::optional<TypedParams> getGuestVcpus() const noexcept; [[nodiscard]] UniqueZstring getHostname() const noexcept; [[nodiscard]] std::string extractHostname() const noexcept; [[nodiscard]] unsigned getID() const noexcept; [[nodiscard]] auto getIOThreadInfo(enums::domain::ModificationImpactFlag flags) const noexcept; [[nodiscard]] auto extractIOThreadInfo(enums::domain::ModificationImpactFlag flags) const -> std::vector<heavy::IOThreadInfo>; [[nodiscard]] Info getInfo() const noexcept; [[nodiscard]] auto getInterfaceParameters(gsl::czstring<> device, enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] std::optional<JobInfo> getJobInfo() const noexcept; [[nodiscard]] auto getLaunchSecurityInfo() const noexcept; [[nodiscard]] int getMaxVcpus() const noexcept; [[nodiscard]] auto getMemoryParameters(enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] UniqueZstring getMetadata(enums::domain::MetadataType type, gsl::czstring<> ns, enums::domain::ModificationImpactFlag flags) const noexcept; [[nodiscard]] std::string extractMetadata(enums::domain::MetadataType type, gsl::czstring<> ns, enums::domain::ModificationImpactFlag flags) const; [[nodiscard]] gsl::czstring<> getName() const noexcept; [[nodiscard]] auto getNumaParameters(enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] int getNumVcpus(enums::domain::VCpuFlag flags) const noexcept; [[nodiscard]] auto getSchedulerType() const noexcept -> std::pair<UniqueZstring, int>; [[nodiscard]] auto getSecurityLabel() const noexcept -> std::unique_ptr<virSecurityLabel>; [[nodiscard]] auto getSecurityLabelList() const noexcept; [[nodiscard]] auto extractSecurityLabelList() const -> std::vector<virSecurityLabel>; [[nodiscard]] auto getState() const noexcept -> StateWReason; [[nodiscard]] auto getTime() const noexcept; [[nodiscard]] auto getUUID() const; [[nodiscard]] bool isActive() const noexcept; [[nodiscard]] auto getUUIDString() const noexcept -> std::optional<std::array<char, VIR_UUID_STRING_BUFLEN>>; [[nodiscard]] auto extractUUIDString() const -> std::string; [[nodiscard]] auto getOSType() const; [[nodiscard]] unsigned long getMaxMemory() const noexcept; [[nodiscard]] auto getSchedulerParameters() const noexcept; [[nodiscard]] auto getSchedulerParameters(enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] auto getPerfEvents(enums::domain::MITPFlags flags) const noexcept; [[nodiscard]] auto getVcpuPinInfo(enums::domain::VCpuFlag flags) -> std::optional<std::vector<unsigned char>>; [[nodiscard]] auto getVcpus() const noexcept; [[nodiscard]] UniqueZstring getXMLDesc(enums::domain::XMLFlags flag) const noexcept; [[nodiscard]] TFE hasManagedSaveImage() const noexcept; bool injectNMI() noexcept; [[nodiscard]] auto interfaceAddressesView(enums::domain::InterfaceAddressesSource source) const noexcept; [[nodiscard]] auto interfaceAddresses(enums::domain::InterfaceAddressesSource source) const -> std::vector<Interface>; [[nodiscard]] auto interfaceStats(gsl::czstring<> device) const noexcept -> std::optional<virDomainInterfaceStatsStruct>; [[nodiscard]] TFE isPersistent() const noexcept; [[nodiscard]] TFE isUpdated() const noexcept; bool PMSuspendForDuration(unsigned target, unsigned long long duration) noexcept; bool PMWakeup() noexcept; // [[nodiscard]] static int listGetStats(gsl::basic_zstring<Domain> doms, StatsType stats, virDomainStatsRecordPtr** retStats, // GetAllDomainStatsFlag flags); bool managedSave(enums::domain::SaveRestoreFlag flag) noexcept; bool managedSaveDefineXML(gsl::czstring<> dxml, enums::domain::SaveRestoreFlag flag) noexcept; [[nodiscard]] UniqueZstring managedSaveGetXMLDesc(enums::domain::SaveImageXMLFlag flag) const noexcept; [[nodiscard]] std::string managedSaveExtractXMLDesc(enums::domain::SaveImageXMLFlag flag) const noexcept; bool managedSaveRemove() noexcept; bool memoryPeek(unsigned long long start, gsl::span<unsigned char> buffer, enums::domain::MemoryFlag flag) const noexcept; auto memoryStats(unsigned int nr_stats) const noexcept; [[nodiscard]] Domain migrate(Connection dconn, enums::domain::MigrateFlag flags, gsl::czstring<> dname, gsl::czstring<> uri, unsigned long bandwidth) noexcept; [[nodiscard]] Domain migrate(Connection dconn, gsl::czstring<> dxml, enums::domain::MigrateFlag flags, gsl::czstring<> dname, gsl::czstring<> uri, unsigned long bandwidth) noexcept; [[nodiscard]] Domain migrate(Connection dconn, const TypedParams& params, enums::domain::MigrateFlag flags) noexcept; bool migrateToURI(gsl::czstring<> duri, enums::domain::MigrateFlag flags, gsl::czstring<> dname, unsigned long bandwidth) noexcept; bool migrateToURI(gsl::czstring<> dconnuri, gsl::czstring<> miguri, gsl::czstring<> dxml, enums::domain::MigrateFlag flags, gsl::czstring<> dname, unsigned long bandwidth) noexcept; bool migrateToURI(gsl::czstring<> dconnuri, const TypedParams& params, enums::domain::MigrateFlag flags) noexcept; [[nodiscard]] auto migrateGetCompressionCache() const noexcept -> std::optional<unsigned long long>; [[nodiscard]] auto migrateGetMaxDowntime() const noexcept -> std::optional<unsigned long long>; [[nodiscard]] auto migrateGetMaxSpeed(unsigned int flag) const noexcept -> std::optional<unsigned long>; bool migrateSetCompressionCache(unsigned long long cacheSize) noexcept; bool migrateSetMaxDowntime(unsigned long long downtime) noexcept; bool migrateSetMaxSpeed(unsigned long bandwidth, unsigned int flag) noexcept; bool migrateStartPostCopy(unsigned int flag) noexcept; bool openChannel(gsl::czstring<> name, Stream& st, enums::domain::ChannelFlag flags) noexcept; bool openConsole(gsl::czstring<> dev_name, Stream& st, enums::domain::ConsoleFlag flags) noexcept; bool openGraphics(unsigned int idx, int fd, enums::domain::OpenGraphicsFlag flags) const noexcept; [[nodiscard]] int openGraphicsFD(unsigned int idx, enums::domain::OpenGraphicsFlag flags) const noexcept; bool pinEmulator(CpuMap cpumap, enums::domain::ModificationImpactFlag flags) noexcept; bool pinIOThread(unsigned int iothread_id, CpuMap cpumap, enums::domain::ModificationImpactFlag flags) noexcept; bool pinVcpu(unsigned int vcpu, CpuMap cpumap) noexcept; bool pinVcpuFlags(unsigned int vcpu, CpuMap cpumap, enums::domain::ModificationImpactFlag flags) noexcept; bool sendKey(enums::domain::KeycodeSet codeset, unsigned int holdtime, gsl::span<const unsigned int> keycodes) noexcept; bool sendProcessSignal(long long pid_value, enums::domain::ProcessSignal signum) noexcept; bool setMaxMemory(unsigned long); bool setMemory(unsigned long); bool setMemoryStatsPeriod(int period, enums::domain::MemoryModFlag flags) noexcept; bool reboot(enums::domain::ShutdownFlag flags); bool reboot(); bool reset(); bool rename(gsl::czstring<>); bool resume() noexcept; bool save(gsl::czstring<> to) noexcept; bool save(gsl::czstring<> to, gsl::czstring<> dxml, enums::domain::SaveRestoreFlag flags) noexcept; UniqueZstring screenshot(Stream& stream, unsigned int screen) const noexcept; bool setAutoStart(bool); bool setBlkioParameters(TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setBlockIoTune(gsl::czstring<> disk, TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setBlockThreshold(gsl::czstring<> dev, unsigned long long threshold) noexcept; bool setGuestVcpus(gsl::czstring<> cpumap, bool state) noexcept; // https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainSetGuestVcpus bool setIOThreadParams(unsigned int iothread_id, TypedParams params, enums::domain::MITPFlags flags) noexcept; bool setInterfaceParameters(gsl::czstring<> device, TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setLifecycleAction(enums::domain::Lifecycle type, enums::domain::LifecycleAction action, enums::domain::ModificationImpactFlag flags) noexcept; bool setMemoryFlags(unsigned long memory, enums::domain::MemoryModFlag flags) noexcept; bool setMemoryParameters(TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setNumaParameters(TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setPerfEvents(TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setSchedulerParameters(TypedParams params) noexcept; bool setSchedulerParameters(TypedParams params, enums::domain::ModificationImpactFlag flags) noexcept; bool setMetadata(enums::domain::MetadataType type, gsl::czstring<> metadata, gsl::czstring<> key, gsl::czstring<> uri, enums::domain::ModificationImpactFlag flags) noexcept; bool setTime(long long seconds, unsigned int nseconds, enums::domain::SetTimeFlag flags) noexcept; bool setUserPassword(gsl::czstring<> user, gsl::czstring<> password, enums::domain::SetUserPasswordFlag flags) noexcept; bool setVcpu(gsl::czstring<> vcpumap, bool state, enums::domain::ModificationImpactFlag flags) noexcept; bool setVcpus(unsigned int nvcpus) noexcept; bool setVcpus(unsigned int nvcpus, enums::domain::VCpuFlag flags) noexcept; bool shutdown() noexcept; bool shutdown(enums::domain::ShutdownFlag flag) noexcept; bool suspend() noexcept; bool undefine() noexcept; bool undefine(enums::domain::UndefineFlag) noexcept; bool updateDeviceFlags(gsl::czstring<> xml, enums::domain::DeviceModifyFlag flags) noexcept; [[nodiscard]] static Domain createXML(Connection&, gsl::czstring<> xml, enums::domain::CreateFlag flags); [[nodiscard]] static Domain createXML(Connection&, gsl::czstring<> xml); // [[nodiscard]] static Domain defineXML(); }; class Domain::StatsRecord { friend Connection; Domain dom; std::vector<TypedParameter> params{}; explicit StatsRecord(const virDomainStatsRecord&) noexcept; public: }; class Domain::StateWReason : public std::variant<enums::domain::state_reason::NoState, enums::domain::state_reason::Running, enums::domain::state_reason::Blocked, enums::domain::state_reason::Paused, enums::domain::state_reason::Shutdown, enums::domain::state_reason::Shutoff, enums::domain::state_reason::Crashed, enums::domain::state_reason::PMSuspended> { constexpr enums::domain::State state() const noexcept { return enums::domain::State(EHTag{}, this->index()); } }; struct alignas(alignof(virDomainDiskError)) Domain::DiskError { enum class Code : decltype(virDomainDiskError::error) { NONE = VIR_DOMAIN_DISK_ERROR_NONE, /* no error */ UNSPEC = VIR_DOMAIN_DISK_ERROR_UNSPEC, /* unspecified I/O error */ NO_SPACE = VIR_DOMAIN_DISK_ERROR_NO_SPACE, /* no space left on the device */ }; UniqueZstring disk; Code error; }; struct Domain::FSInfo { std::string mountpoint; /* path to mount point */ std::string name; /* device name in the guest (e.g. "sda1") */ std::string fstype; /* filesystem type */ std::vector<std::string> dev_alias; /* vector of disk device aliases */ FSInfo(virDomainFSInfo* from) noexcept : mountpoint(from->mountpoint), name(from->name), fstype(from->fstype), dev_alias(from->devAlias, from->devAlias + from->ndevAlias) { virDomainFSInfoFree(from); } }; class Domain::IPAddress { friend Domain; friend Interface; IPAddress(virDomainIPAddressPtr ptr) : type(Type{ptr->type}), addr(ptr->addr), prefix(ptr->prefix) {} public: enum class Type : int { IPV4 = VIR_IP_ADDR_TYPE_IPV4, IPV6 = VIR_IP_ADDR_TYPE_IPV6, }; IPAddress() noexcept = default; IPAddress(const virDomainIPAddress& ref) : type(Type{ref.type}), addr(ref.addr), prefix(ref.prefix) {} IPAddress(Type type, std::string addr, uint8_t prefix) noexcept : type(type), addr(std::move(addr)), prefix(prefix) {} Type type; std::string addr; uint8_t prefix; }; class Domain::IPAddressView : private virDomainIPAddress { friend InterfaceView; using Base = virDomainIPAddress; public: [[nodiscard]] constexpr IPAddress::Type type() const noexcept { return IPAddress::Type{Base::type}; } [[nodiscard]] constexpr gsl::czstring<> addr() const noexcept { return Base::addr; } [[nodiscard]] constexpr uint8_t prefix() const noexcept { return Base::prefix; } [[nodiscard]] operator IPAddress() const noexcept { return {type(), addr(), prefix()}; }; }; class Domain::Interface { friend Domain; public: Interface(virDomainInterfacePtr ptr) : name(ptr->name), hwaddr(ptr->hwaddr), addrs(ptr->addrs, ptr->addrs + ptr->naddrs) {} std::string name; std::string hwaddr; std::vector<IPAddress> addrs; }; class Domain::InterfaceView : private virDomainInterface { using Base = virDomainInterface; public: ~InterfaceView() noexcept { virDomainInterfaceFree(this); } [[nodiscard]] constexpr gsl::czstring<> name() const noexcept { return Base::name; } [[nodiscard]] constexpr gsl::czstring<> hwaddr() const noexcept { return Base::hwaddr; } [[nodiscard]] constexpr gsl::span<IPAddressView> addrs() const noexcept { return {static_cast<IPAddressView*>(Base::addrs), Base::naddrs}; } }; struct alignas(alignof(virDomainJobInfo)) Domain::JobInfo : public virDomainJobInfo { [[nodiscard]] constexpr enums::domain::JobType type() const noexcept { return enums::domain::JobType{virDomainJobInfo::type}; } }; // concept Domain::IOThreadInfo class alignas(alignof(virDomainIOThreadInfo)) Domain::light::IOThreadInfo : private virDomainIOThreadInfo { friend Domain; using Base = virDomainIOThreadInfo; public: inline ~IOThreadInfo() noexcept { virDomainIOThreadInfoFree(this); } constexpr unsigned iothread_id() const noexcept { return Base::iothread_id; } constexpr unsigned& iothread_id() noexcept { return Base::iothread_id; } constexpr CpuMap cpumap() const noexcept { return {Base::cpumap, Base::cpumaplen}; } constexpr CpuMap cpumap() noexcept { return {Base::cpumap, Base::cpumaplen}; } }; class Domain::heavy::IOThreadInfo { friend Domain; unsigned m_iothread_id{}; std::vector<unsigned char> m_cpumap{}; IOThreadInfo(const virDomainIOThreadInfo& ref) noexcept : m_iothread_id(ref.iothread_id), m_cpumap(ref.cpumap, ref.cpumap + ref.cpumaplen) {} // C++2aTODO make constexpr public: IOThreadInfo(virDomainIOThreadInfo* ptr) noexcept : m_iothread_id(ptr->iothread_id), m_cpumap(ptr->cpumap, ptr->cpumap + ptr->cpumaplen) {} // C++2aTODO make constexpr inline ~IOThreadInfo() = default; constexpr unsigned iothread_id() const noexcept { return m_iothread_id; } constexpr unsigned& iothread_id() noexcept { return m_iothread_id; } gsl::span<const unsigned char> cpumap() const noexcept { return {m_cpumap.data(), static_cast<long>(m_cpumap.size())}; } CpuMap cpumap() noexcept { return {m_cpumap.data(), static_cast<int>(m_cpumap.size())}; } }; } // namespace virt #include "impl/Domain.hpp" #endif
43.082353
150
0.721815
AeroStun
6bb046663e3e1ca84b74ca857009a40e40915b9b
7,473
cpp
C++
src/tohir.cpp
kimmoli/tohiri-app
8508dd05bf55847158c3d1ed99fa6dad2d013bfb
[ "MIT" ]
1
2017-10-06T10:39:50.000Z
2017-10-06T10:39:50.000Z
src/tohir.cpp
kimmoli/tohiri-app
8508dd05bf55847158c3d1ed99fa6dad2d013bfb
[ "MIT" ]
null
null
null
src/tohir.cpp
kimmoli/tohiri-app
8508dd05bf55847158c3d1ed99fa6dad2d013bfb
[ "MIT" ]
null
null
null
#include "tohir.h" #include <QSettings> #include <QCoreApplication> #include <QTime> #include <QtDBus/QtDBus> #include <QDBusArgument> #include "amg883x.h" TohIR::TohIR(QObject *parent) : QObject(parent) { // Create seed for the random // That is needed only once on application startup QTime time = QTime::currentTime(); qsrand((uint)time.msec()); m_min = 100.0; m_max = -20.0; m_avg = 0.0; m_hotSpot = 31; readSettings(); controlVdd(true); QThread::msleep(300); amg = new amg883x(0x68); } void TohIR::readSettings() { QSettings s("kimmoli", "tohiri"); s.beginGroup("View"); m_gradientOpacity = s.value("gradientOpacity", "0.5").toReal(); m_updateRate = s.value("updateRate", 500).toInt(); m_granularity = s.value("granularity", "2.0").toReal(); m_contrast = s.value("contrast", 1.0).toReal(); s.endGroup(); emit gradientOpacityChanged(); emit updateRateChanged(); emit granularityChanged(); emit contrastChanged(); } void TohIR::saveSettings() { QSettings s("kimmoli", "tohiri"); s.beginGroup("View"); s.setValue("gradientOpacity", QString::number(m_gradientOpacity,'f',2) ); s.setValue("updateRate", m_updateRate); s.setValue("granularity", m_granularity); s.setValue("contrast", m_contrast); s.endGroup(); } TohIR::~TohIR() { controlVdd(false); } int TohIR::randInt(int low, int high) { // Random number between low and high return qrand() % ((high + 1) - low) + low; } /* Return git describe as string (see .pro file) */ QString TohIR::readVersion() { return QString(APPVERSION); } /**/ qreal TohIR::readGradientOpacity() { return m_gradientOpacity; } /**/ void TohIR::writeGradientOpacity(qreal val) { m_gradientOpacity = val; emit gradientOpacityChanged(); } int TohIR::readUpdateRate() { return m_updateRate; } void TohIR::writeUpdateRate(int val) { m_updateRate = val; emit updateRateChanged(); } qreal TohIR::readGranularity() { return m_granularity; } void TohIR::writeGranularity(qreal val) { m_granularity = val; emit granularityChanged(); } qreal TohIR::readContrast() { return m_contrast; } void TohIR::writeContrast(qreal val) { m_contrast = val; emit contrastChanged(); } /* Return thermistor temperature */ QString TohIR::readThermistor() { return QString("%1 °C").arg(QString::number(amg->getThermistor(), 'g', 3)); } /* Start IR Scan function, emit changed after completed */ void TohIR::startScan() { // printf("Thermistor %0.5f\n", amg->getThermistor()); QList<qreal> res = amg->getTemperatureArray(); int i; qreal thisMax = -40.0; m_min = 200.0; m_max = -40.0; m_avg = 0.0; // for (i=0 ; i < 64 ; i++) // printf("%0.2f%s", res.at(i), (( i%8 == 0 ) ? "\n" : " ") ); /* Return color gradient array */ for (i=0 ; i<64 ; i++) { /* Just use whole numbers */ qreal tmp = res.at(i); if (tmp > thisMax) { thisMax = tmp; m_hotSpot = i; } if (tmp > m_max) m_max = tmp; if (tmp < m_min) m_min = tmp; m_avg = m_avg + tmp; } emit maxTempChanged(); emit minTempChanged(); emit hotSpotChanged(); m_avg = m_avg/64; emit avgTempChanged(); /* Get RGB values for each pixel */ m_temperatures.clear(); for (i=0 ; i<64 ; i++) m_temperatures.append(temperatureColor(res.at(i), m_min, m_max, m_avg)); emit temperaturesChanged(); } /* Return temperature color gradients as array */ QList<QString> TohIR::readTemperatures() { return m_temperatures; } /* Return minimum, average and maximum temperature of last scan */ QString TohIR::readMinTemp() { return QString("%1 °C").arg(QString::number(m_min, 'g', 3)); } QString TohIR::readAvgTemp() { return QString("%1 °C").arg(QString::number(m_avg, 'g', 3)); } QString TohIR::readMaxTemp() { return QString("%1 °C").arg(QString::number(m_max, 'g', 3)); } int TohIR::readHotSpot() { return m_hotSpot; } /* Call dbus method to save screencapture */ void TohIR::saveScreenCapture() { QDate ssDate = QDate::currentDate(); QTime ssTime = QTime::currentTime(); QString ssFilename = QString("%8/tohiri-%1%2%3-%4%5%6-%7.png") .arg((int) ssDate.day(), 2, 10, QLatin1Char('0')) .arg((int) ssDate.month(), 2, 10, QLatin1Char('0')) .arg((int) ssDate.year(), 2, 10, QLatin1Char('0')) .arg((int) ssTime.hour(), 2, 10, QLatin1Char('0')) .arg((int) ssTime.minute(), 2, 10, QLatin1Char('0')) .arg((int) ssTime.second(), 2, 10, QLatin1Char('0')) .arg((int) ssTime.msec(), 3, 10, QLatin1Char('0')) .arg(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); QDBusMessage m = QDBusMessage::createMethodCall("org.nemomobile.lipstick", "/org/nemomobile/lipstick/screenshot", "", "saveScreenshot" ); QList<QVariant> args; args.append(ssFilename); m.setArguments(args); if (QDBusConnection::sessionBus().send(m)) printf("Screenshot success to %s\n", qPrintable(ssFilename)); else printf("Screenshot failed\n"); } QString TohIR::temperatureColor(qreal temp, qreal min, qreal max, qreal avg) { /* We have 61 different colors - for now */ static const QString lookup[61] = { "#0500ff", "#0400ff", "#0300ff", "#0200ff", "#0100ff", "#0000ff", "#0002ff", "#0012ff", "#0022ff", "#0032ff", "#0044ff", "#0054ff", "#0064ff", "#0074ff", "#0084ff", "#0094ff", "#00a4ff", "#00b4ff", "#00c4ff", "#00d4ff", "#00e4ff", "#00fff4", "#00ffd0", "#00ffa8", "#00ff83", "#00ff5c", "#00ff36", "#00ff10", "#17ff00", "#3eff00", "#65ff00", "#8aff00", "#b0ff00", "#d7ff00", "#fdff00", "#FFfa00", "#FFf000", "#FFe600", "#FFdc00", "#FFd200", "#FFc800", "#FFbe00", "#FFb400", "#FFaa00", "#FFa000", "#FF9600", "#FF8c00", "#FF8200", "#FF7800", "#FF6e00", "#FF6400", "#FF5a00", "#FF5000", "#FF4600", "#FF3c00", "#FF3200", "#FF2800", "#FF1e00", "#FF1400", "#FF0a00", "#FF0000" }; /* If true span is low, tweak it to around avg */ if ((max - min) < 20.0) { max = ( ((avg + 10.0) > max) ? (avg + 10.0) : max ); min = ( ((avg - 10.0) < min) ? (avg - 10.0) : min ); } /* Adjust low end to 0, to get only positive numbers */ qreal t = temp - min; /* span is 2x max or min difference to average, which is larger */ qreal span = 2.0 * ((max - avg) > (avg - min) ? (max - avg) : (avg - min)); /* Scale to 60 points */ qreal x = (t * (60000.0/span))/1000.0; /* just to prevent segfaults, return error color (white) */ if ( (x < 0.0) || (x > 60.0) ) return "#FFFFFF"; return lookup[static_cast<int>(x)]; /* Return corresponding RGB color */ } void TohIR::controlVdd(bool state) { int fd = open("/sys/devices/platform/reg-userspace-consumer.0/state", O_WRONLY); if (!(fd < 0)) { if (write (fd, state ? "1" : "0", 1) != 1) qDebug() << "Failed to control VDD."; close(fd); } return; }
23.951923
93
0.569785
kimmoli
6bb36bd032f4b3ce1e8c05db64801b82f06516de
1,159
cpp
C++
solutions/c++/problems/[0013_Medium] 3Sum.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
6
2021-02-20T14:00:22.000Z
2022-03-31T15:26:44.000Z
solutions/c++/problems/[0013_Medium] 3Sum.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
solutions/c++/problems/[0013_Medium] 3Sum.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: void twoSum(vector<vector<int>> &ans, vector<int> &nums, int checkIndex) { int startIndex = checkIndex + 1; int endIndex = nums.size() - 1; while (startIndex < endIndex) { int sum = nums[checkIndex] + nums[startIndex] + nums[endIndex]; if (sum == 0) { ans.push_back({nums[checkIndex], nums[startIndex], nums[endIndex]}); do { startIndex++; } while (nums[startIndex] == nums[startIndex - 1] && startIndex < endIndex); endIndex--; } else if (sum > 0) { endIndex--; } else { startIndex++; } } } vector<vector<int>> threeSum(vector<int> &nums) { vector<vector<int>> ans = {}; if (nums.size() >= 3) { sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; twoSum(ans, nums, i); } } return ans; } };
31.324324
92
0.458154
RageBill
6bb9112c3fbad4bf1581a6992d7a8b50ca744543
1,859
cpp
C++
samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_VisualStudioDemo/cpp/OptionsDlg.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_VisualStudioDemo/cpp/OptionsDlg.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_VisualStudioDemo/cpp/OptionsDlg.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "OptionsDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // COptionsDlg IMPLEMENT_DYNAMIC(COptionsDlg, CMFCPropertySheet) COptionsDlg::COptionsDlg(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) :CMFCPropertySheet(pszCaption, pParentWnd, iSelectPage) { SetLook(CMFCPropertySheet::PropSheetLook_Tree, 150 /* Tree control width */); SetIconsList(IDB_OPTIONSIMAGES, 16 /* Image width */); // <snippet23> // The second parameter is the zero based index of an icon that is displayed when // the control property page is not selected. // The third parameter is the zero based index of an icon that is displayed when // the control property page is selected. CMFCPropertySheetCategoryInfo* pCat1 = AddTreeCategory(_T("Environment"), 0, 1); // </snippet23> AddPageToTree(pCat1, &m_Page11, -1, 2); AddPageToTree(pCat1, &m_Page12, -1, 2); CMFCPropertySheetCategoryInfo* pCat2 = AddTreeCategory(_T("Source Control"), 0, 1); AddPageToTree(pCat2, &m_Page21, -1, 2); AddPageToTree(pCat2, &m_Page22, -1, 2); CMFCPropertySheetCategoryInfo* pCat3 = AddTreeCategory(_T("Text Editor"), 0, 1); AddPageToTree(pCat3, &m_Page31, -1, 2); AddPageToTree(pCat3, &m_Page32, -1, 2); } COptionsDlg::~COptionsDlg() { } BEGIN_MESSAGE_MAP(COptionsDlg, CMFCPropertySheet) END_MESSAGE_MAP()
31.508475
84
0.726735
BaruaSourav
6bb9dfbae9a01e9d577d0bf2e58ac25b2a56466c
18,531
cpp
C++
src/Passes/HFSortPlus.cpp
davidmalcolm/BOLT
c5c46ca08fd846fb22e032a965fbccf2b0415861
[ "NCSA" ]
2
2019-04-14T20:18:08.000Z
2020-02-18T19:31:51.000Z
src/Passes/HFSortPlus.cpp
davidmalcolm/BOLT
c5c46ca08fd846fb22e032a965fbccf2b0415861
[ "NCSA" ]
null
null
null
src/Passes/HFSortPlus.cpp
davidmalcolm/BOLT
c5c46ca08fd846fb22e032a965fbccf2b0415861
[ "NCSA" ]
1
2022-01-12T17:53:25.000Z
2022-01-12T17:53:25.000Z
//===--- HFSortPlus.cpp - Cluster functions by hotness --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// #include "BinaryFunction.h" #include "HFSort.h" #include "ReorderUtils.h" #include "llvm/Support/Options.h" #include <vector> #include <unordered_map> #include <unordered_set> #undef DEBUG_TYPE #define DEBUG_TYPE "hfsort" using namespace llvm; using namespace bolt; namespace opts { extern cl::OptionCategory BoltOptCategory; extern cl::opt<unsigned> ITLBPageSize; extern cl::opt<unsigned> ITLBEntries; cl::opt<double> MergeProbability("merge-probability", cl::desc("The minimum probability of a call for merging two clusters"), cl::init(0.99), cl::ZeroOrMore, cl::cat(BoltOptCategory)); } namespace llvm { namespace bolt { using NodeId = CallGraph::NodeId; using Arc = CallGraph::Arc; using Node = CallGraph::Node; namespace { constexpr size_t InvalidAddr = -1; // The size of a cache page: Since we optimize both for i-TLB cache (2MB pages) // and i-cache (64b pages), using a value that fits both int32_t ITLBPageSize; // Capacity of the iTLB cache: Larger values yield more iTLB-friendly result, // while smaller values result in better i-cache performance int32_t ITLBEntries; /// Density of a cluster formed by merging a given pair of clusters. double density(const Cluster *ClusterPred, const Cluster *ClusterSucc) { const double CombinedSamples = ClusterPred->samples() + ClusterSucc->samples(); const double CombinedSize = ClusterPred->size() + ClusterSucc->size(); return CombinedSamples / CombinedSize; } /// Deterministically compare clusters by density in decreasing order. bool compareClusters(const Cluster *C1, const Cluster *C2) { const double D1 = C1->density(); const double D2 = C2->density(); if (D1 != D2) return D1 > D2; // making sure the sorting is deterministic return C1->target(0) < C2->target(0); } /// Deterministically compare pairs of clusters by density in decreasing order. bool compareClusterPairs(const Cluster *A1, const Cluster *B1, const Cluster *A2, const Cluster *B2) { const auto D1 = density(A1, B1); const auto D2 = density(A2, B2); if (D1 != D2) return D1 > D2; const auto Size1 = A1->size() + B1->size(); const auto Size2 = A2->size() + B2->size(); if (Size1 != Size2) return Size1 < Size2; const auto Samples1 = A1->samples() + B1->samples(); const auto Samples2 = A2->samples() + B2->samples(); if (Samples1 != Samples2) return Samples1 > Samples2; return A1->target(0) < A2->target(0); } /// HFSortPlus - layout of hot functions with iTLB cache optimization /// /// Given an ordering of hot functions (and hence, their assignment to the /// iTLB pages), we can divide all functions calls into two categories: /// - 'short' ones that have a caller-callee distance less than a page; /// - 'long' ones where the distance exceeds a page. /// The short calls are likely to result in a iTLB cache hit. For the long ones, /// the hit/miss result depends on the 'hotness' of the page (i.e., how often /// the page is accessed). Assuming that functions are sent to the iTLB cache /// in a random order, the probability that a page is present in the cache is /// proportional to the number of samples corresponding to the functions on the /// page. The following algorithm detects short and long calls, and optimizes /// the expected number of cache misses for the long ones. class HFSortPlus { public: /// The expected number of calls on different i-TLB pages for an arc of the /// call graph with a specified weight double expectedCalls(int64_t SrcAddr, int64_t DstAddr, double Weight) const { const auto Dist = std::abs(SrcAddr - DstAddr); if (Dist > ITLBPageSize) return 0; double X = double(Dist) / double(ITLBPageSize); // Increasing the importance of shorter calls return (1.0 - X * X) * Weight; } /// The probability that a page with a given weight is not present in the cache /// /// Assume that the hot functions are called in a random order; then the /// probability of a i-TLB page being accessed after a function call is /// p=pageSamples/totalSamples. The probability that the page is not accessed /// is (1-p), and the probability that it is not in the cache (i.e. not accessed /// during the last ITLBEntries function calls) is (1-p)^ITLBEntries double missProbability(double PageSamples) const { double P = PageSamples / TotalSamples; double X = ITLBEntries; return pow(1.0 - P, X); } /// The expected number of calls within a given cluster with both endpoints on /// the same cache page double shortCalls(const Cluster *Cluster) const { double Calls = 0; for (auto TargetId : Cluster->targets()) { for (auto Succ : Cg.successors(TargetId)) { if (FuncCluster[Succ] == Cluster) { const auto &Arc = *Cg.findArc(TargetId, Succ); auto SrcAddr = Addr[TargetId] + Arc.avgCallOffset(); auto DstAddr = Addr[Succ]; Calls += expectedCalls(SrcAddr, DstAddr, Arc.weight()); } } } return Calls; } /// The number of calls between the two clusters with both endpoints on /// the same i-TLB page, assuming that a given pair of clusters gets merged double shortCalls(const Cluster *ClusterPred, const Cluster *ClusterSucc) const { double Calls = 0; for (auto TargetId : ClusterPred->targets()) { for (auto Succ : Cg.successors(TargetId)) { if (FuncCluster[Succ] == ClusterSucc) { const auto &Arc = *Cg.findArc(TargetId, Succ); auto SrcAddr = Addr[TargetId] + Arc.avgCallOffset(); auto DstAddr = Addr[Succ] + ClusterPred->size(); Calls += expectedCalls(SrcAddr, DstAddr, Arc.weight()); } } } for (auto TargetId : ClusterPred->targets()) { for (auto Pred : Cg.predecessors(TargetId)) { if (FuncCluster[Pred] == ClusterSucc) { const auto &Arc = *Cg.findArc(Pred, TargetId); auto SrcAddr = Addr[Pred] + Arc.avgCallOffset() + ClusterPred->size(); auto DstAddr = Addr[TargetId]; Calls += expectedCalls(SrcAddr, DstAddr, Arc.weight()); } } } return Calls; } /// The gain of merging two clusters. /// /// We assume that the final clusters are sorted by their density, and hence /// every cluster is likely to be adjacent with clusters of the same density. /// Thus, the 'hotness' of every cluster can be estimated by density*pageSize, /// which is used to compute the probability of cache misses for long calls /// of a given cluster. /// The result is also scaled by the size of the resulting cluster in order to /// increse the chance of merging short clusters, which is helpful for /// the i-cache performance. double mergeGain(const Cluster *ClusterPred, const Cluster *ClusterSucc) const { if (UseGainCache && GainCache.contains(ClusterPred, ClusterSucc)) { return GainCache.get(ClusterPred, ClusterSucc); } // cache misses on the first cluster double LongCallsPred = ClusterPred->samples() - shortCalls(ClusterPred); double ProbPred = missProbability(ClusterPred->density() * ITLBPageSize); double ExpectedMissesPred = LongCallsPred * ProbPred; // cache misses on the second cluster double LongCallsSucc = ClusterSucc->samples() - shortCalls(ClusterSucc); double ProbSucc = missProbability(ClusterSucc->density() * ITLBPageSize); double ExpectedMissesSucc = LongCallsSucc * ProbSucc; // cache misses on the merged cluster double LongCallsNew = LongCallsPred + LongCallsSucc - shortCalls(ClusterPred, ClusterSucc); double NewDensity = density(ClusterPred, ClusterSucc); double ProbNew = missProbability(NewDensity * ITLBPageSize); double MissesNew = LongCallsNew * ProbNew; double Gain = ExpectedMissesPred + ExpectedMissesSucc - MissesNew; // scaling the result to increase the importance of merging short clusters Gain /= std::min(ClusterPred->size(), ClusterSucc->size()); if (UseGainCache) { GainCache.set(ClusterPred, ClusterSucc, Gain); } return Gain; } /// For every active cluster, compute its total weight of outgoing edges std::unordered_map<Cluster *, double> computeOutgoingWeight() { std::unordered_map<Cluster *, double> OutWeight; for (auto ClusterPred : Clusters) { double Weight = 0; for (auto TargetId : ClusterPred->targets()) { for (auto Succ : Cg.successors(TargetId)) { auto *ClusterSucc = FuncCluster[Succ]; if (!ClusterSucc || ClusterSucc == ClusterPred) continue; const auto &Arc = *Cg.findArc(TargetId, Succ); Weight += Arc.weight(); } } OutWeight[ClusterPred] += Weight; } return OutWeight; } /// Find pairs of clusters that call each other with high probability std::vector<std::pair<Cluster *, Cluster *>> findClustersToMerge() { // compute total weight of outgoing edges for every cluster auto OutWeight = computeOutgoingWeight(); std::vector<std::pair<Cluster *, Cluster *>> PairsToMerge; std::unordered_set<Cluster *> ClustersToMerge; for (auto ClusterPred : Clusters) { for (auto TargetId : ClusterPred->targets()) { for (auto Succ : Cg.successors(TargetId)) { auto *ClusterSucc = FuncCluster[Succ]; if (!ClusterSucc || ClusterSucc == ClusterPred) continue; const auto &Arc = *Cg.findArc(TargetId, Succ); const double CallsFromPred = OutWeight[ClusterPred]; const double CallsToSucc = ClusterSucc->samples(); const double CallsPredSucc = Arc.weight(); // probability that the first cluster is calling the second one const double ProbOut = CallsFromPred > 0 ? CallsPredSucc / CallsFromPred : 0; assert(0.0 <= ProbOut && ProbOut <= 1.0 && "incorrect probability"); // probability that the second cluster is called from the first one const double ProbIn = CallsToSucc > 0 ? CallsPredSucc / CallsToSucc : 0; assert(0.0 <= ProbIn && ProbIn <= 1.0 && "incorrect probability"); if (std::min(ProbOut, ProbIn) >= opts::MergeProbability) { if (ClustersToMerge.count(ClusterPred) == 0 && ClustersToMerge.count(ClusterSucc) == 0) { PairsToMerge.push_back(std::make_pair(ClusterPred, ClusterSucc)); ClustersToMerge.insert(ClusterPred); ClustersToMerge.insert(ClusterSucc); } } } } } return PairsToMerge; } /// Run the first optimization pass of the hfsort+ algorithm: /// Merge clusters that call each other with high probability void runPassOne() { while (Clusters.size() > 1) { // pairs of clusters that will be merged on this iteration auto PairsToMerge = findClustersToMerge(); // stop the pass when there are no pairs to merge if (PairsToMerge.empty()) break; // merge the pairs of clusters for (auto &Pair : PairsToMerge) { mergeClusters(Pair.first, Pair.second); } } } /// Run the second optimization pass of the hfsort+ algorithm: /// Merge pairs of clusters while there is an improvement in the /// expected cache miss ratio void runPassTwo() { while (Clusters.size() > 1) { Cluster *BestClusterPred = nullptr; Cluster *BestClusterSucc = nullptr; double BestGain = -1; for (auto ClusterPred : Clusters) { // get candidates for merging with the current cluster Adjacent.forAllAdjacent( ClusterPred, // find the best candidate [&](Cluster *ClusterSucc) { assert(ClusterPred != ClusterSucc && "loop edges are not supported"); // compute the gain of merging two clusters const double Gain = mergeGain(ClusterPred, ClusterSucc); // breaking ties by density to make the hottest clusters be merged first if (Gain > BestGain || (std::abs(Gain - BestGain) < 1e-8 && compareClusterPairs(ClusterPred, ClusterSucc, BestClusterPred, BestClusterSucc))) { BestGain = Gain; BestClusterPred = ClusterPred; BestClusterSucc = ClusterSucc; } }); } // stop merging when there is no improvement if (BestGain <= 0.0) break; // merge the best pair of clusters mergeClusters(BestClusterPred, BestClusterSucc); } } /// Run hfsort+ algorithm and return ordered set of function clusters. std::vector<Cluster> run() { DEBUG(dbgs() << "Starting hfsort+ w/" << (UseGainCache ? "gain cache" : "no cache") << " for " << Clusters.size() << " clusters " << "with ITLBPageSize = " << ITLBPageSize << ", " << "ITLBEntries = " << ITLBEntries << ", " << "and MergeProbability = " << opts::MergeProbability << "\n"); // Pass 1 runPassOne(); // Pass 2 runPassTwo(); DEBUG(dbgs() << "Completed hfsort+ with " << Clusters.size() << " clusters\n"); // Sorting clusters by density in decreasing order std::stable_sort(Clusters.begin(), Clusters.end(), compareClusters); // Return the set of clusters that are left, which are the ones that // didn't get merged (so their first func is its original func) std::vector<Cluster> Result; Result.reserve(Clusters.size()); for (auto Cluster : Clusters) { Result.emplace_back(std::move(*Cluster)); } return Result; } HFSortPlus(const CallGraph &Cg, bool UseGainCache) : Cg(Cg), FuncCluster(Cg.numNodes(), nullptr), Addr(Cg.numNodes(), InvalidAddr), TotalSamples(0.0), Clusters(initializeClusters()), Adjacent(Cg.numNodes()), UseGainCache(UseGainCache), GainCache(Clusters.size()) { // Initialize adjacency matrix Adjacent.initialize(Clusters); for (auto *A : Clusters) { for (auto TargetId : A->targets()) { for (auto Succ : Cg.successors(TargetId)) { auto *B = FuncCluster[Succ]; if (!B || B == A) continue; const auto &Arc = *Cg.findArc(TargetId, Succ); if (Arc.weight() > 0.0) Adjacent.set(A, B); } for (auto Pred : Cg.predecessors(TargetId)) { auto *B = FuncCluster[Pred]; if (!B || B == A) continue; const auto &Arc = *Cg.findArc(Pred, TargetId); if (Arc.weight() > 0.0) Adjacent.set(A, B); } } } } private: /// Initialize the set of active clusters, function id to cluster mapping, /// total number of samples and function addresses. std::vector<Cluster *> initializeClusters() { outs() << "BOLT-INFO: running hfsort+ for " << Cg.numNodes() << " functions\n"; ITLBPageSize = opts::ITLBPageSize; ITLBEntries = opts::ITLBEntries; // Initialize clusters std::vector<Cluster *> Clusters; Clusters.reserve(Cg.numNodes()); AllClusters.reserve(Cg.numNodes()); for (NodeId F = 0; F < Cg.numNodes(); ++F) { AllClusters.emplace_back(F, Cg.getNode(F)); Clusters.emplace_back(&AllClusters[F]); Clusters.back()->setId(Clusters.size() - 1); FuncCluster[F] = &AllClusters[F]; Addr[F] = 0; TotalSamples += Cg.samples(F); } return Clusters; } /// Merge cluster From into cluster Into and update the list of active clusters void mergeClusters(Cluster *Into, Cluster *From) { // The adjacency merge must happen before the Cluster::merge since that // clobbers the contents of From. Adjacent.merge(Into, From); Into->merge(*From); From->clear(); // Update the clusters and addresses for functions merged from From. size_t CurAddr = 0; for (auto TargetId : Into->targets()) { FuncCluster[TargetId] = Into; Addr[TargetId] = CurAddr; CurAddr += Cg.size(TargetId); // Functions are aligned in the output binary, // replicating the effect here using BinaryFunction::MinAlign const auto Align = BinaryFunction::MinAlign; CurAddr = ((CurAddr + Align - 1) / Align) * Align; } // Invalidate all cache entries associated with cluster Into if (UseGainCache) { GainCache.invalidate(Into); } // Remove cluster From from the list of active clusters auto Iter = std::remove(Clusters.begin(), Clusters.end(), From); Clusters.erase(Iter, Clusters.end()); } // The call graph const CallGraph &Cg; // All clusters std::vector<Cluster> AllClusters; // Target_id => cluster std::vector<Cluster *> FuncCluster; // current address of the function from the beginning of its cluster std::vector<size_t> Addr; // the total number of samples in the graph double TotalSamples; // All clusters with non-zero number of samples. This vector gets // udpated at runtime when clusters are merged. std::vector<Cluster *> Clusters; // Cluster adjacency matrix AdjacencyMatrix<Cluster> Adjacent; // Use cache for mergeGain results bool UseGainCache; // A cache that keeps precomputed values of mergeGain for pairs of clusters; // when a pair of clusters (x,y) gets merged, we need to invalidate the pairs // containing both x and y and all clusters adjacent to x and y (and recompute // them on the next iteration). mutable ClusterPairCache<Cluster, double> GainCache; }; } // end namespace anonymous std::vector<Cluster> hfsortPlus(CallGraph &Cg, bool UseGainCache) { // It is required that the sum of incoming arc weights is not greater // than the number of samples for every function. // Ensuring the call graph obeys the property before running the algorithm. Cg.adjustArcWeights(); return HFSortPlus(Cg, UseGainCache).run(); } }}
35.705202
84
0.640656
davidmalcolm
6bba3869449de6031b534304680e1472cc4667b2
9,225
cpp
C++
WndDesign3/IME simplification/temp2/merged.cpp
hchenqi/CppTest
ae650409282b6ad7a0bd12cb67b961777e16c208
[ "MIT" ]
null
null
null
WndDesign3/IME simplification/temp2/merged.cpp
hchenqi/CppTest
ae650409282b6ad7a0bd12cb67b961777e16c208
[ "MIT" ]
null
null
null
WndDesign3/IME simplification/temp2/merged.cpp
hchenqi/CppTest
ae650409282b6ad7a0bd12cb67b961777e16c208
[ "MIT" ]
null
null
null
#include <string> #include <Windows.h> using Point = struct { int x; int y; }; using Size = struct { int width; int height; }; using Rect = struct { Point point; Size size; }; using uint = unsigned; Rect region_empty = {}; using std::wstring; class IMM32Manager { public: bool is_composing() const { return is_composing_; } IMM32Manager() : is_composing_(false), input_language_id_(LANG_USER_DEFAULT), system_caret_(false), caret_rect_{ -1, -1, 0, 0 }, use_composition_window_(false) { } ~IMM32Manager() {} void SetInputLanguage(); void CreateImeWindow(HWND window_handle); LRESULT SetImeWindowStyle(HWND window_handle, UINT message, WPARAM wparam, LPARAM lparam); void DestroyImeWindow(HWND window_handle); void UpdateImeWindow(HWND window_handle); void CleanupComposition(HWND window_handle); void ResetComposition(HWND window_handle); void GetResult(HWND window_handle, LPARAM lparam, wstring& result); void GetComposition(HWND window_handle, LPARAM lparam, wstring& result); void EnableIME(HWND window_handle); void DisableIME(HWND window_handle); void CancelIME(HWND window_handle); void UpdateCaretRect(HWND window_handle, Rect caret_rect); void SetUseCompositionWindow(bool use_composition_window); LANGID input_language_id() const { return input_language_id_; } bool IsInputLanguageCJK() const; bool IsImm32ImeActive(); protected: void MoveImeWindow(HWND window_handle, HIMC imm_context); void CompleteComposition(HWND window_handle, HIMC imm_context); bool GetString(HIMC imm_context, WPARAM lparam, int type, wstring& result); private: bool is_composing_; LANGID input_language_id_; bool system_caret_; Rect caret_rect_; bool use_composition_window_; }; #include <Windows.h> HWND hWnd; IMM32Manager ime; LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main() { HINSTANCE hInstance = GetModuleHandle(NULL); const wchar_t className[] = L"ImeTestClass"; const wchar_t titleName[] = L"ImeTest"; WNDCLASSEX wc = {}; wc.cbSize = sizeof(WNDCLASSEX); wc.hInstance = hInstance; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpfnWndProc = WndProc; wc.lpszClassName = className; if (!RegisterClassEx(&wc)) { return 0; } hWnd = CreateWindowEx(NULL, className, titleName, WS_OVERLAPPEDWINDOW, 200, 200, 800, 500, NULL, NULL, hInstance, NULL); if (hWnd == NULL) { return 0; } ShowWindow(hWnd, SW_SHOW); UpdateWindow(hWnd); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; static wstring result = L"result", composition = L"composition"; switch (msg) { case WM_PAINT: hdc = BeginPaint(hwnd, &ps); TextOutW(hdc, 50, 50, result.data(), result.length()); TextOutW(hdc, 50, 100, composition.data(), composition.length()); EndPaint(hwnd, &ps); break; case WM_IME_SETCONTEXT: ime.CreateImeWindow(hwnd); ime.CleanupComposition(hwnd); ime.SetImeWindowStyle(hwnd, msg, wParam, lParam); ime.SetUseCompositionWindow(true); break; case WM_IME_STARTCOMPOSITION: ime.CreateImeWindow(hwnd); ime.ResetComposition(hwnd); ime.UpdateCaretRect(hwnd, Rect{ 100, 100, 100, 100 }); break; case WM_IME_COMPOSITION: { ime.UpdateImeWindow(hwnd); ime.GetResult(hwnd, lParam, result); ime.GetComposition(hwnd, lParam, composition); InvalidateRect(hwnd, NULL, true); }break; case WM_IME_ENDCOMPOSITION: ime.ResetComposition(hwnd); ime.DestroyImeWindow(hwnd); break; case WM_INPUTLANGCHANGE: ime.SetInputLanguage(); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } #pragma comment(lib, "imm32.lib") void IMM32Manager::SetInputLanguage() { WCHAR keyboard_layout[KL_NAMELENGTH]; if (::GetKeyboardLayoutNameW(keyboard_layout)) { input_language_id_ = static_cast<LANGID>( wcstol(&keyboard_layout[KL_NAMELENGTH >> 1], nullptr, 16)); } else { input_language_id_ = 0x0409; // Fallback to en-US. } } void IMM32Manager::CreateImeWindow(HWND window_handle) { if (PRIMARYLANGID(input_language_id_) == LANG_CHINESE || PRIMARYLANGID(input_language_id_) == LANG_JAPANESE) { if (!system_caret_) { if (::CreateCaret(window_handle, NULL, 1, 1)) { system_caret_ = true; } } } UpdateImeWindow(window_handle); } LRESULT IMM32Manager::SetImeWindowStyle(HWND window_handle, UINT message, WPARAM wparam, LPARAM lparam) { lparam &= ~ISC_SHOWUICOMPOSITIONWINDOW; return ::DefWindowProc(window_handle, message, wparam, lparam); } void IMM32Manager::DestroyImeWindow(HWND window_handle) { // Destroy the system caret if we have created for this IME input context. if (system_caret_) { ::DestroyCaret(); system_caret_ = false; } } void IMM32Manager::MoveImeWindow(HWND window_handle, HIMC imm_context) { if (GetFocus() != window_handle) return; int x = caret_rect_.point.x; int y = caret_rect_.point.y; const int kCaretMargin = 1; if (!use_composition_window_ && PRIMARYLANGID(input_language_id_) == LANG_CHINESE) { CANDIDATEFORM candidate_position = { 0, CFS_CANDIDATEPOS, {x, y}, {0, 0, 0, 0} }; ::ImmSetCandidateWindow(imm_context, &candidate_position); } if (system_caret_) { switch (PRIMARYLANGID(input_language_id_)) { case LANG_JAPANESE: ::SetCaretPos(x, y + caret_rect_.size.height); break; default: ::SetCaretPos(x, y); break; } } if (use_composition_window_) { COMPOSITIONFORM cf = { CFS_POINT, {x, y} }; ::ImmSetCompositionWindow(imm_context, &cf); return; } if (PRIMARYLANGID(input_language_id_) == LANG_KOREAN) { y += kCaretMargin; } CANDIDATEFORM exclude_rectangle = { 0, CFS_EXCLUDE, {x, y}, {x, y, x + caret_rect_.size.width, y + caret_rect_.size.height} }; ::ImmSetCandidateWindow(imm_context, &exclude_rectangle); } void IMM32Manager::UpdateImeWindow(HWND window_handle) { if (caret_rect_.point.x >= 0 && caret_rect_.point.y >= 0) { HIMC imm_context = ::ImmGetContext(window_handle); if (imm_context) { MoveImeWindow(window_handle, imm_context); ::ImmReleaseContext(window_handle, imm_context); } } } void IMM32Manager::CleanupComposition(HWND window_handle) { if (is_composing_) { HIMC imm_context = ::ImmGetContext(window_handle); if (imm_context) { ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0); ::ImmReleaseContext(window_handle, imm_context); } ResetComposition(window_handle); } } void IMM32Manager::ResetComposition(HWND window_handle) { is_composing_ = false; } void IMM32Manager::CompleteComposition(HWND window_handle, HIMC imm_context) { if (is_composing_) { ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0); ResetComposition(window_handle); } } bool IMM32Manager::GetString(HIMC imm_context, WPARAM lparam, int type, wstring& result) { if (!(lparam & type)) return false; LONG string_size = ::ImmGetCompositionString(imm_context, type, NULL, 0); if (string_size <= 0 || string_size % sizeof(wchar_t) != 0) return false; result.resize(string_size / sizeof(wchar_t)); ::ImmGetCompositionString(imm_context, type, const_cast<wchar_t*>(result.data()), string_size); return true; } void IMM32Manager::GetResult(HWND window_handle, LPARAM lparam, wstring& result) { HIMC imm_context = ::ImmGetContext(window_handle); if (imm_context) { GetString(imm_context, lparam, GCS_RESULTSTR, result); ::ImmReleaseContext(window_handle, imm_context); } } void IMM32Manager::GetComposition(HWND window_handle, LPARAM lparam, wstring& result) { HIMC imm_context = ::ImmGetContext(window_handle); if (imm_context) { if (GetString(imm_context, lparam, GCS_COMPSTR, result)) { is_composing_ = true; } ::ImmReleaseContext(window_handle, imm_context); } } void IMM32Manager::DisableIME(HWND window_handle) { CleanupComposition(window_handle); ::ImmAssociateContextEx(window_handle, NULL, 0); } void IMM32Manager::CancelIME(HWND window_handle) { if (is_composing_) { HIMC imm_context = ::ImmGetContext(window_handle); if (imm_context) { ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_CANCEL, 0); ::ImmReleaseContext(window_handle, imm_context); } ResetComposition(window_handle); } } void IMM32Manager::EnableIME(HWND window_handle) { ::ImmAssociateContextEx(window_handle, NULL, IACE_DEFAULT); } void IMM32Manager::UpdateCaretRect(HWND window_handle, Rect caret_rect) { caret_rect_ = caret_rect; // Move the IME windows. HIMC imm_context = ::ImmGetContext(window_handle); if (imm_context) { MoveImeWindow(window_handle, imm_context); ::ImmReleaseContext(window_handle, imm_context); } } void IMM32Manager::SetUseCompositionWindow(bool use_composition_window) { use_composition_window_ = use_composition_window; } bool IMM32Manager::IsInputLanguageCJK() const { LANGID lang = PRIMARYLANGID(input_language_id_); return lang == LANG_CHINESE || lang == LANG_JAPANESE || lang == LANG_KOREAN; } bool IMM32Manager::IsImm32ImeActive() { return ::ImmGetIMEFileName(::GetKeyboardLayout(0), nullptr, 0) > 0; }
25.912921
105
0.738211
hchenqi
6bbbf22c8780a6b1604e2f72380c1489c216407f
1,182
cpp
C++
algospot/PALINDROMIZE.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
7
2019-08-05T14:49:41.000Z
2022-03-13T07:10:51.000Z
algospot/PALINDROMIZE.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
algospot/PALINDROMIZE.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
4
2021-01-04T03:45:22.000Z
2021-10-06T06:11:00.000Z
/** * problem: https://algospot.com/judge/problem/read/PALINDROMIZE * time complexity: O(N + M) * data structure: string * algorithm : KMP */ #include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> getPi(string s) { int size = s.size(); vector<int> pi(size, 0); for (int i = 1; i < size; i++) { int j = pi[i - 1]; while (j > 0 && s[j] != s[i]) j = pi[j - 1]; if (s[i] == s[j]) pi[i] = ++j; } return pi; } int getSameInd(string s, string p) { int N = s.size(); vector<int> pi = getPi(p); int ans = 0; int start = 0; int sameInd = 0; while (start < N) { if (sameInd < p.size() && s[start + sameInd] == p[sameInd]) { sameInd++; if (sameInd + start == N) return sameInd; } else { if (sameInd == 0) { start++; continue; } int lastSameInd = pi[sameInd - 1]; start += sameInd - lastSameInd; sameInd = lastSameInd; } } } int solve(string s) { string p = s; reverse(p.begin(), p.end()); int N = s.size(); int ans = getSameInd(s, p); return N + (N - ans); } int main() { int C; cin >> C; string s; while (C--) { cin >> s; cout << solve(s) << endl; } return 0; }
16.885714
63
0.560068
Jeongseo21
6bbfaf18cd50d27c0e14dec503a315c9aa3532e6
7,982
hpp
C++
include/unitig_distance/SingleGenomeGraphDistances.hpp
jurikuronen/unitig_distance
d32af0684d699e49698df39c79cf0cb9efbaca0f
[ "MIT" ]
null
null
null
include/unitig_distance/SingleGenomeGraphDistances.hpp
jurikuronen/unitig_distance
d32af0684d699e49698df39c79cf0cb9efbaca0f
[ "MIT" ]
null
null
null
include/unitig_distance/SingleGenomeGraphDistances.hpp
jurikuronen/unitig_distance
d32af0684d699e49698df39c79cf0cb9efbaca0f
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <map> #include <set> #include <thread> #include <unordered_map> #include <utility> #include <vector> #include "Graph.hpp" #include "SearchJobs.hpp" #include "Timer.hpp" #include "types.hpp" using distance_tuple_t = std::tuple<real_t, real_t, real_t, int_t>; class SingleGenomeGraphDistances { public: SingleGenomeGraphDistances( const SingleGenomeGraph& graph, int_t n_threads, int_t block_size, real_t max_distance = REAL_T_MAX) : m_graph(graph), m_n_threads(n_threads), m_block_size(block_size), m_max_distance(max_distance) { } // Calculate distances for single genome graphs. std::vector<std::unordered_map<int_t, distance_tuple_t>> solve(const SearchJobs& search_jobs) { std::vector<std::unordered_map<int_t, distance_tuple_t>> sgg_batch_distances(m_n_threads); auto calculate_distance_block = [this, &search_jobs, &sgg_batch_distances](std::size_t thr, std::size_t block_start, std::size_t block_end) { const auto& graph = m_graph; for (std::size_t i = block_start + thr; i < block_end; i += m_n_threads) { const auto& job = search_jobs[i]; auto v = job.v(); if (!graph.contains_original(v)) continue; // First calculate distances between path start/end nodes. auto sources = get_sgg_sources(v); auto targets = get_sgg_targets(job.ws()); auto target_dist = graph.distance(sources, targets, m_max_distance); std::vector<real_t> job_dist(job.ws().size(), m_max_distance); std::map<int_t, real_t> dist; for (std::size_t j = 0; j < targets.size(); ++j) dist[targets[j]] = target_dist[j]; // Now fix distances for (v, w) that were in paths. process_job_distances(job_dist, graph.left_node(v), job.ws(), dist); process_job_distances(job_dist, graph.right_node(v), job.ws(), dist); add_job_distances_to_sgg_distances(sgg_batch_distances[thr], job, job_dist); } }; std::vector<std::thread> threads(m_n_threads); for (std::size_t block_start = 0; block_start < search_jobs.size(); block_start += m_block_size) { std::size_t block_end = std::min(block_start + m_block_size, search_jobs.size()); for (std::size_t thr = 0; thr < (std::size_t) m_n_threads; ++thr) threads[thr] = std::thread(calculate_distance_block, thr, block_start, block_end); for (auto& thr : threads) thr.join(); } return sgg_batch_distances; } private: const SingleGenomeGraph& m_graph; int_t m_n_threads; int_t m_block_size; real_t m_max_distance; // Update source distance if source exists, otherwise add new source. void update_source(std::vector<std::pair<int_t, real_t>>& sources, int_t mapped_idx, real_t distance) { auto it = sources.begin(); while (it != sources.end() && it->first != (int_t) mapped_idx) ++it; if (it == sources.end()) sources.emplace_back(mapped_idx, distance); else it->second = std::min(it->second, distance); } // Add both sides of v as sources. std::vector<std::pair<int_t, real_t>> get_sgg_sources(int_t v) { std::vector<std::pair<int_t, real_t>> sources; for (int_t v_original_idx = m_graph.left_node(v); v_original_idx <= m_graph.right_node(v); ++v_original_idx) { auto v_mapped_idx = m_graph.mapped_idx(v_original_idx); // Add v normally if it's not on a path, otherwise add both path end points. if (m_graph.is_on_path(v_original_idx)) { auto v_path_idx = m_graph.path_idx(v_original_idx); int_t path_endpoint; real_t distance; // Add path start node. std::tie(path_endpoint, distance) = m_graph.distance_to_start(v_path_idx, v_mapped_idx); update_source(sources, path_endpoint, distance); // Add path end node. std::tie(path_endpoint, distance) = m_graph.distance_to_end(v_path_idx, v_mapped_idx); update_source(sources, path_endpoint, distance); } else { update_source(sources, v_mapped_idx, 0.0); } } return sources; } // Add both sides of each w as targets. std::vector<int_t> get_sgg_targets(const std::vector<int_t>& ws) { std::set<int_t> target_set; for (auto w : ws) { if (!m_graph.contains_original(w)) continue; for (int_t w_original_idx = m_graph.left_node(w); w_original_idx <= m_graph.right_node(w); ++w_original_idx) { if (m_graph.is_on_path(w_original_idx)) { auto w_path_idx = m_graph.path_idx(w_original_idx); target_set.insert(m_graph.start_node(w_path_idx)); target_set.insert(m_graph.end_node(w_path_idx)); } else { target_set.insert(m_graph.mapped_idx(w_original_idx)); } } } std::vector<int_t> targets; for (auto t : target_set) targets.push_back(t); return targets; } // Correct (v, w) distance if w were on a path. real_t get_correct_distance(int_t v_path_idx, int_t v_mapped_idx, int_t w_original_idx, std::map<int_t, real_t>& dist) { auto w_path_idx = m_graph.path_idx(w_original_idx); auto w_mapped_idx = m_graph.mapped_idx(w_original_idx); if (w_path_idx == INT_T_MAX) return dist[w_mapped_idx]; // w not on path, distance from sources is correct already. // Get distance if v and w are on the same path, this distance could be shorter. real_t distance = v_path_idx == w_path_idx ? m_graph.distance_in_path(v_path_idx, v_mapped_idx, w_mapped_idx) : REAL_T_MAX; // w on path, add distances of (w, path_endpoint). int_t w_path_endpoint; real_t w_path_distance; std::tie(w_path_endpoint, w_path_distance) = m_graph.distance_to_start(w_path_idx, w_mapped_idx); distance = std::min(distance, dist[w_path_endpoint] + w_path_distance); std::tie(w_path_endpoint, w_path_distance) = m_graph.distance_to_end(w_path_idx, w_mapped_idx); distance = std::min(distance, dist[w_path_endpoint] + w_path_distance); return distance; } // Fix distances for (v, w) that were in paths. void process_job_distances(std::vector<real_t>& job_dist, int_t v_original_idx, const std::vector<int_t>& ws, std::map<int_t, real_t>& dist) { auto v_path_idx = m_graph.path_idx(v_original_idx); auto v_mapped_idx = m_graph.mapped_idx(v_original_idx); for (std::size_t w_idx = 0; w_idx < ws.size(); ++w_idx) { auto w = ws[w_idx]; if (!m_graph.contains_original(w)) continue; auto distance = get_correct_distance(v_path_idx, v_mapped_idx, m_graph.left_node(w), dist); distance = std::min(distance, get_correct_distance(v_path_idx, v_mapped_idx, m_graph.right_node(w), dist)); job_dist[w_idx] = std::min(job_dist[w_idx], distance); } } void add_job_distances_to_sgg_distances(std::unordered_map<int_t, distance_tuple_t>& sgg_distances, const SearchJob& job, const std::vector<real_t>& job_dist) { for (std::size_t w_idx = 0; w_idx < job_dist.size(); ++w_idx) { auto distance = job_dist[w_idx]; if (distance >= m_max_distance) continue; auto original_idx = job.original_index(w_idx); if (sgg_distances.find(original_idx) == sgg_distances.end()) sgg_distances.emplace(original_idx, std::make_tuple(REAL_T_MAX, 0.0, 0.0, 0)); auto& distances = sgg_distances[original_idx]; distances += std::make_tuple(distance, distance, distance, 1); } } };
47.796407
164
0.638436
jurikuronen
6bc00f04ffb14089e11392466b46d313d66f95a8
1,609
cpp
C++
src/GameObject.cpp
Delpod/This-Hero-That-Villain
0dc504acf3ac5d0cb39cd14c47f2e08880a6f169
[ "Zlib", "Apache-2.0" ]
null
null
null
src/GameObject.cpp
Delpod/This-Hero-That-Villain
0dc504acf3ac5d0cb39cd14c47f2e08880a6f169
[ "Zlib", "Apache-2.0" ]
null
null
null
src/GameObject.cpp
Delpod/This-Hero-That-Villain
0dc504acf3ac5d0cb39cd14c47f2e08880a6f169
[ "Zlib", "Apache-2.0" ]
null
null
null
#include "GameObject.h" #include "Game.h" GameObject::GameObject(sf::Texture &texture, sf::IntRect coords, bool collidable, sf::IntRect collisionRect, float scale, bool loopTexture) { load(texture, coords, collidable, collisionRect, scale, loopTexture); } void GameObject::load(sf::Texture &texture, sf::IntRect coords, bool collidable, sf::IntRect collisionRect, float scale, bool loopTexture) { m_scale = scale; m_bCollidable = collidable; m_pBody = nullptr; if(collisionRect == sf::IntRect(0, 0, 0, 0)) collisionRect = sf::IntRect(0, 0, coords.width, coords.height); m_sprite.setTexture(texture); texture.setRepeated(loopTexture); m_sprite.setTextureRect(sf::IntRect(0, 0, coords.width, coords.height)); if(m_bCollidable) m_sprite.setOrigin((float)collisionRect.left + (float)collisionRect.width / 2.0f, (float)collisionRect.top + (float)collisionRect.height / 2.0f); else m_sprite.setOrigin((float)coords.width / 2.0f, (float)coords.height / 2.0f); m_sprite.setScale(scale, scale); m_sprite.setPosition(coords.left, coords.top); if(m_bCollidable) { m_bodyDef.position = b2Vec2((float)coords.left / scale / 10.0f, (float)coords.top / scale / 10.0f); m_pBody = Game::Inst()->getWorld()->CreateBody(&m_bodyDef); b2PolygonShape box; box.SetAsBox((float)collisionRect.width / 20.0f, (float)collisionRect.height / 20.0f); m_pBody->CreateFixture(&box, 0.0f); } } void GameObject::draw() { Game::Inst()->getWindow()->draw(m_sprite); } GameObject::~GameObject() { if(m_bCollidable) { Game::Inst()->getWorld()->DestroyBody(m_pBody); m_pBody = nullptr; } }
32.836735
147
0.720945
Delpod
6bc0a61e9819b029a89053351a8108e4a04a981d
3,681
cpp
C++
dpcpp/solver/multigrid_kernels.dp.cpp
kliegeois/ginkgo
4defcc07f77828393cc5b4a735a00e50da2cbab0
[ "BSD-3-Clause" ]
null
null
null
dpcpp/solver/multigrid_kernels.dp.cpp
kliegeois/ginkgo
4defcc07f77828393cc5b4a735a00e50da2cbab0
[ "BSD-3-Clause" ]
null
null
null
dpcpp/solver/multigrid_kernels.dp.cpp
kliegeois/ginkgo
4defcc07f77828393cc5b4a735a00e50da2cbab0
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2022, the Ginkgo authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the 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. ******************************<GINKGO LICENSE>*******************************/ #include "core/solver/multigrid_kernels.hpp" #include <ginkgo/core/base/array.hpp> #include <ginkgo/core/base/exception_helpers.hpp> #include <ginkgo/core/base/math.hpp> #include <ginkgo/core/base/types.hpp> #include "core/components/fill_array_kernels.hpp" namespace gko { namespace kernels { namespace dpcpp { /** * @brief The MULTIGRID solver namespace. * * @ingroup multigrid */ namespace multigrid { template <typename ValueType> void kcycle_step_1(std::shared_ptr<const DefaultExecutor> exec, const matrix::Dense<ValueType>* alpha, const matrix::Dense<ValueType>* rho, const matrix::Dense<ValueType>* v, matrix::Dense<ValueType>* g, matrix::Dense<ValueType>* d, matrix::Dense<ValueType>* e) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_MULTIGRID_KCYCLE_STEP_1_KERNEL); template <typename ValueType> void kcycle_step_2(std::shared_ptr<const DefaultExecutor> exec, const matrix::Dense<ValueType>* alpha, const matrix::Dense<ValueType>* rho, const matrix::Dense<ValueType>* gamma, const matrix::Dense<ValueType>* beta, const matrix::Dense<ValueType>* zeta, const matrix::Dense<ValueType>* d, matrix::Dense<ValueType>* e) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_MULTIGRID_KCYCLE_STEP_2_KERNEL); template <typename ValueType> void kcycle_check_stop(std::shared_ptr<const DefaultExecutor> exec, const matrix::Dense<ValueType>* old_norm, const matrix::Dense<ValueType>* new_norm, const ValueType rel_tol, bool& is_stop) GKO_NOT_IMPLEMENTED; GKO_INSTANTIATE_FOR_EACH_NON_COMPLEX_VALUE_TYPE( GKO_DECLARE_MULTIGRID_KCYCLE_CHECK_STOP_KERNEL); } // namespace multigrid } // namespace dpcpp } // namespace kernels } // namespace gko
38.747368
80
0.707416
kliegeois
6bc16ddb7a1cb31d1f0341bef91db5c930e1083b
3,579
cc
C++
celeriteflow/ops/celerite_mat_mul_op.cc
mirca/celeriteflow
ed09a178df05856097552a9081b6eb6d537216ee
[ "MIT" ]
null
null
null
celeriteflow/ops/celerite_mat_mul_op.cc
mirca/celeriteflow
ed09a178df05856097552a9081b6eb6d537216ee
[ "MIT" ]
null
null
null
celeriteflow/ops/celerite_mat_mul_op.cc
mirca/celeriteflow
ed09a178df05856097552a9081b6eb6d537216ee
[ "MIT" ]
null
null
null
#include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/platform/default/logging.h" #include "tensorflow/core/framework/shape_inference.h" #include <Eigen/Core> #include "celerite.h" using namespace tensorflow; REGISTER_OP("CeleriteMatMul") .Attr("T: {float, double}") .Input("a: T") .Input("u: T") .Input("v: T") .Input("p: T") .Input("z: T") .Output("y: T") .SetShapeFn([](shape_inference::InferenceContext* c) { shape_inference::DimensionHandle J; shape_inference::ShapeHandle u, p, a, v, z; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &a)); TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &u)); TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &v)); TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &p)); TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &z)); TF_RETURN_IF_ERROR(c->Merge(u, v, &u)); c->set_output(0, c->input(4)); return Status::OK(); }); template <typename T> class CeleriteMatMulOp : public OpKernel { public: explicit CeleriteMatMulOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> c_vector_t; typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> c_matrix_t; typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> matrix_t; const Tensor& a_t = context->input(0); const Tensor& U_t = context->input(1); const Tensor& V_t = context->input(2); const Tensor& P_t = context->input(3); const Tensor& Z_t = context->input(4); OP_REQUIRES(context, (U_t.dims() == 2), errors::InvalidArgument("U should have the shape (N, J)")); int64 N = U_t.dim_size(0), J = U_t.dim_size(1); OP_REQUIRES(context, ((P_t.dims() == 2) && (P_t.dim_size(0) == N-1) && (P_t.dim_size(1) == J)), errors::InvalidArgument("P should have the shape (N-1, J)")); OP_REQUIRES(context, ((a_t.dims() == 1) && (a_t.dim_size(0) == N)), errors::InvalidArgument("a should have the shape (N)")); OP_REQUIRES(context, ((V_t.dims() == 2) && (V_t.dim_size(0) == N) && (V_t.dim_size(1) == J)), errors::InvalidArgument("V should have the shape (N, J)")); OP_REQUIRES(context, ((Z_t.dims() == 2) && (Z_t.dim_size(0) == N)), errors::InvalidArgument("Z should have the shape (N, Nrhs)")); int64 Nrhs = Z_t.dim_size(1); const auto a = c_vector_t(a_t.template flat<T>().data(), N); const auto U = c_matrix_t(U_t.template flat<T>().data(), N, J); const auto V = c_matrix_t(V_t.template flat<T>().data(), N, J); const auto P = c_matrix_t(P_t.template flat<T>().data(), N-1, J); const auto Z = c_matrix_t(Z_t.template flat<T>().data(), N, Nrhs); // Create the outputs Tensor* Y_t = NULL; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({N, Nrhs}), &Y_t)); auto Y = matrix_t(Y_t->template flat<T>().data(), N, Nrhs); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> F_plus(J, Nrhs), F_minus(J, Nrhs); celerite::matmul(a, U, V, P, Z, Y, F_plus, F_minus); } }; #define REGISTER_KERNEL(type) \ REGISTER_KERNEL_BUILDER( \ Name("CeleriteMatMul").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ CeleriteMatMulOp<type>) REGISTER_KERNEL(float); REGISTER_KERNEL(double); #undef REGISTER_KERNEL
37.28125
107
0.633417
mirca
6bc5c00e3ba8df358133ec650a78a55ef630622f
1,803
cpp
C++
data/randgen.cpp
dhruvarya/simple-ra
2cb3930d5fe75a96c335a55d788d697016d282d4
[ "MIT" ]
null
null
null
data/randgen.cpp
dhruvarya/simple-ra
2cb3930d5fe75a96c335a55d788d697016d282d4
[ "MIT" ]
null
null
null
data/randgen.cpp
dhruvarya/simple-ra
2cb3930d5fe75a96c335a55d788d697016d282d4
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef long double ld; //**************************************************** #define lp(var,start,end) for (ll var = start; var <end ; ++var) #define rlp(var,start,end) for(ll var = start; var>=end ; var--) #define pb push_back #define mp make_pair #define pf push_front #define ff first #define ss second #define vll vector<ll> #define pll pair<ll,ll> #define vpll vector<pll> #define all(X) X.begin(),X.end() #define endl "\n" //comment it for interactive questions #define trace1(a) cerr << #a << ": " << a << endl; #define trace2(a,b) cerr << #a << ": " << a << " " << #b << ": " << b << endl; #define trace3(a,b,c) cerr << #a << ": " << a << " " << #b << ": " << b << " " << #c << ": " << c << endl; #define trace4(a,b,c,d) cerr << #a << ": " << a << " " << #b << ": " << b << " " << #c << ": " << c << #d << ": " << d << endl; #define FAST_IO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) //******************************************************* //Some Functions const ll MOD = (ll)1e9+7; //change it for other mods ll powmod(ll a,ll b) { ll res = 1; while(b > 0) { if(b & 1) res = (res * a) % MOD; a = (a*a)%MOD; b = b >> 1; } return res % MOD; } void solve(ll testnum) { srand(time(0)); ll n, m; cin >> n >> m; for(int i = 0; i < n; i++) { for(int j = 0; j < m - 1; j++) { cout << rand()%500 << ","; } cout << rand()%500 << "\n"; } } int main() { FAST_IO; #ifdef STIO freopen("input.txt" , "r", stdin); freopen("output.txt" , "w", stdout); #endif ll t = 1; // cin >> t; for (ll i = 1; i <= t; i++) { // cout << "Case #" << i << ": "; solve(i); } }
26.910448
127
0.455352
dhruvarya
6bc8e91192d4e68013effdd9d29d505977138ac2
3,386
cpp
C++
EngineTests/Base/Window/Test.Window.cpp
azhirnov/GraphicsGenFramework-modular
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
12
2017-12-23T14:24:57.000Z
2020-10-02T19:52:12.000Z
EngineTests/Base/Window/Test.Window.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
EngineTests/Base/Window/Test.Window.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #include "../Common.h" class WindowApp final : public StaticRefCountedObject { // variables private: TModID::type windowID = Uninitialized; CreateInfo::Window wndDescr; ModulePtr taskMngr; String name; bool looping = true; // methods public: WindowApp (const ModulePtr &taskMngr, TModID::type wndID, const CreateInfo::Window &descr) : windowID( wndID ), wndDescr( descr ), taskMngr( taskMngr ) {} void Initialize (GlobalSystemsRef gs) { auto thread = gs->parallelThread; if ( not gs->taskModule ) thread->AddModule( TaskModuleModuleID, CreateInfo::TaskModule{ taskMngr } ); thread->AddModule( windowID, wndDescr ); thread->AddModule( InputThreadModuleID, CreateInfo::InputThread() ); auto window = thread->GetModuleByID( windowID ); auto input = thread->GetModuleByID( InputThreadModuleID ); //window->AddModule( WinKeyInputModuleID, CreateInfo::RawInputHandler() ); //window->AddModule( WinMouseInputModuleID, CreateInfo::RawInputHandler() ); window->Subscribe( this, &WindowApp::_OnWindowClosed ); window->Subscribe( this, &WindowApp::_OnWindowUpdate ); input->Subscribe( this, &WindowApp::_OnKey ); } void Quit () { } // only for main thread bool Update () { GetMainSystemInstance()->Send( ModuleMsg::Update{} ); return looping; } private: bool _OnWindowClosed (const OSMsg::WindowAfterDestroy &) { looping = false; return true; } bool _OnWindowUpdate (const ModuleMsg::Update &) { return true; } bool _OnKey (const ModuleMsg::InputKey &) { return true; } }; SHARED_POINTER( WindowApp ); extern void Test_Window () { using EFlags = CreateInfo::Window::EWindowFlags; auto ms = GetMainSystemInstance(); auto mf = ms->GlobalSystems()->modulesFactory; Platforms::RegisterPlatforms(); CHECK( OS::FileSystem::FindAndSetCurrentDir( "EngineTests/Base" ) ); ModulePtr platform; CHECK( mf->Create( 0, ms->GlobalSystems(), CreateInfo::Platform{}, OUT platform ) ); ms->Send( ModuleMsg::AttachModule{ platform }); OSMsg::GetOSModules req_ids; CHECK( platform->Send( req_ids ) ); ms->AddModule( InputManagerModuleID, CreateInfo::InputManager() ); ms->AddModule( DataProviderManagerModuleID, CreateInfo::DataProviderManager() ); { auto thread = ms->GlobalSystems()->parallelThread; auto task_mngr = ms->GetModuleByID( TaskManagerModuleID ); ModulePtr thread2; WindowAppPtr app1 = New< WindowApp >( task_mngr, req_ids.result->window, CreateInfo::Window{ "window-0", EFlags::Resizable, uint2(800,600), int2(800,600) } ); WindowAppPtr app2 = New< WindowApp >( task_mngr, req_ids.result->window, CreateInfo::Window{ "window-1", EFlags::bits(), uint2(800,600), int2(-900,400) } ); app1->Initialize( thread->GlobalSystems() ); // create second thread with window CHECK( ms->GlobalSystems()->modulesFactory->Create( ParallelThreadModuleID, ms->GlobalSystems(), CreateInfo::Thread{ "SecondThread", null, LAMBDA( app2 ) (GlobalSystemsRef gs) { app2->Initialize( gs ); } }, OUT (ModulePtr &)(thread2) ) ); thread2 = null; // finish initialization ModuleUtils::Initialize({ ms }); // main loop for (; app1->Update();) {} app1->Quit(); } ms->Send( ModuleMsg::Delete{} ); WARNING( "Window test succeeded!" ); }
24.897059
160
0.692853
azhirnov
6bcc99682f3eef97bab2cabf0616f7dc2d12b849
1,542
hpp
C++
libs/Delphi/src/Syntax/DelphiExceptionHandlerBlockSyntax.hpp
henrikfroehling/interlinck
d9d947b890d9286c6596c687fcfcf016ef820d6b
[ "MIT" ]
null
null
null
libs/Delphi/src/Syntax/DelphiExceptionHandlerBlockSyntax.hpp
henrikfroehling/interlinck
d9d947b890d9286c6596c687fcfcf016ef820d6b
[ "MIT" ]
19
2021-12-01T20:37:23.000Z
2022-02-14T21:05:43.000Z
libs/Delphi/src/Syntax/DelphiExceptionHandlerBlockSyntax.hpp
henrikfroehling/interlinck
d9d947b890d9286c6596c687fcfcf016ef820d6b
[ "MIT" ]
null
null
null
#ifndef ARGOS_DELPHI_SYNTAX_DELPHIEXCEPTIONHANDLERBLOCKSYNTAX_H #define ARGOS_DELPHI_SYNTAX_DELPHIEXCEPTIONHANDLERBLOCKSYNTAX_H #include <string> #include <argos-Core/Syntax/SyntaxVariant.hpp> #include <argos-Core/Types.hpp> #include "Syntax/DelphiExceptionBlockSyntax.hpp" namespace argos::Delphi::Syntax { class DelphiStatementListSyntax; class DelphiTryElseClauseSyntax; class DelphiExceptionHandlerBlockSyntax : public DelphiExceptionBlockSyntax { public: DelphiExceptionHandlerBlockSyntax() = delete; explicit DelphiExceptionHandlerBlockSyntax(const DelphiStatementListSyntax* exceptionHandlers, const DelphiTryElseClauseSyntax* elseClause = nullptr) noexcept; ~DelphiExceptionHandlerBlockSyntax() noexcept override = default; const DelphiStatementListSyntax* exceptionHandlers() const noexcept; const DelphiTryElseClauseSyntax* elseClause() const noexcept; argos_size childCount() const noexcept final; Core::Syntax::SyntaxVariant child(argos_size index) const noexcept final; Core::Syntax::SyntaxVariant first() const noexcept final; Core::Syntax::SyntaxVariant last() const noexcept final; std::string typeName() const noexcept override; bool isExceptionHandlerList() const noexcept final; private: const DelphiStatementListSyntax* _exceptionHandlers; const DelphiTryElseClauseSyntax* _elseClause; // optional }; } // end namespace argos::Delphi::Syntax #endif // ARGOS_DELPHI_SYNTAX_DELPHIEXCEPTIONHANDLERBLOCKSYNTAX_H
32.808511
111
0.789235
henrikfroehling
6bcfd640a0e1ecec09b4cded265770aa49c19d34
1,787
cpp
C++
src/gr_common/arduino/lib/SD/iSdio.cpp
takjn/LiMoRo
df4d2cfc63d8d253e7cdbcf3169668313a77fda9
[ "MIT" ]
null
null
null
src/gr_common/arduino/lib/SD/iSdio.cpp
takjn/LiMoRo
df4d2cfc63d8d253e7cdbcf3169668313a77fda9
[ "MIT" ]
null
null
null
src/gr_common/arduino/lib/SD/iSdio.cpp
takjn/LiMoRo
df4d2cfc63d8d253e7cdbcf3169668313a77fda9
[ "MIT" ]
null
null
null
/* Arduino Sdio Library * Copyright (C) 2014 by Munehiro Doi, Fixstars Corporation * All rights reserved. * Released under the BSD 2-Clause license. * http://flashair-developers.com/documents/license.html */ #include "iSdio.h" //------------------------------------------------------------------------------ /** specific version for string. it adds padding bytes after text data. */ template <> uint8_t* put_T(uint8_t* p, const char* value) { while (*value != 0) { *p++ = *((uint8_t*)value++); } return p; } template <> uint8_t* put_T_arg(uint8_t* p, const char* value) { uint8_t* orig = p; p += sizeof(uint32_t); // skip length area. p = put_T(p, value); // data uint32_t len = p - orig - sizeof(uint32_t); put_T(orig, len); // write length. for (int i = 0; i < ((4 - (len & 3)) & 3); ++i) { // padding *p++ = 0; } return p; } uint8_t* put_command_header(uint8_t* p, uint8_t num_commands, uint32_t command_bytes) { p = put_u8(p, 0x01); // Write Data ID p = put_u8(p, num_commands); // Number of commands. p = put_u16(p, 0); // reserved. p = put_u32(p, command_bytes); // size of command write data. p = put_u32(p, 0); // reserved. return p; } uint8_t* put_command_info_header(uint8_t* p, uint16_t command_id, uint32_t sequence_id, uint16_t num_args) { p = put_u16(p, 0); // reserved. p = put_u16(p, command_id); // iSDIO command id. p = put_u32(p, sequence_id); // iSDIO command sequence id. p = put_u16(p, num_args); // Number of Arguments. p = put_u16(p, 0); // Reserved. return p; }
34.365385
81
0.531617
takjn
6bd6aaca58fb1c46b211a7d95f3d98388988dc91
3,400
cpp
C++
src/main.cpp
mdarocha/software-renderer
e90a24c67dc7a0b71b69b019f1a71e17d6b9f7c1
[ "MIT" ]
null
null
null
src/main.cpp
mdarocha/software-renderer
e90a24c67dc7a0b71b69b019f1a71e17d6b9f7c1
[ "MIT" ]
null
null
null
src/main.cpp
mdarocha/software-renderer
e90a24c67dc7a0b71b69b019f1a71e17d6b9f7c1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cmath> #include "ppm_image.h" #include "realtime_target.h" #include "obj_model.h" #include "drawing_utils.h" #include "camera.h" #include "matrix.h" #include "shader/gouraud.h" #include "fallback_image.h" void render_to_image(OBJModel &model, std::string &output, int width, int height); void render_realtime(OBJModel &model, int width, int height); int main(int argc, char *argv[]) { std::string model_filename; std::string output_filename("o.ppm"); int width, height; width = height = 800; bool realtime = false; switch(argc) { default: std::cout << "Usage: softrender model.obj [output.ppm] [--realtime] [width] [height]" << std::endl; return 1; case 5: std::sscanf(argv[4], "%d", &height); case 4: std::sscanf(argv[3], "%d", &width); case 3: if(std::string(argv[2]) == "--realtime") realtime = true; else output_filename = argv[2]; case 2: model_filename = argv[1]; } OBJModel model(model_filename); model.normalize_model_scale(); if(realtime) render_realtime(model, width, height); else render_to_image(model, output_filename, width, height); return 0; } void render_to_image(OBJModel &model, std::string &output, int width, int height) { PPMImage image(width, height); Camera camera(width, height, Vector3f(0,1,0.1), 1.0f); camera.lookat(Vector3f(0,0,0)); auto diffuse = PPMImage::load(fallback_ppm, fallback_ppm_len); GouraudShader shader(camera.get_model(), camera.get_viewport(), camera.get_projection(), Vector3f(1,1,1), diffuse); std::cout << "Rendering image with resolution " << width << "x" << height << std::endl; DrawingUtils::rasterize(model, image, camera, shader); image.write_to_file(output); } Vector3f spherical(double hor, double ver, double dist) { Vector3f pos; pos.x = dist * sin(hor) * sin(ver); pos.y = dist * cos(ver); pos.z = dist * cos(hor) * sin(ver); return pos; } void render_realtime(OBJModel &model, int width, int height) { double hor = 45, ver = 45, dist = 1; constexpr double move = 0.05; Camera camera(width, height, spherical(hor, ver, dist), 1.0f); camera.lookat(Vector3f(0,0,0)); auto diffuse = PPMImage::load(fallback_ppm, fallback_ppm_len); GouraudShader shader(camera.get_model(), camera.get_viewport(), camera.get_projection(), Vector3f(1,1,1), diffuse); auto handler = [&](SDL_Event *event) { if(event->type == SDL_KEYDOWN) { switch(event->key.keysym.sym) { case SDLK_LEFT: hor -= move; break; case SDLK_RIGHT: hor += move; break; case SDLK_UP: ver += move; break; case SDLK_DOWN: ver -= move; break; } camera.position = spherical(hor, ver, dist); camera.lookat(Vector3f(0,0,0)); shader.update_model(camera.get_model()); } }; RealtimeTarget image_target(width, height, handler); image_target.start(); while(image_target.is_running()) { DrawingUtils::rasterize(model, image_target, camera, shader); image_target.loop(); } }
29.310345
119
0.600882
mdarocha
6be3ce9424a513ae5e03d0253dbff274f99bcc12
4,016
hpp
C++
include/roq/support_type.hpp
roq-trading/tradingapi
13dbcec50eab53627bc29112ffe3cdd81acadda3
[ "MIT" ]
1
2018-03-27T15:43:57.000Z
2018-03-27T15:43:57.000Z
include/roq/support_type.hpp
roq-trading/roq
13dbcec50eab53627bc29112ffe3cdd81acadda3
[ "MIT" ]
null
null
null
include/roq/support_type.hpp
roq-trading/roq
13dbcec50eab53627bc29112ffe3cdd81acadda3
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2022, Hans Erik Thrane */ /* !!! THIS FILE HAS BEEN AUTO-GENERATED !!! */ #pragma once #include <fmt/format.h> #include <cassert> namespace roq { //! Enumeration of support types enum class SupportType : uint64_t { UNDEFINED = 0x0, REFERENCE_DATA = 0x1, //!< Reference data MARKET_STATUS = 0x2, //!< Market status TOP_OF_BOOK = 0x4, //!< Top of book MARKET_BY_PRICE = 0x8, //!< Market by price MARKET_BY_ORDER = 0x10, //!< Market by order TRADE_SUMMARY = 0x20, //!< Trade summary STATISTICS = 0x40, //!< Statistics CREATE_ORDER = 0x10000, //!< Create order MODIFY_ORDER = 0x20000, //!< Modify order CANCEL_ORDER = 0x40000, //!< Cancel order ORDER_ACK = 0x80000, //!< Order ack ORDER = 0x100000, //!< Order ORDER_STATE = 0x800000, //!< Order TRADE = 0x200000, //!< Trade POSITION = 0x400000, //!< Position FUNDS = 0x10000000, //!< Funds }; } // namespace roq template <> struct fmt::formatter<roq::SupportType> { template <typename Context> constexpr auto parse(Context &context) { return std::begin(context); } template <typename Context> auto format(roq::SupportType const &value, Context &context) { using namespace std::literals; #if __cplusplus >= 202002L std::string_view name{[&]() { switch (value) { using enum roq::SupportType; case UNDEFINED: return "UNDEFINED"sv; case REFERENCE_DATA: return "REFERENCE_DATA"sv; case MARKET_STATUS: return "MARKET_STATUS"sv; case TOP_OF_BOOK: return "TOP_OF_BOOK"sv; case MARKET_BY_PRICE: return "MARKET_BY_PRICE"sv; case MARKET_BY_ORDER: return "MARKET_BY_ORDER"sv; case TRADE_SUMMARY: return "TRADE_SUMMARY"sv; case STATISTICS: return "STATISTICS"sv; case CREATE_ORDER: return "CREATE_ORDER"sv; case MODIFY_ORDER: return "MODIFY_ORDER"sv; case CANCEL_ORDER: return "CANCEL_ORDER"sv; case ORDER_ACK: return "ORDER_ACK"sv; case ORDER: return "ORDER"sv; case ORDER_STATE: return "ORDER_STATE"sv; case TRADE: return "TRADE"sv; case POSITION: return "POSITION"sv; case FUNDS: return "FUNDS"sv; default: assert(false); } return "<UNKNOWN>"sv; }()}; #else std::string_view name{[&]() { switch (value) { case roq::SupportType::UNDEFINED: return "UNDEFINED"sv; case roq::SupportType::REFERENCE_DATA: return "REFERENCE_DATA"sv; case roq::SupportType::MARKET_STATUS: return "MARKET_STATUS"sv; case roq::SupportType::TOP_OF_BOOK: return "TOP_OF_BOOK"sv; case roq::SupportType::MARKET_BY_PRICE: return "MARKET_BY_PRICE"sv; case roq::SupportType::MARKET_BY_ORDER: return "MARKET_BY_ORDER"sv; case roq::SupportType::TRADE_SUMMARY: return "TRADE_SUMMARY"sv; case roq::SupportType::STATISTICS: return "STATISTICS"sv; case roq::SupportType::CREATE_ORDER: return "CREATE_ORDER"sv; case roq::SupportType::MODIFY_ORDER: return "MODIFY_ORDER"sv; case roq::SupportType::CANCEL_ORDER: return "CANCEL_ORDER"sv; case roq::SupportType::ORDER_ACK: return "ORDER_ACK"sv; case roq::SupportType::ORDER: return "ORDER"sv; case roq::SupportType::ORDER_STATE: return "ORDER_STATE"sv; case roq::SupportType::TRADE: return "TRADE"sv; case roq::SupportType::POSITION: return "POSITION"sv; case roq::SupportType::FUNDS: return "FUNDS"sv; default: assert(false); } return "<UNKNOWN>"sv; }()}; #endif return fmt::format_to(context.out(), "{}"sv, name); } };
29.970149
64
0.594871
roq-trading
6be618e507d7d6293f6b5c02daf1e5fc86a6f92d
601
cpp
C++
ecs/src/v2/model/NovaDeleteKeypairResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
ecs/src/v2/model/NovaDeleteKeypairResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
ecs/src/v2/model/NovaDeleteKeypairResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/ecs/v2/model/NovaDeleteKeypairResponse.h" namespace HuaweiCloud { namespace Sdk { namespace Ecs { namespace V2 { namespace Model { NovaDeleteKeypairResponse::NovaDeleteKeypairResponse() { } NovaDeleteKeypairResponse::~NovaDeleteKeypairResponse() = default; void NovaDeleteKeypairResponse::validate() { } web::json::value NovaDeleteKeypairResponse::toJson() const { web::json::value val = web::json::value::object(); return val; } bool NovaDeleteKeypairResponse::fromJson(const web::json::value& val) { bool ok = true; return ok; } } } } } }
12.787234
69
0.718802
yangzhaofeng
6be9dd97171a2aa486601635c8e8dda5b9ed1925
1,776
hpp
C++
components/esm/loadarmo.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/esm/loadarmo.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/esm/loadarmo.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef OPENMW_ESM_ARMO_H #define OPENMW_ESM_ARMO_H #include <vector> #include <string> namespace ESM { class ESMReader; class ESMWriter; enum PartReferenceType { PRT_Head = 0, PRT_Hair = 1, PRT_Neck = 2, PRT_Cuirass = 3, PRT_Groin = 4, PRT_Skirt = 5, PRT_RHand = 6, PRT_LHand = 7, PRT_RWrist = 8, PRT_LWrist = 9, PRT_Shield = 10, PRT_RForearm = 11, PRT_LForearm = 12, PRT_RUpperarm = 13, PRT_LUpperarm = 14, PRT_RFoot = 15, PRT_LFoot = 16, PRT_RAnkle = 17, PRT_LAnkle = 18, PRT_RKnee = 19, PRT_LKnee = 20, PRT_RLeg = 21, PRT_LLeg = 22, PRT_RPauldron = 23, PRT_LPauldron = 24, PRT_Weapon = 25, PRT_Tail = 26, PRT_Count = 27 }; // Reference to body parts struct PartReference { unsigned char mPart; // possible values [0, 26] std::string mMale, mFemale; }; // A list of references to body parts struct PartReferenceList { std::vector<PartReference> mParts; void load(ESMReader &esm); void save(ESMWriter &esm) const; }; struct Armor { static unsigned int sRecordId; enum Type { Helmet = 0, Cuirass = 1, LPauldron = 2, RPauldron = 3, Greaves = 4, Boots = 5, LGauntlet = 6, RGauntlet = 7, Shield = 8, LBracer = 9, RBracer = 10 }; struct AODTstruct { int mType; float mWeight; int mValue, mHealth, mEnchant, mArmor; }; AODTstruct mData; PartReferenceList mParts; std::string mId, mName, mModel, mIcon, mScript, mEnchant; void load(ESMReader &esm); void save(ESMWriter &esm) const; void blank(); ///< Set record to default state (does not touch the ID). }; } #endif
17.584158
61
0.595158
Bodillium
6beb0d9741fc27424f21b76c2d366be331157040
4,325
cpp
C++
src/adera/ShipResources.cpp
haennes/osp-magnum
242958d71ab34a79250b9f426d97ab4dfdfc775f
[ "MIT" ]
null
null
null
src/adera/ShipResources.cpp
haennes/osp-magnum
242958d71ab34a79250b9f426d97ab4dfdfc775f
[ "MIT" ]
null
null
null
src/adera/ShipResources.cpp
haennes/osp-magnum
242958d71ab34a79250b9f426d97ab4dfdfc775f
[ "MIT" ]
null
null
null
/** * Open Space Program * Copyright © 2019-2021 Open Space Program Project * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "ShipResources.h" #include "osp/Active/ActiveScene.h" #include "osp/Resource/PrototypePart.h" using namespace osp; using namespace osp::active; using namespace adera::active::machines; /* ShipResourceType */ double ShipResourceType::resource_volume(uint64_t quantity) const { double units = static_cast<double>(quantity) / std::pow(2.0, m_quanta); return units * m_volume; } double ShipResourceType::resource_mass(uint64_t quantity) const { double units = static_cast<double>(quantity) / std::pow(2.0, m_quanta); return units * m_mass; } uint64_t ShipResourceType::resource_capacity(double volume) const { double units = volume / m_volume; double quantaPerUnit = std::pow(2.0, m_quanta); return static_cast<uint64_t>(units * quantaPerUnit); } uint64_t ShipResourceType::resource_quantity(double mass) const { double units = mass / m_mass; double quantaPerUnit = std::pow(2.0, m_quanta); return static_cast<uint64_t>(units * quantaPerUnit); } /* MachineContainer */ void MachineContainer::propagate_output(WireOutput* output) { } WireInput* MachineContainer::request_input(WireInPort port) { return nullptr; } WireOutput* MachineContainer::request_output(WireOutPort port) { return nullptr; } std::vector<WireInput*> MachineContainer::existing_inputs() { return m_inputs; } std::vector<WireOutput*> MachineContainer::existing_outputs() { return m_outputs; } uint64_t MachineContainer::request_contents(uint64_t quantity) { if (quantity > m_contents.m_quantity) { return std::exchange(m_contents.m_quantity, 0); } m_contents.m_quantity -= quantity; return quantity; } /* SysMachineContainer */ SysMachineContainer::SysMachineContainer(ActiveScene& rScene) : SysMachine<SysMachineContainer, MachineContainer>(rScene) , m_updateContainers(rScene.get_update_order(), "mach_container", "", "mach_rocket", [this](ActiveScene& rScene) { this->update_containers(rScene); }) { } void SysMachineContainer::update_containers(ActiveScene& rScene) { auto view = rScene.get_registry().view<MachineContainer>(); for (ActiveEnt ent : view) { auto& container = view.get<MachineContainer>(ent); // Do something useful here... or not } } Machine& SysMachineContainer::instantiate(ActiveEnt ent, PrototypeMachine config, BlueprintMachine settings) { float capacity = std::get<double>(config.m_config["capacity"]); ShipResource resource{}; if (auto resItr = settings.m_config.find("resourcename"); resItr != settings.m_config.end()) { std::string_view resName = std::get<std::string>(resItr->second); Path resPath = decompose_path(resName); Package& pkg = m_scene.get_application().debug_find_package(resPath.prefix); resource.m_type = pkg.get<ShipResourceType>(resPath.identifier); resource.m_quantity = resource.m_type->resource_capacity(capacity); } return m_scene.reg_emplace<MachineContainer>(ent, capacity, resource); } Machine& SysMachineContainer::get(ActiveEnt ent) { return m_scene.reg_get<MachineContainer>(ent); }
30.244755
88
0.734335
haennes
6bebe0f00f8e89c11eca50d3c436266227bfdbfc
676
cc
C++
test/stack.cc
leeliliang/cocoyaxi
0117286d13fd9c97053b665016c7bf2190bab441
[ "MIT" ]
210
2022-01-05T06:40:17.000Z
2022-03-31T18:44:44.000Z
test/stack.cc
leeliliang/cocoyaxi
0117286d13fd9c97053b665016c7bf2190bab441
[ "MIT" ]
13
2022-01-07T03:21:44.000Z
2022-03-03T00:46:39.000Z
test/stack.cc
leeliliang/cocoyaxi
0117286d13fd9c97053b665016c7bf2190bab441
[ "MIT" ]
28
2022-01-11T08:13:42.000Z
2022-03-30T02:55:03.000Z
#include "co/log.h" #include "co/thread.h" #include "co/time.h" #include "co/co.h" DEF_bool(t, false, "if true, run test in thread"); DEF_bool(m, false, "if true, run test in main thread"); DEF_bool(check, false, "if true, run CHECK test"); void a() { char* p = 0; if (FLG_check) { CHECK_EQ(1 + 1, 3); } else { *p = 'c'; } } void b() { a(); } void c() { b(); } int main(int argc, char** argv) { flag::init(argc, argv); if (FLG_m) { c(); } else if (FLG_t) { Thread(c).detach(); } else { go(c); } while (1) sleep::sec(1024); return 0; }
16.095238
56
0.470414
leeliliang
6bee2e0544918db2846467ec14f201e34f03de9c
426
cpp
C++
test/nim_test/nim_play.cpp
mascaretti/mcts
08916e494a3689622b809452fd47f1c841d3a40b
[ "MIT" ]
3
2019-04-02T23:21:49.000Z
2021-06-02T12:33:23.000Z
test/nim_test/nim_play.cpp
mascaretti/mcts
08916e494a3689622b809452fd47f1c841d3a40b
[ "MIT" ]
1
2018-11-12T17:57:28.000Z
2018-11-12T17:57:28.000Z
test/nim_test/nim_play.cpp
mascaretti/mcts
08916e494a3689622b809452fd47f1c841d3a40b
[ "MIT" ]
1
2020-09-28T02:46:11.000Z
2020-09-28T02:46:11.000Z
#include "nim.hpp" int main(int argc, char const *argv[]) { game::Nim::NimGame<> test_game; do { std::cout << "Play a move" << '\n'; std::cout << "Insert pile: "; unsigned int pile; std::cin >> pile; std::cout << "Insert number: "; unsigned int number; std::cin >> number; test_game.apply_action({pile, number}); test_game.print(); } while (test_game.get_terminal_status() == false); return 0; }
16.384615
52
0.615023
mascaretti
6bee5b993ad513d43fac9422d37243e40873330f
1,808
hpp
C++
ql/pricingengines/genericmodelengine.hpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/pricingengines/genericmodelengine.hpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/pricingengines/genericmodelengine.hpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2002, 2003 Ferdinando Ametrano Copyright (C) 2009 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file genericmodelengine.hpp \brief Generic option engine based on a model */ #ifndef quantlib_generic_model_engine_hpp #define quantlib_generic_model_engine_hpp #include <ql/pricingengine.hpp> #include <ql/handle.hpp> namespace QuantLib { //! Base class for some pricing engine on a particular model /*! Derived engines only need to implement the <tt>calculate()</tt> method */ template<class ModelType, class ArgumentsType, class ResultsType> class GenericModelEngine : public GenericEngine<ArgumentsType, ResultsType> { public: GenericModelEngine(const Handle<ModelType>& model = Handle<ModelType>()) : model_(model) { this->registerWith(model_); } GenericModelEngine(const std::shared_ptr<ModelType>& model) : model_(model) { this->registerWith(model_); } protected: Handle<ModelType> model_; }; } #endif
31.172414
80
0.708518
haozhangphd
6beeb011c6f53dcdffa35eb4f6d7c6c9c7def6f6
2,904
cpp
C++
src/lldb/Bindings/SBInstructionListBinding.cpp
atouchet/lldb-sys.rs
22e212a86b0d4fc085e2ecdc34a286cf4c91a1a5
[ "Apache-2.0", "MIT" ]
13
2016-06-29T17:14:24.000Z
2022-01-14T15:50:05.000Z
src/lldb/Bindings/SBInstructionListBinding.cpp
atouchet/lldb-sys.rs
22e212a86b0d4fc085e2ecdc34a286cf4c91a1a5
[ "Apache-2.0", "MIT" ]
13
2016-07-16T16:33:42.000Z
2021-11-14T14:56:38.000Z
src/lldb/Bindings/SBInstructionListBinding.cpp
atouchet/lldb-sys.rs
22e212a86b0d4fc085e2ecdc34a286cf4c91a1a5
[ "Apache-2.0", "MIT" ]
7
2016-09-01T16:17:34.000Z
2021-10-04T22:42:16.000Z
//===-- SBInstructionListBinding.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/API/LLDB.h" #include "lldb/Bindings/LLDBBinding.h" using namespace lldb; #ifdef __cplusplus extern "C" { #endif SBInstructionListRef CreateSBInstructionList() { return reinterpret_cast<SBInstructionListRef>(new SBInstructionList()); } SBInstructionListRef CloneSBInstructionList(SBInstructionListRef instance) { return reinterpret_cast<SBInstructionListRef>( new SBInstructionList(*reinterpret_cast<SBInstructionList *>(instance))); } void DisposeSBInstructionList(SBInstructionListRef instance) { delete reinterpret_cast<SBInstructionList *>(instance); } bool SBInstructionListIsValid(SBInstructionListRef instance) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); return unwrapped->IsValid(); } size_t SBInstructionListGetSize(SBInstructionListRef instance) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); return unwrapped->GetSize(); } SBInstructionRef SBInstructionListGetInstructionAtIndex(SBInstructionListRef instance, uint32_t idx) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); return reinterpret_cast<SBInstructionRef>( new SBInstruction(unwrapped->GetInstructionAtIndex(idx))); } void SBInstructionListClear(SBInstructionListRef instance) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); unwrapped->Clear(); } void SBInstructionListAppendInstruction(SBInstructionListRef instance, SBInstructionRef inst) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); unwrapped->AppendInstruction(*reinterpret_cast<SBInstruction *>(inst)); } void SBInstructionListPrint(SBInstructionListRef instance, FILE *out) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); unwrapped->Print(out); } bool SBInstructionListGetDescription(SBInstructionListRef instance, SBStreamRef description) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); return unwrapped->GetDescription(*reinterpret_cast<SBStream *>(description)); } bool SBInstructionListDumpEmulationForAllInstructions( SBInstructionListRef instance, const char *triple) { SBInstructionList *unwrapped = reinterpret_cast<SBInstructionList *>(instance); return unwrapped->DumpEmulationForAllInstructions(triple); } #ifdef __cplusplus } #endif
32.629213
80
0.724862
atouchet
6bf0581d46f5d769bb2cf7de7750bf4f74df9604
1,244
cpp
C++
dynamic/wrappers/pde/AbstractBoundaryCondition3.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/pde/AbstractBoundaryCondition3.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/pde/AbstractBoundaryCondition3.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <set> #include <vector> #include <string> #include <map> #include "SmartPointers.hpp" #include "UblasIncludes.hpp" #include "AbstractBoundaryCondition.hpp" #include "AbstractBoundaryCondition3.cppwg.hpp" namespace py = pybind11; typedef AbstractBoundaryCondition<3 > AbstractBoundaryCondition3; PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>); class AbstractBoundaryCondition3_Overloads : public AbstractBoundaryCondition3{ public: using AbstractBoundaryCondition3::AbstractBoundaryCondition; double GetValue(::ChastePoint<3> const & rX) const override { PYBIND11_OVERLOAD_PURE( double, AbstractBoundaryCondition3, GetValue, rX); } }; void register_AbstractBoundaryCondition3_class(py::module &m){ py::class_<AbstractBoundaryCondition3 , AbstractBoundaryCondition3_Overloads , boost::shared_ptr<AbstractBoundaryCondition3 > >(m, "AbstractBoundaryCondition3") .def(py::init< >()) .def( "GetValue", (double(AbstractBoundaryCondition3::*)(::ChastePoint<3> const &) const ) &AbstractBoundaryCondition3::GetValue, " " , py::arg("rX") ) ; }
32.736842
162
0.712219
jmsgrogan
6bf20831af4f882e80ac2510f7903d945d044aa9
5,288
hpp
C++
c++/cpp2py/pyref.hpp
TRIQS/cpp2y
a54c23606abe4e19da8f370b9c3faed0fb3ec5ca
[ "Apache-2.0" ]
19
2017-10-16T13:54:56.000Z
2022-01-29T10:34:07.000Z
c++/cpp2py/pyref.hpp
TRIQS/cpp2y
a54c23606abe4e19da8f370b9c3faed0fb3ec5ca
[ "Apache-2.0" ]
38
2017-11-08T10:26:16.000Z
2022-03-04T19:09:47.000Z
c++/cpp2py/pyref.hpp
TRIQS/cpp2y
a54c23606abe4e19da8f370b9c3faed0fb3ec5ca
[ "Apache-2.0" ]
12
2017-11-09T12:28:35.000Z
2022-03-04T18:54:48.000Z
// Copyright (c) 2017-2018 Commissariat à l'énergie atomique et aux énergies alternatives (CEA) // Copyright (c) 2017-2018 Centre national de la recherche scientifique (CNRS) // Copyright (c) 2018-2020 Simons 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Authors: Olivier Parcollet, Nils Wentzell #pragma once #include <Python.h> #include "./get_module.hpp" #include <string> using namespace std::string_literals; namespace cpp2py { /** * A class to own a reference PyObject *, with proper reference counting. */ class pyref { PyObject *ob = NULL; public: /// Null pyref() = default; /// Takes ownership of the reference pyref(PyObject *new_ref) : ob(new_ref) {} /// Release the ref ~pyref() { Py_XDECREF(ob); } /// Copy constructor pyref(pyref const &p) { ob = p.ob; Py_XINCREF(ob); } /// Move constructor pyref(pyref &&p) { ob = p.ob; p.ob = NULL; } /// No copy assign. pyref &operator=(pyref const & p) { Py_XDECREF(ob); ob = p.ob; Py_XINCREF(ob); return *this; } /// Move assign pyref &operator=(pyref &&p) { Py_XDECREF(ob); ob = p.ob; p.ob = NULL; return *this; } /// Returns a borrowed reference operator PyObject *() const { return ob; } /// Returns a new reference to the object PyObject *new_ref() const { Py_XINCREF(ob); return ob; } /// ref counting int refcnt() const { return (ob != NULL ? Py_REFCNT(ob) : -100); } /// True iif the object is not NULL explicit operator bool() const { return (ob != NULL); } /// Is object NULL bool is_null() const { return ob == NULL; } /// Is it Py_None bool is_None() const { return ob == Py_None; } /// Returns the attribute of this. Null if error, or if is_null. pyref attr(const char *s) { return (ob ? PyObject_GetAttrString(ob, s) : NULL); } // NULL : pass the error in chain call x.attr().attr().... /// Call pyref operator()(PyObject *a1) { return (ob ? PyObject_CallFunctionObjArgs(ob, a1, NULL) : NULL); } // NULL : pass the error in chain call x.attr().attr().... /// Call pyref operator()(PyObject *a1, PyObject *a2) { return (ob ? PyObject_CallFunctionObjArgs(ob, a1, a2, NULL) : NULL); } // NULL : pass the error in chain call x.attr().attr().... /// Import the module and returns a pyref to it static pyref module(std::string const &module_name) { // Maybe the module was already imported? PyObject *mod = PyImport_GetModule(PyUnicode_FromString(module_name.c_str())); // If not, import normally if (mod == NULL) mod = PyImport_ImportModule(module_name.c_str()); // Did we succeed? if (mod == NULL) throw std::runtime_error(std::string{"Failed to import module "} + module_name); return mod; } /// Make a Python string from the C++ string static pyref string(std::string const &s) { return PyUnicode_FromString(s.c_str()); } /// Make a Python Tuple from the C++ objects template <typename... T> static pyref make_tuple(T const &... x) { return PyTuple_Pack(sizeof...(T), static_cast<PyObject *>(x)...); } /// gets a reference to the class cls_name in module_name static pyref get_class(const char *module_name, const char *cls_name, bool raise_exception) { pyref cls = pyref::module(module_name).attr(cls_name); if (cls.is_null() && raise_exception) { std::string s = std::string{"Cannot find the class "} + module_name + "." + cls_name; PyErr_SetString(PyExc_TypeError, s.c_str()); } return cls; } /// checks that ob is of type module_name.cls_name static bool check_is_instance(PyObject *ob, PyObject *cls, bool raise_exception) { int i = PyObject_IsInstance(ob, cls); if (i == -1) { // an error has occurred i = 0; if (!raise_exception) PyErr_Clear(); } if ((i == 0) && (raise_exception)) { pyref cls_name_obj = PyObject_GetAttrString(cls, "__name__"); std::string err = "Type error: Python object does not match expected type "; err.append(PyUnicode_AsUTF8(cls_name_obj)); PyErr_SetString(PyExc_TypeError, err.c_str()); } return i; } }; static_assert(sizeof(pyref) == sizeof(PyObject *), "pyref must contain only a PyObject *"); // FIXME : put static or the other functions inline ? /// Returns a pyref from a borrowed ref inline pyref borrowed(PyObject *ob) { Py_XINCREF(ob); return {ob}; } inline std::string to_string(PyObject * ob){ pyref py_str = PyObject_Str(ob); return PyUnicode_AsUTF8(py_str); } } // namespace cpp2py
31.289941
144
0.634266
TRIQS
d404a11a464fcc6b6f19f0e860e17eb714e8cd89
580
cpp
C++
code/313.nthSuperUglyNumber.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
1
2020-10-04T13:39:34.000Z
2020-10-04T13:39:34.000Z
code/313.nthSuperUglyNumber.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
code/313.nthSuperUglyNumber.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
class Solution { public: int nthSuperUglyNumber(int n, vector<int>& primes) { typedef pair<int, int> PII; priority_queue<PII, vector<PII>, greater<PII>> heap; for (int x : primes) heap.push({x, 0}); vector<int> q(n); q[0] = 1; for (int i = 1; i < n;) { auto t = heap.top(); heap.pop(); if (t.first != q[i - 1]) q[i++] = t.first; int idx = t.second; int p = t.first / q[idx]; heap.push({p * q[idx + 1], idx + 1}); } return q[n - 1]; } };
30.526316
60
0.444828
T1mzhou
d40836612262ec02331c7db24a6bc7cc357501af
849
cpp
C++
ACM-ICPC/9506.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/9506.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/9506.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> using namespace std; int main() { while (true) { int n, sum = 0; vector<int> v; scanf("%d", &n); if (n == -1) { return 0; } for (int i = 1; i < n; i++) { if (n % i == 0) { v.push_back(i); } } for (int i = 0; i < v.size(); i++) { sum += v[i]; } printf("%d", n); if (sum == n) { printf(" ="); for (int i = 0; i < v.size(); i++) { if (i == v.size() - 1) { printf(" %d\n", v[i]); } else { printf(" %d +", v[i]); } } } else { printf(" is NOT perfect.\n"); } } }
21.225
49
0.273263
KimBoWoon
d40b6372a4aeb000492fc57093b04f3bff51ddc3
15,032
cpp
C++
view/src/context_menu/trade_config_context_menu_handler.cpp
Rapprise/b2s-trader
ac8a3c2221d15c4df8df63842d20dafd6801e535
[ "BSD-2-Clause" ]
21
2020-06-07T20:34:47.000Z
2021-08-10T20:19:59.000Z
view/src/context_menu/trade_config_context_menu_handler.cpp
Rapprise/b2s-trader
ac8a3c2221d15c4df8df63842d20dafd6801e535
[ "BSD-2-Clause" ]
null
null
null
view/src/context_menu/trade_config_context_menu_handler.cpp
Rapprise/b2s-trader
ac8a3c2221d15c4df8df63842d20dafd6801e535
[ "BSD-2-Clause" ]
4
2020-07-13T10:19:44.000Z
2022-03-11T12:15:43.000Z
/* * Copyright (c) 2020, Rapprise. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "include/context_menu/trade_config_context_menu_handler.h" #include <QtWidgets/QMenu> #include <QtWidgets/QMessageBox> #include "include/dialogs/create_trade_configuration_dialog.h" #include "include/gui_nodes/gui_tree_node.h" #include "view/include/gui_processor.h" namespace auto_trader { namespace view { TradeConfigContextMenuHandler::TradeConfigContextMenuHandler(QTreeView &tradeConfigView, common::AppListener &appListener, GuiProcessor &guiListener) : tradeConfigView_(tradeConfigView), appListener_(appListener), guiListener_(guiListener) { const QIcon editIcon = QIcon(":/b2s_images/edit_currect_config.png"); const QIcon closeIcon = QIcon(":/b2s_images/close_config.png"); const QIcon removeIcon = QIcon(":/b2s_images/remove_config.png"); const QIcon expandIcon = QIcon(":/b2s_images/expand.png"); const QIcon collapseIcon = QIcon(":/b2s_images/collapse.png"); const QIcon activeConfigIcon = QIcon(":/b2s_images/set_active_config.png"); editAction_ = new QAction(editIcon, tr("&Edit"), this); closeAction_ = new QAction(closeIcon, tr("&Close"), this); removeAction_ = new QAction(removeIcon, tr("Remove"), this); expandAction_ = new QAction(expandIcon, tr("&Expand All"), this); collapseAction_ = new QAction(collapseIcon, tr("&Collapse All"), this); activeConfig_ = new QAction(activeConfigIcon, tr("&Set Active"), this); connect(editAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::editConfiguration); connect(closeAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::closeConfiguration); connect(removeAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::removeConfiguration); connect(activeConfig_, &QAction::triggered, this, &TradeConfigContextMenuHandler::setActiveConfig); connect(expandAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::expandAll); connect(collapseAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::collapseAll); connect(&tradeConfigView_, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(onCustomConfigurationContextMenu(const QPoint &))); } void TradeConfigContextMenuHandler::editConfiguration() { if (currentNode_) { currentNode_ = getTradeConfigNode(currentNode_); const std::string &configName = currentNode_->data(0).toString().toStdString(); const auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder(); const auto &tradeConfiguration = tradeConfigsHolder.getTradeConfiguration(configName); if (tradeConfiguration.isActive() && tradeConfiguration.isRunning()) { QMessageBox::information(&guiListener_, tr("Trade configuration cannot be edited."), tr("The trade configuration \'") + QString::fromStdString(configName) + tr("\' is running and cannot be edited.")); currentNode_ = nullptr; return; } auto uiLock = guiListener_.acquireUILock(); if (!uiLock.try_lock() || guiListener_.isUIUpdating()) { QMessageBox::information( &guiListener_, tr("Trade configuration cannot be edited."), tr("The UI is updating right now. Please wait until process is finished.")); currentNode_ = nullptr; return; } auto tradeConfigurationDialog = new dialogs::CreateTradeConfigurationDialog( appListener_, guiListener_, dialogs::CreateTradeConfigurationDialog::DialogType::EDIT, &tradeConfigView_); tradeConfigurationDialog->setAttribute(Qt::WA_DeleteOnClose); tradeConfigurationDialog->setupDefaultParameters(tradeConfiguration); tradeConfigurationDialog->exec(); } currentNode_ = nullptr; } void TradeConfigContextMenuHandler::closeConfiguration() { if (!currentNode_) { return; } const std::string &configName = currentNode_->data(0).toString().toStdString(); auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder(); auto &tradeConfiguration = tradeConfigsHolder.getTradeConfiguration(configName); auto uiLock = guiListener_.acquireUILock(); bool uiUpdating = (!uiLock.try_lock() || guiListener_.isUIUpdating()); if (uiUpdating && tradeConfiguration.isActive()) { QMessageBox::information( &guiListener_, tr("Trade configuration is active and UI is updating."), tr("The UI is updating right now. Please wait until process is finished.")); return; } if (tradeConfiguration.isActive()) { if (tradeConfiguration.isRunning()) { QMessageBox::information( &guiListener_, tr("Trading configuration cannot be closed."), tr("The current trading configuration is running. Please stop trading before removing.")); return; } QMessageBox::StandardButton reply; if (tradeConfigsHolder.getConfigurationsCount() > 1) { reply = QMessageBox::question( &guiListener_, "Close current active configuration", "Are you sure you want to remove current configuration? Since it is active, new active " "configuration will be chosen from remaining ones.", QMessageBox::Yes | QMessageBox::No); } else { reply = QMessageBox::question(&guiListener_, "Close current active configuration", "Are you sure you want to close current active configuration?", QMessageBox::Yes | QMessageBox::No); } if (reply != QMessageBox::Yes) { return; } } else { const std::string message = "Are you sure you want to close configuration " + configName + "?"; QMessageBox::StandardButton reply = QMessageBox::question(&guiListener_, "Close configuration", tr(message.c_str()), QMessageBox::Yes | QMessageBox::No); if (reply != QMessageBox::Yes) { return; } } bool isClosedConfigActive = tradeConfiguration.isActive(); tradeConfigsHolder.removeTradeConfig(configName); if (tradeConfigsHolder.isEmpty()) { guiListener_.resetChart(); guiListener_.disableChart(); guiListener_.refreshConfigurationStatusBar(); appListener_.refreshStockExchangeView(); } else if (isClosedConfigActive) { tradeConfigsHolder.setDefaultActiveConfiguration(); guiListener_.refreshConfigurationStatusBar(); guiListener_.refreshChartViewStart(); appListener_.refreshStockExchangeView(); } appListener_.saveTradeConfigurationsFiles(); guiListener_.refreshTradeConfigurationView(); currentNode_ = nullptr; } void TradeConfigContextMenuHandler::removeConfiguration() { if (!currentNode_) { return; } const std::string &configName = currentNode_->data(0).toString().toStdString(); auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder(); auto &tradeConfiguration = tradeConfigsHolder.getTradeConfiguration(configName); auto uiLock = guiListener_.acquireUILock(); bool uiUpdating = (!uiLock.try_lock() || guiListener_.isUIUpdating()); if (uiUpdating && tradeConfiguration.isActive()) { QMessageBox::information( &guiListener_, tr("Trade configuration is active and UI is updating"), tr("The UI is updating right now. Please wait until process is finished.")); return; } if (tradeConfiguration.isActive()) { if (tradeConfiguration.isRunning()) { QMessageBox::information( &guiListener_, tr("Trading configuration cannot be closed."), tr("The current trading configuration is running. Please stop trading before removing.")); return; } QMessageBox::StandardButton reply; if (tradeConfigsHolder.getConfigurationsCount() > 1) { reply = QMessageBox::question( &guiListener_, "Remove current active configuration", "Are you sure you want to remove current configuration? Since it is active, new active " "configuration will be chosen from remaining ones.", QMessageBox::Yes | QMessageBox::No); } else { reply = QMessageBox::question(&guiListener_, "Remove current active configuration", "Are you sure you want to remove current active configuration?", QMessageBox::Yes | QMessageBox::No); } if (reply != QMessageBox::Yes) { return; } } else { const std::string message = "Are you sure you want to remove configuration " + configName + "?"; QMessageBox::StandardButton reply = QMessageBox::question(&guiListener_, "Remove configuration", tr(message.c_str()), QMessageBox::Yes | QMessageBox::No); if (reply != QMessageBox::Yes) { return; } } bool isRemovedConfigActive = tradeConfiguration.isActive(); tradeConfigsHolder.removeTradeConfig(configName); auto applicationDir = QApplication::applicationDirPath(); const std::string &tradeConfigPath = applicationDir.toStdString() + std::string("/") + "config" + std::string("/") + configName + ".json"; remove(tradeConfigPath.c_str()); if (tradeConfigsHolder.isEmpty()) { guiListener_.refreshConfigurationStatusBar(); guiListener_.resetChart(); guiListener_.disableChart(); appListener_.refreshStockExchangeView(); } else if (isRemovedConfigActive) { tradeConfigsHolder.setDefaultActiveConfiguration(); guiListener_.refreshConfigurationStatusBar(); guiListener_.refreshChartViewStart(); appListener_.refreshStockExchangeView(); } appListener_.saveTradeConfigurationsFiles(); guiListener_.refreshTradeConfigurationView(); currentNode_ = nullptr; } void TradeConfigContextMenuHandler::expandAll() { tradeConfigView_.expandAll(); currentNode_ = nullptr; } void TradeConfigContextMenuHandler::collapseAll() { tradeConfigView_.collapseAll(); currentNode_ = nullptr; } void TradeConfigContextMenuHandler::onCustomConfigurationContextMenu(const QPoint &point) { QModelIndex indexPoint = tradeConfigView_.indexAt(point); auto guiTreeNode = static_cast<GuiTreeNode *>(indexPoint.internalPointer()); contextMenu_ = new QMenu(); if (guiTreeNode) { if (guiTreeNode->getNodeType() == GuiTreeNodeType::TRADE_CONFIG_NODE) { contextMenu_->addAction(editAction_); contextMenu_->addAction(removeAction_); contextMenu_->addAction(closeAction_); contextMenu_->addSeparator(); contextMenu_->addAction(activeConfig_); activeConfig_->setEnabled(true); const std::string &configName = guiTreeNode->data(0).toString().toStdString(); auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder(); auto &tradeConfiguration = tradeConfigsHolder.takeTradeConfiguration(configName); if (tradeConfiguration.isActive()) { activeConfig_->setDisabled(true); } } else if (guiTreeNode->getNodeType() == GuiTreeNodeType::CONFIG_NODE) { contextMenu_->addAction(editAction_); } contextMenu_->addSeparator(); currentNode_ = guiTreeNode; } contextMenu_->addAction(expandAction_); contextMenu_->addAction(collapseAction_); contextMenu_->exec(tradeConfigView_.viewport()->mapToGlobal(point)); } void TradeConfigContextMenuHandler::setActiveConfig() { if (!currentNode_) return; QMessageBox::StandardButton button = QMessageBox::question(&guiListener_, "Set Active configuration", "Are you sure you want to set new active configuration?"); if (button != QMessageBox::StandardButton::Yes) return; auto uiLock = guiListener_.acquireUILock(); if (!uiLock.try_lock() || guiListener_.isUIUpdating()) { QMessageBox::information( &guiListener_, tr("Trade configuration cannot be edited."), tr("The UI is updating right now. Please wait until process is finished.")); currentNode_ = nullptr; return; } const std::string &configName = currentNode_->data(0).toString().toStdString(); auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder(); auto &tradeConfiguration = tradeConfigsHolder.takeTradeConfiguration(configName); auto &currentTradeConfiguration = tradeConfigsHolder.takeCurrentTradeConfiguration(); if (currentTradeConfiguration.isRunning()) { QMessageBox::information(&guiListener_, tr("Current configuration is running."), tr("The current trading configuration is running. Please stop trading " "before changing active configuration.")); return; } if (currentTradeConfiguration.getName() != tradeConfiguration.getName()) { currentTradeConfiguration.setActive(false); tradeConfiguration.setActive(true); appListener_.saveTradeConfigurationsFiles(); appListener_.refreshApiKeys(tradeConfiguration); guiListener_.refreshTradeConfigurationView(); guiListener_.refreshStockExchangeChartInterval(); guiListener_.refreshStockExchangeChartMarket(); guiListener_.refreshConfigurationStatusBar(); guiListener_.refreshChartViewStart(); appListener_.refreshStockExchangeView(); } currentNode_ = nullptr; } GuiTreeNode *TradeConfigContextMenuHandler::getTradeConfigNode(GuiTreeNode *currentNode) { if (!currentNode) return nullptr; GuiTreeNode *toReturnNode = currentNode; while (currentNode->getNodeType() != GuiTreeNodeType::TRADE_CONFIG_NODE) { currentNode = currentNode->getParentNode(); } toReturnNode = currentNode; return toReturnNode; } } // namespace view } // namespace auto_trader
40.408602
100
0.711016
Rapprise
d40f21d6775a42dae7fcaac790f813dc79748474
15,036
cpp
C++
src/Front/GeneralTextEdit/gentextedit.cpp
Igisid/Breeks-desktop
0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6
[ "Apache-2.0" ]
10
2020-12-20T15:32:20.000Z
2021-07-12T18:09:57.000Z
src/Front/GeneralTextEdit/gentextedit.cpp
Igisid/Breeks-desktop
0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6
[ "Apache-2.0" ]
2
2022-01-04T12:51:00.000Z
2022-01-04T14:40:19.000Z
src/Front/GeneralTextEdit/gentextedit.cpp
Igisid/Breeks-desktop
0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6
[ "Apache-2.0" ]
3
2020-12-22T02:50:11.000Z
2021-02-24T01:58:11.000Z
#include "gentextedit.h" #include <iostream> #include <QDebug> #include <QApplication> #include <QClipboard> #include <algorithm> #include <QPainter> #include <QScrollBar> RussianDictionary *GenTextEdit::rusDic_ = new RussianDictionary(); GenTextEdit::GenTextEdit(QWidget *parent) : QTextEdit(parent), timer_(new QTimer()), requestTimer_(new QTimer()) { undoRedoBuffer_ = new UndoRedoText; //rusDic_ = new RussianDictionary; timer_->setSingleShot(true); connect(timer_, SIGNAL(timeout()), this, SLOT(checkSpelling())); requestTimer_->setSingleShot(true); connect(requestTimer_, SIGNAL(timeout()), SLOT(sendServerRequest())); this->setTextColor(QColor(0, 0, 0)); nCurrentFile_ = 1; charCounter_ = 0; detailsSetCharStyle(globCh); this->verticalScrollBar()->setStyleSheet( "QScrollBar:vertical {" "background-color: #FFFFF0;" "width: 9px;" "margin: 0px 0px 0px 0px;}" "QScrollBar::handle:vartical {" "border-radius: 4px;" "background: #e3e3df;" "min-height: 0px;}" "QScrollBar::handle:vertical:hover {" "border-radius: 4px;" "background: #c7c7bf;" "min-height: 0px;}" "QScrollBar::add-line:vertical {" "border: none;" "background: none;}" "QScrollBar::sub-line:vertical {" "border: none;" "background: none;}" ); this->setContextMenuPolicy(Qt::ContextMenuPolicy::NoContextMenu); } //We want to create our Text editor with special functions and hot-keys //that is why we override keyPressEvent() void GenTextEdit::keyPressEvent(QKeyEvent *event) { int iKey = event->key(); Qt::KeyboardModifiers kmModifiers = event->modifiers(); int cursorPos = this->textCursor().position(); QTextCharFormat charFormat; //to back Normal font style of text after Bold, Italic, Underline... words charFormat.setFontWeight(QFont::Normal); charStyle_t ch; detailsSetCharStyle(ch); commandInfo_t command; //all comands which insert smth if (charCounter_ <= MAX_COUNT_CHAR_) { requestTimer_->start(500); //letters if (kmModifiers == 0 || kmModifiers == Qt::ShiftModifier) { if ((iKey >= Qt::Key_A && iKey <= Qt::Key_Z) || (QKeySequence(iKey).toString() >= "А" && (QKeySequence(iKey).toString() <= "Я")) || QKeySequence(iKey).toString() == "Ё") { detailsCheckSelectionAndItem(cursorPos); detailsSetCharStyleByNeighbours(ch, cursorPos); charStyleVector_.insert(cursorPos, 1, ch); QTextEdit::keyPressEvent(event); //we can't identify CapsLock that's why use base method detailsSetCharStyleByIndex(ch, cursorPos + 1); ++charCounter_; //Add coommand to UndoRefoBuffer const QString text = (kmModifiers != 0 ? QKeySequence(iKey).toString() : QKeySequence(iKey).toString().toLower()); setCommandInfo(command, command::insertStr, cursorPos, text); undoRedoBuffer_->pushUndoCommand(command); timer_->stop(); timer_->start(1000); return; } } //numbers if (kmModifiers == 0) { if (iKey >= Qt::Key_0 && iKey <= Qt::Key_9) { detailsCheckSelectionAndItem(cursorPos); this->insertPlainText(QKeySequence(iKey).toString()); detailsSetCharStyleByNeighbours(ch, cursorPos); charStyleVector_.insert(cursorPos, 1, ch); detailsSetCharStyleByIndex(ch, cursorPos + 1); ++charCounter_; //Add coommand to UndoRefoBuffer setCommandInfo(command, command::insertStr, cursorPos, QKeySequence(iKey).toString()); undoRedoBuffer_->pushUndoCommand(command); timer_->stop(); timer_->start(1000); return; } } //special chars if (kmModifiers == 0 || kmModifiers == Qt::ShiftModifier) { for (QChar i : AVAILABLE_CHARS_) { if (QKeySequence(iKey).toString() == i) { detailsCheckSelectionAndItem(cursorPos); this->insertPlainText(QKeySequence(iKey).toString()); detailsSetCharStyleByNeighbours(ch, cursorPos); charStyleVector_.insert(cursorPos, 1, ch); detailsSetCharStyleByIndex(ch, cursorPos + 1); ++charCounter_; //Add coommand to UndoRefoBuffer setCommandInfo(command, command::insertStr, cursorPos, QKeySequence(iKey).toString()); undoRedoBuffer_->pushUndoCommand(command); timer_->stop(); timer_->start(1000); return; } } } switch (iKey) { //Space case Qt::Key_Space : { detailsCheckSelectionAndItem(cursorPos); addSpace(cursorPos); //Add coommand to UndoRefoBuffer setCommandInfo(command, command::insertStr, cursorPos, " "); undoRedoBuffer_->pushUndoCommand(command); checkSpelling(); return; } //Tab case Qt::Key_Tab : { // if (this->textCursor().selectedText() != "") { // detailsEraseSelectedText(cursorPos); // } addTab(cursorPos); timer_->stop(); timer_->start(1000); return; } //Shift + Tab case Qt::Key_Backtab : { backTab(cursorPos); return; } //Return case Qt::Key_Return : detailsCheckSelectionAndItem(cursorPos); this->textCursor().insertText("\n", charFormat); charStyleVector_.insert(cursorPos, 1, ch); ++charCounter_; //Add coommand to UndoRefoBuffer setCommandInfo(command, command::insertStr, cursorPos, "\n"); undoRedoBuffer_->pushUndoCommand(command); checkSpelling(); return; } if (kmModifiers == Qt::ControlModifier) { //Ctrl + z if (QKeySequence(iKey) == Qt::Key_Z || QKeySequence(iKey).toString() == "Я") { undoCommand(); timer_->stop(); timer_->start(1000); } else if (QKeySequence(iKey) == Qt::Key_Y || QKeySequence(iKey).toString() == "Н") { redoCommand(); timer_->stop(); timer_->start(1000); } //Ctrl + d - dash else if (QKeySequence(iKey) == Qt::Key_D ||QKeySequence(iKey).toString() == "В") { detailsCheckSelectionAndItem(cursorPos); this->insertPlainText(dashSign_); charStyleVector_.insert(cursorPos, 1, ch); ++charCounter_; //Add coommand to UndoRefoBuffer setCommandInfo(command, command::insertStr, cursorPos, dashSign_); undoRedoBuffer_->pushUndoCommand(command); timer_->stop(); timer_->start(1000); return; } //Ctrl + V - paste else if (QKeySequence(iKey) == Qt::Key_V) { detailsCheckSelectionAndItem(cursorPos); QClipboard* buffer = QApplication::clipboard(); QString insertLine = buffer->text(); int first = insertLine.length(); int second = MAX_COUNT_CHAR_ - charCounter_ + 1; int end = std::min(first, second); insertLine = insertLine.mid(0, end); //to correct work with limit of chars this->textCursor().insertText(insertLine); charStyleVector_.insert(cursorPos, insertLine.length(), ch); charCounter_ += insertLine.length(); //Add coommand to UndoRefoBuffer setCommandInfo(command, command::insertStr, cursorPos, insertLine); undoRedoBuffer_->pushUndoCommand(command); timer_->stop(); timer_->start(1000); return; } //Ctrl + p - add to-do-list with point else if (QKeySequence(iKey) == Qt::Key_P || QKeySequence(iKey).toString() == "З") { addTodoList(pointSign_); return; } //Ctrl + '-' - add to-do-list with minus else if (QKeySequence(iKey) == Qt::Key_Minus) { addTodoList(minusSign_); return; } //Ctrl + w - add red star else if (QKeySequence(iKey) == Qt::Key_W || QKeySequence(iKey).toString() == "Ц") { addStar(); return; } } } //Esc canceled all selection if (iKey == Qt::Key_Escape) { if (this->textCursor().hasSelection()) { this->moveCursor(QTextCursor::Right); } return; } //Home if (iKey == Qt::Key_Home) { QTextCursor c = this->textCursor(); c.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); this->setTextCursor(c); return; } //End if (iKey == Qt::Key_End) { QTextCursor c = this->textCursor(); c.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); this->setTextCursor(c); return; } //Arrows Left, Up, Right, Down - move to chars and lines if (kmModifiers == 0) { switch (iKey) { case Qt::Key_Left : this->moveCursor(QTextCursor::Left); return; case Qt::Key_Right : this->moveCursor(QTextCursor::Right); return; case Qt::Key_Up : this->moveCursor(QTextCursor::Up); return; case Qt::Key_Down : this->moveCursor(QTextCursor::Down); return; } } //Shift + arrows if (kmModifiers == Qt::ShiftModifier || kmModifiers == (Qt::ShiftModifier | Qt::ControlModifier)) { if (QKeySequence(iKey) == Qt::Key_Up || QKeySequence(iKey) == Qt::Key_Down || QKeySequence(iKey) == Qt::Key_Right || QKeySequence(iKey) == Qt::Key_Left) { //it is tmp soluton, I want to reimplementate work with shift QTextEdit::keyPressEvent(event); return; } } //Ctrl + arrows if (kmModifiers == Qt::ControlModifier) { //Ctrl + arrows Up/Down move cursor to start/end of text if (QKeySequence(iKey) == Qt::Key_Up) { this->moveCursor(QTextCursor::Start); return; } else if (QKeySequence(iKey) == Qt::Key_Down) { this->moveCursor(QTextCursor::End); return; } //Ctrl + arrows <-/-> - move to words else if (QKeySequence(iKey) == Qt::Key_Left) { this->moveCursor(QTextCursor::PreviousWord); return; } else if (QKeySequence(iKey) == Qt::Key_Right) { this->moveCursor(QTextCursor::NextWord); return; } } if (kmModifiers == Qt::ControlModifier) { QClipboard* buffer = QApplication::clipboard(); //Ctrl + C - copy if (QKeySequence(iKey) == Qt::Key_C) { QString Selectline = this->textCursor().selectedText(); buffer->setText(Selectline); return; } //Ctrl + A - select all else if (QKeySequence(iKey) == Qt::Key_A) { this->selectAll(); return; } //Ctrl + X - cut else if (QKeySequence(iKey) == Qt::Key_X) { detailsCheckSelectionAndItem(cursorPos); //work with UndoRedoBuffer in that function this->cut(); timer_->stop(); timer_->start(1000); } //Ctrl + b - Bold else if (QKeySequence(iKey) == Qt::Key_B || QKeySequence(iKey).toString() == "И") { if (this->textCursor().hasSelection()) { setCharStyle(charStyle::Bold); } else { detailsSetCharStyle(globCh, charStyle::Bold); } } //Ctrl + i - Italic else if (QKeySequence(iKey) == Qt::Key_I || QKeySequence(iKey).toString() == "Ш") { if (this->textCursor().hasSelection()) { setCharStyle(charStyle::Italic); } else { detailsSetCharStyle(globCh, charStyle::Italic); } } //Ctrl + u - Underline else if (QKeySequence(iKey) == Qt::Key_U || QKeySequence(iKey).toString() == "Г") { if (this->textCursor().hasSelection()) { setCharStyle(charStyle::Underline); } else { detailsSetCharStyle(globCh, charStyle::Underline); } } //Ctrl + s - Strike else if (QKeySequence(iKey) == Qt::Key_S || QKeySequence(iKey).toString() == "Ы") { if (this->textCursor().hasSelection()) { setCharStyle(charStyle::Strike); } else { detailsSetCharStyle(globCh, charStyle::Strike); } } //Ctrl + n - Normal else if (QKeySequence(iKey) == Qt::Key_N || QKeySequence(iKey).toString() == "Т") { makeCharNormal(); detailsSetCharStyle(globCh); return; } //Ctrl + g - highlight in green else if (QKeySequence(iKey) == Qt::Key_G || QKeySequence(iKey).toString() == "П") { colorText(colors::green); this->moveCursor(QTextCursor::Right); return; } //Ctrl + l - lavender else if (QKeySequence(iKey) == Qt::Key_L || QKeySequence(iKey).toString() == "Д") { colorText(colors::lavender); this->moveCursor(QTextCursor::Right); return; } //Ctrl + m - marina else if (QKeySequence(iKey) == Qt::Key_M || QKeySequence(iKey).toString() == "Ь") { colorText(colors::marina); this->moveCursor(QTextCursor::Right); return; } //Ctrl + o - orange else if (QKeySequence(iKey) == Qt::Key_O || QKeySequence(iKey).toString() == "Щ") { colorText(colors::orange); this->moveCursor(QTextCursor::Right); return; } //Ctrl + r - red else if (QKeySequence(iKey) == Qt::Key_R || QKeySequence(iKey).toString() == "К") { colorText(colors::red); this->moveCursor(QTextCursor::Right); checkSpelling(); return; } } //Ctrl + Shift + D - add new word to dictionary if (kmModifiers == (Qt::ShiftModifier | Qt::ControlModifier) && (QKeySequence(iKey) == Qt::Key_D || QKeySequence(iKey).toString() == "В")) { rusDic_->addNewWord(this->textCursor().selectedText().toLower()); timer_->stop(); timer_->start(1000); return; } //Backspace if (QKeySequence(iKey) == Qt::Key_Backspace) { //analize item posotion if it is item detailsCheckItemPosInDeleting(cursorPos, true, kmModifiers); deleteSmth(kmModifiers, QTextCursor::PreviousWord, cursorPos, 0, 1); this->textCursor().deletePreviousChar(); timer_->stop(); timer_->start(1000); } //Delete else if (QKeySequence(iKey) == Qt::Key_Delete) { detailsCheckItemPosInDeleting(cursorPos, false, kmModifiers); deleteSmth(kmModifiers, QTextCursor::NextWord, cursorPos, charStyleVector_.size()); this->textCursor().deleteChar(); timer_->stop(); timer_->start(1000); } } /*void GenTextEdit::paintEvent(QPaintEvent *event) { // use paintEvent() of base class to do the main work QTextEdit::paintEvent(event); // draw cursor (if widget has focus) if (hasFocus()) { const QRect qRect = cursorRect(textCursor()); QPainter qPainter(viewport()); qPainter.fillRect(qRect, QColor(Qt::red)); } }*/ void GenTextEdit::checkSpelling() { QString text = this->toPlainText(); QTextStream sourseText(&text); QChar curCh; QString word = ""; for (int i = 0; i < text.length(); ++i) { sourseText >> curCh; //dictionary doesn't know about 'Ё' letter if (curCh == "ё" || curCh == "Ё") { curCh = QChar(RUS_YO_UNICODE); } curCh = curCh.toLower(); if (detailsIsLetter(curCh)) { word += curCh; } else if (!word.isEmpty() && curCh == "-") { word += curCh; } else if (!word.isEmpty()) { detailsCheckSpelling(word, i); word = ""; } } //check the last word if (!word.isEmpty()) { detailsCheckSpelling(word, charCounter_); } } void GenTextEdit::sendServerRequest() { emit sendServerRequest(nCurrentFile_); }
29.598425
104
0.617717
Igisid
d41220133c669dd40b70064305fdaa00e382d62a
995
hpp
C++
include/sampling/time_series_slice.hpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
1
2020-07-31T01:34:47.000Z
2020-07-31T01:34:47.000Z
include/sampling/time_series_slice.hpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
null
null
null
include/sampling/time_series_slice.hpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
null
null
null
#ifndef TIME_SERIES_SLICE_H #define TIME_SERIES_SLICE_H #include <unistd.h> #include <vector> #include "agg_window.hpp" #include "aliases.hpp" namespace bandwit { namespace sampling { // FIXME: should this be a struct? class TimeSeriesSlice { public: explicit TimeSeriesSlice(std::vector<TimePoint> tps, std::vector<uint64_t> vals, AggregationWindow agg_win) : time_points{std::move(tps)}, values{std::move(vals)}, agg_window{ agg_win} {} // We need this to be able to declare a variable in an outer scope and // populate it in an inner scope. The value should not be used for anything // cause it's going to be empty. TimeSeriesSlice() {} std::vector<TimePoint> time_points{}; std::vector<uint64_t> values{}; AggregationWindow agg_window; }; } // namespace sampling } // namespace bandwit #endif // TIME_SERIES_SLICE_H
28.428571
79
0.628141
numerodix
d4141327adfe48efc12d8c04a2f468df3e24ce6f
1,669
hpp
C++
msaa/deps/lpp/include/lpp/common/iteration.hpp
leddoo/raster
aa58a04e0549a44a8212b57020397587ebe51eb7
[ "MIT" ]
null
null
null
msaa/deps/lpp/include/lpp/common/iteration.hpp
leddoo/raster
aa58a04e0549a44a8212b57020397587ebe51eb7
[ "MIT" ]
null
null
null
msaa/deps/lpp/include/lpp/common/iteration.hpp
leddoo/raster
aa58a04e0549a44a8212b57020397587ebe51eb7
[ "MIT" ]
null
null
null
#pragma once #include <lpp/core/basic.hpp> namespace lpp { // TODO: these rely on range based for to be expanded as "it != end". it // would probably be more robust to actually implement != and create the // iterators with "clamping". // "monotonic" because of less than comparison. template <typename T> struct Monotonic_Iterator { T value; Monotonic_Iterator(T value) : value(value) {} T operator*() const { return this->value; } void operator++() { this->value += 1; } Bool operator!=(const Monotonic_Iterator<T>& other) const { return this->value < other.value; } }; // also monotonic. template <typename T> struct Ptr_Iterator { Ptr<T> value; Ptr_Iterator(Ptr<T> value) : value(value) {} Ref<T> operator*() { return *this->value; } void operator++() { this->value += 1; } Bool operator!=(const Ptr_Iterator<T>& other) const { return this->value < other.value; } }; template <typename T> struct Range { T _begin; T _end; Range() : _begin(0), _end(0) {} Range(T end) : _begin(0), _end(end) {} Range(T begin, T end) : _begin(begin), _end(end) {} T length() const { return (this->_end > this->_begin) ? (this->_end - this->_begin) : T(0); } Monotonic_Iterator<T> begin() const { return Monotonic_Iterator<T> { this->_begin }; } Monotonic_Iterator<T> end() const { return Monotonic_Iterator<T> { this->_end }; } }; }
25.287879
94
0.541642
leddoo
d414ac5a9028e16ae6db5b92cd723cebf2ae1d19
2,973
cpp
C++
src/ace/ACE_wrappers/examples/IPC_SAP/FIFO_SAP/FIFO-test.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/examples/IPC_SAP/FIFO_SAP/FIFO-test.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/examples/IPC_SAP/FIFO_SAP/FIFO-test.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
// Purpose: This program uses ACE_FIFO wrappers to perform // interprocess communication between a parent process and a child // process. The parents reads from an input file and writes it into // the fifo. The child reads from the ACE_FIFO and executes the more // command. #include "ace/FIFO_Recv.h" #include "ace/FIFO_Send.h" #include "ace/Log_Msg.h" #include "ace/OS_NS_sys_wait.h" #include "ace/OS_NS_unistd.h" #include "ace/OS_NS_stdlib.h" #include "ace/OS_NS_fcntl.h" #define PERMS 0666 #define EXEC_NAME "more" #define EXEC_COMMAND_ARG "more" static const ACE_TCHAR *FIFO_NAME = ACE_TEXT ("/tmp/fifo"); static int do_child (ACE_FIFO_Recv &fifo_reader) { // Set child's stdin to read from the fifo. if (ACE_OS::close (ACE_STDIN) == -1 || ACE_OS::dup (fifo_reader.get_handle ()) == ACE_INVALID_HANDLE) return -1; char *argv[2]; argv[0] = const_cast<char *> (EXEC_COMMAND_ARG); argv[1] = 0; if (ACE_OS::execvp (EXEC_NAME, argv) == -1) return -1; return 0; } static int do_parent (const ACE_TCHAR fifo_name[], ACE_TCHAR input_filename[]) { ACE_FIFO_Send fifo_sender (fifo_name, O_WRONLY | O_CREAT); ssize_t len; char buf[BUFSIZ]; if (fifo_sender.get_handle () == ACE_INVALID_HANDLE) return -1; ACE_HANDLE inputfd = ACE_OS::open (input_filename, O_RDONLY); if (inputfd == ACE_INVALID_HANDLE) return -1; // Read from input file and write into input end of the fifo. while ((len = ACE_OS::read (inputfd, buf, sizeof buf)) > 0) if (fifo_sender.send (buf, len) != len) return -1; if (len == -1) return -1; if (fifo_sender.remove () == -1) return -1; return 0; } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { ACE_LOG_MSG->open (argv[0]); if (argc != 2) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("usage: %n input-file\n"), 1)); ACE_OS::exit (1); } ACE_FIFO_Recv fifo_reader (FIFO_NAME, O_RDONLY | O_CREAT, PERMS, 0); if (fifo_reader.get_handle () == ACE_INVALID_HANDLE) return -1; pid_t child_pid = ACE_OS::fork (); switch (child_pid) { case -1: ACE_ERROR ((LM_ERROR, ACE_TEXT ("%n: %p\n%a"), ACE_TEXT ("fork"), 1)); case 0: if (do_child (fifo_reader) == -1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%n: %p\n%a"), ACE_TEXT ("do_child"), 1)); default: if (do_parent (FIFO_NAME, argv[1]) == -1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%n: %p\n%a"), ACE_TEXT ("do_parent"), 1)); // wait for child to ACE_OS::exit. if (ACE_OS::waitpid (child_pid, (ACE_exitcode *) 0, 0) == -1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%n: %p\n%a"), ACE_TEXT ("waitpid"), 1)); } return 0; }
24.570248
71
0.57484
wfnex
d415c93e4991a714c0ebd646ce3e9a242627094b
6,608
cpp
C++
tests/channel.cpp
initcrash/fnpp
34e633ba6ec0fe0024f7457369040ce1e7919f5a
[ "MIT" ]
3
2015-05-06T20:34:43.000Z
2016-10-27T13:30:33.000Z
tests/channel.cpp
initcrash/fnpp
34e633ba6ec0fe0024f7457369040ce1e7919f5a
[ "MIT" ]
null
null
null
tests/channel.cpp
initcrash/fnpp
34e633ba6ec0fe0024f7457369040ce1e7919f5a
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <map> #include <utility> #include <thread> #include "catch.hpp" #include <fn/iterators.hpp> #include <fn/channel.hpp> using namespace fn; TEST_CASE("Channel [int]") { auto channel = Channel<int>(3); REQUIRE_FALSE(channel.receive(0).valid()); SECTION("send one message") { channel.send(123); CHECK(123 == ~channel.receive(0)); REQUIRE_FALSE(channel.receive(0).valid()); } SECTION("send two messages") { CHECK(channel.send(123)); CHECK(channel.send(124)); CHECK(123 == ~channel.receive(0)); CHECK(124 == ~channel.receive(0)); CHECK_FALSE(channel.receive(0).valid()); } SECTION("send more messages than fit") { CHECK(channel.send(123)); CHECK(channel.send(124)); CHECK(channel.send(125)); CHECK_FALSE(channel.send(126)); CHECK(123 == ~channel.receive(0)); CHECK(124 == ~channel.receive(0)); CHECK(125 == ~channel.receive(0)); CHECK_FALSE(channel.receive(0).valid()); } SECTION("copy sender") { auto send = channel.send; CHECK(channel.send(2)); CHECK(send(1)); CHECK(2 == ~channel.receive(0)); CHECK(1 == ~channel.receive(0)); CHECK_FALSE(channel.receive(0).valid()); } SECTION("move receiver, then send") { auto receive = std::move(channel.receive); CHECK(channel.send(1)); CHECK_FALSE(channel.receive(0).valid()); CHECK(1 == ~receive(0)); CHECK_FALSE(receive(0).valid()); } SECTION("send, then move receiver") { CHECK(channel.send(1)); auto receive = std::move(channel.receive); CHECK_FALSE(channel.receive(0).valid()); CHECK(1 == ~receive(0)); CHECK_FALSE(receive(0).valid()); } SECTION("remove elements") { CHECK(channel.send(1)); CHECK(channel.send(2)); CHECK(channel.send(3)); channel.receive.remove_if([](int const& i) -> bool { return i % 2; }); CHECK(2 == ~channel.receive(0)); CHECK_FALSE(channel.receive(0).valid()); } SECTION("send one message to thread, receive gets called after send") { auto thread = std::thread([&]{ CHECK(123 == ~channel.receive(10000)); }); std::this_thread::sleep_for(std::chrono::milliseconds(100)); channel.send(123); thread.join(); } SECTION("send one message to thread, receive gets called before send") { auto thread = std::thread([&]{ std::this_thread::sleep_for(std::chrono::milliseconds(100)); CHECK(123 == ~channel.receive(10000)); }); channel.send(123); thread.join(); } } TEST_CASE("Channel [unique_ptr]") { auto channel = Channel<std::unique_ptr<int>>(3); REQUIRE_FALSE(channel.receive(0).valid()); SECTION("send one message") { auto up = std::unique_ptr<int>(new int); *up = 1234; channel.send(std::move(up)); CHECK(nullptr == up); auto r = channel.receive(0); CHECK(r.valid()); r >>[&](std::unique_ptr<int>& i){ REQUIRE(i != nullptr); CHECK(1234 == *i); }; REQUIRE_FALSE(channel.receive(0).valid()); } SECTION("move receiver, then send") { auto receive = std::move(channel.receive); CHECK(channel.send(std::unique_ptr<int>(new int(1)))); CHECK_FALSE(channel.receive(0).valid()); CHECK(receive(0).valid()); CHECK_FALSE(receive(0).valid()); } SECTION("send, then move receiver") { CHECK(channel.send(std::unique_ptr<int>(new int(1)))); auto receive = std::move(channel.receive); CHECK_FALSE(channel.receive(0).valid()); CHECK(receive(0).valid()); CHECK_FALSE(receive(0).valid()); } } TEST_CASE("Ring") { auto queue = fn_::Ring<int>::create(3); CHECK_FALSE(queue->pop()); CHECK(queue->empty()); SECTION("push once") { new (queue->push()) int(7); CHECK_FALSE(queue->empty()); CHECK(7 == *queue->pop()); CHECK_FALSE(queue->pop()); } SECTION("push twice") { new (queue->push()) int(6); CHECK_FALSE(queue->empty()); new (queue->push()) int(8); CHECK_FALSE(queue->empty()); CHECK(6 == *queue->pop()); CHECK_FALSE(queue->empty()); CHECK(8 == *queue->pop()); CHECK(queue->empty()); } SECTION("push twice, twice") { new (queue->push()) int(6); new (queue->push()) int(8); CHECK(6 == *queue->pop()); CHECK(8 == *queue->pop()); new (queue->push()) int(2); new (queue->push()) int(3); CHECK(2 == *queue->pop()); CHECK(3 == *queue->pop()); } SECTION("overflow") { new (queue->push()) int(1); new (queue->push()) int(2); new (queue->push()) int(3); CHECK_FALSE(queue->push()); CHECK_FALSE(queue->push()); CHECK_FALSE(queue->push()); CHECK(1 == *queue->pop()); CHECK(2 == *queue->pop()); CHECK(3 == *queue->pop()); CHECK(queue->empty()); } }; struct M { int value; static int counter; M(int value): value(value) { ++counter; } ~M() { --counter; } M(M const&) = delete; M(M&& m): value(m.value) { ++counter; } }; int M::counter = 0; TEST_CASE("Ring remove_if") { M::counter = 0; auto queue = fn_::Ring<M>::create(5); CHECK(queue->empty()); CHECK(0 == M::counter); new (queue->push()) M(1); new (queue->push()) M(2); new (queue->push()) M(3); new (queue->push()) M(4); CHECK(4 == M::counter); SECTION("remove none") { queue->remove_if([](M const&) -> bool { return false; }); CHECK(1 == queue->pop()->value); CHECK(2 == queue->pop()->value); CHECK(3 == queue->pop()->value); CHECK(4 == queue->pop()->value); CHECK(queue->empty()); CHECK(4 == M::counter); } SECTION("remove all") { queue->remove_if([](M const&) -> bool { return true; }); CHECK(queue->empty()); CHECK(0 == M::counter); } SECTION("remove uneven") { queue->remove_if([](M const& x) -> bool { return x.value % 2; }); CHECK(2 == queue->pop()->value); CHECK(4 == queue->pop()->value); CHECK(queue->empty()); CHECK(2 == M::counter); } }
23.855596
74
0.52618
initcrash
d420416b0f41711b6368aa8d8b311f6f1ecf6913
783
cc
C++
source/options.cc
JaMo42/spaceinfo
534d69d61930a858b3880ac10fc693edbe792f4e
[ "BSD-3-Clause" ]
null
null
null
source/options.cc
JaMo42/spaceinfo
534d69d61930a858b3880ac10fc693edbe792f4e
[ "BSD-3-Clause" ]
null
null
null
source/options.cc
JaMo42/spaceinfo
534d69d61930a858b3880ac10fc693edbe792f4e
[ "BSD-3-Clause" ]
null
null
null
#include "options.hh" #include "flag-cpp/flag.hh" namespace Options { bool si = false; bool raw_size = false; int bar_length = 10; unsigned history_size = 16; } const char * parse_args (int argc, const char *const *argv) { flag::add (Options::si, "si", "Use powers of 1000 not 1024 for human readable sizes."); flag::add (Options::raw_size, "r", "Do not print human readable sizes."); flag::add (Options::bar_length, "bar-length", "Length for the relative size bar."); flag::add (Options::history_size, "hist-len", "Maximum length of search/go-to history."); flag::add_help (); std::vector<const char *> args = flag::parse (argc, argv); if (Options::history_size == 0) Options::history_size = 1; return args.empty () ? nullptr : args.front (); }
27.964286
91
0.666667
JaMo42
d4207c0ef66cb65f8756179c9b37797ff1df8913
729
cpp
C++
Source/Parser/LanguageTypes/Invokable.cpp
JoinCAD/CPP-Reflection
61163369b6b3b370c4ce726dbf8e60e441723821
[ "MIT" ]
540
2015-09-18T09:44:57.000Z
2022-03-25T07:23:09.000Z
Source/Parser/LanguageTypes/Invokable.cpp
yangzhengxing/CPP-Reflection
43ec755b7a5c62e3252c174815c2e44727e11e72
[ "MIT" ]
16
2015-09-23T06:37:43.000Z
2020-04-10T15:40:08.000Z
Source/Parser/LanguageTypes/Invokable.cpp
yangzhengxing/CPP-Reflection
43ec755b7a5c62e3252c174815c2e44727e11e72
[ "MIT" ]
88
2015-09-21T15:12:32.000Z
2021-11-30T14:07:34.000Z
/* ---------------------------------------------------------------------------- ** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved. ** ** Invokable.cpp ** --------------------------------------------------------------------------*/ #include "Precompiled.h" #include "LanguageTypes/Invokable.h" Invokable::Invokable(const Cursor &cursor) : m_returnType( utils::GetQualifiedName( cursor.GetReturnType( ) )) { auto type = cursor.GetType( ); unsigned count = type.GetArgumentCount( ); m_signature.clear( ); for (unsigned i = 0; i < count; ++i) { auto argument = type.GetArgument( i ); m_signature.emplace_back( utils::GetQualifiedName( argument ) ); } }
27
79
0.500686
JoinCAD
d4269f5f60e3ac334285c2efa78f5c9b0ba56924
730
cpp
C++
Libs/MainWindow/glfwLibrary.cpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
Libs/MainWindow/glfwLibrary.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
Libs/MainWindow/glfwLibrary.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "glfwLibrary.hpp" #include "ConsoleCommands/Console.hpp" #include "GLFW/glfw3.h" #include <stdexcept> using namespace cf; static void error_callback(int error, const char* description) { // fprintf(stderr, "GLFW Error: %s\n", description); Console->Print("GLFW Error: "); Console->Print(description); Console->Print("\n"); } glfwLibraryT::glfwLibraryT() { glfwSetErrorCallback(error_callback); if (!glfwInit()) throw std::runtime_error("GLFW could not be initialized."); } glfwLibraryT::~glfwLibraryT() { glfwTerminate(); }
19.72973
67
0.7
dns
2d6b75e40d6908cef5f34cc874ffc0696777c42f
1,988
cpp
C++
cpp/tests/utilities_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
133
2017-06-24T02:44:28.000Z
2022-03-25T05:17:00.000Z
cpp/tests/utilities_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
null
null
null
cpp/tests/utilities_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
33
2017-06-19T03:24:40.000Z
2022-02-03T20:13:12.000Z
#include "tests/utilities_UT.hpp" #include <gtest/gtest.h> #include <iostream> #include <unistd.h> #include <string> namespace util { Utilities_UT::Utilities_UT() { } void Utilities_UT::SetUpTestCase(void) { } void Utilities_UT::SetUp(void) { } TEST_F(Utilities_UT, hashElement) { SHA_CTX context; SHA1_Init(&context); // Test hashing of int unsigned int intVal = 120; unsigned char hashVal[20] = {119, 91, 197, 195, 14, 39, 240, 229, 98, 17, 93, 19, 110, 127, 126, 219, 211, 206, 173, 137}; hashElement(&context, intVal); unsigned char outHash[20]; SHA1_Final(outHash, &context); for (unsigned int i = 0; i < 20; i++) { EXPECT_TRUE(outHash[i] == hashVal[i]); } // Test proper truncation of floats double doubleVal = 123456789.987654321; unsigned char doubleHashVal[20] = {57, 184, 2, 193, 35, 225, 250, 6, 9, 174, 32, 17, 151, 2, 189, 243, 98, 4, 114, 56}; SHA1_Init(&context); hashElement(&context, doubleVal); SHA1_Final(outHash, &context); for (unsigned int i = 0; i < 20; i++) { EXPECT_TRUE(outHash[i] == doubleHashVal[i]); } // Test equality of floats SHA1_Init(&context); hashElement(&context, 123456789.9876543); SHA1_Final(outHash, &context); for (unsigned int i = 0; i < 20; i++) { EXPECT_TRUE(outHash[i] == doubleHashVal[i]); } // Test hashing of string unsigned char strHashVal[20] = {32, 7, 193, 121, 130, 25, 101, 249, 148, 120, 27, 125, 133, 199, 187, 217, 166, 183, 81, 227}; std::string strVal = "thisIsAString"; SHA1_Init(&context); hashElement(&context, strVal); SHA1_Final(outHash, &context); for (unsigned int i = 0; i < 20; i++) { EXPECT_TRUE(outHash[i] == strHashVal[i]); } } }
30.584615
134
0.555835
MinesJA
2d6c1457d640b0b9a5a7bb7449222b328397bb5a
4,181
cpp
C++
sd_log.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
1
2018-10-08T13:28:32.000Z
2018-10-08T13:28:32.000Z
sd_log.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
9
2019-08-21T18:07:49.000Z
2019-09-30T19:48:28.000Z
sd_log.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
null
null
null
#include <SPI.h> #include <SdFat.h> #include <errno.h> #include "sd_log.h" #include "common.h" #define SPI_SPEED SD_SCK_MHZ(8) const uint8_t sd_CS = 10; static bool sdReady = 0; SdFat sd; SdFile root; static SdFile dataFile; static SdFile rawLogFile; static bool dataFileOpened = 0; static bool rawFileOpened = 0; static uint8_t dataFileHour; static char logFilename[13]; /* 8.3 filename + \0 */ int isSdReady(void) { return sdReady; } char *currentLogFilename(void) { return logFilename; } const char sd_counter_dir[] = "/counter"; void setup_sd() { Serial.print(F("\nInit SD...")); if (!sd.begin(sd_CS, SPI_SPEED)) goto err; if (!sd.exists(sd_counter_dir)) sd.mkdir(sd_counter_dir); if (!root.open(sd_counter_dir, O_READ)) goto err; sdReady = 1; Serial.println(F("SD OK")); #ifdef DEBUG_MEMORY Serial.print(F("freeMemory()=")); Serial.println(freeMemory()); #endif return; err: sdReady = 0; Serial.println(F("SD ERROR")); } static char *make_filename(char *buf, time_t time) { char *p = buf; itoa_10lz(p, year(time) % 100, 2); p += 2; itoa_10lz(p, month(time), 2); p += 2; itoa_10lz(p, day(time), 2); p += 2; itoa_10lz(p, hour(time), 2); p += 2; p[0] = '.'; p[1] = 'C'; p[2] = 'S'; p[3] = 'V'; p[4] = '\0'; return buf; } int sdFileOpen() { time_t t = now(); if (dataFileOpened && (hour(t) != dataFileHour)) { dataFile.close(); dataFileOpened = 0; } if (!dataFileOpened) { bool exists; #ifdef DEBUG_MEMORY Serial.print(F("freeMemory()=")); Serial.println(freeMemory()); #endif dataFileHour = hour(t); make_filename(logFilename, t); Serial.println(logFilename); exists = root.exists(logFilename); if (dataFile.open(&root, logFilename, O_CREAT | O_WRITE | O_APPEND)) { dataFileOpened = 1; if (!exists) dataFile.println(F("ts,time,count,direction,speed,length,bat_mV")); } else { Serial.println(F("Cannot open logfile")); return 1; } } return 0; } int sdRawFileOpen() { if (!rawFileOpened) { if (rawLogFile.open(&root, "raw.log", O_CREAT | O_WRITE | O_APPEND)) { rawFileOpened = 1; } else { Serial.println(F("Cannot open raw log file")); return -EIO; } } return 0; } int logToSd(int count, int direction, float speed, float length, time_t time, bool verbose) { static char buf[STRBUF_TIME_SIZE]; sprintf_time(buf, time); if (verbose) { Serial.print("V:"); Serial.print(time - LOCAL_TIME_OFFSET); /* UTC Unix timestamp */ Serial.print(","); Serial.print(buf); Serial.print(","); Serial.print(count); Serial.print(","); Serial.print(direction); Serial.print(","); Serial.print(speed); Serial.print(","); Serial.print(length); Serial.print(","); Serial.println(readBattery_mV()); } if (!sdReady) { return 1; } if (sdFileOpen()) return 1; #ifdef DEBUG_MEMORY Serial.print(F("freeMemory()=")); Serial.println(freeMemory()); #endif dataFile.print(time - LOCAL_TIME_OFFSET); /* UTC Unix timestamp */ dataFile.print(","); dataFile.print(buf); dataFile.print(","); dataFile.print(count); dataFile.print(","); dataFile.print(direction); dataFile.print(","); dataFile.print(speed); dataFile.print(","); dataFile.print(length); dataFile.print(","); dataFile.println(readBattery_mV()); dataFile.sync(); return 0; } int logToSdRaw(time_t time, struct hit *hit_series, uint8_t count) { if (!sdReady) return -EIO; if (sdRawFileOpen()) return -EIO; rawLogFile.print(localtime2utc(time)); rawLogFile.print(", "); for (int i = 0; i < count; i++) { rawLogFile.print(hit_series[i].channel); rawLogFile.print(":"); rawLogFile.print(hit_series[i].time); rawLogFile.print(" "); } rawLogFile.println(); rawLogFile.sync(); return 0; } char dumpSdLog(char *file) { if (!sdReady) return 1; if (!file) { sdFileOpen(); file = currentLogFilename(); } if (dataFileOpened) { dataFile.close(); dataFileOpened = 0; } if (!dataFile.open(&root, file, O_READ)) { Serial.print(F("Failed to open file ")); Serial.println(file); return 1; } while (dataFile.available()) Serial.write(dataFile.read()); Serial.println(""); dataFile.close(); return 0; }
17.348548
91
0.651519
jekhor
2d6d97a78b074c005566715494b8152f51378362
470
cpp
C++
1-8-4z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-8-4z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-8-4z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
// // Created by grey on 22.10.2019. // #include <iostream> using namespace std; void foo_1_8_4z(){ int n; cin >> n; char a[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j || j == n/2 || i == n/2 || i + j == n - 1){ a[i][j] = '*'; } else { a[i][j] = '.'; } cout << a[i][j] << " "; } cout << endl; } }
18.076923
66
0.308511
Kaermor
2d73e45d9cbdae04872b0a94ab0ea895ec28f591
4,213
hpp
C++
Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_ChangeDrvSrvDlg_.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_ChangeDrvSrvDlg_.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_ChangeDrvSrvDlg_.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCTreeBrws_ChangeDrvSrvDlg.hpp // // AUTHOR: Dean Roddey // // CREATED: 10/02/2016 // // 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 for the CQCTreeBrws_ChangeDrvSrvDlg.cpp file, which implements // the TChangeDrvSrvDlg class. This dialog allows the user to change the host for which // drivers are configured, for when they change the host name or move the CQC install // to a new machine. They click on the current server name, and we let them select a // new server. If they commit, we just return the selected host, and the caller will // do the work. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TChangeDrvSrvDlg // PREFIX: dlg // --------------------------------------------------------------------------- class TChangeDrvSrvDlg : public TDlgBox { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TChangeDrvSrvDlg(); TChangeDrvSrvDlg(const TChangeDrvSrvDlg&) = delete; ~TChangeDrvSrvDlg(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TChangeDrvSrvDlg& operator=(const TChangeDrvSrvDlg&) = delete; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bRun ( const TWindow& wndOwner , const tCIDLib::TStrList& colList , const TString& strOrgHost , TString& strSelected ); protected : // ------------------------------------------------------------------- // Protected inherited methods // ------------------------------------------------------------------- tCIDLib::TBoolean bCreated() override; private : // ------------------------------------------------------------------- // Private, non-virtual methods // ------------------------------------------------------------------- tCIDCtrls::EEvResponses eClickHandler ( TButtClickInfo& wnotEvent ); tCIDCtrls::EEvResponses eLBHandler ( TListChangeInfo& wnotEvent ); // ------------------------------------------------------------------- // Private data members // // m_pcolList // This is the list of servers the caller wants us to select between. // // m_pwndXXX // We get typed pointers to controls we need to interact with // // m_strOrgHost // The original host from which the driver's will be moved, so that we can // put into the instruction text. // // m_strSelected // The host selected until we can get it back to the caller's parameters. // ------------------------------------------------------------------- const tCIDLib::TStrList* m_pcolHosts; TPushButton* m_pwndCancel; TPushButton* m_pwndChange; TMultiColListBox* m_pwndList; TString m_strOrgHost; TString m_strSelected; // ------------------------------------------------------------------- // Magic Macros // ------------------------------------------------------------------- RTTIDefs(TChangeDrvSrvDlg,TDlgBox) }; #pragma CIDLIB_POPPACK
33.436508
88
0.411108
MarkStega
2d73e57208714aeedd1889bbd7ccc1662e1c9eb9
4,119
cpp
C++
src/Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.cpp
Peixinho/Pyros3D
d6857ce99f3731a851ca5e7d67afbb13aafd18e0
[ "MIT" ]
20
2016-02-15T23:22:06.000Z
2021-12-07T00:13:49.000Z
src/Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.cpp
Peixinho/Pyros3D
d6857ce99f3731a851ca5e7d67afbb13aafd18e0
[ "MIT" ]
1
2017-09-04T00:28:19.000Z
2017-09-05T11:00:12.000Z
src/Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.cpp
Peixinho/Pyros3D
d6857ce99f3731a851ca5e7d67afbb13aafd18e0
[ "MIT" ]
3
2016-08-10T02:44:08.000Z
2021-05-28T23:03:10.000Z
//============================================================================ // Name : Cylinder // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Cylinder Geometry //============================================================================ #include <Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.h> namespace p3d { Cylinder::Cylinder(const f32 radius, const f32 height, const uint32 segmentsW, const uint32 segmentsH, bool openEnded, bool smooth, bool flip, bool TangentBitangent) { isFlipped = flip; isSmooth = smooth; calculateTangentBitangent = TangentBitangent; this->segmentsH = (f32)segmentsH; this->height = height; size_t i, j; int jMin, jMax; Vec3 normal; std::vector <Vec3> aRowT, aRowB; std::vector <std::vector<Vec3> > aVtc; if (!openEnded) { this->segmentsH += 2; jMin = 1; jMax = (int)this->segmentsH - 1; // Bottom Vec3 oVtx = Vec3(0, -this->height, 0); for (i = 0; i < segmentsW; ++i) { aRowB.push_back(oVtx); } aVtc.push_back(aRowB); //Top oVtx = Vec3(0, this->height, 0); for (i = 0; i < segmentsW; i++) { aRowT.push_back(oVtx); } } else { jMin = 0; jMax = (int)this->segmentsH; } for (j = jMin; (int)j <= jMax; ++j) { f32 z = -this->height + 2 * this->height*(f32)(j - jMin) / (f32)(jMax - jMin); std::vector <Vec3> aRow; for (i = 0; i < segmentsW; ++i) { f32 verangle = (f32)(2 * (f32)i / segmentsW*PI); f32 x = radius * sin(verangle); f32 y = radius * cos(verangle); Vec3 oVtx = Vec3(y, z, x); aRow.push_back(oVtx); } aVtc.push_back(aRow); } if (!openEnded) aVtc.push_back(aRowT); for (j = 1; j <= this->segmentsH; ++j) { for (i = 0; i < segmentsW; ++i) { Vec3 a = aVtc[j][i]; Vec3 b = aVtc[j][(i - 1 + segmentsW) % segmentsW]; Vec3 c = aVtc[j - 1][(i - 1 + segmentsW) % segmentsW]; Vec3 d = aVtc[j - 1][i]; int i2; (i == 0 ? i2 = segmentsW : i2 = i); f32 vab = (f32)j / this->segmentsH; f32 vcd = (f32)(j - 1) / this->segmentsH; f32 uad = (f32)i2 / (f32)segmentsW; f32 ubc = (f32)(i2 - 1) / (f32)segmentsW; Vec2 aUV = Vec2(uad, -vab); Vec2 bUV = Vec2(ubc, -vab); Vec2 cUV = Vec2(ubc, -vcd); Vec2 dUV = Vec2(uad, -vcd); normal = ((a - b).cross(c - b)).normalize(); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(cUV); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(bUV); geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(aUV); geometry->index.push_back(geometry->tVertex.size() - 3); geometry->index.push_back(geometry->tVertex.size() - 2); geometry->index.push_back(geometry->tVertex.size() - 1); normal = ((a - c).cross(d - c)).normalize(); geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(dUV); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(cUV); geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(aUV); geometry->index.push_back(geometry->tVertex.size() - 3); geometry->index.push_back(geometry->tVertex.size() - 2); geometry->index.push_back(geometry->tVertex.size() - 1); } } if (!openEnded) { this->segmentsH -= 2; } Vec3 min = geometry->tVertex[0]; for (uint32 i = 0; i < geometry->tVertex.size(); i++) { if (geometry->tVertex[i].x < min.x) min.x = geometry->tVertex[i].x; if (geometry->tVertex[i].y < min.y) min.y = geometry->tVertex[i].y; if (geometry->tVertex[i].z < min.z) min.z = geometry->tVertex[i].z; geometry->tTexcoord[i].x = 1 - geometry->tTexcoord[i].x; } Build(); // Bounding Box minBounds = min; maxBounds = min.negate(); // Bounding Sphere BoundingSphereCenter = Vec3(0, 0, 0); BoundingSphereRadius = min.distance(Vec3::ZERO); } };
30.286765
166
0.585336
Peixinho
2d78bedbb075d63f155dbaf249b1eca044d25218
1,882
cpp
C++
utils/add_preimage_to_signed_tx.cpp
jmjatlanta/bitcoin-toolbox
26dd27004c0e3ef13046b0aa598fba3f11dcbcc2
[ "MIT" ]
null
null
null
utils/add_preimage_to_signed_tx.cpp
jmjatlanta/bitcoin-toolbox
26dd27004c0e3ef13046b0aa598fba3f11dcbcc2
[ "MIT" ]
null
null
null
utils/add_preimage_to_signed_tx.cpp
jmjatlanta/bitcoin-toolbox
26dd27004c0e3ef13046b0aa598fba3f11dcbcc2
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <cstdint> #include <rapidjson/rapidjson.h> #include <rapidjson/document.h> #include <transaction.hpp> #include <hex_conversion.hpp> #include <script.hpp> void print_syntax_and_exit(int argc, char**argv) { std::cerr << "Syntax: " << argv[0] << " signed_tx_json_file preimage_as_string public_key_as_hex_string\n"; exit(1); } std::string read_json_file(std::string filename) { std::ifstream f(filename); std::string str((std::istreambuf_iterator<char>(f)),std::istreambuf_iterator<char>()); return str; } int main(int argc, char** argv) { if (argc < 4) print_syntax_and_exit(argc, argv); // first parameter is the signed transaction as a string std::string tx_as_json = read_json_file(argv[1]); rapidjson::Document doc; doc.Parse(tx_as_json.c_str()); rapidjson::Value& tx_as_value = doc["hex"]; std::string tx_as_string = tx_as_value.GetString(); // second parameter is the preimage std::string preimage_string(argv[2]); std::vector<uint8_t> preimage(preimage_string.begin(), preimage_string.end()); // third parameter is the public key std::vector<uint8_t> public_key = bc_toolbox::hex_string_to_vector(std::string(argv[3])); // build the script bc_toolbox::script new_script; new_script.add_bytes_with_size(public_key); new_script.add_bytes_with_size(preimage); // convert tx_as_string back to a transaction bc_toolbox::transaction tx( bc_toolbox::hex_string_to_vector(tx_as_string) ); bc_toolbox::input& in = tx.inputs.at(0); // merge the two scripts std::vector<uint8_t> merged_script = new_script.get_bytes_as_vector(); merged_script.insert(merged_script.end(), in.sig_script.begin(), in.sig_script.end() ); in.sig_script = merged_script; std::cout << bc_toolbox::vector_to_hex_string( tx.to_bytes() ); }
31.366667
110
0.723167
jmjatlanta
2d7b32c84a48cb870a90be6b2bde752380007605
149
hpp
C++
Plus7/Modules/Gfx/Include/DepthState.hpp
txfx/plus7
44df3622ea8abe296d921759144e5f0d630b2945
[ "MIT" ]
null
null
null
Plus7/Modules/Gfx/Include/DepthState.hpp
txfx/plus7
44df3622ea8abe296d921759144e5f0d630b2945
[ "MIT" ]
null
null
null
Plus7/Modules/Gfx/Include/DepthState.hpp
txfx/plus7
44df3622ea8abe296d921759144e5f0d630b2945
[ "MIT" ]
null
null
null
#pragma once #include "SdlGl/GlDepthState.hpp" namespace p7 { namespace gfx { using DepthState = GlDepthState; } // namespace gfx } // namespace p7
16.555556
33
0.738255
txfx
2d7f02109fb7da4fb5f8cd8d7e38ce2635d69bd7
7,211
inl
C++
inc/lak/binary_writer.inl
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
3
2021-07-12T02:32:50.000Z
2022-01-30T03:39:53.000Z
inc/lak/binary_writer.inl
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
1
2020-11-03T08:57:04.000Z
2020-11-03T09:04:41.000Z
inc/lak/binary_writer.inl
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
null
null
null
#include "lak/binary_writer.hpp" #include "lak/memmanip.hpp" #include "lak/span_manip.hpp" #include "lak/debug.hpp" /* --- to_bytes --- */ template<typename T, lak::endian E> void lak::to_bytes(lak::span<byte_t, lak::to_bytes_size_v<T, E>> bytes, const T &value) { lak::to_bytes_traits<T, E>::to_bytes(lak::to_bytes_data<T, E>::make( bytes, lak::span<const T, 1>::from_ptr(&value))); } template<typename T, lak::endian E> lak::result<> lak::to_bytes(lak::span<byte_t> bytes, const T &value) { return lak::first_as_const_sized<lak::to_bytes_size_v<T, E>>(bytes).map( [&value](auto bytes) { lak::to_bytes(bytes, value); return lak::monostate{}; }); } template<typename T, lak::endian E> lak::array<byte_t, lak::to_bytes_size_v<T, E>> lak::to_bytes(const T &value) { lak::array<byte_t, lak::to_bytes_size_v<T, E>> result; lak::to_bytes(lak::span<byte_t, lak::to_bytes_size_v<T, E>>(result), value); return result; } /* --- array_to_bytes --- */ template<typename T, size_t S, lak::endian E> lak::array<byte_t, S * lak::to_bytes_size_v<T, E>> lak::array_to_bytes( lak::span<const T, S> values) { lak::array<byte_t, S * lak::to_bytes_size_v<T, E>> result; lak::to_bytes_traits<T, E>::to_bytes(lak::to_bytes_data<T, E>::make( lak::span<byte_t, S * lak::to_bytes_size_v<T, E>>(result), lak::span<const T, S>(values))); return result; } template<typename T, lak::endian E> lak::array<byte_t> lak::array_to_bytes(lak::span<const T> values) { lak::array<byte_t> result; result.resize(values.size() * lak::to_bytes_size_v<T, E>); lak::to_bytes_traits<T, E>::to_bytes( lak::to_bytes_data<T, E>::maybe_make(lak::span<byte_t>(result), values) .unwrap()); return result; } template<typename T, lak::endian E> lak::result<> lak::array_to_bytes(lak::span<byte_t> bytes, lak::span<const T> values) { return lak::to_bytes_data<T, E>::maybe_make(bytes, values) .map( [](lak::to_bytes_data<T, E> data) { lak::to_bytes_traits<T, E>::to_bytes(data); return lak::monostate{}; }); } namespace lak { template<typename T, lak::endian E> inline void _basic_memcpy_to_bytes(lak::to_bytes_data<T, E> data) { static_assert(E == lak::endian::native || ~E == lak::endian::native); lak::memcpy(data.dst, lak::span<const byte_t>(data.src)); if constexpr (E != lak::endian::native) lak::byte_swap(data.dst); } } /* --- byte_t --- */ template<lak::endian E> struct lak::to_bytes_traits<byte_t, E> { using value_type = byte_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::memcpy(data.dst, data.src); } }; /* --- uint8_t --- */ template<lak::endian E> struct lak::to_bytes_traits<uint8_t, E> { using value_type = uint8_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::memcpy(data.dst, lak::span<const byte_t>(data.src)); } }; /* --- int8_t --- */ template<lak::endian E> struct lak::to_bytes_traits<int8_t, E> { using value_type = int8_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::memcpy(data.dst, lak::span<const byte_t>(data.src)); } }; /* --- uint16_t --- */ template<lak::endian E> struct lak::to_bytes_traits<uint16_t, E> { using value_type = uint16_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- int16_t --- */ template<lak::endian E> struct lak::to_bytes_traits<int16_t, E> { using value_type = int16_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- uint32_t --- */ template<lak::endian E> struct lak::to_bytes_traits<uint32_t, E> { using value_type = uint32_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- int32_t --- */ template<lak::endian E> struct lak::to_bytes_traits<int32_t, E> { using value_type = int32_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- uint64_t --- */ template<lak::endian E> struct lak::to_bytes_traits<uint64_t, E> { using value_type = uint64_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- int64_t --- */ template<lak::endian E> struct lak::to_bytes_traits<int64_t, E> { using value_type = int64_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- f32_t --- */ template<lak::endian E> struct lak::to_bytes_traits<f32_t, E> { using value_type = f32_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- f64_t --- */ template<lak::endian E> struct lak::to_bytes_traits<f64_t, E> { using value_type = f64_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- char --- */ template<lak::endian E> struct lak::to_bytes_traits<char, E> { using value_type = char; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::memcpy(data.dst, lak::span<const byte_t>(data.src)); } }; #ifdef LAK_COMPILER_CPP20 /* --- char8_t --- */ template<lak::endian E> struct lak::to_bytes_traits<char8_t, E> { using value_type = char8_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::memcpy(data.dst, lak::span<const byte_t>(data.src)); } }; #endif /* --- char16_t --- */ template<lak::endian E> struct lak::to_bytes_traits<char16_t, E> { using value_type = char16_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- char32_t --- */ template<lak::endian E> struct lak::to_bytes_traits<char32_t, E> { using value_type = char32_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } }; /* --- wchar_t --- */ template<lak::endian E> struct lak::to_bytes_traits<wchar_t, E> { using value_type = wchar_t; static constexpr size_t size = sizeof(value_type); static void to_bytes(lak::to_bytes_data<value_type, E> data) { lak::_basic_memcpy_to_bytes(data); } };
23.33657
77
0.669394
LAK132
2d83dbe4e3b3ae914b47bef9ddbbf9324897e666
13,598
cpp
C++
src/common/ob_obj_type.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
74
2021-05-31T15:23:49.000Z
2022-03-12T04:46:39.000Z
src/common/ob_obj_type.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
16
2021-05-31T15:26:38.000Z
2022-03-30T06:02:43.000Z
src/common/ob_obj_type.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
64
2021-05-31T15:25:36.000Z
2022-02-23T08:43:58.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #include <float.h> #include "lib/ob_define.h" #include "common/ob_obj_type.h" #include "lib/charset/ob_charset.h" namespace oceanbase { namespace common { const char *ob_obj_type_str(ObObjType type) { return ob_sql_type_str(type); } const char *ob_obj_tc_str(ObObjTypeClass tc) { return ob_sql_tc_str(tc); } const char *ob_sql_type_str(ObObjType type) { static const char *sql_type_name[ObMaxType+1] = { "NULL", "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT", "TINYINT UNSIGNED", "SMALLINT UNSIGNED", "MEDIUMINT UNSIGNED", "INT UNSIGNED", "BIGINT UNSIGNED", "FLOAT", "DOUBLE", "FLOAT UNSIGNED", "DOUBLE UNSIGNED", "DECIMAL", "DECIMAL UNSIGNED", "DATETIME", "TIMESTAMP", "DATE", "TIME", "YEAR", "VARCHAR", "CHAR", "HEX_STRING", "EXT", "UNKNOWN", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT", "" }; return sql_type_name[OB_LIKELY(type < ObMaxType) ? type : ObMaxType]; } typedef int (*obSqlTypeStrFunc)(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type); //For date, null/unkown/max/extend #define DEF_TYPE_STR_FUNCS(TYPE, STYPE1, STYPE2) \ int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type)\ { \ int ret = OB_SUCCESS; \ UNUSED(length); \ UNUSED(precision); \ UNUSED(scale); \ UNUSED(coll_type); \ int64_t pos = 0; \ ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \ return ret; \ } //For tinyint/smallint/mediumint/int/bigint (unsigned), year #define DEF_TYPE_STR_FUNCS_PRECISION(TYPE, STYPE1, STYPE2) \ int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type)\ { \ int ret = OB_SUCCESS; \ UNUSED(length); \ UNUSED(scale); \ UNUSED(coll_type); \ int64_t pos = 0; \ if (precision < 0) { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \ } else { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld)" STYPE2, precision); \ } \ return ret; \ } //For datetime/timestamp/time #define DEF_TYPE_STR_FUNCS_SCALE(TYPE, STYPE1, STYPE2) \ int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) \ { \ int ret = OB_SUCCESS; \ UNUSED(length); \ UNUSED(precision); \ UNUSED(coll_type); \ int64_t pos = 0; \ if (scale <= 0) { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \ } else { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld)" STYPE2, scale); \ } \ return ret; \ } //For number/float/double (unsigned) #define DEF_TYPE_STR_FUNCS_PRECISION_SCALE(TYPE, STYPE1, STYPE2) \ int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) \ { \ int ret = OB_SUCCESS; \ UNUSED(length); \ UNUSED(coll_type); \ int64_t pos = 0; \ if (precision < 0 && scale < 0) { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \ } else { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld,%ld)" STYPE2, precision, scale); \ } \ return ret; \ } //For char/varchar #define DEF_TYPE_STR_FUNCS_LENGTH(TYPE, STYPE1, STYPE2) \ int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) \ { \ int ret = OB_SUCCESS; \ UNUSED(precision); \ UNUSED(scale) ; \ int64_t pos = 0; \ if (CS_TYPE_BINARY == coll_type) { \ ret = databuff_printf(buff, buff_length, pos, STYPE2 "(%ld)", length); \ } else { \ ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld)", length); \ } \ return ret; \ } DEF_TYPE_STR_FUNCS(null, "null", ""); DEF_TYPE_STR_FUNCS_PRECISION(tinyint, "tinyint", ""); DEF_TYPE_STR_FUNCS_PRECISION(smallint, "smallint", ""); DEF_TYPE_STR_FUNCS_PRECISION(mediumint, "mediumint", ""); DEF_TYPE_STR_FUNCS_PRECISION(int, "int", ""); DEF_TYPE_STR_FUNCS_PRECISION(bigint, "bigint", ""); DEF_TYPE_STR_FUNCS_PRECISION(utinyint, "tinyint", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION(usmallint, "smallint", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION(umediumint, "mediumint", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION(uint, "int", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION(ubigint, "bigint", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION_SCALE(float, "float", ""); DEF_TYPE_STR_FUNCS_PRECISION_SCALE(double, "double", ""); DEF_TYPE_STR_FUNCS_PRECISION_SCALE(ufloat, "float", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION_SCALE(udouble, "double", " unsigned"); DEF_TYPE_STR_FUNCS_PRECISION_SCALE(number, "decimal", ""); DEF_TYPE_STR_FUNCS_PRECISION_SCALE(unumber, "decimal", " unsigned"); DEF_TYPE_STR_FUNCS_SCALE(datetime, "datetime", ""); DEF_TYPE_STR_FUNCS_SCALE(timestamp, "timestamp", ""); DEF_TYPE_STR_FUNCS(date, "date", ""); DEF_TYPE_STR_FUNCS_SCALE(time, "time", ""); DEF_TYPE_STR_FUNCS_PRECISION(year, "year", ""); DEF_TYPE_STR_FUNCS_LENGTH(varchar, "varchar", "varbinary"); DEF_TYPE_STR_FUNCS_LENGTH(char, "char", "binary"); DEF_TYPE_STR_FUNCS_LENGTH(hex_string, "hex_string", "hex_string"); DEF_TYPE_STR_FUNCS(extend, "ext", ""); DEF_TYPE_STR_FUNCS(unknown, "unknown", ""); DEF_TYPE_STR_FUNCS_LENGTH(tinytext, "tinytext", "tinyblob"); DEF_TYPE_STR_FUNCS_LENGTH(text, "text", "blob"); DEF_TYPE_STR_FUNCS_LENGTH(mediumtext, "mediumtext", "mediumblob"); DEF_TYPE_STR_FUNCS_LENGTH(longtext, "longtext", "longblob"); int ob_empty_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) { int ret = OB_SUCCESS; UNUSED(length); UNUSED(scale) ; UNUSED(precision); UNUSED(coll_type); if (buff_length > 0) { buff[0] = '\0'; } return ret; } int ob_sql_type_str(char *buff, int64_t buff_length, ObObjType type, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) { static obSqlTypeStrFunc sql_type_name[ObMaxType+1] = { ob_null_str, // NULL ob_tinyint_str, // TINYINT ob_smallint_str, // SAMLLINT ob_mediumint_str, // MEDIUM ob_int_str, // INT ob_bigint_str, // BIGINT ob_utinyint_str, // TYIYINT UNSIGNED ob_usmallint_str, // SMALLINT UNSIGNED ob_umediumint_str, // MEDIUM UNSIGNED ob_uint_str, // INT UNSIGNED ob_ubigint_str, // BIGINT UNSIGNED ob_float_str, // FLOAT ob_double_str, // DOUBLE ob_ufloat_str, // FLOAT UNSIGNED ob_udouble_str, // DOUBLE UNSIGNED ob_number_str, // DECIMAL ob_unumber_str, // DECIMAL UNSIGNED ob_datetime_str, // DATETIME ob_timestamp_str, // TIMESTAMP ob_date_str, // DATE ob_time_str, // TIME ob_year_str, // YEAR ob_varchar_str, // VARCHAR ob_char_str, // CHAR ob_hex_string_str, // HEX_STRING ob_extend_str, // EXT ob_unknown_str, // UNKNOWN ob_tinytext_str, //TINYTEXT ob_text_str, //TEXT ob_mediumtext_str, //MEDIUMTEXT ob_longtext_str, //LONGTEXT ob_empty_str // MAX }; return sql_type_name[OB_LIKELY(type < ObMaxType) ? type : ObMaxType](buff, buff_length, length, precision, scale, coll_type); } //DEF_TYPE_STR_FUNCS(number, "decimal", ""); const char *ob_sql_tc_str(ObObjTypeClass tc) { static const char *sql_tc_name[] = { "NULL", "INT", "UINT", "FLOAT", "DOUBLE", "DECIMAL", "DATETIME", "DATE", "TIME", "YEAR", "STRING", "EXT", "UNKNOWN", "TEXT", "" }; return sql_tc_name[OB_LIKELY(tc < ObMaxTC) ? tc : ObMaxTC]; } int32_t ob_obj_type_size(ObObjType type) { int32_t size = 0; UNUSED(type); // @todo return size; } #ifndef INT24_MIN #define INT24_MIN (-8388607 - 1) #endif #ifndef INT24_MAX #define INT24_MAX (8388607) #endif #ifndef UINT24_MAX #define UINT24_MAX (16777215U) #endif const int64_t INT_MIN_VAL[ObMaxType] = { 0, // null. INT8_MIN, INT16_MIN, INT24_MIN, INT32_MIN, INT64_MIN }; const int64_t INT_MAX_VAL[ObMaxType] = { 0, // null. INT8_MAX, INT16_MAX, INT24_MAX, INT32_MAX, INT64_MAX }; const uint64_t UINT_MAX_VAL[ObMaxType] = { 0, // null. 0, 0, 0, 0, 0, // int8, int16, int24, int32, int64. UINT8_MAX, UINT16_MAX, UINT24_MAX, UINT32_MAX, UINT64_MAX }; const double REAL_MIN_VAL[ObMaxType] = { 0.0, // null. 0.0, 0.0, 0.0, 0.0, 0.0, // int8, int16, int24, int32, int64. 0.0, 0.0, 0.0, 0.0, 0.0, // uint8, uint16, uint24, uint32, uint64. -FLT_MAX, -DBL_MAX, 0.0, 0.0 }; const double REAL_MAX_VAL[ObMaxType] = { 0.0, // null. 0.0, 0.0, 0.0, 0.0, 0.0, // int8, int16, int24, int32, int64. 0.0, 0.0, 0.0, 0.0, 0.0, // uint8, uint16, uint24, uint32, uint64. FLT_MAX, DBL_MAX, FLT_MAX, DBL_MAX }; } // common } // oceanbase
38.412429
145
0.474482
stutiredboy
2d85b453c4050e3c09b02049df1cafbea26612cf
688
cpp
C++
src/BH1750.cpp
JVKran/OneTimeBH1750
132515b2099f1f96e5c13cca92269151f57850f7
[ "Apache-2.0" ]
1
2020-11-24T05:27:33.000Z
2020-11-24T05:27:33.000Z
src/BH1750.cpp
JVKran/OneTimeBH1750
132515b2099f1f96e5c13cca92269151f57850f7
[ "Apache-2.0" ]
null
null
null
src/BH1750.cpp
JVKran/OneTimeBH1750
132515b2099f1f96e5c13cca92269151f57850f7
[ "Apache-2.0" ]
1
2021-05-07T18:47:46.000Z
2021-05-07T18:47:46.000Z
/* OneTime-BH1750 Library Jochem van Kranenburg - jochemvk.duckdns.org - 9 March 2020 */ #include "BH1750.h" #ifdef BH1750_ATTINY BH1750::BH1750(USI_TWI & bus, const uint8_t address): bus(bus), address(address) {} #else BH1750::BH1750(TwoWire & bus, const uint8_t address): bus(bus), address(address) {} #endif void BH1750::begin(){ bus.begin(); } uint16_t BH1750::getLightIntensity(){ bus.beginTransmission(address); bus.write((uint8_t)opCodes::ONE_TIME_LOW_RES); bus.endTransmission(); delay((uint8_t)measurementDurations::LOW_RES_MEAS_TIME); bus.requestFrom(address, (uint8_t)2); uint16_t intensity = bus.read() << 8; intensity |= bus.read(); return intensity; }
19.657143
62
0.728198
JVKran
2d88e7ce82d6248f3d63d2278c6f91572baeb2df
544
cpp
C++
LeetCode/ThousandOne/0397-int_replacement.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0397-int_replacement.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0397-int_replacement.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 397. 整数替换 给定一个正整数 n,你可以做如下操作: 1. 如果 n 是偶数,则用 n / 2替换 n。 2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。 n 变为 1 所需的最小替换次数是多少? 示例 1: 输入: 8 输出: 3 解释: 8 -> 4 -> 2 -> 1 示例 2: 输入: 7 输出: 4 解释: 7 -> 8 -> 4 -> 2 -> 1 或 7 -> 6 -> 3 -> 2 -> 1 */ // 抄的,3 真是够了 int integerReplacement(int _n) { int ans = 0; uint32_t u = _n; for (; u != 1; ++ans) { if (u & 1) { if (u > 4 && (u & 3) == 3) u += 1; else u -= 1; } else u >>= 1; } return ans; } int main() { OutExpr(integerReplacement(100000000), "%d"); }
9.714286
46
0.481618
Ginkgo-Biloba
2d8bb4e1f22ea74f51b8845d67bc58bd9ffab508
10,219
cpp
C++
src/obproxy/utils/ob_proxy_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
74
2021-05-31T15:23:49.000Z
2022-03-12T04:46:39.000Z
src/obproxy/utils/ob_proxy_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
16
2021-05-31T15:26:38.000Z
2022-03-30T06:02:43.000Z
src/obproxy/utils/ob_proxy_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
64
2021-05-31T15:25:36.000Z
2022-02-23T08:43:58.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX PROXY #include "utils/ob_proxy_utils.h" #include "utils/ob_proxy_lib.h" #include "lib/file/ob_file.h" #include "lib/time/ob_time_utility.h" using namespace oceanbase::common; namespace oceanbase { namespace obproxy { const char *OBPROXY_TIMESTAMP_VERSION_FORMAT = "%Y%m%d%H%i%s%f"; bool ObRandomNumUtils::is_seed_inited_ = false; int64_t ObRandomNumUtils::seed_ = -1; int ObRandomNumUtils::get_random_num(const int64_t min, const int64_t max, int64_t &random_num) { int ret = OB_SUCCESS; random_num = 0; if (OB_UNLIKELY(min > max)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid input value", K(min), K(max), K(ret)); } else if (!is_seed_inited_) { if (OB_FAIL(init_seed())) { LOG_WARN("fail to init random seed", K(ret)); } } if (OB_SUCC(ret)) { random_num = min + random() % (max - min + 1); } return ret; } int64_t ObRandomNumUtils::get_random_half_to_full(const int64_t full_num) { int ret = OB_SUCCESS; int64_t ret_value = 0; if (OB_UNLIKELY(full_num < 0)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid input value", K(full_num), K(ret)); } else if (OB_UNLIKELY(0 == full_num)) { LOG_INFO("full_num is zero, will return 0 as random num"); } else if (OB_FAIL(get_random_num(full_num / 2, full_num, ret_value))) { LOG_WARN("fail to get random num, will return full_num as random num", K(ret)); ret_value = full_num; } else {/*do nothing*/} return ret_value; } int ObRandomNumUtils::init_seed() { int ret = OB_SUCCESS; if (OB_LIKELY(!is_seed_inited_)) { if (OB_FAIL(get_random_seed(seed_))) { LOG_WARN("fail to get random seed", K(ret)); } else { srandom(static_cast<uint32_t>(seed_)); is_seed_inited_ = true; } } return ret; } int ObRandomNumUtils::get_random_seed(int64_t &seed) { int ret = OB_SUCCESS; ObFileReader file_reader; const bool dio = false; if (OB_FAIL(file_reader.open(ObString::make_string("/dev/urandom"), dio))) { LOG_WARN("fail to open /dev/urandom", KERRMSGS, K(ret)); } else { int64_t random_value = 0; int64_t ret_size = 0; int64_t read_size = sizeof(random_value); int64_t offset = 0; char *buf = reinterpret_cast<char *>(&random_value); if (OB_FAIL(file_reader.pread(buf, read_size, offset, ret_size))) { LOG_WARN("fail to read", KERRMSGS, K(ret)); } else if (OB_UNLIKELY(read_size != ret_size)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("readed data is not enough", K(read_size), K(ret_size), K(ret)); } else { seed = labs(random_value); } file_reader.close(); } return ret; } int get_int_value(const ObString &str, int64_t &value, const int radix /*10*/) { int ret = OB_SUCCESS; if (OB_UNLIKELY(str.empty())) { ret = OB_INVALID_ARGUMENT; LOG_WARN("str is empty", K(str), K(ret)); } else { static const int32_t MAX_INT64_STORE_LEN = 31; char int_buf[MAX_INT64_STORE_LEN + 1]; int64_t len = std::min(str.length(), MAX_INT64_STORE_LEN); MEMCPY(int_buf, str.ptr(), len); int_buf[len] = '\0'; char *end_ptr = NULL; value = strtoll(int_buf, &end_ptr, radix); if (('\0' != *int_buf ) && ('\0' == *end_ptr)) { // succ, do nothing } else { ret = OB_INVALID_DATA; LOG_WARN("invalid int value", K(value), K(ret), K(str)); } } return ret; } int get_double_value(const ObString &str, double &value) { int ret = OB_SUCCESS; if (OB_UNLIKELY(str.empty())) { ret = OB_INVALID_ARGUMENT; LOG_WARN("str is empty", K(str), K(ret)); } else { double ret_val = 0.0; static const int32_t MAX_UINT64_STORE_LEN = 32; char double_buf[MAX_UINT64_STORE_LEN + 1]; int64_t len = std::min(str.length(), static_cast<ObString::obstr_size_t>(MAX_UINT64_STORE_LEN)); MEMCPY(double_buf, str.ptr(), len); double_buf[len] = '\0'; char *end_ptr = NULL; ret_val = strtod(double_buf, &end_ptr); if (('\0' != *double_buf ) && ('\0' == *end_ptr)) { value = ret_val; } else { ret = OB_INVALID_DATA; LOG_WARN("invalid dobule value", K(value), K(str), K(ret)); } } return ret; } bool has_upper_case_letter(common::ObString &string) { bool bret = false; if (OB_LIKELY(NULL != string.ptr())) { int64_t length = static_cast<int64_t>(string.length()); for (int64_t i = 0; !bret && i < length; ++i) { if (string[i] >= 'A' && string[i] <= 'Z') { bret = true; } } } return bret; } void string_to_lower_case(char *str, const int32_t str_len) { if (OB_LIKELY(NULL != str) && OB_LIKELY(str_len > 0)) { for (int32_t i = 0; NULL != str && i < str_len; ++i, ++str) { if ((*str) >= 'A' && (*str) <= 'Z') { (*str) = static_cast<char>((*str) + 32); } } } } void string_to_upper_case(char *str, const int32_t str_len) { if (OB_LIKELY(NULL != str) && OB_LIKELY(str_len > 0)) { for (int32_t i = 0; NULL != str && i < str_len; ++i, ++str) { if ((*str) >= 'a' && (*str) <= 'z') { (*str) = static_cast<char>((*str) - 32); } } } } bool is_available_md5(const ObString &string) { bool bret = true; if (!string.empty() && OB_DEFAULT_PROXY_MD5_LEN == string.length()) { for (int64_t i = 0; bret && i < OB_DEFAULT_PROXY_MD5_LEN; ++i) { if (string[i] < '0' || ('9' < string[i] && string[i] < 'a') || string[i] > 'z') { bret = false; } } } else { bret = false; } return bret; } ObString trim_header_space(const ObString &input) { ObString ret; if (NULL != input.ptr()) { const char *ptr = input.ptr(); ObString::obstr_size_t start = 0; ObString::obstr_size_t end = input.length(); while (start < end && IS_SPACE(ptr[start])) { start++; } ret.assign_ptr(input.ptr() + start, end - start); } return ret; } ObString trim_tailer_space(const ObString &input) { ObString ret; if (NULL != input.ptr()) { const char *ptr = input.ptr(); ObString::obstr_size_t start = 0; ObString::obstr_size_t end = input.length(); while (start < end && IS_SPACE(ptr[end - 1])) { end--; } ret.assign_ptr(input.ptr() + start, end - start); } return ret; } common::ObString trim_quote(const common::ObString &input) { ObString ret; //trim single quotes if (!input.empty() && input.length() > 1) { if ('\'' == input[0] && '\'' == input[input.length() - 1]) { ret.assign_ptr(input.ptr() + 1, input.length() - 2); } } else { ret.assign_ptr(input.ptr(), input.length()); } return ret; } int str_replace(char *input_buf, const int32_t input_size, char *output_buf, const int32_t output_size, const char *target_key, const int32_t target_key_len, const ObString &target_value, int32_t &output_pos) { int ret = OB_SUCCESS; if (OB_ISNULL(input_buf) || OB_UNLIKELY(input_size <= 0) || OB_ISNULL(output_buf) || OB_UNLIKELY(output_size <= 0) || OB_ISNULL(target_key) || OB_UNLIKELY(target_key_len <= 0) || OB_UNLIKELY(output_pos < 0) || OB_UNLIKELY(output_pos >= output_size)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid_argument", KP(input_buf), K(input_size), KP(output_buf), K(output_size), KP(target_key), K(target_key_len), K(output_pos), K(ret)); } else { char *found_ptr = NULL; int32_t ipos = 0; int32_t copy_len = 0; while (OB_SUCC(ret) && ipos < input_size && NULL != (found_ptr = strstr(input_buf + ipos, target_key))) { copy_len = static_cast<int32_t>(found_ptr - input_buf - ipos); if (output_pos + copy_len < output_size) { memcpy(output_buf + output_pos, input_buf + ipos, copy_len); output_pos += copy_len; ipos += (copy_len + target_key_len); if (!target_value.empty()) { copy_len = target_value.length(); if (output_pos + copy_len < output_size) { memcpy(output_buf + output_pos, target_value.ptr(), copy_len); output_pos += copy_len; } else { ret = OB_SIZE_OVERFLOW; LOG_INFO("size is overflow", K(output_pos), K(copy_len), K(output_size), K(ret)); } } } else { ret = OB_SIZE_OVERFLOW; LOG_INFO("size is overflow", K(output_pos), K(copy_len), K(output_size), K(ret)); } } if (OB_SUCC(ret) && ipos < input_size) { copy_len = input_size - ipos; if (output_pos < output_size && output_pos + copy_len < output_size) { memcpy(output_buf + output_pos, input_buf + ipos, copy_len); output_pos += copy_len; } else { ret = OB_SIZE_OVERFLOW; LOG_INFO("size is overflow", K(output_pos), K(copy_len), K(output_size), K(ret)); } } ObString key(target_key_len, target_key); ObString input(input_size, input_buf); ObString output(output_pos, output_buf); LOG_DEBUG("finish str_replace", K(key), K(target_value), K(input), K(output), K(ret)); } return ret; } int convert_timestamp_to_version(int64_t time_us, char *buf, int64_t len) { int ret = OB_SUCCESS; int64_t pos = 0; if (OB_FAIL(ObTimeUtility::usec_format_to_str(time_us, ObString(OBPROXY_TIMESTAMP_VERSION_FORMAT), buf, len, pos))) { LOG_WARN("fail to format timestamp to str", K(time_us), K(ret)); } else if (OB_UNLIKELY(pos < 3)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid timestamp", K(time_us), K(pos), K(ret)); } else { buf[pos - 3] = '\0'; // ms } return ret; } } // end of namespace obproxy } // end of namespace oceanbase
30.873112
100
0.620609
stutiredboy
2d8cfdec4c380009d3527bebf17e9f376ee006e6
3,689
hpp
C++
inc/state/interfacelogicaldevices.hpp
wolfviking0/vuda
4d3593c9e06a1ff3399078e377a92ec26627c483
[ "MIT" ]
null
null
null
inc/state/interfacelogicaldevices.hpp
wolfviking0/vuda
4d3593c9e06a1ff3399078e377a92ec26627c483
[ "MIT" ]
null
null
null
inc/state/interfacelogicaldevices.hpp
wolfviking0/vuda
4d3593c9e06a1ff3399078e377a92ec26627c483
[ "MIT" ]
null
null
null
#pragma once namespace vuda { namespace detail { // // singleton interface for vulkan logical devices // class interface_logical_devices final : public singleton { public: static logical_device* create(const vk::PhysicalDevice& physDevice, const int device) { std::unordered_map<int, logical_device>::iterator iter; // // take exclusive lock // [ contention ] std::lock_guard<std::shared_mutex> lck(mtx()); // // return the logical device if it exists iter = get().find(device); if (iter != get().end()) return &iter->second; // // create a logical device if it is not already in existence return create_logical_device(physDevice, device); } private: static std::unordered_map<int, logical_device>& get(void) { static std::unordered_map<int, logical_device> local_logical_devices; return local_logical_devices; } static std::shared_mutex& mtx(void) { static std::shared_mutex local_mtx; return local_mtx; } /*static std::atomic_flag& writers_lock_af(void) { static std::atomic_flag wlock = ATOMIC_FLAG_INIT; return wlock; } static std::atomic<bool>& writers_lock(void) { static std::atomic<bool> wlock = false; return wlock; } static std::condition_variable_any& cv(void) { static std::condition_variable_any cv; return cv; }*/ static logical_device* create_logical_device(const vk::PhysicalDevice& physDevice, const int device) { // // get physical device // const vk::PhysicalDevice& physDevice = Instance::GetPhysicalDevice(device); // // get the QueueFamilyProperties of the PhysicalDevice std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physDevice.getQueueFamilyProperties(); // // get the first index into queueFamiliyProperties which supports compute uint32_t computeQueueFamilyIndex = detail::vudaGetFamilyQueueIndex(queueFamilyProperties, vk::QueueFlagBits::eCompute | vk::QueueFlagBits::eTransfer); // // HARDCODED MAX NUMBER OF STREAMS const uint32_t queueCount = queueFamilyProperties[computeQueueFamilyIndex].queueCount; const uint32_t queueComputeCount = queueCount; const std::vector<float> queuePriority(queueComputeCount, 0.0f); vk::DeviceQueueCreateInfo deviceQueueCreateInfo(vk::DeviceQueueCreateFlags(), computeQueueFamilyIndex, queueComputeCount, queuePriority.data()); #ifdef VUDA_STD_LAYER_ENABLED vk::DeviceCreateInfo info(vk::DeviceCreateFlags(), 1, &deviceQueueCreateInfo, 1, Instance::vk_validationLayers.data(), 0, nullptr, nullptr); #else vk::DeviceCreateInfo info(vk::DeviceCreateFlags(), 1, &deviceQueueCreateInfo); #endif // get().insert({ device, logical_device(info, physDevice) }); // auto pair = get().emplace(std::piecewise_construct, std::forward_as_tuple(device), std::forward_as_tuple(info, physDevice)); // c++17 auto pair = get().try_emplace(device, info, physDevice); assert(pair.second); return &pair.first->second; } }; } // namespace detail } // namespace vuda
37.262626
163
0.597723
wolfviking0
2d93e16a5984a75ba0dde7597f7d11447fea1331
2,706
cpp
C++
mpc_least_square_engl/matrix.cpp
pronenewbits/Arduino_Unconstrained_MPC_Library
e406fe1edabfaf240d0884975d0b1caf869367cb
[ "CC0-1.0" ]
38
2020-01-14T20:08:00.000Z
2022-03-05T03:12:27.000Z
mpc_opt_engl/matrix.cpp
pronenewbits/Arduino_MPC_Library
e406fe1edabfaf240d0884975d0b1caf869367cb
[ "CC0-1.0" ]
1
2021-08-25T12:40:27.000Z
2021-08-25T12:40:27.000Z
mpc_opt_engl/matrix.cpp
pronenewbits/Arduino_MPC_Library
e406fe1edabfaf240d0884975d0b1caf869367cb
[ "CC0-1.0" ]
6
2020-03-29T14:58:44.000Z
2022-03-05T03:12:29.000Z
/************************************************************************************ * Class Matrix * See matrix.h for description * * See https://github.com/pronenewbits for more! *************************************************************************************/ #include "matrix.h" Matrix operator + (const float_prec _scalar, Matrix _mat) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _scalar + _mat[_i][_j]; } } return _outp; } Matrix operator - (const float_prec _scalar, Matrix _mat) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _scalar - _mat[_i][_j]; } } return _outp; } Matrix operator * (const float_prec _scalar, Matrix _mat) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _scalar * _mat[_i][_j]; } } return _outp; } Matrix operator + (Matrix _mat, const float_prec _scalar) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _mat[_i][_j] + _scalar; } } return _outp; } Matrix operator - (Matrix _mat, const float_prec _scalar) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _mat[_i][_j] - _scalar; } } return _outp; } Matrix operator * (Matrix _mat, const float_prec _scalar) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _mat[_i][_j] * _scalar; } } return _outp; } Matrix operator / (Matrix _mat, const float_prec _scalar) { Matrix _outp(_mat.i32getRow(), _mat.i32getColumn()); if (fabs(_scalar) < float_prec(float_prec_ZERO)) { _outp.vSetMatrixInvalid(); return _outp; } for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) { for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) { _outp[_i][_j] = _mat[_i][_j] / _scalar; } } return _outp; }
25.528302
87
0.533629
pronenewbits
2d9599f506676e2daf5556c68954dee54ad6dc3f
1,545
hpp
C++
plugins/opengl/include/sge/opengl/vf/client_state_combiner.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/include/sge/opengl/vf/client_state_combiner.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/include/sge/opengl/vf/client_state_combiner.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_OPENGL_VF_CLIENT_STATE_COMBINER_HPP_INCLUDED #define SGE_OPENGL_VF_CLIENT_STATE_COMBINER_HPP_INCLUDED #include <sge/opengl/context/object_ref.hpp> #include <sge/opengl/vf/attribute_context_fwd.hpp> #include <sge/opengl/vf/client_state.hpp> #include <sge/opengl/vf/client_state_combiner_fwd.hpp> #include <sge/opengl/vf/context_fwd.hpp> #include <sge/renderer/texture/stage.hpp> #include <fcppt/nonmovable.hpp> #include <fcppt/reference_impl.hpp> #include <fcppt/log/object_reference.hpp> namespace sge::opengl::vf { class client_state_combiner { FCPPT_NONMOVABLE(client_state_combiner); public: client_state_combiner(fcppt::log::object_reference, sge::opengl::context::object_ref); void enable(GLenum); void disable(GLenum); void enable_texture(sge::renderer::texture::stage); void disable_texture(sge::renderer::texture::stage); void enable_attribute(GLuint); void disable_attribute(GLuint); ~client_state_combiner(); private: fcppt::log::object_reference const log_; sge::opengl::context::object_ref const context_; fcppt::reference<sge::opengl::vf::context> const vf_context_; fcppt::reference<sge::opengl::vf::attribute_context> const attribute_context_; sge::opengl::vf::client_state const old_states_; sge::opengl::vf::client_state new_states_; }; } #endif
25.75
88
0.768285
cpreh
2d9691c02ca65193539f6d65ea91d70d4d191bbd
3,649
hpp
C++
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/task_description__builder.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/task_description__builder.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/task_description__builder.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__builder.hpp.em // with input from rmf_task_msgs:msg/TaskDescription.idl // generated code does not contain a copyright notice #ifndef RMF_TASK_MSGS__MSG__DETAIL__TASK_DESCRIPTION__BUILDER_HPP_ #define RMF_TASK_MSGS__MSG__DETAIL__TASK_DESCRIPTION__BUILDER_HPP_ #include "rmf_task_msgs/msg/detail/task_description__struct.hpp" #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <utility> namespace rmf_task_msgs { namespace msg { namespace builder { class Init_TaskDescription_clean { public: explicit Init_TaskDescription_clean(::rmf_task_msgs::msg::TaskDescription & msg) : msg_(msg) {} ::rmf_task_msgs::msg::TaskDescription clean(::rmf_task_msgs::msg::TaskDescription::_clean_type arg) { msg_.clean = std::move(arg); return std::move(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; class Init_TaskDescription_delivery { public: explicit Init_TaskDescription_delivery(::rmf_task_msgs::msg::TaskDescription & msg) : msg_(msg) {} Init_TaskDescription_clean delivery(::rmf_task_msgs::msg::TaskDescription::_delivery_type arg) { msg_.delivery = std::move(arg); return Init_TaskDescription_clean(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; class Init_TaskDescription_loop { public: explicit Init_TaskDescription_loop(::rmf_task_msgs::msg::TaskDescription & msg) : msg_(msg) {} Init_TaskDescription_delivery loop(::rmf_task_msgs::msg::TaskDescription::_loop_type arg) { msg_.loop = std::move(arg); return Init_TaskDescription_delivery(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; class Init_TaskDescription_station { public: explicit Init_TaskDescription_station(::rmf_task_msgs::msg::TaskDescription & msg) : msg_(msg) {} Init_TaskDescription_loop station(::rmf_task_msgs::msg::TaskDescription::_station_type arg) { msg_.station = std::move(arg); return Init_TaskDescription_loop(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; class Init_TaskDescription_task_type { public: explicit Init_TaskDescription_task_type(::rmf_task_msgs::msg::TaskDescription & msg) : msg_(msg) {} Init_TaskDescription_station task_type(::rmf_task_msgs::msg::TaskDescription::_task_type_type arg) { msg_.task_type = std::move(arg); return Init_TaskDescription_station(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; class Init_TaskDescription_priority { public: explicit Init_TaskDescription_priority(::rmf_task_msgs::msg::TaskDescription & msg) : msg_(msg) {} Init_TaskDescription_task_type priority(::rmf_task_msgs::msg::TaskDescription::_priority_type arg) { msg_.priority = std::move(arg); return Init_TaskDescription_task_type(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; class Init_TaskDescription_start_time { public: Init_TaskDescription_start_time() : msg_(::rosidl_runtime_cpp::MessageInitialization::SKIP) {} Init_TaskDescription_priority start_time(::rmf_task_msgs::msg::TaskDescription::_start_time_type arg) { msg_.start_time = std::move(arg); return Init_TaskDescription_priority(msg_); } private: ::rmf_task_msgs::msg::TaskDescription msg_; }; } // namespace builder } // namespace msg template<typename MessageType> auto build(); template<> inline auto build<::rmf_task_msgs::msg::TaskDescription>() { return rmf_task_msgs::msg::builder::Init_TaskDescription_start_time(); } } // namespace rmf_task_msgs #endif // RMF_TASK_MSGS__MSG__DETAIL__TASK_DESCRIPTION__BUILDER_HPP_
24.006579
103
0.768978
flitzmo-hso
2d99f73f8d3198a21805b3f715cddc56d5bfdcfd
6,561
hpp
C++
deepsim_gazebo_plugin/include/deepsim_gazebo_plugin/converters/geometry_converter.hpp
aws-deepracer/deepsim
cad2639f525c2f94ec5c03d8b855cc65b0b8ee55
[ "Apache-2.0" ]
1
2022-03-25T07:20:49.000Z
2022-03-25T07:20:49.000Z
deepsim_gazebo_plugin/include/deepsim_gazebo_plugin/converters/geometry_converter.hpp
aws-deepracer/deepsim
cad2639f525c2f94ec5c03d8b855cc65b0b8ee55
[ "Apache-2.0" ]
null
null
null
deepsim_gazebo_plugin/include/deepsim_gazebo_plugin/converters/geometry_converter.hpp
aws-deepracer/deepsim
cad2639f525c2f94ec5c03d8b855cc65b0b8ee55
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////// // Copyright Amazon.com, Inc. or its affiliates. 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. // /////////////////////////////////////////////////////////////////////////////////// #ifndef DEEPSIM_GAZEBO_PLUGIN__GEOMETRY_CONVERTER_HPP_ #define DEEPSIM_GAZEBO_PLUGIN__GEOMETRY_CONVERTER_HPP_ #include <geometry_msgs/Vector3.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Point32.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Quaternion.h> #include <geometry_msgs/Transform.h> #include <ignition/math/Pose3.hh> #include <ignition/math/Quaternion.hh> #include <ignition/math/Vector3.hh> #include <gazebo/msgs/msgs.hh> namespace deepsim_gazebo_plugin { class GeometryConverter { public: /// \brief Specialized conversion from a ROS vector message to an Ignition Math vector. /// \param[in] msg ROS message to convert. /// \return An Ignition Math vector. static ignition::math::Vector3d Convert2MathVector3d(const geometry_msgs::Vector3 & msg); /// \brief Specialized conversion from a ROS point message to a ROS vector message. /// \param[in] in ROS message to convert. /// \return ROS geometry_msgs::Vector3 static geometry_msgs::Vector3 Convert2GeoVector3(const geometry_msgs::Point & in); /// \brief Specialized conversion from a ROS point message to an Ignition math vector. /// \param[in] in ROS message to convert. /// \return An Ignition Math vector. static ignition::math::Vector3d Convert2MathVector3d(const geometry_msgs::Point & in); /// \brief Specialized conversion from an Ignition Math vector to a ROS message. /// \param[in] vec Ignition vector to convert. /// \return ROS geometry vector message static geometry_msgs::Vector3 Convert2GeoVector3(const ignition::math::Vector3d & vec); /// \brief Specialized conversion from an Ignition Math vector to a ROS message. /// \param[in] vec Ignition vector to convert. /// \return ROS geometry point message static geometry_msgs::Point Convert2GeoPoint(const ignition::math::Vector3d & vec); /// \brief Specialized conversion from an Ignition Math Quaternion to a ROS message. /// \param[in] in Ignition Quaternion to convert. /// \return ROS geometry quaternion message static geometry_msgs::Quaternion Convert2GeoQuaternion(const ignition::math::Quaterniond & in); /// \brief Specialized conversion from an Ignition Math Pose3d to a ROS geometry transform message. /// \param[in] in Ignition Pose3d to convert. /// \return ROS geometry transform message static geometry_msgs::Transform Convert2GeoTransform(const ignition::math::Pose3d & in); /// \brief Specialized conversion from an Ignition Math Pose3d to a ROS geometry pose message. /// \param[in] in Ignition Pose3d to convert. /// \return ROS geometry pose message static geometry_msgs::Pose Convert2GeoPose(const ignition::math::Pose3d & in); /// \brief Specialized conversion from a ROS quaternion message to ignition quaternion /// \param[in] in Input quaternion message /// \return Ignition math quaternion with same values as the input message static ignition::math::Quaterniond Convert2MathQuaterniond(const geometry_msgs::Quaternion & in); /// \brief Specialized conversion from a ROS geometry transform message to an Ignition math pose3d. /// \param[in] in ROS message to convert. /// \return A Ignition Math pose3d. static ignition::math::Pose3d Convert2MathPose3d(const geometry_msgs::Transform & in); /// \brief Specialized conversion from a ROS pose message to a ROS geometry transform message. /// \param[in] in ROS pose message to convert. /// \return A ROS geometry transform message. static geometry_msgs::Transform Convert2GeoTransform(const geometry_msgs::Pose & in); /// \brief Specialized conversion from a ROS pose message to an Ignition Math pose. /// \param[in] in ROS pose message to convert. /// \return Ignition Math pose. static ignition::math::Pose3d Convert2MathPose3d(const geometry_msgs::Pose & in); /// \brief Specialized conversion from a ROS pose message to an Ignition Math pose. /// \param[in] in ROS pose message to convert. /// \return ROS geometry pose message static geometry_msgs::Pose Convert2GeoPose(const gazebo::msgs::Pose & in); /// \brief Specialized conversion from a ROS pose message to an Ignition Math pose. /// \param[in] in the gazebo msgs::Vector3d to convert. /// \return ROS geometry_msgs::Vector3. static geometry_msgs::Vector3 Convert2GeoVector3(const gazebo::msgs::Vector3d & in); /// \brief Specialized conversion from a ROS pose message to an Ignition Math pose. /// \param[in] in ROS gazebo::msgs::Quaternion message to convert. /// \return geometry_msgs::Quaternion static geometry_msgs::Quaternion Convert2GeoQuaternion(const gazebo::msgs::Quaternion & in); /// \brief Specialized conversion from a gazebo vector3d message to an Ignition Math pose. /// \param[in] in gazebo::msgs::Vector3d gazebo message to convert /// \return ROS geometry_msgs::Point message static geometry_msgs::Point Convert2GeoPoint(const gazebo::msgs::Vector3d & in); /// \brief Get a geometry_msgs::Vector3 of all ones /// \return geometry_msgs::Vector3 of all ones static geometry_msgs::Vector3 GeoVector3Ones(); }; } // namespace deepsim_gazebo_plugin #endif // DEEPSIM_GAZEBO_PLUGIN__GEOMETRY_CONVERTER_HPP_
53.341463
103
0.667124
aws-deepracer
2d9a108d33a3cd9dff7f6081ee429615eeeaaeba
3,295
cpp
C++
src/main/cpp/sdk/MessageQueueONS.cpp
RayneHwang/rocketmq-ons-cpp
9d69c0a0e91c5030b7fe9054faed1b559d9929e9
[ "Apache-2.0", "MIT" ]
9
2019-07-30T08:08:44.000Z
2021-11-10T19:02:56.000Z
src/main/cpp/sdk/MessageQueueONS.cpp
RayneHwang/rocketmq-ons-cpp
9d69c0a0e91c5030b7fe9054faed1b559d9929e9
[ "Apache-2.0", "MIT" ]
null
null
null
src/main/cpp/sdk/MessageQueueONS.cpp
RayneHwang/rocketmq-ons-cpp
9d69c0a0e91c5030b7fe9054faed1b559d9929e9
[ "Apache-2.0", "MIT" ]
4
2019-07-30T09:41:09.000Z
2021-11-03T11:02:13.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "MessageQueueONS.h" #include "ONSClientException.h" #include "UtilAll.h" namespace ons { MessageQueueONS::MessageQueueONS() { m_queueId = -1;//invalide mq m_topic.clear(); m_brokerName.clear(); } MessageQueueONS::MessageQueueONS(const string &topic, const string &brokerName, int queueId) : m_topic(topic), m_brokerName(brokerName), m_queueId(queueId) { } MessageQueueONS::MessageQueueONS(const MessageQueueONS &other) : m_topic(other.m_topic), m_brokerName(other.m_brokerName), m_queueId(other.m_queueId) { } MessageQueueONS &MessageQueueONS::operator=(const MessageQueueONS &other) { if (this != &other) { m_brokerName = other.m_brokerName; m_topic = other.m_topic; m_queueId = other.m_queueId; } return *this; } string MessageQueueONS::getTopic() const { return m_topic; } void MessageQueueONS::setTopic(const string &topic) { m_topic = topic; } string MessageQueueONS::getBrokerName() const { return m_brokerName; } void MessageQueueONS::setBrokerName(const string &brokerName) { m_brokerName = brokerName; } int MessageQueueONS::getQueueId() const { return m_queueId; } void MessageQueueONS::setQueueId(int queueId) { m_queueId = queueId; } bool MessageQueueONS::operator==(const MessageQueueONS &mq) const { if (this == &mq) { return true; } if (m_brokerName != mq.m_brokerName) { return false; } if (m_queueId != mq.m_queueId) { return false; } if (m_topic != mq.m_topic) { return false; } return true; } int MessageQueueONS::compareTo(const MessageQueueONS &mq) const { int result = m_topic.compare(mq.m_topic); if (result != 0) { return result; } result = m_brokerName.compare(mq.m_brokerName); if (result != 0) { return result; } return m_queueId - mq.m_queueId; } bool MessageQueueONS::operator<(const MessageQueueONS &mq) const { return compareTo(mq) < 0; } //<!*************************************************************************** } //<!end namespace;
27.923729
79
0.596965
RayneHwang
2d9aa54936e484fd5340166aa44ee8b78ba9fe74
700
cpp
C++
solutions/5.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
solutions/5.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
solutions/5.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
#include <string> #include <vector> class Solution { std::string_view longestPalindrome(const std::string_view &s, size_t lo, size_t hi) { while (lo > 0 and hi < s.size() and s[lo - 1] == s[hi]) { --lo; ++hi; } return s.substr(lo, hi - lo); } public: std::string longestPalindrome(std::string s) { std::string_view sv(s); std::string_view result; for (size_t i = 0; i < s.size(); ++i) { for (auto hi : {0u, 1u}) { auto longest = longestPalindrome(sv, i + 1, i + hi); if (longest.size() > result.size()) { result = longest; } } } return std::string(result); } };
24.137931
74
0.512857
tdakhran
2d9ba9b8c49c6ad2fcf617aa97693ea9f67ecf59
7,747
hpp
C++
include/canard/net/ofp/v13/message/multipart/table_features.hpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
null
null
null
include/canard/net/ofp/v13/message/multipart/table_features.hpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
8
2016-07-21T11:29:13.000Z
2016-12-03T05:16:42.000Z
include/canard/net/ofp/v13/message/multipart/table_features.hpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
null
null
null
#ifndef CANARD_NET_OFP_V13_MESSAGES_MULTIPART_TABLE_FEATURES_HPP #define CANARD_NET_OFP_V13_MESSAGES_MULTIPART_TABLE_FEATURES_HPP #include <cstdint> #include <algorithm> #include <iterator> #include <utility> #include <boost/range/adaptor/sliced.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/utility/string_ref.hpp> #include <canard/net/ofp/detail/basic_protocol_type.hpp> #include <canard/net/ofp/detail/decode.hpp> #include <canard/net/ofp/detail/encode.hpp> #include <canard/net/ofp/detail/memcmp.hpp> #include <canard/net/ofp/get_xid.hpp> #include <canard/net/ofp/list.hpp> #include <canard/net/ofp/v13/detail/basic_multipart.hpp> #include <canard/net/ofp/v13/detail/byteorder.hpp> #include <canard/net/ofp/v13/exception.hpp> #include <canard/net/ofp/v13/openflow.hpp> #include <canard/net/ofp/v13/utility/table_feature_property_set.hpp> namespace canard { namespace net { namespace ofp { namespace v13 { namespace messages { namespace multipart { class table_features : public detail::basic_protocol_type<table_features> { public: using ofp_type = protocol::ofp_table_features; using properties_type = ofp::list<any_table_feature_property>; table_features( std::uint8_t const table_id , boost::string_ref const name , std::uint64_t const metadata_match , std::uint64_t const metadata_write , std::uint32_t const config , std::uint32_t const max_entries , properties_type properties) : table_features_{ properties.calc_ofp_length(sizeof(ofp_type)) , table_id , { 0, 0, 0, 0, 0 } , "" , metadata_match , metadata_write , config , max_entries } , properties_(std::move(properties)) { auto const name_size = std::min(name.size(), sizeof(table_features_.name) - 1); using boost::adaptors::sliced; boost::copy(name | sliced(0, name_size), table_features_.name); } table_features( std::uint8_t const table_id , boost::string_ref const name , std::uint64_t const metadata_match , std::uint64_t const metadata_write , std::uint32_t const config , std::uint32_t const max_entries , table_feature_property_set properties) : table_features{ table_id, name, metadata_match, metadata_write, config, max_entries , std::move(properties).to_list() } { } table_features(table_features const&) = default; table_features(table_features&& other) : table_features_(other.table_features_) , properties_(other.extract_properties()) { } auto operator=(table_features const& other) -> table_features& { return operator=(table_features{other}); } auto operator=(table_features&& other) -> table_features& { auto tmp = std::move(other); std::swap(table_features_, tmp.table_features_); properties_.swap(tmp.properties_); return *this; } auto length() const noexcept -> std::uint16_t { return table_features_.length; } auto table_id() const noexcept -> std::uint8_t { return table_features_.table_id; } auto name() const -> boost::string_ref { return table_features_.name; } auto metadata_match() const noexcept -> std::uint64_t { return table_features_.metadata_match; } auto metadata_write() const noexcept -> std::uint64_t { return table_features_.metadata_write; } auto config() const noexcept -> std::uint32_t { return table_features_.config; } auto max_entries() const noexcept -> std::uint32_t { return table_features_.max_entries; } auto properties() const noexcept -> properties_type const& { return properties_; } auto extract_properties() -> properties_type { auto properties = properties_type{}; properties.swap(properties_); table_features_.length = min_length(); return properties; } private: table_features(ofp_type const& features, properties_type&& properties) : table_features_(features) , properties_(std::move(properties)) { } friend basic_protocol_type; template <class Container> void encode_impl(Container& container) const { detail::encode(container, table_features_); properties_.encode(container); } template <class Iterator> static auto decode_impl(Iterator& first, Iterator last) -> table_features { auto const features = detail::decode<ofp_type>(first, last); if (features.length < min_length()) { throw exception{ exception::ex_error_type::bad_multipart_element , exception::ex_error_code::bad_length , "too small table_features length" } << CANARD_NET_OFP_ERROR_INFO(); } auto const prop_length = std::uint16_t(features.length - sizeof(ofp_type)); if (std::distance(first, last) < prop_length) { throw exception{ protocol::bad_request_code::bad_len , "too small data size for table_features" } << CANARD_NET_OFP_ERROR_INFO(); } last = std::next(first, prop_length); auto properties = properties_type::decode(first, last); return table_features{features, std::move(properties)}; } auto equal_impl(table_features const& rhs) const noexcept -> bool { return detail::memcmp(table_features_, rhs.table_features_) && properties_ == rhs.properties_; } private: ofp_type table_features_; properties_type properties_; }; class table_features_request : public multipart_detail::basic_multipart_request< table_features_request, table_features[] > { public: static constexpr protocol::ofp_multipart_type multipart_type_value = protocol::OFPMP_TABLE_FEATURES; explicit table_features_request(std::uint32_t const xid = get_xid()) : basic_multipart_request{0, {}, xid} { } table_features_request( body_type table_features , std::uint16_t const flags = 0 , std::uint32_t const xid = get_xid()) : basic_multipart_request{flags, std::move(table_features), xid} { } private: friend basic_multipart_request::base_type; static constexpr bool is_fixed_length_element = false; table_features_request( ofp_type const& multipart_request, body_type&& table_features) : basic_multipart_request{ multipart_request, std::move(table_features) } { } }; class table_features_reply : public multipart_detail::basic_multipart_reply< table_features_reply, table_features[] > { public: static constexpr protocol::ofp_multipart_type multipart_type_value = protocol::OFPMP_TABLE_FEATURES; table_features_reply( body_type table_features , std::uint16_t const flags = 0 , std::uint32_t const xid = get_xid()) : basic_multipart_reply{flags, std::move(table_features), xid } { } private: friend basic_multipart_reply::base_type; static constexpr bool is_fixed_length_element = false; table_features_reply( ofp_type const& multipart_reply, body_type&& table_features) : basic_multipart_reply{multipart_reply, std::move(table_features)} { } }; } // namespace multipart } // namespace messages } // namespace v13 } // namespace ofp } // namespace net } // namespace canard #endif // CANARD_NET_OFP_V13_MESSAGES_MULTIPART_TABLE_FEATURES_HPP
26.993031
79
0.666322
amedama41
2d9c07d42d9b42e59b1a834b2253c93a3e391fcb
673
cpp
C++
Main/P1004.cpp
qinyihao/Luogu_Problem_Solver
bb4675f045affe513613023394027c3359bb0876
[ "MIT" ]
null
null
null
Main/P1004.cpp
qinyihao/Luogu_Problem_Solver
bb4675f045affe513613023394027c3359bb0876
[ "MIT" ]
null
null
null
Main/P1004.cpp
qinyihao/Luogu_Problem_Solver
bb4675f045affe513613023394027c3359bb0876
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define max(u,v) u>v ? u:v int a[10][10], f[10][10][10][10], x, y, n, k; int main() { scanf("%d",&n); while(scanf("%d%d%d", &x, &y, &k) == 3 && x) { a[x][y] = k; } for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) for(int k = 1; k <= n; k++) for(int l = 1; l <= n; l++) { int tmp=max(f[i][j][k][l],f[i-1][j][k-1][l]); tmp=max(tmp,f[i][j-1][k][l-1]); tmp=max(tmp,f[i][j-1][k-1][l]); tmp=max(tmp,f[i-1][j][k][l-1]); if(i==k && j==l) f[i][j][k][l]=tmp+a[i][j]; else f[i][j][k][l]=tmp+a[i][j]+a[k][l]; } printf("%d\n",f[n][n][n][n]); return 0; }
25.884615
56
0.380386
qinyihao
2d9e5de236720bc7b8efb91dceb232bb0a3f6f78
316
cpp
C++
engine/gtp/Move.cpp
imalerich/imgo
1dc999b62d95b74dd992fd1daf1cb0d974bba8a7
[ "MIT" ]
null
null
null
engine/gtp/Move.cpp
imalerich/imgo
1dc999b62d95b74dd992fd1daf1cb0d974bba8a7
[ "MIT" ]
null
null
null
engine/gtp/Move.cpp
imalerich/imgo
1dc999b62d95b74dd992fd1daf1cb0d974bba8a7
[ "MIT" ]
null
null
null
#include "Move.hpp" namespace gtp { ArgMove::ArgMove(std::string color, std::string vertex) { iArgument::type = ARG_MOVE; this->color = Color(color); this->vertex = Vertex(vertex); } ArgMove::ArgMove(Color color, Vertex vertex) { iArgument::type = ARG_MOVE; this->color = color; this->vertex = vertex; } }
17.555556
57
0.689873
imalerich
2da7120f1e231f9f4eb9610c14a9a4e1c579edcc
1,874
cpp
C++
src/Nazara/Physics3D/Systems/Physics3DSystem.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
src/Nazara/Physics3D/Systems/Physics3DSystem.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
src/Nazara/Physics3D/Systems/Physics3DSystem.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
// Copyright (C) 2022 Jérôme "Lynix" Leclercq ([email protected]) // This file is part of the "Nazara Engine - Physics3D module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Physics3D/Systems/Physics3DSystem.hpp> #include <Nazara/Utility/Components/NodeComponent.hpp> #include <Nazara/Physics3D/Debug.hpp> namespace Nz { Physics3DSystem::Physics3DSystem(entt::registry& registry) : m_registry(registry) { m_constructConnection = registry.on_construct<RigidBody3DComponent>().connect<OnConstruct>(); } Physics3DSystem::~Physics3DSystem() { // Ensure every NewtonBody is destroyed before world is auto rigidBodyView = m_registry.view<RigidBody3DComponent>(); for (auto [entity, rigidBodyComponent] : rigidBodyView.each()) rigidBodyComponent.Destroy(); m_constructConnection.release(); } void Physics3DSystem::Update(entt::registry& registry, float elapsedTime) { m_physWorld.Step(elapsedTime); // Replicate rigid body position to their node components auto view = registry.view<NodeComponent, const RigidBody3DComponent>(); for (auto [entity, nodeComponent, rigidBodyComponent] : view.each()) { if (rigidBodyComponent.IsSleeping()) continue; nodeComponent.SetPosition(rigidBodyComponent.GetPosition(), CoordSys::Global); nodeComponent.SetRotation(rigidBodyComponent.GetRotation(), CoordSys::Global); } } void Physics3DSystem::OnConstruct(entt::registry& registry, entt::entity entity) { // If our entity already has a node component when adding a rigid body, initialize it with its position/rotation NodeComponent* node = registry.try_get<NodeComponent>(entity); if (node) { RigidBody3DComponent& rigidBody = registry.get<RigidBody3DComponent>(entity); rigidBody.SetPosition(node->GetPosition()); rigidBody.SetRotation(node->GetRotation()); } } }
34.072727
114
0.763074
jayrulez
2da85679ccacda2a91a386f0117749e402e5354a
3,196
cpp
C++
tests/runtime_tests/EvaluatorSymbolTests.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
tests/runtime_tests/EvaluatorSymbolTests.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
tests/runtime_tests/EvaluatorSymbolTests.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
#include "support/EvaluatorFixture.h" #include "runtime/Evaluator.h" #include "runtime/RuntimeApi.h" #include "runtime/Value.h" #include "runtime/VmState.h" #include "support/TestHelpers.h" #include <catch2/catch.hpp> using namespace Shiny; TEST_CASE_METHOD(EvaluatorFixture, "Is symbol", "[Procedures]") { SECTION("true for symbols") { REQUIRE(Value::True == evaluate("(symbol? 'foo)")); REQUIRE(Value::True == evaluate("(symbol? (car '(a b)))")); REQUIRE(Value::True == evaluate("(symbol? 'nil)")); } SECTION("false for other types") { REQUIRE(Value::False == evaluate("(symbol? \"bar\")")); REQUIRE(Value::False == evaluate("(symbol? '())")); REQUIRE(Value::False == evaluate("(symbol? #f)")); REQUIRE(Value::False == evaluate("(symbol? 0)")); REQUIRE(Value::False == evaluate("(symbol? '(1 2))")); REQUIRE(Value::False == evaluate("(symbol? #\\0)")); } SECTION("error if wrong argument count") { auto fn1 = [this]() { evaluate("(symbol?)"); }; REQUIRE_THROWS_AS(fn1(), ArgumentMissingException); auto fn2 = [this]() { evaluate("(symbol? 'foo 'bar)"); }; REQUIRE_THROWS_AS(fn2(), ArgCountMismatch); } } TEST_CASE_METHOD(EvaluatorFixture, "Symbol to string", "[Procedures]") { SECTION("returns name") { REQUIRE( "\"flying-fish\"" == evaluate("(symbol->string 'flying-fish)").toString()); REQUIRE("\"Martin\"" == evaluate("(symbol->string 'Martin)").toString()); REQUIRE("\"foo\"" == evaluate("(symbol->string 'foo)").toString()); } SECTION("error if not a symbol") { auto fn1 = [this]() { evaluate("(symbol->string \"foo\")"); }; REQUIRE_THROWS_AS(fn1(), WrongArgTypeException); auto fn2 = [this]() { evaluate("(symbol->string #t)"); }; REQUIRE_THROWS_AS(fn2(), WrongArgTypeException); } SECTION("error if wrong argument count") { auto fn1 = [this]() { evaluate("(symbol->string)"); }; REQUIRE_THROWS_AS(fn1(), ArgumentMissingException); auto fn2 = [this]() { evaluate("(symbol->string 'foo 'bar)"); }; REQUIRE_THROWS_AS(fn2(), ArgCountMismatch); } } TEST_CASE_METHOD(EvaluatorFixture, "String to symbol", "[Procedures]") { SECTION("returns symbol") { auto v = evaluate("(string->symbol \"foo\")"); REQUIRE(ValueType::Symbol == v.type()); REQUIRE("foo" == v.toStringView()); v = evaluate("(string->symbol \"flying-fish\")"); REQUIRE(ValueType::Symbol == v.type()); REQUIRE("flying-fish" == v.toStringView()); v = evaluate("(string->symbol \"Marvin\")"); REQUIRE(ValueType::Symbol == v.type()); REQUIRE("Marvin" == v.toStringView()); } SECTION("error if not a string") { auto fn1 = [this]() { evaluate("(string->symbol 'foo)"); }; REQUIRE_THROWS_AS(fn1(), WrongArgTypeException); auto fn2 = [this]() { evaluate("(string->symbol #t)"); }; REQUIRE_THROWS_AS(fn2(), WrongArgTypeException); } SECTION("error if wrong argument count") { auto fn1 = [this]() { evaluate("(string->symbol)"); }; REQUIRE_THROWS_AS(fn1(), ArgumentMissingException); auto fn2 = [this]() { evaluate("(string->symbol \"foo\" \"bar\")"); }; REQUIRE_THROWS_AS(fn2(), ArgCountMismatch); } }
32.948454
77
0.622653
smacdo
2db05e592c573a07efaba293fa1b3fed85d2e1b5
38
cpp
C++
lander.cpp
nathan-tagg/skeet
ed3909ba63863c8120ddf290286fa6b2502a5874
[ "MIT" ]
1
2016-04-05T20:06:13.000Z
2016-04-05T20:06:13.000Z
lander.cpp
nathan-tagg/skeet
ed3909ba63863c8120ddf290286fa6b2502a5874
[ "MIT" ]
null
null
null
lander.cpp
nathan-tagg/skeet
ed3909ba63863c8120ddf290286fa6b2502a5874
[ "MIT" ]
null
null
null
// lander bird // #include "lander.h"
12.666667
19
0.631579
nathan-tagg
2db0b1b0f6bbfcd17425987bfa2da490ea3dd3f4
5,002
cpp
C++
RubbishDebugger/PortableExecutable.cpp
Woodykaixa/RubbishDebugger
4d80163ef7a3350a0f57b026608365d0c9dc0218
[ "MIT" ]
null
null
null
RubbishDebugger/PortableExecutable.cpp
Woodykaixa/RubbishDebugger
4d80163ef7a3350a0f57b026608365d0c9dc0218
[ "MIT" ]
null
null
null
RubbishDebugger/PortableExecutable.cpp
Woodykaixa/RubbishDebugger
4d80163ef7a3350a0f57b026608365d0c9dc0218
[ "MIT" ]
null
null
null
#include "PortableExecutable.h" #include <exception> #include "Misc.h" PortableExecutable::PortableExecutable(const char* filename) { _file = nullptr; fopen_s(&_file, filename, "rb"); if (_file == nullptr) { throw std::exception("Cannot open pe file"); } fread(&DosHeader, sizeof IMAGE_DOS_HEADER, 1, _file); if (DosHeader.e_magic != IMAGE_DOS_SIGNATURE) { throw std::exception("Invalid Dos header"); } fseek(_file, DosHeader.e_lfanew, SEEK_SET); fread(&NtHeaders, sizeof IMAGE_NT_HEADERS, 1, _file); if (NtHeaders.Signature != IMAGE_NT_SIGNATURE) { throw std::exception("Invalid NT headers"); } ImageBase = reinterpret_cast<void*>(NtHeaders.OptionalHeader.ImageBase); EntryPoint = reinterpret_cast<void*>(NtHeaders.OptionalHeader.AddressOfEntryPoint + NtHeaders.OptionalHeader.ImageBase); Is32Bit = NtHeaders.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC; _sections.resize(NtHeaders.FileHeader.NumberOfSections); PdbPath = nullptr; fread(&_sections[0], sizeof IMAGE_SECTION_HEADER, _sections.size(), _file); // imports auto const& importTable = NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; if (importTable.Size) { fseek(_file, static_cast<long>(VirtualToRaw(importTable.VirtualAddress)), SEEK_SET); for (;;) { IMAGE_IMPORT_DESCRIPTOR import_desc; fread(&import_desc, sizeof(IMAGE_IMPORT_DESCRIPTOR), 1, _file); if (!import_desc.Characteristics) { break; } _imports.emplace_back().Desc = import_desc; } } for (auto& current_import : _imports) { constexpr auto Size = 0x100; char name_buf[Size]; fseek(_file, static_cast<long>(VirtualToRaw(current_import.Desc.Name)), SEEK_SET); fgets(name_buf, Size, _file); current_import.Name = name_buf; // thunks fseek(_file, static_cast<long>(VirtualToRaw(current_import.Desc.FirstThunk)), SEEK_SET); for (;;) { IMAGE_THUNK_DATA thunk_data; fread(&thunk_data, sizeof(IMAGE_THUNK_DATA), 1, _file); if (!thunk_data.u1.AddressOfData) { break; } current_import.Thunks.emplace_back().ThunkData = thunk_data; } auto thunk_addr = reinterpret_cast<IMAGE_THUNK_DATA*>(current_import.Desc.FirstThunk); for (auto& thunk : current_import.Thunks) { thunk.Address = reinterpret_cast<DWORD>(thunk_addr++); thunk.IsOrdinal = IMAGE_SNAP_BY_ORDINAL(thunk.ThunkData.u1.Ordinal); if (thunk.IsOrdinal) { thunk.Ordinal = IMAGE_ORDINAL(thunk.ThunkData.u1.Ordinal); } else { fseek(_file, static_cast<long>(VirtualToRaw(thunk.ThunkData.u1.AddressOfData)), SEEK_SET); fread(&thunk.Word, 2, 1, _file); fgets(name_buf, Size, _file); thunk.Name = name_buf; } } } // pdb const auto& debug = NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG]; if (debug.Size) { fseek(_file, static_cast<long>(VirtualToRaw(debug.VirtualAddress)), SEEK_SET); IMAGE_DEBUG_DIRECTORY debugDir; fread(&debugDir, sizeof IMAGE_DEBUG_DIRECTORY, 1, _file); if (debugDir.Type == IMAGE_DEBUG_TYPE_CODEVIEW) { fseek(_file, VirtualToRaw(debugDir.AddressOfRawData + 0x18), SEEK_SET); PdbPath = new char[debugDir.SizeOfData - 0x18]; fread(const_cast<char*>(PdbPath), 1, debugDir.SizeOfData - 0x18, _file); } } // DebugCall(DebugPrintInfo); } PortableExecutable::~PortableExecutable() { if (_file) { fclose(_file); } } DWORD PortableExecutable::VirtualToRaw(DWORD const dwAddress) const noexcept { for (auto const& section : _sections) { if (auto const diff = dwAddress - section.VirtualAddress; diff < section.SizeOfRawData) { return section.PointerToRawData + diff; } } return 0; } std::tuple<bool, std::string> PortableExecutable::FindImportFunction(DWORD address) { for (const auto& currentImport : _imports) { for (const auto& thunk : currentImport.Thunks) { if ((thunk.Address + reinterpret_cast<DWORD>(ImageBase) + 0x00001000) == address) { std::string name = currentImport.Name; name += "::"; name += thunk.Name; return std::make_tuple(true, name); } } } return std::make_tuple(false, std::string()); } const IMAGE_SECTION_HEADER* PortableExecutable::FindSection(const char* name) { for (const auto& sec : _sections) { if (memcmp(name, sec.Name, 8) == 0) { return &sec; } } return nullptr; } #ifndef NDEBUG void PortableExecutable::DebugPrintInfo() const { printf("Is PE32 program: %s\n", Bool2String(Is32Bit)); printf("ImageBase: %p\n", ImageBase); printf("EntryPoint: %p\n", EntryPoint); printf("%d Sections:\n", _sections.size()); for (auto& section : _sections) { printf("\tName: %s\n", section.Name); printf("\tVirtual Size: %d\n", section.Misc.VirtualSize); printf("\tVirtual Address: %08X\n\n", section.VirtualAddress); } printf("ImportTable:\n"); printf("\t%d modules imported\n", _imports.size()); for (const auto& import : _imports) { printf("\tName: %s\n", import.Name.data()); for (const auto& thunk : import.Thunks) { printf("\t\t%s : %08X\n", thunk.Name.data(), thunk.Address); } } } #endif
30.315152
96
0.717113
Woodykaixa
2db2027e3d3f27d88fec76a46c7ef607419f97c4
1,548
cpp
C++
src/Problem_32.cpp
BenjaminHb/WHU_CS_WebLearn
2920621268bd3af7b9f8940d539144ae1f9afd4a
[ "MIT" ]
null
null
null
src/Problem_32.cpp
BenjaminHb/WHU_CS_WebLearn
2920621268bd3af7b9f8940d539144ae1f9afd4a
[ "MIT" ]
null
null
null
src/Problem_32.cpp
BenjaminHb/WHU_CS_WebLearn
2920621268bd3af7b9f8940d539144ae1f9afd4a
[ "MIT" ]
null
null
null
/** * File Name: Problem_32.cpp * Project Name: WHU_CS_WebLearn * Author: Benjamin Zhang * Created Time: 01/13/2019 19:04 * Version: 0.0.1.20190113 * * Copyright (c) Benjamin Zhang 2019 * All rights reserved. **/ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;} int m, n; int rec1[11][3010], rec2[11][3010]; int main() { while(scanf("%d%d", &m, &n) != EOF) { for(int i = 0; i < m; ++ i) for(int j = 0; j < n; ++ j) { scanf("%d", &rec1[i][j]); } int maxm = 1 << m, ans = 0; for(int i = 0; i < maxm; ++ i) { for(int j = 0; j < m; ++ j) for(int k = 0; k < n; ++ k) rec2[j][k] = rec1[j][k]; int tmp = i; for(int j = 0; j < m; ++ j) { if((tmp & 1) == 1) for(int k = 0; k < n; ++ k) rec2[j][k] ^= 1; tmp >>= 1; } tmp = 0; for(int j = 0; j < n; ++ j) { int ttmp = 0; for(int k = 0; k < m; ++ k) ttmp += rec2[k][j]; if(ttmp < m - ttmp) ttmp = m - ttmp; tmp += ttmp; } get_max(ans, tmp); } printf("%d\n", ans); } return 0; }
26.689655
78
0.392119
BenjaminHb
2db877bf5367306565fb975d03af246aa902f9f3
47
hpp
C++
src/boost_math_distributions_normal.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_math_distributions_normal.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_math_distributions_normal.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/math/distributions/normal.hpp>
23.5
46
0.808511
miathedev
2dba55ec969bfc9c4b7bc88eac51dfc8b75bb172
617
cpp
C++
TrocaVariavelCHAR/main.cpp
VitorVeector/Projetos-Estacio
e54f6f765e8c552cba27819a2f6fae3d819fb0e8
[ "MIT" ]
null
null
null
TrocaVariavelCHAR/main.cpp
VitorVeector/Projetos-Estacio
e54f6f765e8c552cba27819a2f6fae3d819fb0e8
[ "MIT" ]
null
null
null
TrocaVariavelCHAR/main.cpp
VitorVeector/Projetos-Estacio
e54f6f765e8c552cba27819a2f6fae3d819fb0e8
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; int main() { char sexo[2], aux; cout << "Digite a inicial do sexo da primeira pessoa: " << endl; cin >> sexo[0]; cout << "Digite a inicial do sexo da segunda pessoa: " << endl; cin >> sexo[1]; cout << "Antes da troca de sexo: " << endl; cout << sexo[0] << ", " << sexo [1] << endl; if(sexo[0],sexo[1]>0){ aux = sexo[0]; sexo[0] = sexo [1]; sexo[1] = aux; } cout << "Apos a troca de sexo: " << endl; cout << sexo[0] << ", " << sexo [1] << endl; system("pause"); return 0; }
22.851852
68
0.504052
VitorVeector
2dc0bd04a90e72289320c99f61c1bcc8e15e92a0
2,437
hh
C++
TrkBase/TrkPocaBase.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkBase/TrkPocaBase.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkBase/TrkPocaBase.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: TrkPocaBase.hh,v 1.11 2006/03/25 15:15:56 brownd Exp $ // // Description: // Base class for various Poca classes; holds infrastructure, and one // common algorithm. Ctor and dtor protected, to prevent instantiation. // // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Author(s): Steve Schaffner //------------------------------------------------------------------------ #ifndef TRKPOCABASE_HH #define TRKPOCABASE_HH #include "TrkBase/TrkErrCode.hh" class Trajectory; class HepPoint; // struct for passing around associated traj information struct TrkPocaTraj{ TrkPocaTraj(const Trajectory& traj, double flt, bool rflt) : _traj(traj),_flt(flt),_rflt(rflt) {} const Trajectory& _traj; double _flt; bool _rflt; }; // Class interface class TrkPocaBase { protected: TrkPocaBase(double flt1, double flt2, double precision); TrkPocaBase(double flt1, double precision); TrkPocaBase(); TrkPocaBase(const TrkPocaBase& other); TrkPocaBase& operator = (const TrkPocaBase& other); public: inline const TrkErrCode& status() const; // did the calculation succeed? inline double flt1() const; // path length on traj 1 @ poca inline double flt2() const; inline double precision(); // In case anyone wants to know virtual ~TrkPocaBase(); virtual double doca() const = 0; virtual TrkPocaBase* clone() const = 0; // returns ownership protected: double _precision; double _flt1; double _flt2; TrkErrCode _status; void minimize(TrkPocaTraj& traj1, TrkPocaTraj& traj2); void minimize(TrkPocaTraj& traj1, const HepPoint& pt); void stepTowardPoca(TrkPocaTraj& traj1,TrkPocaTraj& traj2); void stepToPointPoca(TrkPocaTraj& traj, const HepPoint& pt); static void setFlt(double flt,TrkPocaTraj& traj); static double _maxDist; // step > maxDist => parallel static int _maxTry; static double _extrapToler; // error allowed in picking step size }; // Inlined functions double TrkPocaBase::precision() {return _precision;} const TrkErrCode& TrkPocaBase::status() const {return _status;} double TrkPocaBase::flt1() const {return _flt1;} double TrkPocaBase::flt2() const {return _flt2;} #endif
29.719512
78
0.651621
brownd1978
2dc0e3dc4aa7f7f24b3b0264c14ab5ab99c17226
1,644
cpp
C++
Source/opennwa/construct/nwa_complement.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-03-07T17:25:57.000Z
2022-02-04T20:17:00.000Z
src/wpds/Source/opennwa/construct/nwa_complement.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
1
2018-03-03T05:58:55.000Z
2018-03-03T12:26:10.000Z
src/wpds/Source/opennwa/construct/nwa_complement.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
15
2015-09-25T17:44:35.000Z
2021-07-18T18:25:38.000Z
#include "opennwa/Nwa.hpp" #include "opennwa/construct/complement.hpp" #include "opennwa/construct/determinize.hpp" namespace opennwa { namespace construct { NwaRefPtr complement( Nwa const & source ) { NwaRefPtr nwa( new Nwa()); complement(*nwa, source); return nwa; } /** * * @brief constructs the NWA that is the complement of the given NWA * * @param - first: the NWA to perform the complement of * */ void complement( Nwa & out, Nwa const & first ) { //Q: How should clientInfos be generated for the complemented NWA? //A: The clientInfos from the component machines are copied and added to the complemented NWA. //Clear all states(except the stuck state) and transitions from this machine. out.clear(); //Start with a deterministic copy of the given NWA. // FIXME: keep information about whether a machine is deterministic if(CONSTANT_CONDITION(true)) //! first.isDeterministic() ) { determinize(out, first); //Note: determinize() will take care of clientInfo information. } else { out = first; } //FinalStates = AllStates - FinalStates StateSet oldFinalStates(out.beginFinalStates(), out.endFinalStates()); out.clearFinalStates(); for( Nwa::StateIterator sit = out.beginStates(); sit != out.endStates(); sit++ ) { if( oldFinalStates.count(*sit) == 0 ) out.addFinalState(*sit); } } } } // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End:
25.292308
100
0.615572
jusito
2dc465643cc9382902e1629f2794fe969d7bcb0e
461
cpp
C++
Assignment/Assignment-1/2140_Herd_Sums.cpp
Hantao-Ye/CS97-SI
410dd79cc563d47f93d8d1c96e603e4de8dfcf70
[ "MIT" ]
null
null
null
Assignment/Assignment-1/2140_Herd_Sums.cpp
Hantao-Ye/CS97-SI
410dd79cc563d47f93d8d1c96e603e4de8dfcf70
[ "MIT" ]
null
null
null
Assignment/Assignment-1/2140_Herd_Sums.cpp
Hantao-Ye/CS97-SI
410dd79cc563d47f93d8d1c96e603e4de8dfcf70
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int num = 0, output = 1; cin >> num; for (int i = 1; i <= (num / 2) + 1; i++) { int sum = 0; for (int j = i; j <= (num / 2) + 1; j++) { sum += j; if (sum == num) { output++; break; } else if (sum > num) break; } } cout << output << endl; }
17.074074
48
0.32538
Hantao-Ye
2dc49896be9f0606c4795f3c5288a2aebe6b3b88
38,017
hpp
C++
src/lib/common/plot.hpp
bitslow/fcpp
abdaed70ccedb1a377e24d3b7c78b2ec203e111f
[ "ECL-2.0", "Apache-2.0" ]
3
2020-05-03T15:53:22.000Z
2020-11-30T12:14:01.000Z
src/lib/common/plot.hpp
bitslow/fcpp
abdaed70ccedb1a377e24d3b7c78b2ec203e111f
[ "ECL-2.0", "Apache-2.0" ]
4
2021-05-17T16:46:22.000Z
2021-12-22T15:12:22.000Z
src/lib/common/plot.hpp
bitslow/fcpp
abdaed70ccedb1a377e24d3b7c78b2ec203e111f
[ "ECL-2.0", "Apache-2.0" ]
7
2020-05-08T11:47:57.000Z
2022-01-15T21:28:10.000Z
// Copyright © 2021 Giorgio Audrito. All Rights Reserved. /** * @file plot.hpp * @brief Plot building tools. */ #ifndef FCPP_COMMON_PLOT_H_ #define FCPP_COMMON_PLOT_H_ #include <cstdint> #include <ctime> #include <limits> #include <map> #include <ratio> #include <set> #include <sstream> #include <vector> #include "lib/common/mutex.hpp" #include "lib/common/serialize.hpp" #include "lib/common/tagged_tuple.hpp" #include "lib/option/aggregator.hpp" /** * @brief Namespace containing all the objects in the FCPP library. */ namespace fcpp { //! @brief Namespace for filtering functions. namespace filter { //! @brief Filters values within `L/den` and `U/den` (included). template <intmax_t L, intmax_t U, intmax_t den = 1> struct within { template <typename V> bool operator()(V v) const { v *= den; if (L > std::numeric_limits<intmax_t>::min() and L > v) return false; if (U < std::numeric_limits<intmax_t>::max() and U < v) return false; return true; } }; //! @brief Filters values above `L/den` (included). template <intmax_t L, intmax_t den = 1> using above = within<L, std::numeric_limits<intmax_t>::max(), den>; //! @brief Filters values below `U/den` (included). template <intmax_t U, intmax_t den = 1> using below = within<std::numeric_limits<intmax_t>::min(), U, den>; //! @brief Filters values equal to `V/den`. template <intmax_t V, intmax_t den = 1> using equal = within<V, V, den>; //! @brief Negate a filter. template <typename F> struct neg : F { template <typename V> bool operator()(V v) const { return not F::operator()(v); } }; //! @brief Joins filters (or). template <typename F, typename G> struct vee : F, G { template <typename V> bool operator()(V v) const { return F::operator()(v) or G::operator()(v); } }; //! @brief Disjoins filters (and). template <typename F, typename G> struct wedge : F, G { template <typename V> bool operator()(V v) const { return F::operator()(v) and G::operator()(v); } }; } //! @brief Namespace for plot building tools. namespace plot { //! @cond INTERNAL namespace details { //! @brief Shortens a string. std::string shorten(std::string s); //! @brief Shortens a title string. std::string multi_shorten(std::string s); } //! @endcond //! @brief Tag for time information. struct time {}; //! @brief Structure representing a point in a plot. struct point { //! @brief Default constructor. point() = default; //! @brief The unit of the measured value. std::string unit; //! @brief The source of the measured value. std::string source; //! @brief The measured value. double value; }; //! @brief Printing a single point. template <typename O> O& operator<<(O& o, point const& p) { o << "("; if (p.unit.size()) o << p.unit << ", "; o << p.source << ", " << p.value << ")"; return o; } //! @brief Structure representing a single plot. struct plot { //! @brief Default constructor. plot() = default; //! @brief Title of the plot. std::string title; //! @brief Label of the x axis. std::string xname; //! @brief Label of the y axis. std::string yname; //! @brief Values of x coordinates. std::vector<double> xvals; //! @brief Values of y coordinates with labels. std::vector<std::pair<std::string, std::vector<double>>> yvals; }; //! @brief Printing a single plot. template <typename O> O& operator<<(O& o, plot const& p) { o << "plot.put(plot.plot(name+\"-" << details::shorten(p.xname) << details::shorten(p.yname) << (p.title.size() ? "-" : "") << details::multi_shorten(p.title) << "\", \"" << p.title << "\", \"" << p.xname << "\", \"" << p.yname << "\", new string[] {"; bool first = true; for (auto const& y : p.yvals) { if (first) first = false; else o << ", "; o << "\"" << y.first << "\""; } o << "}, new pair[][] {"; first = true; for (auto const& y : p.yvals) { if (first) first = false; else o << ", "; o << "{"; for (size_t i=0; i<y.second.size(); ++i) { if (i > 0) o << ", "; o << "(" << p.xvals[i] << ", " << y.second[i] << ")"; } o << "}"; } o << "}));\n"; return o; } //! @brief Structure representing a page of plots. struct page { //! @brief Default constructor. page() = default; //! @brief Constructor with a vector of plots. page(std::vector<plot> p) : title(), rows(1), cols(p.size()), plots(p) {} //! @brief Constructor with an array of plots. template <size_t N> page(std::array<plot, N> p) : title(), rows(1), cols(N), plots(p.begin(), p.end()) {} //! @brief Title of the page. std::string title; //! @brief Number of rows. size_t rows; //! @brief Number of columns. size_t cols; //! @brief Plot list. std::vector<plot> plots; }; //! @brief Printing a single page. template <typename O> O& operator<<(O& o, page const& p) { if (p.title.size()) o << "// " << p.title << "\n\n"; o << "plot.ROWS = " << p.rows << ";\n"; o << "plot.COLS = " << p.cols << ";\n\n"; for (plot const& q : p.plots) o << q << "\n"; return o; } //! @brief Structure representing a whole file of plots. struct file { //! @brief Constructor with a vector of pages. file(std::string title, std::vector<page> p) : title(title), pages(p) {} //! @brief Constructor with an array of pages. template <size_t N> file(std::string title, std::array<page, N> p) : title(title), pages(p.begin(), p.end()) {} //! @brief Constructor with a vector of plots. file(std::string title, std::vector<plot> p) : title(title) { pages.emplace_back(p); } //! @brief Constructor with an array of plots. template <size_t N> file(std::string title, std::array<plot, N> p) : title(title) { pages.emplace_back(p); } //! @brief Title of the file. std::string title; //! @brief Page list. std::vector<page> pages; }; //! @brief Printing a file. template <typename O> O& operator<<(O& o, file const& f) { o << "// " << f.title << "\n"; o << "string name = \"" << f.title << "\";\n\n"; o << "import \"plot.asy\" as plot;\n"; o << "unitsize(1cm);\n\n"; for (page const& p : f.pages) o << p << "\n"; o << "shipout(\"" << f.title << "\");\n"; return o; } //! @brief Empty class not producing a plot. class none { public: //! @brief The internal build type. using build_type = typename std::array<point, 0>; //! @brief Default constructor. none() = default; //! @brief Row processing. template <typename R> none& operator<<(R const&) { return *this; } //! @brief Plot building for internal use. build_type build() const { return {}; } }; //! @cond INTERNAL namespace details { //! @brief Extract any multi-type option from a single type. template <typename T> struct option_types { using type = common::type_sequence<>; }; template <template<class...> class T, typename... Ts> struct option_types<T<Ts...>> { using type = common::type_sequence<Ts...>; }; //! @brief Integer holding a bit for every type in a type sequence. template <typename T> struct integer_delta_type; template <size_t n> struct integer_delta_type<std::array<int, n>> { using type = std::conditional_t<n <= 16, std::conditional_t<n <= 8, uint8_t, uint16_t>, std::conditional_t<n <= 32, uint32_t, uint64_t> >; }; template <typename... Ts> struct integer_delta_type<common::type_sequence<Ts...>> { using type = typename integer_delta_type<std::array<int, sizeof...(Ts)>>::type; }; //! @brief Tagged tuple wrapper, serialising the difference with a reference tuple. template <typename T> class delta_tuple : public T { //! @brief Type for storing deltas. using delta_type = typename integer_delta_type<typename T::tags>::type; public: //! @brief Default constructor. delta_tuple() : T(), m_ref(*this) {} //! @brief Reference constructor. delta_tuple(delta_tuple const& t) : T(), m_ref(t) {} //! @brief Inherit assignment operators. using T::operator=; //! @brief Assignment with delta tuples. delta_tuple& operator=(delta_tuple const& t) { T::operator=(static_cast<T const&>(t)); return *this; } //! @brief Serialises the content from/to a given input/output stream. template <typename S> S& serialize(S& s) { delta_type d = serialize_delta(s); serialize_impl(s, d, typename T::tags{}); return s; } private: //! @brief Serialises the delta bits. delta_type serialize_delta(common::isstream& s) { delta_type d; s.read(d); return d; } delta_type serialize_delta(common::type_sequence<>) { return 0; } template <typename S, typename... Ss> delta_type serialize_delta(common::type_sequence<S, Ss...>) { return (serialize_delta(common::type_sequence<Ss...>{}) << 1) + (common::get<S>(*this) == common::get<S>(m_ref)); } delta_type serialize_delta(common::osstream& s) { delta_type d = serialize_delta(typename T::tags{}); s.write(d); return d; } //! @brief Serialises a skipped field. template <typename S> void serialize_skip(common::isstream const&, common::type_sequence<S>) { common::get<S>(*this) = common::get<S>(m_ref); } template <typename S> void serialize_skip(common::osstream const&, common::type_sequence<S>) {} //! @brief Serialises given delta and tags. template <typename S> void serialize_impl(S&, delta_type, common::type_sequence<>) {} template <typename S, typename S1, typename... Ss> void serialize_impl(S& s, delta_type d, common::type_sequence<S1, Ss...>) { if (d & 1) serialize_skip(s, common::type_sequence<S1>{}); else s & common::get<S1>(*this); serialize_impl(s, d >> 1, common::type_sequence<Ss...>{}); } //! @brief Reference tuple. delta_tuple const& m_ref; }; } //! @endcond /** * @brief Plotter storing all rows for later printing. * * @param C Tags and types to be delta-compressed upon serialisation. * @param M Tags and types not compressed on serialisation. * @param F Tags and types assumed constant and stored only once. * @param max_size The maximum size in bytes allowed for the buffer (0 for no maximum size). */ template <typename C, typename M = void, typename F = void, size_t max_size = 0> class rows { public: //! @brief Sequence of tags and types to be delta-compressed upon serialisation. using compressible_tuple_type = details::delta_tuple<common::tagged_tuple_t<typename details::option_types<C>::type>>; //! @brief Sequence of tags and types not compressed on serialisation. using mutable_tuple_type = common::tagged_tuple_t<typename details::option_types<M>::type>; //! @brief Sequence of tags and types assumed constant and stored only once. using fixed_tuple_type = common::tagged_tuple_t<typename details::option_types<F>::type>; //! @brief The expected limit size of the object. static constexpr size_t limit_size = max_size; //! @brief Default constructor. rows() { m_start = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); m_rows.data().reserve(max_size); m_length = m_row_size = 0; } //! @brief Row processing. template <typename R> rows& operator<<(R const& row) { size_t prev_size = m_rows.size(); if (max_size == 0 or prev_size + m_row_size < max_size) { m_fixed = row; compressible_tuple_type tc(m_last); mutable_tuple_type tm; tc = row; tm = row; (m_rows << tc << tm); m_last = row; m_row_size = std::max(m_row_size, m_rows.size() - prev_size); ++m_length; } return *this; } //! @brief The number of rows stored. size_t size() const { return m_length; } //! @brief The number of bytes occupied by the structure. size_t byte_size() const { return sizeof(rows) + m_rows.size(); } //! @brief Prints the object's contents. template <typename O> void print(O& o) { common::isstream rows({}); std::swap(rows.data(), m_rows.data()); std::string tstr = std::string(ctime(&m_start)); tstr.pop_back(); o << "########################################################\n"; o << "# FCPP execution started at: " << tstr << " #\n"; o << "########################################################\n# "; m_fixed.print(o, common::assignment_tuple); o << "\n#\n"; o << "# The columns have the following meaning:\n# "; print_headers(o, typename mutable_tuple_type::tags{}); print_headers(o, typename compressible_tuple_type::tags{}); o << "\n"; m_last = compressible_tuple_type(); for (size_t i=0; i<m_length; ++i) { compressible_tuple_type tc(m_last); mutable_tuple_type tm; rows >> tc >> tm; m_last = tc; print_output(o, tm, typename mutable_tuple_type::tags{}); print_output(o, tc, typename compressible_tuple_type::tags{}); o << "\n"; } std::time_t m_end = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); tstr = std::string(ctime(&m_end)); tstr.pop_back(); o << "########################################################\n"; o << "# FCPP execution finished at: " << tstr << " #\n"; o << "########################################################" << std::endl; std::swap(rows.data(), m_rows.data()); } private: //! @brief Prints the storage headers. template <typename O> void print_headers(O&, common::type_sequence<>) const {} template <typename O, typename U, typename... Us> void print_headers(O& o, common::type_sequence<U,Us...>) const { o << common::details::strip_namespaces(common::type_name<U>()) << " "; print_headers(o, common::type_sequence<Us...>{}); } //! @brief Prints the storage values. template <typename O, typename T> void print_output(O&, T const&, common::type_sequence<>) const {} template <typename O, typename T, typename U, typename... Us> void print_output(O& o, T const& t, common::type_sequence<U,Us...>) const { o << common::escape(common::get<U>(t)) << " "; print_output(o, t, common::type_sequence<Us...>{}); } //! @brief Start time. std::time_t m_start; //! @brief Fixed data. fixed_tuple_type m_fixed; //! @brief Last row of compressible data. compressible_tuple_type m_last; //! @brief Serialised rows. common::osstream m_rows; //! @brief Number of rows stored. size_t m_length; //! @brief Maximum size of a row ever recorded. size_t m_row_size; }; template <typename C, typename M, typename F, size_t max_size> constexpr size_t rows<C,M,F,max_size>::limit_size; //! @brief Filters values for column S according to property F in plotter P. template <typename S, typename F, typename P> class filter { public: //! @brief The internal build type. using build_type = typename P::build_type; //! @brief Default constructor. filter() = default; //! @brief Row processing. template <typename R> filter& operator<<(R const& row) { if (m_filter(common::get<S>(row))) (m_plotter << row); return *this; } //! @brief Plot building for internal use. build_type build() const { return m_plotter.build(); } private: //! @brief The plotter. P m_plotter; //! @brief The callable filter class. F m_filter; }; //! @cond INTERNAL namespace details { //! @brief Concatenate vector and array types. template <typename... Ts> struct array_cat; //! @brief Concatenate one vector type. template <typename T> struct array_cat<std::vector<T>> { using type = std::vector<T>; }; //! @brief Concatenate one array type. template <typename T, size_t N> struct array_cat<std::array<T,N>> { using type = std::array<T,N>; }; //! @brief Concatenate two compatible vector types. template <typename T> struct array_cat<std::vector<T>, std::vector<T>> { using type = std::vector<T>; }; //! @brief Concatenate vector and array types. template <typename T, size_t N> struct array_cat<std::vector<T>, std::array<T,N>> { using type = std::vector<T>; }; //! @brief Concatenate array and vector types. template <typename T, size_t N> struct array_cat<std::array<T,N>, std::vector<T>> { using type = std::vector<T>; }; //! @brief Concatenate two compatible array types. template <typename T, size_t N, size_t M> struct array_cat<std::array<T,N>, std::array<T,M>> { using type = std::array<T,N+M>; }; //! @brief Concatenate plots and pages arrays. template <size_t N, size_t M> struct array_cat<std::array<plot,N>, std::array<page,M>> { using type = std::array<page,M+1>; }; template <size_t N, size_t M> struct array_cat<std::array<page,N>, std::array<plot,M>> { using type = std::array<page,N+1>; }; //! @brief Concatenate plots and pages vectors. template <> struct array_cat<std::vector<plot>, std::vector<page>> { using type = std::vector<page>; }; template <> struct array_cat<std::vector<page>, std::vector<plot>> { using type = std::vector<page>; }; //! @brief Concatenate plots arrays and pages vectors. template <size_t N> struct array_cat<std::array<plot,N>, std::vector<page>> { using type = std::vector<page>; }; template <size_t N> struct array_cat<std::vector<page>, std::array<plot,N>> { using type = std::vector<page>; }; //! @brief Concatenate plots vectors and pages arrays. template <size_t N> struct array_cat<std::vector<plot>, std::array<page,N>> { using type = std::array<page,N+1>; }; template <size_t N> struct array_cat<std::array<page,N>, std::vector<plot>> { using type = std::array<page,N+1>; }; //! @brief Concatenate multiple vector and array types. template <typename T, typename U, typename... Us> struct array_cat<T, U, Us...> { using type = typename array_cat<T, typename array_cat<U, Us...>::type>::type; }; //! @brief Resizes a vector. template <typename T> void maybe_resize(std::vector<T>& v, size_t s) { v.resize(s); } //! @brief Does not resize an array. template <typename T, size_t N> void maybe_resize(std::array<T,N>&, size_t) {} //! @brief Does not convert a vector. template <typename T> inline std::vector<T> maybe_promote(common::type_sequence<T>, std::vector<T> v) { return v; } //! @brief Does not convert an array. template <typename T, size_t N> inline std::array<T,N> maybe_promote(common::type_sequence<T>, std::array<T,N> v) { return v; } //! @brief Converts a vector of plots. inline std::array<page,1> maybe_promote(common::type_sequence<page>, std::vector<plot> v) { return {v}; } //! @brief Converts an array of plots. template <size_t N> inline std::array<page,1> maybe_promote(common::type_sequence<page>, std::array<plot,N> v) { return {v}; } } //! @endcond //! @brief Joins a sequence of plotters. template <typename... Ps> class join { public: //! @brief The internal build type. using build_type = typename details::array_cat<typename Ps::build_type...>::type; //! @brief Default constructor. join() = default; //! @brief Row processing. template <typename R> join& operator<<(R const& row) { input_impl(row, std::make_index_sequence<sizeof...(Ps)>{}); return *this; } //! @brief Plot building for internal use. build_type build() const { build_type res; build_impl(res, std::make_index_sequence<sizeof...(Ps)>{}); return res; } private: //! @brief Forwarding rows to plotters. template <typename R, size_t... is> void input_impl(R const& row, std::index_sequence<is...>) { common::details::ignore((std::get<is>(m_plotters) << row)...); } //! @brief Stop joining plotter builds. void build_impl(build_type&, std::index_sequence<>, size_t) const {} //! @brief Joining plotter builds. template <size_t i, size_t... is> void build_impl(build_type& res, std::index_sequence<i, is...>, size_t x = 0) const { auto ri = details::maybe_promote(common::type_sequence<typename build_type::value_type>{}, std::get<i>(m_plotters).build()); details::maybe_resize(res, x+ri.size()); for (size_t j = 0; j < ri.size(); ++j) res[x+j] = std::move(ri[j]); build_impl(res, std::index_sequence<is...>{}, x + ri.size()); } //! @brief The plotters. std::tuple<Ps...> m_plotters; }; //! @brief Optimised Join of a single plotter. template <typename P> class join<P> : public P {}; //! @cond INTERNAL namespace details { //! @brief Formats a type description. inline std::string& format_type(std::string& s) { for (size_t i=0; i<s.size(); ++i) if (s[i] == '_') s[i] = ' '; return s; } //! @brief Formats a type description. inline std::string format_type(std::string&& s) { return format_type(s); } //! @brief Formats a type description. inline std::string format_type(std::string const& s) { return format_type(std::string(s)); } //! @brief Checks whether C has a static name method. template<typename C> struct has_name_method { private: template <typename T> static constexpr auto check(T*) -> typename std::is_same< decltype(T::name()), std::string >::type; template <typename> static constexpr std::false_type check(...); typedef decltype(check<C>(0)) type; public: static constexpr bool value = type::value; }; } //! @endcond //! @brief Maintains a value for the column S aggregated with A. template <typename S, typename A = aggregator::mean<double>> class value { public: //! @brief The internal build type. using build_type = std::array<point, 1>; //! @brief Default constructor. value() = default; //! @brief Row processing. template <typename R> value& operator<<(R const& row) { common::lock_guard<true> l(m_mutex); m_aggregator.insert(common::get<S>(row)); return *this; } //! @brief Plot building for internal use. build_type build() const { point p; std::string t = tag_name(common::bool_pack<details::has_name_method<S>::value>{}); // tag name size_t pos = t.find("<"); if (pos != std::string::npos) { p.unit = common::details::strip_namespaces(t.substr(0, pos)); p.source = common::details::strip_namespaces(t.substr(pos+1, t.size()-pos-2)); } else { pos = t.find("__"); if (pos != std::string::npos) { p.source = common::details::strip_namespaces(t.substr(0, pos)); p.unit = t.substr(pos+2); } else { p.unit = ""; p.source = common::details::strip_namespaces(t); } } details::format_type(p.unit); details::format_type(p.source); std::string ar = A::name(); // row aggregator std::string ad = aggregator_name(common::bool_pack<details::has_name_method<S>::value>{}); // device aggregator p.source += " (" + ad + ar + ")"; p.value = std::get<0>(m_aggregator.template result<S>()); return {p}; } private: //! @brief Device aggregator name (if present). std::string aggregator_name(common::bool_pack<true>) const { return S::name() + "-"; } //! @brief Device aggregator name (if absent). std::string aggregator_name(common::bool_pack<false>) const { return ""; } //! @brief Tag name (if aggregator present). std::string tag_name(common::bool_pack<true>) const { return common::type_name<typename S::type>(); } //! @brief Tag name (if aggregator absent). std::string tag_name(common::bool_pack<false>) const { return common::type_name<S>(); } //! @brief A mutex for synchronised access to the aggregator. common::mutex<true> m_mutex; //! @brief The aggregator. A m_aggregator; }; //! @brief Tag for declaring units to be extracted. template <template<class> class... Ts> struct unit; //! @cond INTERNAL namespace details { //! @brief Smart append of a plotter to a join. template <typename Q, typename... Ps> struct appender { using type = join<Ps..., Q>; }; //! @brief Smart append of a join to a join. template <typename... Qs, typename... Ps> struct appender<join<Qs...>, Ps...> { using type = join<Ps..., Qs...>; }; //! @brief Smart join of plotters. template <typename... Ps> struct joiner; //! @brief Smart join of one plotter. template <typename P> struct joiner<P> { using type = P; }; //! @brief Smart join of two plotters (first non-join). template <typename P, typename Q> struct joiner<P, Q> : public appender<Q, P> {}; //! @brief Smart join of two plotter (first join). template <typename... Ps, typename Q> struct joiner<join<Ps...>, Q> : public appender<Q, Ps...> {}; //! @brief Smart join of multiple plotters. template <typename P, typename Q, typename... Qs> struct joiner<P, Q, Qs...> : public joiner<typename joiner<P, Q>::type, Qs...> {}; //! @brief Searches type T within tags and aggregators in S (general form). template <typename T, typename S> struct field_grep; //! @brief Searches type T within tags and aggregators in S. template <typename T, typename... Ss, typename... As> struct field_grep<T, common::tagged_tuple<common::type_sequence<Ss...>, common::type_sequence<As...>>> { using type = common::type_cat<std::conditional_t<std::is_same<Ss,T>::value or std::is_same<As,T>::value, typename As::template result_type<Ss>::tags, common::type_sequence<>>...>; }; //! @brief Searches template T within tags in S (general form). template <template<class> class T, typename S> struct unit_grep { using type = common::type_sequence<bool>; }; //! @brief Searches template T within tags in S. template <template<class> class T, typename... Ss, typename... As> struct unit_grep<T, common::tagged_tuple<common::type_sequence<Ss...>, common::type_sequence<As...>>> { using type = common::type_cat<std::conditional_t<common::is_class_template<T,Ss>, typename As::template result_type<Ss>::tags, common::type_sequence<>>...>; }; //! @brief Maintains values for multiple columns and aggregators (general form). template <typename S, typename A, typename... Ts> struct values; //! @brief Maintains values for one explicit column and one aggregator. template <template<class...> class S, typename S1, template<class...> class A, typename A1> struct values<S<S1>, A<A1>> { using type = value<S1, A1>; }; //! @brief Maintains values for multiple explicit columns and one aggregator. template <template<class...> class S, typename S1, typename... Ss, template<class...> class A, typename A1> struct values<S<S1, Ss...>, A<A1>> { using type = join<value<S1, A1>, value<Ss, A1>...>; }; //! @brief Maintains values for multiple explicit columns and no aggregators (defaults to `mean<double>`). template <typename S, template<class...> class A> struct values<S, A<>> : public values<S, A<aggregator::mean<double>>> {}; //! @brief Maintains values for multiple explicit columns and multiple aggregators. template <typename S, template<class...> class A, typename A1, typename... As> struct values<S, A<A1, As...>> : public joiner<typename values<S, A<A1>>::type, typename values<S, A<As>>::type...> {}; //! @brief Maintains values for multiple columns and aggregators, defined through a single field. template <template<class...> class S, typename... Ss, typename A, typename T> struct values<S<Ss...>, A, T> : public values<typename field_grep<T, common::tagged_tuple_t<common::type_sequence<Ss...>>>::type, A> {}; //! @brief Maintains values for multiple columns and aggregators, defined through a single unit. template <template<class...> class S, typename... Ss, typename A, template<class> class T> struct values<S<Ss...>, A, unit<T>> : public values<typename unit_grep<T, common::tagged_tuple_t<common::type_sequence<Ss...>>>::type, A> {}; //! @brief Maintains values for multiple columns and aggregators, defined through multiple units. template <typename S, typename A, template<class> class T, template<class> class... Ts> struct values<S, A, unit<T, Ts...>> : public joiner<typename values<S, A, unit<T>>::type, typename values<S, A, unit<Ts>>::type...> {}; //! @brief Maintains values for multiple columns and aggregators, defined through multiple fields. template <typename S, typename A, typename T1, typename T2, typename... Ts> struct values<S, A, T1, T2, Ts...> : public joiner<typename values<S, A, T1>::type, typename values<S, A, T2>::type, typename values<S, A, Ts>::type...> {}; } //! @endcond /** * @brief Maintains values for multiple columns and aggregators. * * @param S The sequence of tags and aggregators for logging (intertwined). * @param A The sequence of row aggregators (if empty, `mean<double>` is assumed). * @param Ts Description of fields to be extracted as tags, aggregators or units (if empty, S is interpreted as fields). */ template <typename S, typename A, typename... Ts> using values = typename details::values<S, A, Ts...>::type; namespace details { //! @brief The type to be used for a single key. template <typename S> struct key_type { using type = common::tagged_tuple_t<S, double>; static constexpr bool single = true; }; //! @brief The type to be used for multiple keys. template <typename... Ss> struct key_type<common::type_sequence<Ss...>> { using type = common::tagged_tuple_cat<common::tagged_tuple_t<Ss, double>...>; static constexpr bool single = (sizeof...(Ss) == 1); }; //! @brief Inspects a build type. template <typename T> struct inspector; //! @brief Whether a vector build type contains a single object. template <typename T> struct inspector<std::vector<T>> { using type = T; static constexpr bool single = false; }; //! @brief Whether an array build type contains a single object. template <typename T, size_t N> struct inspector<std::array<T,N>> { using type = T; static constexpr bool single = (N == 1); }; //! @brief Promotes a maximal build type after split. template <typename P, bool single> struct promote_impl { using type = std::vector<page>; }; //! @brief Promotes multiple plots after split. template <> struct promote_impl<plot, false> { using type = std::array<page, 1>; }; //! @brief Promotes a single plot after split. template <> struct promote_impl<plot, true> { using type = std::vector<plot>; }; //! @brief Promotes points after split. template <bool single> struct promote_impl<point, single> { using type = std::array<plot, 1>; }; //! @brief Promotes a build type after split. template <typename P> using promote = typename promote_impl<typename inspector<P>::type, inspector<P>::single>::type; } /** * Split rows depending on * * @param S A column tag, or a `type_sequence` of column tags. * @param P The plotter to be split. * @param B A bucket size (as `std::ratio`, only for a single key). */ template <typename S, typename P, typename B = std::ratio<0>> class split { //! @brief The build type of dependent plotters. using parent_build_type = typename P::build_type; static_assert(details::key_type<S>::single or not std::is_same<typename details::inspector<parent_build_type>::type, point>::value, "cannot split points with multiple keys"); static_assert(details::key_type<S>::single or std::is_same<std::ratio<0>, B>::value, "cannot use bucket size with multiple keys"); //! @brief The type used for splitting keys. using key_type = typename details::key_type<S>::type; public: //! @brief The internal build type. using build_type = details::promote<parent_build_type>; //! @brief Default constructor. split() = default; //! @brief Row processing. template <typename R> split& operator<<(R const& row) { static_assert(common::type_intersect<typename R::tags, typename key_type::tags>::size == key_type::tags::size, "splitting key not in plot row"); key_type k = approx_impl(row, B{}); P* p; { common::lock_guard<true> l(m_mutex); p = &m_plotters[k]; } *p << row; return *this; } //! @brief Plot building for internal use. build_type build() const { std::map<key_type, parent_build_type> m; for (auto const& x : m_plotters) m.emplace(x.first, x.second.build()); build_type res; build_impl(res, m); return res; } private: //! @brief No approximations without buckets. template <typename R> key_type approx_impl(R const& row, std::ratio<0>) const { return row; } //! @brief Approximating the key to the closest bucket multiple. template <typename R, intmax_t num, intmax_t den, typename = std::enable_if_t<num != 0>> key_type approx_impl(R const& row, std::ratio<num,den>) const { key_type k = row; intmax_t n = std::get<0>(k) * den / num + 0.5; std::get<0>(k) = double(n*num)/den; return k; } //! @brief Single plot building. void build_impl(std::array<plot, 1>& res, std::map<key_type, parent_build_type>& m) const { res[0].xname = details::format_type(common::details::strip_namespaces(common::type_name<S>())); std::set<std::string> units; if (m.size()) for (point const& q : m.begin()->second) { if (q.unit.size()) units.insert(q.unit); res[0].yvals.emplace_back(q.source, std::vector<double>{}); } for (std::string const& s : units) { res[0].yname += (res[0].yname.size() ? "/" : "") + s; } if (units.empty()) res[0].yname = "y"; for (auto const& p : m) { res[0].xvals.push_back(std::get<0>(p.first)); for (size_t i = 0; i < p.second.size(); ++i) res[0].yvals[i].second.push_back(p.second[i].value); } } //! @brief Multiple plot building. void build_impl(std::vector<plot>& res, std::map<key_type, parent_build_type>& m) const { for (auto& p : m) { std::stringstream ss; p.first.print(ss, common::assignment_tuple); p.second[0].title = details::format_type(ss.str()); res.push_back(std::move(p.second[0])); } } //! @brief Single page building. void build_impl(std::array<page, 1>& res, std::map<key_type, parent_build_type>& m) const { res[0].rows = m.size(); res[0].cols = m.size() ? m.begin()->second.size() : 0; for (auto& p : m) { std::stringstream ss; p.first.print(ss, common::assignment_tuple); for (auto& q : p.second) { q.title = details::format_type(ss.str()) + (q.title.size() ? ", " : "") + q.title; res[0].plots.push_back(std::move(q)); } } } //! @brief Multiple page building. void build_impl(std::vector<page>& res, std::map<key_type, parent_build_type>& m) const { for (auto& p : m) { std::stringstream ss; p.first.print(ss, common::assignment_tuple); for (auto& q : p.second) { q.title = details::format_type(ss.str()) + (q.title.size() ? ", " : "") + q.title; res.push_back(std::move(q)); } } } //! @brief A mutex for synchronised access to the map. common::mutex<true> m_mutex; //! @brief The plotter. std::map<key_type, P> m_plotters; }; /** * @brief Produces a single plot. * * @param S The sequence of tags and aggregators for logging (intertwined). * @param X The tag to be used for the x axis. * @param Y The unit to be used for the y axis. * @param A The sequence of row aggregators (defaults to `mean<double>`). */ template <typename S, typename X, template<class> class Y, typename A = common::type_sequence<>> using plotter = split<X, values<S, A, unit<Y>>>; } } #endif // FCPP_COMMON_PLOT_H_
35.13586
256
0.596759
bitslow
2dc9d69e1e110f26c3e825995142eec7fcd7f432
4,232
cpp
C++
mechanics/src/core/NetVarManager.cpp
robindittmar/mechanics
ea62f750d3cd448cbd708dee972d5a5b9a1464a0
[ "MIT" ]
null
null
null
mechanics/src/core/NetVarManager.cpp
robindittmar/mechanics
ea62f750d3cd448cbd708dee972d5a5b9a1464a0
[ "MIT" ]
null
null
null
mechanics/src/core/NetVarManager.cpp
robindittmar/mechanics
ea62f750d3cd448cbd708dee972d5a5b9a1464a0
[ "MIT" ]
null
null
null
#include "NetVarManager.h" CNetVarManager::CNetVarManager() { m_bSummarizeOffsets = false; } CNetVarManager::~CNetVarManager() { CNetVar* pCurrent; for (std::map<uint32_t, CNetVar*>::iterator it = m_mapNetVars.begin(); it != m_mapNetVars.end(); it++) { pCurrent = it->second; if (pCurrent) delete pCurrent; } } void CNetVarManager::AddTable(const char* pTable) { #ifdef _DEBUG g_pConsole->Write(LOGLEVEL_INFO, "Added '%s' to NetVarMgr\n", pTable); #endif uint32_t iHash = murmurhash(pTable, strlen(pTable), 0xB16B00B5); m_mapTablesToLoad[iHash] = true; } void CNetVarManager::LoadTables(ClientClass* pClass, bool bRecursive) { uint32_t iHash; RecvTable* pTable; CNetVar* pNetVar; // Iterate over list while(pClass) { // Grab current table pTable = pClass->m_pRecvTable; // Build hash from name & 'load' if necessary iHash = murmurhash(pTable->m_pNetTableName, strlen(pTable->m_pNetTableName), 0xB16B00B5); if(m_mapTablesToLoad[iHash]) { // Init and load netvar pNetVar = new CNetVar(); pNetVar->LoadTable(pTable, bRecursive); // Add netvar to map m_mapNetVars[iHash] = pNetVar; } // Next element pClass = pClass->m_pNext; } } CNetVar* CNetVarManager::GetNetVar(const char* pTable, const char* pNetVarName) { if (!pNetVarName) { return m_mapNetVars[murmurhash(pTable, strlen(pTable), 0xB16B00B5)]; } return this->GetNetVar(1, pTable, pNetVarName); } CNetVar* CNetVarManager::GetNetVar(int iCountToResolve, const char* pTable, ...) { uint32_t iHash = murmurhash(pTable, strlen(pTable), 0xB16B00B5); CNetVar* pNetVar = m_mapNetVars[iHash]; const char* pCurArg; va_list pArgList; va_start(pArgList, pTable); for (int i = 0; i < iCountToResolve; i++) { if (!pNetVar->GetIsTable()) { break; } pCurArg = va_arg(pArgList, const char*); pNetVar = pNetVar->GetChild(pCurArg); if (!pNetVar) return NULL; } va_end(pArgList); return pNetVar; } int CNetVarManager::GetOffset(const char* pTable, const char* pNetVarName) { return this->GetOffset(1, pTable, pNetVarName); } int CNetVarManager::GetOffset(int iCountToResolve, const char* pTable, ...) { int iOffset = 0; uint32_t iHash = murmurhash(pTable, strlen(pTable), 0xB16B00B5); CNetVar* pNetVar = m_mapNetVars[iHash]; const char* pCurArg; va_list pArgList; va_start(pArgList, pTable); for(int i = 0; i < iCountToResolve; i++) { if (!pNetVar->GetIsTable()) { iOffset = -1; break; } pCurArg = va_arg(pArgList, const char*); pNetVar = pNetVar->GetChild(pCurArg); if (!pNetVar) { iOffset = -1; break; } if (m_bSummarizeOffsets) iOffset += pNetVar->GetOffset(); else iOffset = pNetVar->GetOffset(); } va_end(pArgList); return iOffset; } void CNetVarManager::DumpAll(FILE* pFile, ClientClass* pClass) { while(pClass) { DumpTable(pFile, pClass->m_pRecvTable); pClass = pClass->m_pNext; } } void CNetVarManager::DumpTable(FILE* pFile, ClientClass* pClass, const char* pTableName) { RecvTable* pTable; while(pClass) { pTable = pClass->m_pRecvTable; if(!strcmp(pTable->m_pNetTableName, pTableName)) { DumpTable(pFile, pTable); } pClass = pClass->m_pNext; } } void CNetVarManager::DumpClientClasses(FILE* pFile, ClientClass* pClass) { std::map<int, const char*> mapTest; while (pClass) { mapTest[pClass->m_ClassID] = pClass->m_pNetworkName; pClass = pClass->m_pNext; } for (std::map<int, const char*>::iterator it = mapTest.begin(); it != mapTest.end(); it++) { fprintf(pFile, "%s = %d,\n", it->second, it->first); } } void printTabs(FILE* pFile, int iCount) { for(int i = 0; i < iCount; i++) { fputs(" ", pFile); } } void CNetVarManager::DumpTable(FILE* pFile, RecvTable* pTable, int iLevel) { RecvProp* pProp; fprintf(pFile, "%s\n", pTable->m_pNetTableName); for (int i = 0; i < pTable->m_nProps; i++) { pProp = pTable->m_pProps + i; if (pProp->m_RecvType == SendPropType::DPT_DataTable) { printTabs(pFile, iLevel + 1); fprintf(pFile, "[%s (0x%X)] ", pProp->m_pVarName, pProp->m_Offset); DumpTable(pFile, pProp->m_pDataTable, iLevel + 1); } else { printTabs(pFile, iLevel + 1); fprintf(pFile, "%s (0x%X)\n", pProp->m_pVarName, pProp->m_Offset); } } }
20.543689
103
0.681947
robindittmar
2dcbcce595687f861aba1ee80bb0510da3f94348
866
cpp
C++
src/io/KegType.cpp
caseymcc/Vorb
a2782bbff662c226002fa69bae688a44770deaf4
[ "MIT" ]
1
2018-10-17T06:37:17.000Z
2018-10-17T06:37:17.000Z
src/io/KegType.cpp
caseymcc/Vorb
a2782bbff662c226002fa69bae688a44770deaf4
[ "MIT" ]
null
null
null
src/io/KegType.cpp
caseymcc/Vorb
a2782bbff662c226002fa69bae688a44770deaf4
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "io/KegType.h" #include "io/Keg.h" keg::Type::Type() : m_sizeInBytes(0), m_values() { // Empty } keg::Type::Type(const nString& name, Environment* env) { if (env) env->addType(name, this); keg::getGlobalEnvironment()->addType(name, this); } void keg::Type::addValue(const nString& name, const Value& type) { m_values[name] = type; } void keg::Type::addSuper(const Type* type, size_t offset /*= 0*/) { for (auto kvPair : type->m_values) { kvPair.second.offset += offset; m_values[kvPair.first] = kvPair.second; } } void keg::Type::construct(void* data) { m_ctor(data); } void* keg::Type::alloc() { return m_alloc(); } void* keg::Type::allocArray(size_t s) { return m_allocArray(s); } keg::DeallocatorFunction keg::Type::getDeallocator() const { return m_deallocArray; }
22.789474
67
0.642032
caseymcc
2dcdb536cc76486ed6b6a0e50b7edd0134ce6491
2,512
hpp
C++
engine/include/game_object.hpp
antonkanin/potatoengine
9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd
[ "MIT" ]
null
null
null
engine/include/game_object.hpp
antonkanin/potatoengine
9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd
[ "MIT" ]
null
null
null
engine/include/game_object.hpp
antonkanin/potatoengine
9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd
[ "MIT" ]
1
2020-01-29T10:18:23.000Z
2020-01-29T10:18:23.000Z
#pragma once #include "mesh.hpp" #include "model.hpp" #include "ptm/vec3.hpp" #include "transformation.hpp" #include <BulletDynamics/Dynamics/btRigidBody.h> #include <engine.hpp> #include <memory> namespace pt { class component; class game_object { public: explicit game_object(std::string name); virtual ~game_object(); /** called once for each game object before the main loop */ virtual void start(){}; /** called every frame */ virtual void update(){}; /** add custom GUI */ virtual void on_gui(){}; [[nodiscard]] virtual bool is_serializable() const { return false; } void set_transform(const transformation& transform); [[nodiscard]] const transformation& get_transformation() const; game_object* set_position(const ptm::vec3& position); [[nodiscard]] ptm::vec3 get_position() const; game_object* set_scale(const ptm::vec3& scale); [[nodiscard]] ptm::vec3 get_scale() const; game_object* set_rotation(const ptm::vec3& rotation_vector, float angle); [[nodiscard]] const model& get_model() const; void set_model(std::unique_ptr<model>&); game_object* load_model(const std::string& path); game_object* add_body(bool is_dynamic); // physics btRigidBody* body_ = nullptr; btMotionState* motion_state_ = nullptr; [[nodiscard]] std::string get_name() const; void self_destroy(); engine& get_engine(); void add_component(std::unique_ptr<component> component); private: void set_position_forced(const ptm::vec3& position); void set_rotation_forced(const ptm::vec3& rotation_vector, float angle); void set_name(const std::string& name); void destroy_forced(); friend engine; friend engine_impl; friend game_objects_list; engine* engine_ = nullptr; bool has_model_ = false; std::unique_ptr<model> model_; transformation transformation_ = { .position = ptm::vec3::zero(), .rotation_vector = ptm::vec3::up(), .rotation_angle = 0.0f, .scale = { 1.f, 1.f, 1.f } }; std::string name_ = "NoName"; bool to_be_destroyed_ = false; std::vector<std::unique_ptr<component>> components_; }; template <typename T> game_object* make_object(engine& e, std::string_view object_name) { return e.add_object<T>(object_name); } } // namespace pt
24.627451
78
0.636943
antonkanin
2dcdd25b4e25abf12c26b7141086a50240ac99fc
2,096
cpp
C++
Source Files/Application/Scripts/Managers/FadeManager.cpp
ZackaryCowled/C-Game-Engine
ea26370036f348058000f007fe3c9a8a792e8db4
[ "MIT" ]
null
null
null
Source Files/Application/Scripts/Managers/FadeManager.cpp
ZackaryCowled/C-Game-Engine
ea26370036f348058000f007fe3c9a8a792e8db4
[ "MIT" ]
null
null
null
Source Files/Application/Scripts/Managers/FadeManager.cpp
ZackaryCowled/C-Game-Engine
ea26370036f348058000f007fe3c9a8a792e8db4
[ "MIT" ]
null
null
null
//Internal includes #include "ApplicationHeaders.h" //Fades in all registered GUI objects //Function returns true when all registered GUI objects are fully faded in const bool FadeManager::FadeInGUIObjects(const float fadeSpeed) { //Flag representing whether all registered GUI objects are fully faded in bool fadeStatus = true; //For each registered GUI object for (unsigned int guiObjectIndex = 0; guiObjectIndex < guiObjectContainer.size(); ++guiObjectIndex) { //Fade in the GUI object if (!guiObjectContainer[guiObjectIndex]->FadeIn(fadeSpeed)) { //Set the fade status flag to false fadeStatus = false; } } //Return the fade status return fadeStatus; } //Fades out all registered GUI objects //Function reutrns true when all registered GUI objects are fully faded out const bool FadeManager::FadeOutGUIObjects(const float fadeSpeed) { //Flag representing whether all registered GUI objects are fully faded out bool fadeStatus = true; //For each registered GUI object for (unsigned int guiObjectIndex = 0; guiObjectIndex < guiObjectContainer.size(); ++guiObjectIndex) { //Fade out the GUI object if (!guiObjectContainer[guiObjectIndex]->FadeOut(fadeSpeed)) { //Set the fade status flag to false fadeStatus = false; } } //Return the fade status return fadeStatus; } //Registers the specified GUI object void FadeManager::RegisterGUIObject(GUIObject* p_guiObject) { //Register the specified GUI object guiObjectContainer.push_back(p_guiObject); } //Unregisters the specified GUI object void FadeManager::UnregisterGUIObject(GUIObject* p_guiObject) { //For each registered GUI object for (unsigned int guiObjectIndex = 0; guiObjectIndex < guiObjectContainer.size(); ++guiObjectIndex) { //If the address of the registered GUI object is the same as the specified GUI object if (guiObjectContainer[guiObjectIndex] == p_guiObject) { //Erase the GUI object from the GUI object container (Unregister GUI object) guiObjectContainer.erase(guiObjectContainer.begin() + guiObjectIndex); //Return from the function return; } } }
29.521127
100
0.761927
ZackaryCowled
2dd337a073373ec7ffd812049adc1d75e543a980
2,426
cpp
C++
src/Mahi/Com/MelShare.cpp
chip5441/mahi-com
fc7efcc5d7e9ff995303bbc162e694f25f47d6dd
[ "MIT" ]
1
2021-09-22T08:37:01.000Z
2021-09-22T08:37:01.000Z
src/Mahi/Com/MelShare.cpp
chip5441/mahi-com
fc7efcc5d7e9ff995303bbc162e694f25f47d6dd
[ "MIT" ]
1
2020-11-16T04:05:47.000Z
2020-11-16T04:05:47.000Z
src/Mahi/Com/MelShare.cpp
chip5441/mahi-com
fc7efcc5d7e9ff995303bbc162e694f25f47d6dd
[ "MIT" ]
2
2020-12-21T09:28:26.000Z
2021-09-17T03:08:19.000Z
#include <Mahi/Com/MelShare.hpp> #include <Mahi/Util/Types.hpp> #include <Mahi/Com/Packet.hpp> // #include <Mahi/Util.hpp> // #include <Mahi/Com.hpp> using namespace mahi::util; namespace mahi { namespace com { //============================================================================== // CLASS DEFINITIONS //============================================================================== MelShare::MelShare(const std::string& name, OpenMode mode, std::size_t max_bytes) : shm_(name, mode, max_bytes), mutex_(name + "_mutex", mode) { } void MelShare::write(Packet& packet) { Lock lock(mutex_); std::size_t size = 0; const void* data = packet.on_send(size); uint32 size32 = static_cast<uint32>(size); shm_.write(&size32, sizeof(uint32)); shm_.write(data, size, sizeof(uint32)); } void MelShare::read(Packet& packet) { Lock lock(mutex_); uint32 size32 = get_size(); std::size_t size = static_cast<std::size_t>(size32); if (size > 0) { std::vector<char> data(size); shm_.read(&data[0], size, sizeof(uint32)); packet.on_receive(&data[0], size); } } void MelShare::write_data(const std::vector<double>& data) { Lock lock(mutex_); uint32 size = static_cast<uint32>(data.size() * sizeof(double)); shm_.write(&size, sizeof(uint32)); shm_.write(&data[0], size, sizeof(uint32)); } std::vector<double> MelShare::read_data() { Lock lock(mutex_); uint32 size = get_size(); if (size > 0) { std::vector<double> data(size / sizeof(double)); shm_.read(&data[0], size, sizeof(uint32)); return data; } else return std::vector<double>(); } void MelShare::write_message(const std::string &message) { Lock lock(mutex_); uint32 size = static_cast<uint32>(message.length() + 1); shm_.write(&size, sizeof(uint32)); shm_.write(message.c_str(), size, sizeof(uint32)); } std::string MelShare::read_message() { Lock lock(mutex_); uint32 size = get_size(); if (size > 0) { std::vector<char> message(size); shm_.read(&message[0], size, sizeof(uint32)); return std::string(&message[0]); } else return std::string(); } bool MelShare::is_mapped() const { return shm_.is_mapped(); } uint32 MelShare::get_size() { uint32 size; shm_.read(&size, sizeof(uint32)); return size; } } // namespace mahi } // namespace com
26.086022
83
0.589448
chip5441
2dd35e9c6291a88fe722124cd581c24456425036
1,642
cpp
C++
Atomic/AtObjId.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
4
2019-11-10T21:56:40.000Z
2021-12-11T20:10:55.000Z
Atomic/AtObjId.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
null
null
null
Atomic/AtObjId.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
1
2019-11-11T08:38:59.000Z
2019-11-11T08:38:59.000Z
#include "AtIncludes.h" #include "AtObjId.h" namespace At { ObjId ObjId::None(0, 0); ObjId ObjId::Root(1, 0); byte* ObjId::EncodeBin_Ptr(byte* p) const { memcpy(p, &m_index, 8); p += 8; memcpy(p, &m_uniqueId, 8); p += 8; return p; } void ObjId::EncodeBin(Enc& enc) const { Enc::Write write = enc.IncWrite(16); memcpy(write.Ptr(), &m_index, 8); memcpy(write.Ptr()+8, &m_uniqueId, 8); write.Add(16); } bool ObjId::DecodeBin(Seq& s) { if (s.n < 16) return false; memcpy(&m_index, s.p, 8); memcpy(&m_uniqueId, s.p+8, 8); s.DropBytes(16); return true; } bool ObjId::SkipDecodeBin(Seq& s) { if (s.n < 16) return false; s.DropBytes(16); return true; } void ObjId::EncObj(Enc& s) const { if (*this == ObjId::None) s.Add("[None]"); else if (*this == ObjId::Root) s.Add("[Root]"); else s.Add("[").UInt(m_uniqueId).Add(".").UInt(m_index).Add("]"); } bool ObjId::ReadStr(Seq& s) { m_uniqueId = 0; m_index = 0; if (s.StartsWithInsensitive("[None]")) { s.DropBytes(6); return true; } if (s.StartsWithInsensitive("[Root]")) { m_uniqueId = 1; s.DropBytes(6); return true; } Seq reader { s }; if (reader.ReadByte() == '[') { uint64 u = reader.ReadNrUInt64Dec(); if (reader.ReadByte() == '.') { uint64 i = reader.ReadNrUInt64Dec(); if (reader.ReadByte() == ']') { m_uniqueId = u; m_index = i; s = reader; return true; } } } return false; } }
16.42
94
0.517052
denisbider
2dde8d70e8073f5f6f676d86915b244e62d384b3
13,999
cc
C++
example_cpp_smart_card_client_app/src/pp_module.cc
FabianHenneke/poc-smart-sign
14d598a60e007293633df129771e4ca44b798846
[ "Apache-2.0" ]
2
2021-03-29T20:39:42.000Z
2021-10-17T16:48:16.000Z
example_cpp_smart_card_client_app/src/pp_module.cc
ermuur/chromeos_smart_card_connector
3e1f6744f8e731a824320a5bca7066677de9c249
[ "Apache-2.0" ]
null
null
null
example_cpp_smart_card_client_app/src/pp_module.cc
ermuur/chromeos_smart_card_connector
3e1f6744f8e731a824320a5bca7066677de9c249
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file contains implementation of the NaCl module entry point // pp::CreateModule, which creates an instance of class inherited from the // pp::Instance class (see // <https://developer.chrome.com/native-client/devguide/coding/application-structure#native-client-modules-a-closer-look> // for reference). #include <stdint.h> #include <memory> #include <string> #include <thread> #include <vector> #include <ppapi/c/ppb_instance.h> #include <ppapi/cpp/core.h> #include <ppapi/cpp/instance.h> #include <ppapi/cpp/module.h> #include <ppapi/cpp/var.h> #include <google_smart_card_common/logging/logging.h> #include <google_smart_card_common/messaging/typed_message.h> #include <google_smart_card_common/messaging/typed_message_router.h> #include <google_smart_card_common/pp_var_utils/debug_dump.h> #include <google_smart_card_pcsc_lite_client/global.h> #include <google_smart_card_pcsc_lite_cpp_demo/demo.h> #include "chrome_certificate_provider/api_bridge.h" #include "chrome_certificate_provider/types.h" #include "pin-dialog/pin_dialog_server.h" namespace scc = smart_card_client; namespace ccp = scc::chrome_certificate_provider; namespace gsc = google_smart_card; namespace smart_card_client { namespace { // This class contains the actual NaCl module implementation. // // The implementation presented here is a skeleton that initializes all pieces // necessary for PC/SC-Lite client API initialization, // chrome.certificateProvider JavaScript API integration and PIN dialog // execution. // // As an example, this implementation starts a background thread running the // Work method after the initialization happens. // // Please note that all blocking operations (for example, PC/SC-Lite API calls // or PIN requests) should be never executed on the main thread. This is because // all communication with the JavaScript side works through exchanging of // messages between NaCl module and JavaScript side, and the incoming messages // are passed by the NaCl framework to the HandleMessage method of this class // always on the main thread (see // <https://developer.chrome.com/native-client/devguide/coding/message-system>). // Actually, most of the blocking operations implemented in this code contain // assertions that they are not called on the main thread. class PpInstance final : public pp::Instance { public: // The constructor that is executed during the NaCl module startup. // // The implementation presented here does the following: // * creates a google_smart_card::TypedMessageRouter class instance that will // be used for handling messages received from the JavaScript side (see the // HandleMessage method); // * creates a google_smart_card::PcscLiteClientNaclGlobal class instance that // initializes the internal state required for PC/SC-Lite API functions // implementation; // * creates a PinDialogServer class instance that allows to perform PIN // dialog requests; // * creates a chrome_certificate_provider::ApiBridge class instance that can // be used to handle requests received from the chrome.certificateProvider // JavaScript API event listeners (see // <https://developer.chrome.com/extensions/certificateProvider#events>). explicit PpInstance(PP_Instance instance) : pp::Instance(instance), pcsc_lite_over_requester_global_( new gsc::PcscLiteOverRequesterGlobal( &typed_message_router_, this, pp::Module::Get()->core())), pin_dialog_server_(new PinDialogServer( &typed_message_router_, this, pp::Module::Get()->core())), chrome_certificate_provider_api_bridge_( &typed_message_router_, this, /* execute_requests_sequentially */ false), certificates_request_handler_(new ClientCertificatesRequestHandler), sign_digest_request_handler_(new ClientSignDigestRequestHandler( pin_dialog_server_)) { chrome_certificate_provider_api_bridge_.SetCertificatesRequestHandler( certificates_request_handler_); chrome_certificate_provider_api_bridge_.SetSignDigestRequestHandler( sign_digest_request_handler_); StartWorkInBackgroundThread(); } // The destructor that is executed when the NaCl framework is about to destroy // the NaCl module (though, actually, it's not guaranteed to be executed at // all - the NaCl module can be just shut down by the browser). // // The implementation presented here essentially leaves the previously // allocated google_smart_card::PcscLiteOverRequesterGlobal not destroyed // (i.e. leaves it as a leaked pointer). This is done intentionally: there may // be still PC/SC-Lite API function calls being executed, and they are using // the common state provided by this // google_smart_card::PcscLiteOverRequesterGlobal object. So, instead of // deleting it (which may lead to undefined behavior), the Detach method of // this class is called - which prevents it from using pointer to this // instance of PpInstance class. ~PpInstance() override { pcsc_lite_over_requester_global_->Detach(); pcsc_lite_over_requester_global_.release(); pin_dialog_server_->Detach(); } // This method is called with each message received by the NaCl module from // the JavaScript side. // // All the messages are processed through the // google_smart_card::TypedMessageRouter class instance, which routes them to // the objects that subscribed for receiving them. The routing is based on the // "type" key of the message (for the description of the typed messages, see // header common/cpp/src/google_smart_card_common/messaging/typed_message.h). // // In the implementation presented here, the following messages are received // and handled here: // * results of the submitted PC/SC-Lite API calls (see the // google_smart_card::PcscLiteOverRequesterGlobal class); // * results returned from PIN dialogs (see the PinDialogServer class); // * requests received from chrome.certificateProvider API event handlers (see // the chrome_certificate_provider::ApiBridge class). // // Note that this method should not perform any long operations or // blocking operations that wait for responses received from the JavaScript // side - because this method is called by NaCl framework on the main thread, // and blocking it prevents the NaCl module from receiving new incoming // messages (see // <https://developer.chrome.com/native-client/devguide/coding/message-system>). void HandleMessage(const pp::Var& message) override { if (!typed_message_router_.OnMessageReceived(message)) { GOOGLE_SMART_CARD_LOG_FATAL << "Unexpected message received: " << gsc::DebugDumpVar(message); } } private: // This class is the implementation of the onCertificatesRequested request // from the chrome.certificateProvider JavaScript API (see // <https://developer.chrome.com/extensions/certificateProvider#event-onCertificatesRequested>). class ClientCertificatesRequestHandler final : public ccp::CertificatesRequestHandler { public: // Handles the received certificates request. // // Returns whether the operation finished successfully. In case of success, // the resulting certificates information should be returned through the // result output argument. // // Note that this method is executed by // chrome_certificate_provider::ApiBridge object on a separate background // thread. Multiple requests can be executed simultaneously (they will run // in different background threads). bool HandleRequest(std::vector<ccp::CertificateInfo>* result) override { // // CHANGE HERE: // Place your custom code here: // ccp::CertificateInfo certificate_info_1; certificate_info_1.certificate.assign({1, 2, 3}); certificate_info_1.supported_hashes.push_back(ccp::Hash::kMd5Sha1); ccp::CertificateInfo certificate_info_2; certificate_info_2.supported_hashes.push_back(ccp::Hash::kSha512); result->push_back(certificate_info_1); result->push_back(certificate_info_2); return true; } }; // This class is the implementation of the onSignDigestRequested request // from the chrome.certificateProvider JavaScript API (see // <https://developer.chrome.com/extensions/certificateProvider#event-onSignDigestRequested>). class ClientSignDigestRequestHandler final : public ccp::SignDigestRequestHandler { public: explicit ClientSignDigestRequestHandler( std::weak_ptr<PinDialogServer> pin_dialog_server) : pin_dialog_server_(pin_dialog_server) {} // Handles the received sign digest request (the request data is passed // through the sign_request argument). // // Returns whether the operation finished successfully. In case of success, // the resulting signature should be returned through the result output // argument. // // Note that this method is executed by // chrome_certificate_provider::ApiBridge object on a separate background // thread. Multiple requests can be executed simultaneously (they will run // in different background threads). bool HandleRequest( const ccp::SignRequest& sign_request, std::vector<uint8_t>* result) override { // // CHANGE HERE: // Place your custom code here: // *result = sign_request.digest; const std::shared_ptr<PinDialogServer> locked_pin_dialog_server = pin_dialog_server_.lock(); if (!locked_pin_dialog_server) { GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] Skipped PIN dialog " << "demo: the shutdown process has started"; return false; } GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] Running PIN dialog " << "demo..."; std::string pin; if (locked_pin_dialog_server->RequestPin(&pin)) { GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] demo finished: " << "received PIN enter by the user."; } else { GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] demo finished: " << "dialog was canceled."; } return true; } private: const std::weak_ptr<PinDialogServer> pin_dialog_server_; }; // This method is called by the constructor once all of the initialization // steps finish. void StartWorkInBackgroundThread() { std::thread(&PpInstance::Work).detach(); } // This method is executed on a background thread after all of the // initialization steps finish. static void Work() { // // CHANGE HERE: // Place your custom code here: // GOOGLE_SMART_CARD_LOG_INFO << "[PC/SC-Lite DEMO] Starting PC/SC-Lite " << "demo..."; if (gsc::ExecutePcscLiteCppDemo()) { GOOGLE_SMART_CARD_LOG_INFO << "[PC/SC-Lite DEMO] demo finished " << "successfully."; } else { GOOGLE_SMART_CARD_LOG_ERROR << "[PC/SC-Lite DEMO] demo failed."; } } // Router of the incoming typed messages that passes incoming messages to the // appropriate handlers according the the special type field of the message // (see common/cpp/src/google_smart_card_common/messaging/typed_message.h). gsc::TypedMessageRouter typed_message_router_; // Object that initializes the global common state used by the PC/SC-Lite // client API functions. // // The stored pointer is leaked intentionally in the class destructor - see // its comment for the justification. std::unique_ptr<gsc::PcscLiteOverRequesterGlobal> pcsc_lite_over_requester_global_; // Object that allows to perform PIN dialog requests. std::shared_ptr<PinDialogServer> pin_dialog_server_; // Object that allows to receive and handle requests received from the // chrome.certificateProvider JavaScript API event listeners (see // <https://developer.chrome.com/extensions/certificateProvider#events>). ccp::ApiBridge chrome_certificate_provider_api_bridge_; // Handler of the onCertificatesRequested request // from the chrome.certificateProvider JavaScript API (see // <https://developer.chrome.com/extensions/certificateProvider#event-onCertificatesRequested>). const std::shared_ptr<ClientCertificatesRequestHandler> certificates_request_handler_; // Handler of the onSignDigestRequested request // from the chrome.certificateProvider JavaScript API (see // <https://developer.chrome.com/extensions/certificateProvider#event-onSignDigestRequested>). const std::shared_ptr<ClientSignDigestRequestHandler> sign_digest_request_handler_; }; // This class represents the NaCl module for the NaCl framework. // // Note that potentially the NaCl framework can request creating multiple // pp::Instance objects through this module object, though, actually, this never // happens with the current NaCl framework (and with no exact plans to change it // in the future: see <http://crbug.com/385783>). class PpModule final : public pp::Module { public: pp::Instance* CreateInstance(PP_Instance instance) override { return new PpInstance(instance); } }; } // namespace } // namespace smart_card_client namespace pp { // Entry point of the NaCl module, that is called by the NaCl framework when the // module is being loaded. Module* CreateModule() { return new scc::PpModule; } } // namespace pp
42.550152
121
0.739339
FabianHenneke
2de1e63d7c6598ad8eabf00967b3dad0bce691bb
3,985
hpp
C++
src/storage/tree/Accounts.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/storage/tree/Accounts.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/storage/tree/Accounts.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include "Internal.hpp" #include "opentxs/core/Identifier.hpp" #include "Node.hpp" #include <map> #include <set> namespace opentxs::storage { class Accounts : public Node { public: OTIdentifier AccountContract(const Identifier& accountID) const; OTIdentifier AccountIssuer(const Identifier& accountID) const; OTIdentifier AccountOwner(const Identifier& accountID) const; OTIdentifier AccountServer(const Identifier& accountID) const; OTIdentifier AccountSigner(const Identifier& accountID) const; proto::ContactItemType AccountUnit(const Identifier& accountID) const; std::set<OTIdentifier> AccountsByContract(const Identifier& unit) const; std::set<OTIdentifier> AccountsByIssuer(const Identifier& issuerNym) const; std::set<OTIdentifier> AccountsByOwner(const Identifier& ownerNym) const; std::set<OTIdentifier> AccountsByServer(const Identifier& server) const; std::set<OTIdentifier> AccountsByUnit( const proto::ContactItemType unit) const; std::string Alias(const std::string& id) const; bool Load( const std::string& id, std::string& output, std::string& alias, const bool checking) const; bool Delete(const std::string& id); bool SetAlias(const std::string& id, const std::string& alias); bool Store( const std::string& id, const std::string& data, const std::string& alias, const Identifier& ownerNym, const Identifier& signerNym, const Identifier& issuerNym, const Identifier& server, const Identifier& contract, const proto::ContactItemType unit); ~Accounts() = default; private: friend class Tree; using Index = std::map<OTIdentifier, std::set<OTIdentifier>>; using UnitIndex = std::map<proto::ContactItemType, std::set<OTIdentifier>>; /** owner, signer, issuer, server, contract, unit */ using AccountData = std::tuple< OTIdentifier, OTIdentifier, OTIdentifier, OTIdentifier, OTIdentifier, proto::ContactItemType>; using ReverseIndex = std::map<OTIdentifier, AccountData>; Index owner_index_{}; Index signer_index_{}; Index issuer_index_{}; Index server_index_{}; Index contract_index_{}; UnitIndex unit_index_{}; mutable ReverseIndex account_data_{}; static bool add_set_index( const Identifier& accountID, const Identifier& argID, Identifier& mapID, Index& index); template <typename K, typename I> static void erase(const Identifier& accountID, const K& key, I& index) { try { auto& set = index.at(key); set.erase(accountID); if (0 == set.size()) { index.erase(key); } } catch (...) { } } AccountData& get_account_data( const Lock& lock, const OTIdentifier& accountID) const; proto::StorageAccounts serialize() const; bool check_update_account( const Lock& lock, const OTIdentifier& accountID, const Identifier& ownerNym, const Identifier& signerNym, const Identifier& issuerNym, const Identifier& server, const Identifier& contract, const proto::ContactItemType unit); void init(const std::string& hash) override; bool save(const Lock& lock) const override; Accounts( const opentxs::api::storage::Driver& storage, const std::string& key); Accounts() = delete; Accounts(const Accounts&) = delete; Accounts(Accounts&&) = delete; Accounts operator=(const Accounts&) = delete; Accounts operator=(Accounts&&) = delete; }; } // namespace opentxs::storage
32.137097
79
0.667503
nopdotcom
2dea9af562d4923a538b4c47a971342b551f7837
885
hpp
C++
inference-engine/src/legacy_api/src/network_serializer_v7.hpp
Mobious96/openvino
cbdd50556bc350db36da53da2a2db9a2f54e201e
[ "Apache-2.0" ]
null
null
null
inference-engine/src/legacy_api/src/network_serializer_v7.hpp
Mobious96/openvino
cbdd50556bc350db36da53da2a2db9a2f54e201e
[ "Apache-2.0" ]
null
null
null
inference-engine/src/legacy_api/src/network_serializer_v7.hpp
Mobious96/openvino
cbdd50556bc350db36da53da2a2db9a2f54e201e
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <ie_icnn_network.hpp> #include <legacy/ie_layers.h> #include <string> #include <vector> namespace InferenceEngine { namespace Serialization { /** * @brief Serialize execution network into IE IR-like XML file * @param xmlPath Path to XML file * @param network network to be serialized */ INFERENCE_ENGINE_API_CPP(void) Serialize(const std::string& xmlPath, const InferenceEngine::ICNNNetwork& network); /** * @brief Returns set of topologically sorted layers * @param network network to be sorted * @return `std::vector` of topologically sorted CNN layers */ INFERENCE_ENGINE_API_CPP(std::vector<CNNLayerPtr>) TopologicalSort(const InferenceEngine::ICNNNetwork& network); } // namespace Serialization } // namespace InferenceEngine
27.65625
114
0.740113
Mobious96
2dee881bc9c468e5c55a5dfcc49d00c728b46c34
1,388
cpp
C++
Codeforces/258C.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/258C.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/258C.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 100 , MOD = 1e9 + 7 ; int dp[MAXN] , n , mx; long long ans , temp; vector <int> divv; long long power(long long x , long long y){ if (y == 0) return 1; long long t = power (x, y / 2); t = (t * t) % MOD; if (y % 2 == 1) t = (t * x) % MOD; return t; } void dive(int x){ divv.clear(); for (int i = 1 ; i*i <=x ; i++){ if (i * i == x) divv.push_back(i); else if (x % i == 0){ divv.push_back(i); divv.push_back(x/i); } } } int main(){ cin >> n; for (int i = 0; i < n; i++){ int x; cin >> x; mx = max(x,mx); dp [x]++; } for (int i = 1; i < MAXN; i++) dp[i] = dp[i-1] + dp[i]; for (int i = 1; i <= mx; i++){ dive(i); sort(divv.begin(),divv.end()); temp = 1; for (int j = 1; j < divv.size(); j++){ temp = (temp * power(j,dp[divv[j]-1] - dp[divv[j-1]-1])) % MOD; } long long a = ((temp * power(divv.size(),(dp[100000]-dp[divv[divv.size()-1]-1])) )%MOD); long long b = ((temp * power(divv.size() - 1,(dp[100000]-dp[divv[divv.size()-1]-1])) )%MOD); temp = a - b; if (temp <0) temp += MOD; ans = (ans +temp)%MOD; } cout<<ans<<endl; return 0; }
22.754098
100
0.423631
Alipashaimani
2df158dfc7812335c241a4b8113f9fa09fad53d9
4,129
hpp
C++
extlib/include/xyginext/audio/AudioScape.hpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
[ "Unlicense" ]
17
2018-06-23T14:40:56.000Z
2019-07-02T11:58:55.000Z
extlib/include/xyginext/audio/AudioScape.hpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
[ "Unlicense" ]
3
2018-06-23T12:35:12.000Z
2018-06-23T12:38:54.000Z
extlib/include/xyginext/audio/AudioScape.hpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
[ "Unlicense" ]
null
null
null
/********************************************************************* (c) Matt Marchant 2017 - 2019 http://trederia.blogspot.com xygineXT - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #pragma once #include "../Config.hpp" #include "../ecs/components/AudioEmitter.hpp" #include "../core/ConfigFile.hpp" #include <string> #include <unordered_map> namespace xy { class AudioResource; /*! \brief Contains one or more definitions used to create AudioEmitter components. Similarly to the SpriteSheet class used for loading Sprites from configuration files, AudioScapes can be used to define the settings used to create AudioEmitter components. AudioScape files usually have the extension *.xas with the following ConfigFile compatible layout: \code audio_scape NAME { emitter NAME_ONE { path = "STR_PATH_TO_FILE" streaming = BOOL pitch = FLOAT volume = FLOAT relative_listener = BOOL min_distance = FLOAT attenuation = FLOAT looped = BOOL mixer_channel = INT } emitter NAME_TWO { path = "STR_PATH_TO_FILE" streaming = BOOL pitch = FLOAT volume = FLOAT relative_listener = BOOL min_distance = FLOAT attenuation = FLOAT looped = BOOL mixer_channel = INT } } \endcode Emitter properties are optional (except path and streaming) and any omitted properties will fall back to their default values. */ class XY_EXPORT_API AudioScape final { public: /*! \brief Constructor \param rx Reference to an AudioResource object used to cache any non-streamed audio files. */ AudioScape(AudioResource& rx); /*! \brief Attempts to load an AudioScape file from the given path \param path String containing the path to the *.xas file to load \returns bool true if successful else false */ bool loadFromFile(const std::string& path); /*! \brief Saves the AudioScape configuration to a given path. AudioScape files normally have the extension *.xas */ bool saveToFile(const std::string& path); /*! \brief Returns an AudioEmitter configured with the given name from the loaded confugration, if it exists, else returns an Uninitialised AudioEmitter. Use AudioEmitter::hasSource() to check validity of the returned emitter. */ AudioEmitter getEmitter(const std::string& name) const; /*! \brief Adds an emitter configuration to the AudioScape. \param name Name of the AudioEmitter as it appears in the configuration. If an emitter with the name already exists then it will be overwritten. \param emitter An AudioEmitter whose current settings will be saved in the configuration file. */ void addEmitter(const std::string& name, const AudioEmitter& emitter); private: AudioResource& m_audioResource; std::unordered_map<std::string, ConfigObject> m_emitterConfigs; }; } //namespace xy
33.298387
90
0.644224
fallahn
2df7102107f72e7e5c0f5d5a7caedad4300879e1
4,103
hpp
C++
linear_algebra.inl.hpp
matheuscscp/linear_algebra
2a8d5dee1ab1b6d62ba1e1987e2251b87febe74e
[ "MIT" ]
null
null
null
linear_algebra.inl.hpp
matheuscscp/linear_algebra
2a8d5dee1ab1b6d62ba1e1987e2251b87febe74e
[ "MIT" ]
null
null
null
linear_algebra.inl.hpp
matheuscscp/linear_algebra
2a8d5dee1ab1b6d62ba1e1987e2251b87febe74e
[ "MIT" ]
null
null
null
/* * linear_algebra.inl.hpp * * Created on: Feb 21, 2015 * Author: Pimenta */ #ifndef LINEAR_ALGEBRA_INL_HPP_ #define LINEAR_ALGEBRA_INL_HPP_ #include <cmath> namespace linear_algebra { template <typename T> struct Vector3 { T x, y, z; Vector3(T x = 0, T y = 0, T z = 0) : x(x), y(y), z(z) { } // arithmetic operators inline Vector3 operator+(const Vector3& other) { return Vector3(x + other.x, y + other.y, z + other.z); } inline Vector3 operator-(const Vector3& other) { return Vector3(x - other.x, y - other.y, z - other.z); } inline Vector3 operator-() { return Vector3(-x, -y, -z); } inline Vector3 operator*(T scalar) { return Vector3(x*scalar, y*scalar, z*scalar); } inline Vector3 operator/(T scalar) { return Vector3(x/scalar, y/scalar, z/scalar); } // compound assignment Vector3& operator+=(const Vector3& other) { x += other.x; y += other.y; z += other.z; return *this; } Vector3& operator-=(const Vector3& other) { x -= other.x; y -= other.y; z -= other.z; return *this; } Vector3& operator*=(T scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; } Vector3& operator/=(T scalar) { x /= scalar; y /= scalar; z /= scalar; return *this; } // relational operators inline bool operator==(const Vector3& other) { return x == other.x && y == other.y && z == other.z; } inline bool operator!=(const Vector3& other) { return x != other.x || y != other.y || z != other.z; } // methods inline T length() { return sqrt(x*x + y*y + z*z); } inline Vector3 versor() { T len = length(); if (len == 0) { return *this; } return operator/(len); } inline T dot(const Vector3& other) { return x*other.x + y*other.y + z*other.z; } inline Vector3 cross(const Vector3& v) { return Vector3(y*v.z - z*v.y, z*v.x - x*v.z, x*v.x - y*v.x); } inline T angle(const Vector3& other) { T len = length()*other.length(); if (len == 0) { return 0; } return acos(dot(other)/len); } inline Vector3 proj(const Vector3& other) { // other on this Vector3 v = versor(); return v*v.dot(other); } inline Vector3 rej(const Vector3& other) { // other from this return other - proj(other); } inline T scalarproj(const Vector3& other) { // other on this return versor().dot(other); } inline Vector3 rotate(const Vector3& other, T angle) { // other around this Vector3 u = versor(); T a2 = u.x*u.x, ab = u.x*u.y, ac = u.x*u.z; T b2 = u.y*u.y, bc = u.y*u.z, c2 = u.z*u.z; T sint = sin(angle), cost = cos(angle), _1mcost = 1 - cost; T asint = u.x*sint, bsint = u.y*sint, csint = u.z*sint; T x = other.x, y = other.y, z = other.z; return Vector3( x*(a2*_1mcost + cost) + y*(ab*_1mcost - csint) + z*(ac*_1mcost + bsint), x*(ab*_1mcost + csint) + y*(b2*_1mcost + cost) + z*(bc*_1mcost - asint), x*(ac*_1mcost - bsint) + y*(bc*_1mcost + asint) + z*(c2*_1mcost + cost) ); } }; // determinant template <typename T> T det(const Vector3<T>& a, const Vector3<T>& b) { return a.x*b.y - a.y*b.x; } template <typename T> T det(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c) { return a.x*b.y*c.z + b.x*c.y*a.z + c.x*a.y*b.z - a.z*b.y*c.x - b.z*c.y*a.x - c.z*a.y*b.x ; } // linear system template <typename T> bool solvesys( const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c, T& x, T& y ) { T D = det(a, b); if (D == 0) { return false; } x = det(c, b)/D; y = det(a, c)/D; return true; } template <typename T> bool solvesys( const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c, const Vector3<T>& d, T& x, T& y, T& z ) { T D = det(a, b, c); if (D == 0) { return false; } x = det(d, b, c)/D; y = det(a, d, c)/D; z = det(a, b, d)/D; return true; } // basic types typedef Vector3<float> Vector3f; typedef Vector3<double> Vector3d; } // namespace linear_algebra #endif /* LINEAR_ALGEBRA_INL_HPP_ */
23.58046
79
0.571289
matheuscscp
2df8e2bd2ca2f77a3b26a8885c3b5578f87b74cc
5,233
cxx
C++
Modules/IO/IOGDAL/test/otbGDALRPCTransformerTest2.cxx
liuxuvip/OTB
73ed482d62c2924aea158aac14d725dc9447083b
[ "Apache-2.0" ]
317
2015-01-19T08:40:58.000Z
2022-03-17T11:55:48.000Z
Modules/IO/IOGDAL/test/otbGDALRPCTransformerTest2.cxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
18
2015-07-29T14:13:45.000Z
2021-03-29T12:36:24.000Z
Modules/IO/IOGDAL/test/otbGDALRPCTransformerTest2.cxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
132
2015-02-21T23:57:25.000Z
2022-03-25T16:03:16.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "itkPoint.h" #include "otbGDALRPCTransformer.h" #include "itkEuclideanDistanceMetric.h" #include "otbGeographicalDistance.h" #include "otbImageMetadata.h" #include "otbMetaDataKey.h" #include "otbGeomMetadataSupplier.h" #include "otbImageMetadataInterfaceFactory.h" #include "otbMacro.h" #include "otbDEMHandler.h" #include "otbImage.h" #include "otbImageFileReader.h" //typedef otb::Image<double> ImageType; typedef std::vector<itk::Point<double, 3>> pointsContainerType; typedef itk::Statistics::EuclideanDistanceMetric<otb::GDALRPCTransformer::PointType> DistanceType; typedef otb::GeographicalDistance<otb::GDALRPCTransformer::PointType> GeographicalDistanceType; int otbGDALRPCTransformerTest2(int itkNotUsed(argc), char* argv[]) { bool success = true; otb::GDALRPCTransformer::PointType imagePoint; otb::GDALRPCTransformer::PointType geo3dPoint; // Inputs std::string rpcFile(argv[1]); std::string gcpFileName(argv[2]); double geoTol(atof(argv[3])); double imgTol(atof(argv[4])); // Tools auto distance = DistanceType::New(); auto geoDistance = GeographicalDistanceType::New(); otb::ImageMetadata imd; if (0 == rpcFile.compare(rpcFile.length() - 4, 4, "geom")) { // Fetching the RPC model from a GEOM file otb::GeomMetadataSupplier geomSupplier(rpcFile); for (int loop = 0 ; loop < geomSupplier.GetNbBands() ; ++loop) imd.Bands.emplace_back(); otb::ImageMetadataInterfaceFactory::CreateIMI(imd, geomSupplier); geomSupplier.FetchRPC(imd); } else { // Fetching the RPC model from a product typedef otb::Image<double, 2> ImageType; typedef otb::ImageFileReader<ImageType> ImageFileReaderType; auto reader = ImageFileReaderType::New(); reader->SetFileName(rpcFile); reader->UpdateOutputInformation(); imd = reader->GetOutput()->GetImageMetadata(); } auto rpcModel = boost::any_cast<otb::Projection::RPCParam>(imd[otb::MDGeom::RPC]); // Setting the RPCTransformer // otb::DEMHandler::GetInstance().SetDefaultHeightAboveEllipsoid(0.0); otb::GDALRPCTransformer transformer(rpcModel.LineOffset, rpcModel.SampleOffset, rpcModel.LatOffset, rpcModel.LonOffset, rpcModel.HeightOffset, rpcModel.LineScale, rpcModel.SampleScale, rpcModel.LatScale, rpcModel.LonScale, rpcModel.HeightScale, rpcModel.LineNum, rpcModel.LineDen, rpcModel.SampleNum, rpcModel.SampleDen, false); // Loading the GCP pointsContainerType pointsContainer; pointsContainerType geo3dPointsContainer; std::ifstream file(gcpFileName, std::ios::in); if (file) { std::string line; while (getline(file, line)) { if (line.find_first_of("#") != 0) { std::istringstream iss(line); iss >> imagePoint[0] >> imagePoint[1] >> geo3dPoint[0] >> geo3dPoint[1] >> geo3dPoint[2]; imagePoint[2] = geo3dPoint[2]; pointsContainer.push_back(imagePoint); geo3dPointsContainer.push_back(geo3dPoint); } } file.close(); } // For each CGP for (pointsContainerType::iterator pointsIt = pointsContainer.begin(), geo3dPointsIt = geo3dPointsContainer.begin() ; (pointsIt != pointsContainer.end()) && (geo3dPointsIt != geo3dPointsContainer.end()) ; ++pointsIt, ++geo3dPointsIt) { // std::cout << "Point: " << *pointsIt << " GeoPoint: " << *geo3dPointsIt << "\n"; // Testing forward transform geo3dPoint = transformer.ForwardTransform(*pointsIt); auto forwardPointDistance = geoDistance->Evaluate(geo3dPoint, *geo3dPointsIt); if (forwardPointDistance > geoTol) { std::cerr << "Geo distance between otbGDALRPCTransformer->ForwardTransform and GCP too high :\n" << "GCP: " << *geo3dPointsIt << " / computed: " << geo3dPoint << "\n" << "dist = " << forwardPointDistance << " (tol = " << geoTol << ")" << std::endl; success = false; } // Testing inverse transform imagePoint = transformer.InverseTransform(*geo3dPointsIt); auto inversePointDistance = distance->Evaluate(imagePoint, *pointsIt); if (inversePointDistance > imgTol) { std::cerr << "Distance between otbGDALRPCTransformer->InverseTransform and GCP too high :\n" << "GCP: " << *pointsIt << " / computed: " << imagePoint << "\n" << "dist = " << inversePointDistance << " (tol = " << imgTol << ")" << std::endl; success = false; } } if (success) return EXIT_SUCCESS; else return EXIT_FAILURE; }
37.378571
144
0.688324
liuxuvip
93046434ae89d0310e0d9f6a5e72487c0425faf4
775
cpp
C++
packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_CylindricalSpatialCoordinateConversionPolicy.cpp //! \author Alex Robinson //! \brief Cylindrical coordinate conversion policy template instantiations //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "FRENSIE_Archives.hpp" #include "Utility_CylindricalSpatialCoordinateConversionPolicy.hpp" EXPLICIT_CLASS_SERIALIZE_INST( Utility::CylindricalSpatialCoordinateConversionPolicy ); //---------------------------------------------------------------------------// // end Utility_CylindricalSpatialCoordinateConversionPolicy.cpp //---------------------------------------------------------------------------//
43.055556
87
0.492903
bam241
9304e43be421663bdce11be46852fde98a892444
1,091
cpp
C++
perftest/testlocator.cpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
perftest/testlocator.cpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
perftest/testlocator.cpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
/* * testlocator.cpp * * Created on: Mar 23, 2015 * Author: masha */ #include "testlocator.hpp" #include "performancetest.hpp" #include "testfactory.hpp" #include <xtomic/aux/cppbasics.hpp> #include <stdexcept> namespace xtomic { namespace perftest { PerfTestInfo* PerfTestLocator::m_link = nullptr; PerfTestLocator::PerfTestLocator() { } const PerfTestLocator& PerfTestLocator::getInstance() { static const PerfTestLocator instance; return instance; } void PerfTestLocator::registerTest(PerfTestInfo* info) { info->m_id = getSize(); info->m_link = m_link; m_link = info; } void PerfTestLocator::getTest(const id_type id, PerformanceTest & test) const { test.attach(at(id)->m_factory->create()); } const PerfTestInfo* PerfTestLocator::at(const id_type id) const { if (id >= getSize()) { throw std::out_of_range("PerfTestLocator::at()"); } PerfTestInfo* link = m_link; while (link) { if (link->m_id == id) { break; } link = link->m_link; } return link; } } }
16.044118
77
0.64528
mashavorob
93076ebed2da5f10879ce444c000c80e472b2f75
4,918
cpp
C++
service/src/sys/autorun2.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
service/src/sys/autorun2.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
service/src/sys/autorun2.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
#include <exodus/library.h> libraryinit() #include <getsubs.h> #include <sys_common.h> var mode; var datax; var runasusercode; var targetusercodes; var title; var usern;//num function main(in mode0, in title0, in module, in request, in data0, in runasusercode0, in targetusercodes0, io document0, io docid, out msg) { //c sys in,in,in,in,in,in,in,io,io,out //creates an autorun record in documents //GBP CREATEALERT mode WRITE //GBP GENERAL.SUBS2 mode ASAP //BP MEDIADIARY mode WRITE/ASP for media diary //ABP none #include <system_common.h> //default unassigned parameters if (mode0.unassigned()) { mode = ""; } else { mode = mode0; } if (data0.unassigned()) { datax = ""; } else { datax = data0; } if (runasusercode0.unassigned()) { runasusercode = ""; } else { runasusercode = runasusercode0; } if (targetusercodes0.unassigned()) { targetusercodes = ""; } else { targetusercodes = targetusercodes0; } if (document0.unassigned()) { sys.document = ""; } else { sys.document = document0; } if (docid.unassigned()) { docid = ""; } if (title0) { title = title0; } else { title = sys.document.a(1); } //default runtime to once if (not(sys.document.field(FM, 20, 10).convert(FM, ""))) { //run once now sys.document(27) = 1; } var fullrequest = module ^ "PROXY" ^ FM ^ request; //get target usercodes var users; if (not(users.open("USERS", ""))) { msg = "USERS file is missing"; return 0; } //determine the runas usercode if not specified if (not runasusercode) { //allow for runuser to be passed in document runasusercode = sys.document.a(1); } if (runasusercode) { var runasuser; if (not(runasuser.read(users, runasusercode))) { if (not(runasusercode eq "EXODUS")) { msg = runasusercode.quote() ^ " user doesnt exist"; return 0; } runasuser = ""; } } else { //run as the bottom user in the current users group //assuming we are going to send it to all members of the group var usercode = USERNAME; runasusercode = usercode.xlate("USERS", 5, ""); //if not a proper user (eg EXODUS then skip) if (not runasusercode) { msg = usercode.quote() ^ " can only autorun if specified as the runas user"; return 0; } } //if no targets specified then //send to the "run as" user and all users above in the same group if (targetusercodes eq "") { //allow for targetusers to be passed in document targetusercodes = sys.document.a(14); //runasuser is NOT a target unless there are no recipients //if targetusercodes='' then // targetusercodes=runasusercode // end } //auto targeting var initialtargetusercodes = targetusercodes; if (targetusercodes eq "{GROUP}") { var tt = runasusercode; if (SECURITY.a(1).locate(tt, usern)) { while (true) { var userx; if (userx.read(users, tt)) { //only to users with emails if (userx.a(7)) { var seniorfirst = 1; if (seniorfirst) { targetusercodes.inserter(1, 1, tt); } else { targetusercodes(1, -1) = tt; } } } usern -= 1; tt = SECURITY.a(1, usern); ///BREAK; if (not((usern and tt) and tt ne "---")) break; }//loop; } } else { //check all users exist (even if they dont have emails) if (targetusercodes) { var nusers = targetusercodes.count(VM) + 1; for (usern = nusers; usern >= 1; --usern) { var usercode = targetusercodes.a(1, usern); var userx; if (not(userx.read(users, usercode))) { if (not(usercode eq "EXODUS")) { msg = usercode.quote() ^ " user doesnt exist"; return 0; } userx = ""; } } //usern; } } //if no targets have emails then skip if (initialtargetusercodes and targetusercodes eq "") { msg = "No target users have email addresses"; return 0; } //got all data, prepare autorun document sys.document(2) = title; sys.document(5) = lower(fullrequest); sys.document(6) = lower(datax); sys.document(1) = runasusercode; sys.document(14) = targetusercodes; sys.document(7) = APPLICATION; sys.document(3) = var().date(); sys.document(4) = var().time(); if (sys.document.a(12) eq "") { sys.document(12) = 1; } //email delivery - save if report successful or not run if (docid) { //dont lose last run date/time to avoid rerunning. //to force rerun delete and recreate var olddoc; if (olddoc.read(sys.documents, docid)) { sys.document(13) = olddoc.a(13); } } else { var saveid = ID; call getsubs("DEF.DOCUMENT.NO"); docid = ID; ID = saveid; if (not docid) { msg = "Could not get next document number in AUTORUN2|Please try again after 1 minute"; return 0; } } //prevent document from being run until the request has been processed //relies on unlock all in listen if (mode eq "ASAP") { if (not(sys.documents.lock( docid))) { {} } } sys.document.write(sys.documents, docid); return 1; } libraryexit()
22.874419
142
0.642741
BOBBYWY
930dfb0d9be75eaed422e27eff72f9cc840075e0
1,479
cc
C++
src/base/resolution.cc
miguelpinho/gem5-thesis
3a604b7a742dbfd40a1157749c461e8a71911c45
[ "BSD-3-Clause" ]
2
2021-02-20T21:41:39.000Z
2021-11-09T14:52:01.000Z
src/base/resolution.cc
miguelpinho/gem5-thesis
3a604b7a742dbfd40a1157749c461e8a71911c45
[ "BSD-3-Clause" ]
null
null
null
src/base/resolution.cc
miguelpinho/gem5-thesis
3a604b7a742dbfd40a1157749c461e8a71911c45
[ "BSD-3-Clause" ]
null
null
null
/// MPINHO 2-mar-2019 BEGIN /// #include "base/resolution.hh" #include "arch/utility.hh" int unsignedIntResolution(uint64_t val) { if (val == 0) return 0; int prc = 1; // in findMsbSet they don't have this if (val >> 32) { val += 32; val = val >> 32; } if (val >> 16) { prc += 16; val = val >> 16; } if (val >> 8) { prc += 8; val = val >> 8; } if (val >> 4) { prc += 4; val = val >> 4; } if (val >> 2) { prc += 2; val = val >> 2; } if (val >> 1) { prc++; } return prc; } int signedIntResolution(uint64_t val) { // the precision of a value is equal to its complement's if (val >> 63) val = ~val; int prc = 1; // fast result if (!val) return prc; // find the most significative 1 bit and add one prc++; if (val >> 32) { prc += 32; val = val >> 32; } if (val >> 16) { prc += 16; val = val >> 16; } if (val >> 8) { prc += 8; val = val >> 8; } if (val >> 4) { prc += 4; val = val >> 4; } if (val >> 2) { prc += 2; val = val >> 2; } if (val >> 1) { prc++; } return prc; } /// MPINHO 15-may-2019 BEGIN /// int roundPrcBlock(int prc, int block) { assert(prc >= 0 && block >= 0); // Source: https://stackoverflow.com/questions/3407012/ // Make sure block is a power of 2. assert(block && ((block & (block-1)) == 0)); return (prc + block - 1) & -block; } // TODO: implement roundPrcBlockLog function /// MPINHO 15-may-2019 END /// /// MPINHO 2-mar-2019 END ///
23.109375
60
0.521298
miguelpinho
93101178a438876b9b6f3c3b691a0c2e3c26e612
3,101
cpp
C++
Aurora/Aurora/timer.cpp
manaskamal/aurora-xeneva
fe277f7ac155a40465c70f1db3c27046e4d0f7b5
[ "BSD-2-Clause" ]
8
2021-07-19T04:46:35.000Z
2022-03-12T17:56:00.000Z
Aurora/Aurora/timer.cpp
manaskamal/aurora-xeneva
fe277f7ac155a40465c70f1db3c27046e4d0f7b5
[ "BSD-2-Clause" ]
null
null
null
Aurora/Aurora/timer.cpp
manaskamal/aurora-xeneva
fe277f7ac155a40465c70f1db3c27046e4d0f7b5
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (C) Manas Kamal Choudhury 2021 * * timer.h -- The Global Timer used by usermode objects * * /PROJECT - Aurora's Xeneva v1.0 * /AUTHOR - Manas Kamal Choudhury * */ #include <timer.h> #include <_null.h> #include <pmmngr.h> #include <stdio.h> #include <arch\x86_64\cpu.h> #include <ipc\postbox.h> timer_t *timer_head = NULL; timer_t *timer_last = NULL; uint32_t utimer_id = 0; void timer_insert (timer_t* new_timer ) { new_timer->next = NULL; new_timer->prev = NULL; if (timer_head == NULL) { timer_last = new_timer; timer_head = new_timer; } else { timer_last->next = new_timer; new_timer->prev = timer_last; } timer_last = new_timer; } void timer_delete (timer_t* new_timer) { if (timer_head == NULL) return; if (new_timer == timer_head) { timer_head = timer_head->next; } else { new_timer->prev->next = new_timer->next; } if (new_timer == timer_last) { timer_last = new_timer->prev; } else { new_timer->next->prev = new_timer->prev; } pmmngr_free(new_timer); } /* create_timer -- Creates a new timer @param interval -- the difference time @param id -- the caller thread id @return -- a unique id of the timer */ int create_timer (uint32_t interval, uint16_t id) { utimer_id++; timer_t *t = (timer_t*)pmmngr_alloc(); t->timer_count = 0; t->task_id = id; t->interval = interval; t->utimer_id = utimer_id; t->start = false; timer_insert (t); return utimer_id; } /* pause_timer -- pauses the timer @param utimer_id -- Unique timer id to pause */ void pause_timer (int utimer_id) { for (timer_t *t = timer_head; t != NULL; t = t->next) { if (t->utimer_id == utimer_id) { t->start = false; break; } } } /* start_timer - start the timer @param utimer_id -- Unique timer id to start */ void start_timer (int utimer_id ) { for (timer_t *t = timer_head; t != NULL; t = t->next) { if (t->utimer_id == utimer_id) { t->start = true; break; } } } /* destroy_timer -- Destroy a specific timer @param utimer_id -- Unique timer id to destroy */ void destroy_timer (int utimer_id) { for (timer_t *t = timer_head; t != NULL; t = t->next) { if (t->utimer_id == utimer_id) { timer_delete (t); utimer_id--; break; } } } /* find_timer_id -- find a timer by a given task id @param id -- task id @return -- unique timer id of the timer, if found */ int find_timer_id (uint16_t id) { for (timer_t *t = timer_head; t != NULL; t = t->next) { if (t->task_id == id) { return t->utimer_id; break; } } return -1; } /** timer_fire -- this routine is called by the scheduler for monitoring time for threads. */ void timer_fire () { x64_cli(); if (timer_head != NULL) { for (timer_t *t = timer_head; t != NULL; t = t->next) { if (t->start) { if (t->timer_count == t->interval ) { postmsg_t msg; msg.type = SYSTEM_MESSAGE_TIMER_EVENT; msg.to_id = t->task_id; post_box_put_msg (&msg,t->task_id); t->timer_count = 0; } t->timer_count++; } } } }
19.26087
57
0.62238
manaskamal
9311892ac3c1fd2b8a3db6e74e57269792d352f0
4,279
cpp
C++
src/navmesh_parameters.cpp
TheFamousRat/GodotFlowField
0da627f73aff1149bd7838cab03b380fb7f34b86
[ "MIT" ]
3
2021-02-25T18:39:07.000Z
2022-01-28T16:11:08.000Z
src/navmesh_parameters.cpp
TheFamousRat/GodotFlowField
0da627f73aff1149bd7838cab03b380fb7f34b86
[ "MIT" ]
1
2021-04-05T15:42:18.000Z
2021-04-05T15:42:18.000Z
src/navmesh_parameters.cpp
TheFamousRat/GodotFlowField
0da627f73aff1149bd7838cab03b380fb7f34b86
[ "MIT" ]
null
null
null
#include "navmesh_parameters.h" static const int DEFAULT_TILE_SIZE = 64; static const float DEFAULT_CELL_SIZE = 0.3f; static const float DEFAULT_CELL_HEIGHT = 0.2f; static const float DEFAULT_AGENT_HEIGHT = 2.0f; static const float DEFAULT_AGENT_RADIUS = 0.6f; static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f; static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f; static const float DEFAULT_REGION_MIN_SIZE = 8.0f; static const float DEFAULT_REGION_MERGE_SIZE = 20.0f; static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f; static const float DEFAULT_EDGE_MAX_ERROR = 1.3f; static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f; static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f; static const int DEFAULT_MAX_OBSTACLES = 1000; static const int DEFAULT_MAX_LAYERS = 8; using namespace godot; void NavmeshParameters::_register_methods() { register_property<NavmeshParameters, real_t>("cell_size", &NavmeshParameters::set_cell_size, &NavmeshParameters::get_cell_size, DEFAULT_CELL_SIZE); register_property<NavmeshParameters, int>("tile_size", &NavmeshParameters::set_tile_size, &NavmeshParameters::get_tile_size, DEFAULT_TILE_SIZE); register_property<NavmeshParameters, real_t>("cell_height", &NavmeshParameters::set_cell_height, &NavmeshParameters::get_cell_height, DEFAULT_CELL_HEIGHT); register_property<NavmeshParameters, real_t>("agent_height", &NavmeshParameters::set_agent_height, &NavmeshParameters::get_agent_height, DEFAULT_AGENT_HEIGHT); register_property<NavmeshParameters, real_t>("agent_radius", &NavmeshParameters::set_agent_radius, &NavmeshParameters::get_agent_radius, DEFAULT_AGENT_RADIUS); register_property<NavmeshParameters, real_t>("agent_max_climb", &NavmeshParameters::set_agent_max_climb, &NavmeshParameters::get_agent_max_climb, DEFAULT_AGENT_MAX_CLIMB); register_property<NavmeshParameters, real_t>("agent_max_slope", &NavmeshParameters::set_agent_max_slope, &NavmeshParameters::get_agent_max_slope, DEFAULT_AGENT_MAX_SLOPE); register_property<NavmeshParameters, real_t>("region_min_size", &NavmeshParameters::set_region_min_size, &NavmeshParameters::get_region_min_size, DEFAULT_REGION_MIN_SIZE); register_property<NavmeshParameters, real_t>("region_merge_size", &NavmeshParameters::set_region_merge_size, &NavmeshParameters::get_region_merge_size, DEFAULT_REGION_MERGE_SIZE); register_property<NavmeshParameters, real_t>("edge_max_length", &NavmeshParameters::set_edge_max_length, &NavmeshParameters::get_edge_max_length, DEFAULT_EDGE_MAX_LENGTH); register_property<NavmeshParameters, real_t>("edge_max_error", &NavmeshParameters::set_edge_max_error, &NavmeshParameters::get_edge_max_error, DEFAULT_EDGE_MAX_ERROR); register_property<NavmeshParameters, real_t>("detail_sample_distance", &NavmeshParameters::set_detail_sample_distance, &NavmeshParameters::get_detail_sample_distance, DEFAULT_DETAIL_SAMPLE_DISTANCE); register_property<NavmeshParameters, real_t>("detail_sample_max_error", &NavmeshParameters::set_detail_sample_max_error, &NavmeshParameters::get_detail_sample_max_error, DEFAULT_DETAIL_SAMPLE_MAX_ERROR); // register_property<NavmeshParameters, Vector3>("padding", &NavmeshParameters::set_padding, &NavmeshParameters::get_padding, Vector3(1.0f, 1.0f, 1.0f)); register_property<NavmeshParameters, int>("max_layers", &NavmeshParameters::set_max_layers, &NavmeshParameters::get_max_layers, DEFAULT_MAX_LAYERS); } NavmeshParameters::NavmeshParameters() { } void NavmeshParameters::_init() { if (OS::get_singleton()->is_stdout_verbose()) { Godot::print("Navigation parameters inited."); } tile_size = DEFAULT_TILE_SIZE; cell_size = DEFAULT_CELL_SIZE; cell_height = DEFAULT_CELL_HEIGHT; agent_height = DEFAULT_AGENT_HEIGHT; agent_radius = DEFAULT_AGENT_RADIUS; agent_max_climb = DEFAULT_AGENT_MAX_CLIMB; agent_max_slope = DEFAULT_AGENT_MAX_SLOPE; region_min_size = DEFAULT_REGION_MIN_SIZE; region_merge_size = DEFAULT_REGION_MERGE_SIZE; edge_max_length = DEFAULT_EDGE_MAX_LENGTH; edge_max_error = DEFAULT_EDGE_MAX_ERROR; detail_sample_distance = DEFAULT_DETAIL_SAMPLE_DISTANCE; detail_sample_max_error = DEFAULT_DETAIL_SAMPLE_MAX_ERROR; padding = Vector3(1.f, 1.f, 1.f); max_layers = DEFAULT_MAX_LAYERS; } void NavmeshParameters::_ready() { } NavmeshParameters::~NavmeshParameters() { }
52.82716
204
0.838046
TheFamousRat
93124e5242aaec99a07bd9cad0ba8d70d8e84fe9
4,808
cc
C++
tagging_tools/entity_binding.cc
nickroess/hope-policy-engine
3c8686b41dd933985c1eead593754c14d9a8728d
[ "MIT" ]
1
2021-05-02T07:09:40.000Z
2021-05-02T07:09:40.000Z
tagging_tools/entity_binding.cc
nickroess/hope-policy-engine
3c8686b41dd933985c1eead593754c14d9a8728d
[ "MIT" ]
13
2019-07-01T14:49:16.000Z
2020-08-04T15:24:05.000Z
tagging_tools/entity_binding.cc
nickroess/hope-policy-engine
3c8686b41dd933985c1eead593754c14d9a8728d
[ "MIT" ]
3
2019-06-18T17:09:12.000Z
2021-05-02T07:09:42.000Z
/* * Copyright © 2017-2018 Dover Microsystems, Inc. * All rights reserved. * * Use and disclosure subject to the following license. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <yaml-cpp/yaml.h> #include "validator_exception.h" #include "entity_binding.h" using namespace policy_engine; static void expect_field(YAML::Node const *n, const char *field, std::string entity_name) { if (!(*n)[field]) throw configuration_exception_t("expected field " + std::string(field) + " in entity " + entity_name); } static void process_element(const YAML::Node &n, std::list<std::unique_ptr<entity_binding_t>> &bindings) { std::string elt_path; if (!n["name"]) throw configuration_exception_t("binding must have an entity name"); std::string entity_name = n["name"].as<std::string>(); expect_field(&n, "kind", entity_name); std::string element_name = n["kind"].as<std::string>(); if (element_name == "symbol") { entity_symbol_binding_t *binding = new entity_symbol_binding_t; std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding); binding->entity_name = entity_name; expect_field(&n, "elf_name", entity_name); binding->elf_name = n["elf_name"].as<std::string>(); if (n["tag_all"]) binding->is_singularity = !n["tag_all"].as<bool>(); if (n["optional"]) binding->optional = n["optional"].as<bool>(); bindings.push_back(std::move(u)); } else if (element_name == "range") { entity_range_binding_t *binding = new entity_range_binding_t; std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding); binding->entity_name = entity_name; expect_field(&n, "elf_start", entity_name); expect_field(&n, "elf_end", entity_name); binding->elf_start_name = n["elf_start"].as<std::string>(); binding->elf_end_name = n["elf_end"].as<std::string>(); if (n["optional"]) binding->optional = n["optional"].as<bool>(); bindings.push_back(std::move(u)); } else if (element_name == "soc") { entity_soc_binding_t *binding = new entity_soc_binding_t; std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding); binding->entity_name = entity_name; if (n["optional"]) binding->optional = n["optional"].as<bool>(); bindings.push_back(std::move(u)); } else if (element_name == "isa") { entity_isa_binding_t *binding = new entity_isa_binding_t; std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding); binding->entity_name = entity_name; if (n["optional"]) binding->optional = n["optional"].as<bool>(); bindings.push_back(std::move(u)); } else if (element_name == "image") { entity_image_binding_t *binding = new entity_image_binding_t; std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding); binding->entity_name = entity_name; if (n["optional"]) binding->optional = n["optional"].as<bool>(); bindings.push_back(std::move(u)); } else { throw configuration_exception_t("unexpected kind " + element_name); } } void policy_engine::load_entity_bindings(const char *file_name, std::list<std::unique_ptr<entity_binding_t>> &bindings, reporter_t *err) { try { YAML::Node n = YAML::LoadFile(file_name); // if (n["entities"]) { // YAML::Node soc = n["entities"]; // for (YAML::const_iterator it = soc.begin(); it != soc.end(); ++it) { for (YAML::const_iterator it = n.begin(); it != n.end(); ++it) { process_element(*it, bindings); } } catch (std::exception &e) { err->error("while parsing %s: %s\n", file_name, e.what()); } // } else { // throw configuration_exception_t("Expected a root 'entities' node"); // } }
41.448276
106
0.691348
nickroess
931864a852a0a1633c69d6bcf21831da5265257a
1,308
cpp
C++
cmake-build-debug/test/unit/mechanisms/test0_kin_conserve_gpu.cpp
anstaf/arbsimd
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
[ "BSD-3-Clause" ]
null
null
null
cmake-build-debug/test/unit/mechanisms/test0_kin_conserve_gpu.cpp
anstaf/arbsimd
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
[ "BSD-3-Clause" ]
null
null
null
cmake-build-debug/test/unit/mechanisms/test0_kin_conserve_gpu.cpp
anstaf/arbsimd
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
[ "BSD-3-Clause" ]
null
null
null
#include <arbor/mechanism_abi.h> #include <cmath> namespace testing { void mechanism_test0_kin_conserve_gpu_init_(arb_mechanism_ppack*); void mechanism_test0_kin_conserve_gpu_advance_state_(arb_mechanism_ppack*); void mechanism_test0_kin_conserve_gpu_compute_currents_(arb_mechanism_ppack*); void mechanism_test0_kin_conserve_gpu_write_ions_(arb_mechanism_ppack*); void mechanism_test0_kin_conserve_gpu_apply_events_(arb_mechanism_ppack*, arb_deliverable_event_stream*); void mechanism_test0_kin_conserve_gpu_post_event_(arb_mechanism_ppack*); } // namespace testing extern "C" { arb_mechanism_interface* make_testing_test0_kin_conserve_interface_gpu() { static arb_mechanism_interface result; result.backend=arb_backend_kind_gpu; result.partition_width=1; result.alignment=1; result.init_mechanism=testing::mechanism_test0_kin_conserve_gpu_init_; result.compute_currents=testing::mechanism_test0_kin_conserve_gpu_compute_currents_; result.apply_events=testing::mechanism_test0_kin_conserve_gpu_apply_events_; result.advance_state=testing::mechanism_test0_kin_conserve_gpu_advance_state_; result.write_ions=testing::mechanism_test0_kin_conserve_gpu_write_ions_; result.post_event=testing::mechanism_test0_kin_conserve_gpu_post_event_; return &result; } };
43.6
105
0.856269
anstaf
7933dc15b6801eb0fb6326bfd120ff6d021f9338
9,118
cpp
C++
Sources/Modules/Renderer/SM2/OcclusionMapGenerator.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
Sources/Modules/Renderer/SM2/OcclusionMapGenerator.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
Sources/Modules/Renderer/SM2/OcclusionMapGenerator.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * 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 OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Core/Logger.h> #include <Core/TGA.h> #include <Renderer/Common/Tools.h> #include <Renderer/Common/Texture.h> #include <Renderer/Common/Camera.h> #include <Renderer/SM2/OcclusionMapGenerator.h> #include <Renderer/SM2/SceneSM2.h> namespace Renderer { //----------------------------------------------------------------------------- OcclusionMapGenerator::OcclusionMapGenerator(const Ptr<Gfx::IDevice> & pDevice, const Ptr<ShaderLib> & pShaderLib, const Ptr<PackedVerticesFormat> & pFormat, const Ptr<ScreenQuad> & pScreenQuad) : _pDevice(pDevice), _pShaderLib(pShaderLib), _pFormat(pFormat), _pScreenQuad(pScreenQuad) { } //----------------------------------------------------------------------------- bool OcclusionMapGenerator::initialise() { bool result = true; try { // Pixel shaders - Generate texcoords { Core::List<Gfx::ShaderMacro> macros; if(_pFormat->packedNormals()) macros.push_back(Gfx::ShaderMacro(L"PACKED_NORMAL_FLAG", L"1")); _pVShaderGen = _pShaderLib->getVShader(L"generate-occlusionmap.vsh", Gfx::VS_V3_0, L"vs_main", macros); _pPShaderGen = _pShaderLib->getPShader(L"generate-occlusionmap.psh", Gfx::PS_V3_0, L"ps_main", macros); _idTextureSizeGen = _pVShaderGen->getConstantTable()->getConstantIndex(L"TextureSize"); _idIsTextureBorderOnGen = _pVShaderGen->getConstantTable()->getConstantIndex(L"IsTextureBorderOn"); Gfx::RSRasterizerDesc raster(Gfx::CM_NOCM, true, Gfx::FM_SOLID); Gfx::RSDepthStencilDesc depth(false, false, Gfx::COMPARISON_LESS_EQUAL); Gfx::RSBlendDesc blend; _stateGen = _pDevice->createState(raster, depth, blend); _pFormatGen = _pFormat->getVertexFormat(_pDevice, _pVShaderGen, VD_SKIN_G_B); } // Pixel shaders - Build mipmaps { Core::List<Gfx::ShaderMacro> macros; _pPShaderMip = _pShaderLib->getPShader(L"build-mipmap.psh", Gfx::PS_V3_0, L"ps_main", macros); _idSourceSizeMip = _pPShaderMip->getConstantTable()->getConstantIndex(L"SourceSize"); _idSamplerImageMip = _pPShaderMip->getConstantTable()->getConstantIndex(L"SamplerImage"); _idIsAlphaWeightedMip = _pPShaderMip->getConstantTable()->getConstantIndex(L"IsAlphaWeighted"); Gfx::RSRasterizerDesc raster(Gfx::CM_NOCM, true, Gfx::FM_SOLID); Gfx::RSDepthStencilDesc depth(false, false, Gfx::COMPARISON_LESS_EQUAL); Gfx::RSBlendDesc blend; _stateMip = _pDevice->createState(raster, depth, blend); } } catch(Core::Exception & exception) { ERR << L"Error initializing Occlusion generator : " << exception.getMessage() << L"\n"; ERR << exception.getCallStack(); result = false; } return result; } //----------------------------------------------------------------------------- Ptr<Core::Bitmap> OcclusionMapGenerator::generateOcclusionMap(const OcclusionMapInfos & om, const Ptr<Assets::VerticeSet> & pVSet) { Ptr<IPackedSkinnedVertices> pPackedVertices = _pFormat->packSkinnedVerts(_pDevice, pVSet); // Surfaces int32 sizeMul = (om.internalTextureBorder || !om.superSampleUV) ? 1 : std::max(1, std::min(2048 / om.width, 2048 / om.height)); int32 srcWidth = sizeMul * om.width; int32 srcHeight = sizeMul * om.height; Gfx::Texture2DDesc texDesc; texDesc.width = srcWidth; texDesc.height = srcHeight; texDesc.mipLevels = 1; texDesc.format = Gfx::TF_A8R8G8B8; texDesc.usage = Gfx::BUFFER_USAGE_DEFAULT; texDesc.cpuAccess = Gfx::BCA_NO_ACCESS; texDesc.bind = Gfx::TB_RENDER_TARGET; texDesc.autoGenMipmap = false; Gfx::RenderTargetViewDesc rtDesc; rtDesc.texture2D.mipSlice = 0; Ptr<Gfx::ITexture2D> pTexOcclusion = _pDevice->createTexture2D(texDesc); Ptr<Gfx::IRenderTargetView> pViewOcclusion = _pDevice->createRenderTargetView(pTexOcclusion, rtDesc); _pDevice->beginDraw(); _pDevice->setState(_stateGen); _pDevice->setVertexFormat(_pFormatGen); _pDevice->setVertexShader(_pVShaderGen); _pDevice->setPixelShader(_pPShaderGen); _pVShaderGen->getConstantTable()->setConstant(_idTextureSizeGen, Core::Vector2f(float(srcWidth), float(srcHeight))); _pVShaderGen->getConstantTable()->setConstant(_idIsTextureBorderOnGen, om.internalTextureBorder); Gfx::IRenderTargetViewPtr targets[2]; _pDevice->setRenderTarget(pViewOcclusion, null); _pDevice->clearCurrentRenderTargetView(Core::Vector4f(1.0f, 1.0f, 1.0f, 0.0f), 0.0f, 0, Gfx::CLEAR_COLOR_BUFFER); pPackedVertices->bindData(_pDevice, VD_SKIN_G_B); pPackedVertices->sendData(_pDevice, VD_SKIN_G_B, 0); targets[0] = null; targets[1] = null; resize(pTexOcclusion, pViewOcclusion, srcWidth, srcHeight, om.width, om.height); Ptr<Core::Bitmap> pBitmapOcclusion = _pDevice->toBitmap(pViewOcclusion); _pDevice->endDraw(); pViewOcclusion = null; for(int32 ii=0; ii < 4; ii++) pBitmapOcclusion = borderDiffuse(pBitmapOcclusion); return pBitmapOcclusion; } //----------------------------------------------------------------------------- void OcclusionMapGenerator::resize(Ptr<Gfx::ITexture2D> & pTex, Ptr<Gfx::IRenderTargetView> & pView, int32 srcWidth, int32 srcHeight, int32 dstWidth, int32 dstHeight) { if(srcWidth == dstWidth && srcHeight == dstHeight) return; int32 halfWidth = std::max(dstWidth, srcWidth / 2); int32 halfHeight = std::max(dstHeight, srcHeight / 2); Gfx::Texture2DDesc texDesc; texDesc.width = halfWidth; texDesc.height = halfHeight; texDesc.mipLevels = 1; texDesc.format = Gfx::TF_A8R8G8B8; texDesc.usage = Gfx::BUFFER_USAGE_DEFAULT; texDesc.cpuAccess = Gfx::BCA_NO_ACCESS; texDesc.bind = Gfx::TB_RENDER_TARGET; texDesc.autoGenMipmap = false; Gfx::RenderTargetViewDesc rtDesc; rtDesc.texture2D.mipSlice = 0; Ptr<Gfx::ITexture2D> pTexHalf = _pDevice->createTexture2D(texDesc); Ptr<Gfx::IRenderTargetView> pViewHalf = _pDevice->createRenderTargetView(pTexHalf, rtDesc); _pDevice->setState(_stateMip); _pDevice->setPixelShader(_pPShaderMip); _pPShaderMip->getConstantTable()->setConstant(_idSourceSizeMip, Core::Vector2f(float(srcWidth), float(srcHeight))); _pPShaderMip->getConstantTable()->setConstant(_idIsAlphaWeightedMip, true); _pPShaderMip->getConstantTable()->setSampler2D(_idSamplerImageMip, pTex->getShaderResourceView()); _pDevice->setRenderTarget(pViewHalf, null); _pDevice->clearCurrentRenderTargetView(Core::Vector4f(0.0f, 0.0f, 0.0f, 0.0f), 0.0f, 0, Gfx::CLEAR_COLOR_BUFFER); _pScreenQuad->send(halfWidth, halfHeight); if(halfWidth != dstWidth || halfHeight != dstHeight) { resize(pTexHalf, pViewHalf, halfWidth, halfHeight, dstWidth, dstHeight); } std::swap(pTex, pTexHalf); std::swap(pView, pViewHalf); _pDevice->setRenderTarget(pView, null); _pPShaderMip->getConstantTable()->setSampler2D(_idSamplerImageMip, null); pViewHalf = null; pTexHalf = null; } //----------------------------------------------------------------------------- }
42.212963
197
0.665826
benkaraban
793e9d490330920025aca555b4bc7cc7bcf440a4
1,424
cpp
C++
Source/LogiLed/Private/LogiLedModule.cpp
ue4plugins/LogitechLed
6347c14d2b785b5a4d7636998ab0c99bc8a5b166
[ "BSD-3-Clause" ]
null
null
null
Source/LogiLed/Private/LogiLedModule.cpp
ue4plugins/LogitechLed
6347c14d2b785b5a4d7636998ab0c99bc8a5b166
[ "BSD-3-Clause" ]
null
null
null
Source/LogiLed/Private/LogiLedModule.cpp
ue4plugins/LogitechLed
6347c14d2b785b5a4d7636998ab0c99bc8a5b166
[ "BSD-3-Clause" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "LogiLedPrivate.h" #include "Modules/ModuleInterface.h" #include "Modules/ModuleManager.h" #include "LogitechLEDLib.h" DEFINE_LOG_CATEGORY(LogLogiLed); #define LOCTEXT_NAMESPACE "FLogiLedModule" /** * Implements the LogiLed module. */ class FLogiLedModule : public IModuleInterface { public: /** Default constructor. */ FLogiLedModule() : Initialized(false) { } public: //~ IModuleInterface interface virtual void StartupModule() override { #if LOGILED_SUPPORTED_PLATFORM // initialize Logitech SDK if (!::LogiLedInit()) { UE_LOG(LogLogiLed, Error, TEXT("Failed to initialize Logitech LED SDK")); return; } #else return; #endif //LOGILED_SUPPORTED_PLATFORM int Major, Minor, Build; if (::LogiLedGetSdkVersion(&Major, &Minor, &Build)) { UE_LOG(LogLogiLed, Log, TEXT("Initialized Logitech LED SDK %i.%i.%i."), Major, Minor, Build); } else { UE_LOG(LogLogiLed, Log, TEXT("Initialized Logitech LED SDK (unknown version)")); } Initialized = true; } virtual void ShutdownModule() override { if (!Initialized) { return; } #if LOGILED_SUPPORTED_PLATFORM // shut down SDK ::LogiLedShutdown(); #endif Initialized = false; } private: /** Whether the module has been initialized. */ bool Initialized; }; IMPLEMENT_MODULE(FLogiLedModule, LogiLed); #undef LOCTEXT_NAMESPACE
16.55814
96
0.707865
ue4plugins
794349e6afc59dff7efd2a109daa192786bd1679
439
cpp
C++
raygame/SteeringBehaviour.cpp
lodisperkins/AI2021---Graph-Framework
84c5f5d733c27b1ea144b90ca66bce276586cd63
[ "MIT" ]
null
null
null
raygame/SteeringBehaviour.cpp
lodisperkins/AI2021---Graph-Framework
84c5f5d733c27b1ea144b90ca66bce276586cd63
[ "MIT" ]
null
null
null
raygame/SteeringBehaviour.cpp
lodisperkins/AI2021---Graph-Framework
84c5f5d733c27b1ea144b90ca66bce276586cd63
[ "MIT" ]
null
null
null
#include "SteeringBehaviour.h" SteeringBehaviour::SteeringBehaviour() { } SteeringBehaviour::SteeringBehaviour(SteeringForce * steeringForce) { steeringForceObject = steeringForce; } SteeringBehaviour::~SteeringBehaviour() { } void SteeringBehaviour::execute(Agent* agent) { force = steeringForceObject->GetForce(agent); } void SteeringBehaviour::update(Agent * agent, float deltatime) { execute(agent); agent->AddForce(force); }
16.884615
67
0.776765
lodisperkins