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
f84381986bc199b3e2b8f142d7b97c934dfd94b2
1,951
cc
C++
set_modulation_curve/main.cc
tsubasatamba/cipher_analysis
395aa270810c12515d64cacd74cb70388ce55ada
[ "Unlicense" ]
null
null
null
set_modulation_curve/main.cc
tsubasatamba/cipher_analysis
395aa270810c12515d64cacd74cb70388ce55ada
[ "Unlicense" ]
null
null
null
set_modulation_curve/main.cc
tsubasatamba/cipher_analysis
395aa270810c12515d64cacd74cb70388ce55ada
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <fstream> #include <TStyle.h> #include <TROOT.h> #include <TFile.h> #include <TTree.h> #include <TH1.h> #include <TCanvas.h> #include <TF1.h> #include <TGraphErrors.h> #include "FitModulationCurve.hh" #include "GetAngle.hh" #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { const std::string json_filename = "/Users/tamba/work/cipher/SPring8_analysis_2021/modulation_factor/modulation_factors.json"; json js; std::ifstream fin(json_filename); fin >> js; json js_out; for (auto e1: js.items()) { const std::string experiment_name = e1.key(); int n = 0; for (json e2: e1.value().items()) { n++; } TGraphErrors* gr = new TGraphErrors(n); int index = 0; for (auto e2: e1.value().items()) { const std::string degree = e2.key(); const double x = getAngle(degree); const double xerror = 0.0; const double y = e2.value()["modulation_factor"]; const double yerror = e2.value()["error"]; gr->SetPoint(index, x, y); gr->SetPointError(index, xerror, yerror); index++; } TF1* f = fitModulationCurve(gr); std::vector<std::string> parameters = {"offset", "amplitude", "phase"}; json js_now; for (int i=0; i<3; i++) { const double value = f->GetParameter(i); const double error = f->GetParError(i); json js_tmp; js_tmp.push_back(json::object_t::value_type("value", value)); js_tmp.push_back(json::object_t::value_type("error", error)); js_now.push_back(json::object_t::value_type(parameters[i], js_tmp)); } js_out.push_back(json::object_t::value_type(experiment_name, js_now)); } const std::string output_json_filename = "/Users/tamba/work/cipher/SPring8_analysis_2021/analysis/modulation_curve/modulation_curves.json"; std::ofstream fout(output_json_filename); fout << std::setw(2) << js_out; return 0; }
30.484375
141
0.660174
tsubasatamba
f848c06c62dadad4f9e00b4264a6df74cd2010b3
5,983
cpp
C++
CPUT/source/opengl/CPUTGPUTimerOGL.cpp
GameTechDev/ChatHeads
f83c43f7fd3537badd74c31545ce2a45340474ee
[ "Apache-2.0" ]
13
2016-03-11T16:39:13.000Z
2021-09-16T09:05:50.000Z
CPUT/source/opengl/CPUTGPUTimerOGL.cpp
GameTechDev/ChatHeads
f83c43f7fd3537badd74c31545ce2a45340474ee
[ "Apache-2.0" ]
1
2016-09-14T01:57:00.000Z
2016-09-18T19:29:06.000Z
CPUT/source/opengl/CPUTGPUTimerOGL.cpp
GameTechDev/ChatHeads
f83c43f7fd3537badd74c31545ce2a45340474ee
[ "Apache-2.0" ]
10
2016-04-27T02:09:52.000Z
2019-12-08T12:35:40.000Z
///////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or imlied. // See the License for the specific language governing permissions and // limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////// #include "CPUTGPUTimerOGL.h" #include "CPUT_OGL.h" #include <algorithm> std::vector<CPUTGPUTimerOGL*> CPUTGPUTimerOGL::s_instances; unsigned int CPUTGPUTimerOGL::s_lastFrameID = 0; bool CPUTGPUTimerOGL::s_frameActive = false; std::vector<GLuint> CPUTGPUTimerOGL::s_timerQueries; #ifdef CPUT_OS_WINDOWS #define OSSleep Sleep #else #include <unistd.h> #define OSSleep sleep #endif CPUTGPUTimerOGL::CPUTGPUTimerOGL() { s_instances.push_back( this ); memset( m_history, 0, sizeof(m_history) ); for( int i = 0; i < (int)c_historyLength; i++ ) { m_history[i].TimingResult = -1.0; m_history[i].StartData = 0; m_history[i].StopData = 0; } m_historyLastIndex = 0; m_active = false; m_lastTime = 0.0f; m_avgTime = 0.0f; } CPUTGPUTimerOGL::~CPUTGPUTimerOGL() { std::vector<CPUTGPUTimerOGL*>::iterator it = std::find(s_instances.begin(), s_instances.end(), this); if( it != s_instances.end() ) { s_instances.erase( it ); } else { // this instance not found in the global list? assert( false ); } } void CPUTGPUTimerOGL::OnDeviceAndContextCreated() { s_lastFrameID = 0; s_frameActive = false; } void CPUTGPUTimerOGL::OnDeviceAboutToBeDestroyed() { FrameFinishQueries( true ); s_timerQueries.clear(); } void CPUTGPUTimerOGL::FrameFinishQueries(bool forceAll) { assert( !s_frameActive ); for( int i = 0; i < (int)s_instances.size(); i++ ) s_instances[i]->FinishQueries( forceAll ); } GLuint CPUTGPUTimerOGL::GetTimerQuery2() { GLuint queryID; if( s_timerQueries.size() == 0 ) { GL_CHECK(glGenQueries(1,&queryID)); } else { queryID = s_timerQueries.back(); s_timerQueries.pop_back(); } return queryID; } void CPUTGPUTimerOGL::OnFrameStart() { FrameFinishQueries( false ); assert( !s_frameActive ); s_frameActive = true; s_lastFrameID++; } void CPUTGPUTimerOGL::OnFrameEnd() { assert( s_frameActive ); s_frameActive = false; } static bool GetQueryDataHelper( bool loopUntilDone, GLuint query, GLuint64* startTime ) { if( query == 0 ) return false; int attempts = 0; do { // wait until the results are available GLint stopTimerAvailable = 0; glGetQueryObjectiv(query,GL_QUERY_RESULT_AVAILABLE, &stopTimerAvailable); if (stopTimerAvailable == 0) { // results not available yet - should try again later } else { glGetQueryObjectui64v(query, GL_QUERY_RESULT, startTime); return true; } attempts++; if( attempts > 1000 ) OSSleep(0); if( attempts > 100000 ) { ASSERT( false, "CPUTGPUTimerOGL.cpp - Infinite loop while doing s_immediateContext->GetData()\n"); return false; } } while ( loopUntilDone); return false; } void CPUTGPUTimerOGL::FinishQueries(bool forceAll) { assert( !m_active ); int dataGathered = 0; m_avgTime = 0.0; m_NewRetires = 0; // get data from previous frames queries if available for( int i = 0; i < (int)c_historyLength; i++ ) { int safeIndex = (i % c_historyLength); GPUTimerInfo & item = m_history[safeIndex]; bool tryGather = true; if( item.QueryActive ) { bool loopUntilDone = ((s_lastFrameID - item.FrameID) >= c_dataQueryMaxLag) || forceAll; GLuint64 startTime = 0, stopTime = 0; GetQueryDataHelper( loopUntilDone, item.StartQuery2, &startTime ); GetQueryDataHelper( loopUntilDone, item.StopQuery2, &stopTime ); if(startTime && stopTime ) { item.TimingResult = (double)(stopTime-startTime)/1000000000.0f; item.QueryActive = false; m_NewRetires++; if(item.FrameID>m_lastFrameID) { m_lastFrameID = item.FrameID; m_lastTime = item.TimingResult; } } } if( (!item.QueryActive) && (item.TimingResult != -1.0) ) { dataGathered++; m_avgTime += item.TimingResult; if(item.StartQuery2 && item.StopQuery2) { s_timerQueries.push_back(item.StartQuery2); s_timerQueries.push_back(item.StopQuery2); item.StartQuery2 = 0; item.StopQuery2 = 0; } } } if( dataGathered == 0 ) m_avgTime = 0.0f; else m_avgTime /= (double)dataGathered; } void CPUTGPUTimerOGL::Start() { assert( s_frameActive ); assert( !m_active ); m_historyLastIndex = (m_historyLastIndex+1)%c_historyLength; assert( !m_history[m_historyLastIndex].QueryActive ); m_history[m_historyLastIndex].StartQuery2 = GetTimerQuery2(); glQueryCounter(m_history[m_historyLastIndex].StartQuery2, GL_TIMESTAMP); m_history[m_historyLastIndex].QueryActive = true; m_history[m_historyLastIndex].FrameID = s_lastFrameID; m_active = true; m_history[m_historyLastIndex].TimingResult = -1.0; } void CPUTGPUTimerOGL::Stop() { assert( s_frameActive ); assert( m_active ); assert( m_history[m_historyLastIndex].QueryActive ); m_history[m_historyLastIndex].StopQuery2 = GetTimerQuery2(); glQueryCounter(m_history[m_historyLastIndex].StopQuery2, GL_TIMESTAMP); m_active = false; }
23.011538
111
0.644994
GameTechDev
f84d951333fd041c064a8d421406648cdf837983
2,015
cpp
C++
src/lib/AST/PType.cpp
LittleLaGi/p2llvm
549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3
[ "MIT" ]
null
null
null
src/lib/AST/PType.cpp
LittleLaGi/p2llvm
549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3
[ "MIT" ]
null
null
null
src/lib/AST/PType.cpp
LittleLaGi/p2llvm
549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3
[ "MIT" ]
null
null
null
#include "AST/PType.hpp" #include <cassert> const char *kTypeString[] = {"void", "integer", "real", "boolean", "string"}; // logical constness const char *PType::getPTypeCString() const { if (!m_type_string_is_valid) { m_type_string += kTypeString[static_cast<size_t>(m_type)]; if (m_dimensions.size() != 0) { m_type_string += " "; for (const auto &dim : m_dimensions) { m_type_string += "[" + std::to_string(dim) + "]"; } } m_type_string_is_valid = true; } return m_type_string.c_str(); } PType *PType::getStructElementType(const std::size_t nth) const { if (nth > m_dimensions.size()) { return nullptr; } auto *type_ptr = new PType(m_type); std::vector<uint64_t> dims; for (std::size_t i = nth; i < m_dimensions.size(); ++i) { dims.emplace_back(m_dimensions[i]); } type_ptr->setDimensions(dims); return type_ptr; } bool PType::compare(const PType *p_type) const { // primitive type comparison switch(m_type) { case PrimitiveTypeEnum::kIntegerType: case PrimitiveTypeEnum::kRealType: if (!p_type->isPrimitiveInteger() && !p_type->isPrimitiveReal()) { return false; } break; case PrimitiveTypeEnum::kBoolType: if (!p_type->isPrimitiveBool()) { return false; } break; case PrimitiveTypeEnum::kStringType: if (!p_type->isPrimitiveString()) { return false; } break; default: assert(false && "comparing unknown primitive type or void type"); return false; } // dimensions comparison auto &dimensions = p_type->getDimensions(); if (m_dimensions.size() != dimensions.size()) { return false; } for (decltype(m_dimensions)::size_type i = 0; i < m_dimensions.size(); ++i) { if (m_dimensions[i] != dimensions[i]) { return false; } } return true; }
25.833333
81
0.583623
LittleLaGi
f84ed5a21909008dd393c61e05f5a189c81629e6
627
cpp
C++
.emacs.d/cedet/semantic/tests/testfriends.cpp
littletwolee/emacs-configure
6fe0f3e99cab1c40de8e32e50740ff5d0d765fa3
[ "MIT" ]
6
2019-01-06T05:55:47.000Z
2021-05-28T09:29:58.000Z
.emacs.d/cedet/semantic/tests/testfriends.cpp
littletwolee/emacs-configure
6fe0f3e99cab1c40de8e32e50740ff5d0d765fa3
[ "MIT" ]
null
null
null
.emacs.d/cedet/semantic/tests/testfriends.cpp
littletwolee/emacs-configure
6fe0f3e99cab1c40de8e32e50740ff5d0d765fa3
[ "MIT" ]
2
2015-12-09T19:06:16.000Z
2021-12-02T14:41:31.000Z
// Test parsing of friends and how they are used in completion. /* >> Thanks Damien Profeta for the nice example. > > I paste a small example. > It would be great if friend can be well parsed and even greater if > class B can access to all the members of A. */ class Af // %2% ( ( "testfriends.cpp" ) ( "Af" "B::testB" ) ) { public: int pubVar; private: int privateVar; friend class B; }; class B { public: int testB(); int testAB(); }; int B::testB() { Af classA; classA.//-1- ; //#1# ( "privateVar" "pubVar" ) } int B::testAB() { // %1% ( ( "testfriends.cpp" ) ( "B" "B::testAB" ) ) }
16.5
71
0.590112
littletwolee
f8515cb5e9bbf5ef7a813577bf3884c9c6c7ef4b
6,122
hpp
C++
src/pyinterp/core/include/pyinterp/detail/math.hpp
apatlpo/pangeo-pyinterp
b5242c6869d7e601a5695b304c81992deb63367d
[ "BSD-3-Clause" ]
null
null
null
src/pyinterp/core/include/pyinterp/detail/math.hpp
apatlpo/pangeo-pyinterp
b5242c6869d7e601a5695b304c81992deb63367d
[ "BSD-3-Clause" ]
null
null
null
src/pyinterp/core/include/pyinterp/detail/math.hpp
apatlpo/pangeo-pyinterp
b5242c6869d7e601a5695b304c81992deb63367d
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019 CNES // // All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #pragma once #include <cmath> #include <tuple> namespace pyinterp { namespace detail { namespace math { /// π template <typename T> inline constexpr T pi() noexcept { return std::atan2(T(0), T(-1)); } /// π/2 template <typename T> inline constexpr T pi_2() noexcept { return 0.5 * pi<T>(); } /// 2π template <typename T> inline constexpr T two_pi() noexcept { return T(2) * pi<T>(); } /// Convert angle x from radians to degrees. template <typename T> inline constexpr T radians(const T& x) noexcept { return x * pi<T>() / T(180); } /// Convert angle x from degrees to radians. template <typename T> inline constexpr T degrees(const T& x) noexcept { return x * T(180) / pi<T>(); } /// Normalize an angle. /// /// @param x The angle in degrees. /// @param min Minimum circle value /// @param circle Circle value /// @return the angle reduced to the range [min, circle + min[ template <typename T> inline constexpr T normalize_angle(const T& x, const T& min = T(-180), const T& circle = T(360)) noexcept { T result = std::remainder(x - min, circle); if (result < T(0)) { result += circle; } result += min; return result; } /// Computes the remainder of the operation x/y /// /// @return a result with the same sign as its second operand template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>> inline constexpr T remainder(const T& x, const T& y) noexcept { auto result = x % y; return result != 0 && (result ^ y) < 0 ? result + y : result; } /// Evaluate the sine function with the argument in degrees /// /// In order to minimize round-off errors, this function exactly reduces the /// argument to the range [-45, 45] before converting it to radians. /// /// @param x x in degrees. /// @return sin(x). template <typename T> inline constexpr T sind(const T& x) noexcept { int quotient{}; T result = radians(std::remquo(x, T(90), &quotient)); // now |result| <= π/4 auto quadrant = static_cast<unsigned int>(quotient); result = (quadrant & 1U) ? std::cos(result) : std::sin(result); if (quadrant & 2U) { result = -result; } return result; } /// Evaluate the cosine function with the argument in degrees /// /// @param x in degrees. /// @return cos(x). template <typename T> inline constexpr T cosd(const T& x) noexcept { int quotient{}; T result = radians(std::remquo(x, T(90), &quotient)); // now |result| <= π/4 auto quadrant = static_cast<unsigned int>(quotient + 1); result = (quadrant & 1U) ? std::cos(result) : std::sin(result); if (quadrant & 2U) { result = -result; } return result; } /// Evaluate the sine and cosine function with the argument in degrees /// /// @param x in degrees. /// @return a tuple that contains sin(x) and cos(x) template <typename T> inline constexpr std::tuple<T, T> sincosd(const T& x) noexcept { int quotient{}; T angle = radians(std::remquo(x, T(90), &quotient)); // now |angle| <= π/4 switch (static_cast<unsigned int>(quotient) & 3U) { case 0U: return std::make_tuple(std::sin(angle), std::cos(angle)); case 1U: return std::make_tuple(std::cos(angle), -std::sin(angle)); case 2U: return std::make_tuple(-std::sin(angle), -std::cos(angle)); // case 3U default: return std::make_tuple(-std::cos(angle), std::sin(angle)); } } /// Evaluate the tangent function with the argument in degrees /// /// @param x in degrees. /// @return tan(x). template <typename T> inline constexpr T tand(const T& x) noexcept { T sinx{}, cosx{}; std::tie(sinx, cosx) = sincosd(x); return cosx != 0 ? sinx / cosx : (sinx < 0 ? -HUGE_VAL : HUGE_VAL); } /// Evaluate the atan2 function with the result in degrees /// /// @param y /// @param x /// @return atan2(y, x) in degrees. template <typename T> inline constexpr T atan2d(T y, T x) noexcept { // In order to minimize round-off errors, this function rearranges the // arguments so that result of atan2 is in the range [-π/4, π/4] before // converting it to degrees and mapping the result to the correct // quadrant. int quadrant = 0; if (std::abs(y) > std::abs(x)) { std::swap(x, y); quadrant = 2; } if (x < 0) { x = -x; ++quadrant; } // here x >= 0 and x >= abs(y), so angle is in [-π/4, π/4] T angle = degrees(std::atan2(y, x)); switch (quadrant) { case 1: angle = (y >= 0 ? 180 : -180) - angle; break; case 2: angle = 90 - angle; break; case 3: angle = -90 + angle; break; default: break; } return angle; } /// Evaluate the atan function with the result in degrees /// /// @param x /// @return atan(x) in degrees. template <typename T> inline constexpr T atand(const T& x) noexcept { return atan2d(x, T(1)); } /// Square a number. /// /// @return \f$x^2\f$ template <typename T> inline constexpr T sqr(const T& x) noexcept { return x * x; } /// True if a and b are two values identical to an epsilon. template <typename T> inline constexpr bool is_same(const T& a, const T& b, const T& epsilon) noexcept { return std::fabs(a - b) <= epsilon; } /// Represents a filling value template <typename T, class Enable = void> struct Fill; /// Represents a filling value for floating point number template <class T> struct Fill<T, std::enable_if_t<std::is_floating_point<T>::value>> { static inline constexpr T value() noexcept { return std::numeric_limits<T>::quiet_NaN(); } static inline constexpr T is_not(const T& x) noexcept { return !std::isnan(x); } }; /// Represents a filling value for integer number template <class T> struct Fill<T, std::enable_if_t<std::is_integral<T>::value>> { static inline constexpr T value() noexcept { return std::numeric_limits<T>::max(); } static inline constexpr T is_not(const T& x) noexcept { return Fill::value() != x; } }; } // namespace math } // namespace detail } // namespace pyinterp
26.617391
78
0.639824
apatlpo
f8517aaf27e3823e0bab69f02e0c7766c43c9a3f
1,144
cpp
C++
niceday-1.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
264
2015-01-08T10:07:01.000Z
2022-03-26T04:11:51.000Z
niceday-1.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
17
2016-04-15T03:38:07.000Z
2020-10-30T00:33:57.000Z
niceday-1.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
127
2015-01-08T04:56:44.000Z
2022-02-25T18:40:37.000Z
// 2008-09-01 // niceday-1.cpp uses misof's "staircase" data structure. // See niceday-2.cpp for another approach. #include <cstdio> #include <algorithm> #include <map> using namespace std; #define MAX(a,b) ((a)>(b)?(a):(b)) #ifdef _MSC_VER #define GC getchar #else #define GC getchar_unlocked #endif #define SIZE 100000 int input() { int x=0; char c; for(;;) { c=GC(); if (c==' '||c=='\n') return x; x=10*x+c-'0'; } } static pair<int,pair<int,int> > C[SIZE]; int main() { int i,t,N,j,excellent; t=input(); for (i=0; i<t; i++) { N=input(); map<int,int> M; for (j=0; j<N; j++) { C[j].first=input(); C[j].second.first=input(); C[j].second.second=input(); } excellent=1; sort(C,C+N); map<int,int>::iterator I1,I2; M.insert(C[0].second); int x,y; for (j=1; j<N; j++) { x=C[j].second.first; y=C[j].second.second; I1=M.lower_bound(x); if (I1!=M.begin()) { I1--; if (I1->second<y) continue; I1++; } I2=I1; while (I2!=M.end()&&I2->second>y) I2++; M.erase(I1,I2); M.insert(C[j].second); excellent++; } printf("%d\n",excellent); } return 0; }
16.342857
57
0.557692
ohmyjons
f859bebd724186d33d763504c385dacb0309ff7e
4,430
cpp
C++
src/in_2sf/desmume/addons/slot1_retail.cpp
CyberBotX/in_xsf
6d78469746b17bf1a9356c7a26ecd2850ba46eb3
[ "BSD-3-Clause" ]
15
2015-09-04T10:36:15.000Z
2022-02-23T23:52:37.000Z
src/in_2sf/desmume/addons/slot1_retail.cpp
WACUP/in_xsf
719f5b443af91e53f35f86055dd0b1b4851db2b0
[ "BSD-3-Clause" ]
3
2017-11-09T18:09:47.000Z
2021-02-04T05:39:09.000Z
src/in_2sf/desmume/addons/slot1_retail.cpp
WACUP/in_xsf
719f5b443af91e53f35f86055dd0b1b4851db2b0
[ "BSD-3-Clause" ]
9
2016-11-22T10:05:20.000Z
2021-06-12T19:48:53.000Z
/* Copyright (C) 2010-2011 DeSmuME team This file is part of DeSmuME DeSmuME is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. DeSmuME is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DeSmuME; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../slot1.h" #include "../registers.h" #include "../MMU.h" #include "../NDSSystem.h" static void info(char *info) { strcpy(info, "Slot1 Retail card emulation"); } static void config() {} static bool init() { return true; } static void reset() {} static void close() {} static void write08(uint8_t, uint32_t, uint8_t) {} static void write16(uint8_t, uint32_t, uint16_t) {} static void write32_GCROMCTRL(uint8_t PROCNUM, uint32_t) { nds_dscard &card = MMU.dscard[PROCNUM]; switch (card.command[0]) { case 0x00: // Data read case 0xB7: card.address = (card.command[1] << 24) | (card.command[2] << 16) | (card.command[3] << 8) | card.command[4]; card.transfer_count = 0x80; break; case 0xB8: // Chip ID card.address = 0; card.transfer_count = 1; break; default: card.address = 0; card.transfer_count = 0; } } static void write32(uint8_t PROCNUM, uint32_t adr, uint32_t val) { switch (adr) { case REG_GCROMCTRL: write32_GCROMCTRL(PROCNUM, val); } } static uint8_t read08(uint8_t, uint32_t) { return 0xFF; } static uint16_t read16(uint8_t, uint32_t) { return 0xFFFF; } static uint32_t read32_GCDATAIN(uint8_t PROCNUM) { nds_dscard &card = MMU.dscard[PROCNUM]; switch (card.command[0]) { // Get ROM chip ID case 0x90: case 0xB8: { // Note: the BIOS stores the chip ID in main memory // Most games continuously compare the chip ID with // the value in memory, probably to know if the card // was removed. // As DeSmuME normally boots directly from the game, the chip // ID in main mem is zero and this value needs to be // zero too. // note that even if desmume was booting from firmware, and reading this chip ID to store in main memory, // this still works, since it will have read 00 originally and then read 00 to validate. // staff of kings verifies this (it also uses the arm7 IRQ 20) if (nds.cardEjected) // TODO - handle this with ejected card slot1 device (and verify using this case) return 0xFFFFFFFF; else return 0; } // Data read case 0x00: case 0xB7: { // it seems that etrian odyssey 3 doesnt work unless we mask this to cart size. // but, a thought: does the internal rom address counter register wrap around? we may be making a mistake by keeping the extra precision // but there is no test case yet uint32_t address = card.address & gameInfo.mask; // Make sure any reads below 0x8000 redirect to 0x8000+(adr&0x1FF) as on real cart if (card.command[0] == 0xB7 && address < 0x8000) { // TODO - refactor this to include the PROCNUM, for debugging purposes if nothing else // (can refactor gbaslot also) //INFO("Read below 0x8000 (0x%04X) from: ARM%s %08X\n", card.address, (PROCNUM ? "7":"9"), (PROCNUM ? NDS_ARM7:NDS_ARM9).instruct_adr); address = 0x8000 + (address & 0x1FF); } // as a sanity measure for funny-sized roms (homebrew and perhaps truncated retail roms) // we need to protect ourselves by returning 0xFF for things still out of range if (address >= gameInfo.romsize) { //DEBUG_Notify.ReadBeyondEndOfCart(address, gameInfo. romsize); return 0xFFFFFFFF; } return T1ReadLong(MMU.CART_ROM, address); } default: return 0; } //switch(card.command[0]) } //read32_GCDATAIN static uint32_t read32(uint8_t PROCNUM, uint32_t adr) { switch (adr) { case REG_GCDATAIN: return read32_GCDATAIN(PROCNUM); default: return 0; } } SLOT1INTERFACE slot1Retail = { "Retail", init, reset, close, config, write08, write16, write32, read08, read16, read32, info };
26.369048
140
0.688713
CyberBotX
f85d695eed711dbf2fc70ef58615aa9d44d562b1
799
cpp
C++
arc060_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
arc060_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
arc060_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, n, s) for (LL i = (s); i < (n); i++) #define SIZE 1 using namespace std; typedef long long int LL; typedef long double LD; LL func(LL b, LL n) { if (n < b) return n; return func(b, floor(n/b)) + (n % b); } int main() { ios::sync_with_stdio(0); cin.tie(0); LL N, S; cin >> N >> S; LL res = -1; LL _N = ceil(sqrt((double)N)); REP(i, _N+1, 2) { if (func(i, N) == S && res == -1) { res = i; break; } } if (res != -1) { cout << res << endl; return 0; } for (LL p = _N - 1; p > 0; p--) { if (S < p) continue; LL q = S - p, b = (N - q) / p; if ((N - q)%p == 0 && q < b && b > _N) { res = (N - q) / p; break; } } if (res == -1 && N == S) { cout << (N+1) << endl; return 0; } cout << res << endl; return 0; }
15.365385
51
0.459324
s-shirayama
f86122b64e73a12002a05e074d397c9ae9536865
26
cc
C++
examples/POSIX/json-rpc-server/jsonRpcServer.cc
PetroShevchenko/lib-coap-cpp
f99bff174925257ea63480f598f5753ece0f392d
[ "Apache-2.0" ]
null
null
null
examples/POSIX/json-rpc-server/jsonRpcServer.cc
PetroShevchenko/lib-coap-cpp
f99bff174925257ea63480f598f5753ece0f392d
[ "Apache-2.0" ]
null
null
null
examples/POSIX/json-rpc-server/jsonRpcServer.cc
PetroShevchenko/lib-coap-cpp
f99bff174925257ea63480f598f5753ece0f392d
[ "Apache-2.0" ]
null
null
null
#include "jsonRpcServer.h"
26
26
0.807692
PetroShevchenko
f861ec595025bdb258c2ae0cb3f416f88b0a6742
1,583
cpp
C++
C++/Valid Sudoku.cpp
mafia1989/leetcode
f0bc9708a58602866818120556d8b8caf114811e
[ "MIT" ]
3
2015-08-29T15:25:13.000Z
2015-08-29T15:25:21.000Z
C++/Valid Sudoku.cpp
mafia1989/leetcode
f0bc9708a58602866818120556d8b8caf114811e
[ "MIT" ]
null
null
null
C++/Valid Sudoku.cpp
mafia1989/leetcode
f0bc9708a58602866818120556d8b8caf114811e
[ "MIT" ]
null
null
null
// Valid Sudoku // Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. // The Sudoku board could be partially filled, where empty cells are filled with the character '.'. // A partially filled sudoku which is valid. // Note: // A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. //My solution class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { if(board.size() != 9 || board[0].size() != 9) return false; for(int i = 0; i< 9 ; i++) { if(checkNine(board,i,i,0,8) == false) return false; if(checkNine(board,0,8,i,i) == false) return false; } for (int i=0;i<3;i++) for(int j=0;j<3;j++) { if (!checkNine(board,i*3,i*3+2,j*3,j*3+2)) return false; } return true; } bool checkNine(vector<vector<char>>& board,int x1,int x2,int y1,int y2) { vector<int> countArray(board.size(),0); for(int i = x1;i<=x2;i++) for(int j = y1;j<=y2;j++) { if(board[i][j] != '.') { int k = board[i][j] - '1'; if(countArray[k] == 0) { countArray[k] = 1; } else return false; } } return true; } };
25.532258
115
0.44662
mafia1989
d379c1471b7caf3cdbf0d0efade3bd5a414b6754
1,437
cpp
C++
tests/TestMain.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
2
2021-01-27T15:49:04.000Z
2021-01-28T07:40:30.000Z
tests/TestMain.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
null
null
null
tests/TestMain.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
1
2021-03-07T23:17:31.000Z
2021-03-07T23:17:31.000Z
#include "pch.h" #include "engine/Logger.h" #define CATCH_CONFIG_RUNNER #include <catch2/catch.hpp> int main(int argc, char* argv[]) { Catch::Session session; // There must be exactly one instance int height = 0; // Some user variable you want to be able to set Log.Init(LogLevel::Error); // Build a new parser on top of Catch's using namespace Catch::clara; auto cli = session.cli() // Get Catch's composite command line parser | Opt(height, "height") // bind variable to a new option, with a hint string ["-g"]["--height"] // the option names it will respond to ("how high?"); // description string for the help output // Now pass the new composite back to Catch so it uses that session.cli(cli); // Let Catch (using Clara) parse the command line int returnCode = session.applyCommandLine(argc, argv); if (returnCode != 0) // Indicates a command line error return returnCode; // if set on the command line then 'height' is now set at this point if (height > 0) std::cout << "height: " << height << std::endl; return session.run(); } /* #include "pch/pch.h" #include "AppBase.h" #include "engine/Logger.h" #include <iostream> int32 main(int32 argc, char* argv[]) { std::cout << "Hello Test!\n"; // Init logger (global access, not engine, app or window bound) LOGGER_INIT(LogLevel::INFO); App app; app.PreMainInit(argc, argv); return app.Main(argc, argv); } */
26.127273
82
0.673626
RaygenEngine
d37bb5937797e26b8648e5cd79d5d1c5f0f70e42
1,217
cpp
C++
src/mt-options.cpp
chrmoritz/lzma-native
313fb09ede27bed1c4e7f189b5fc99eadfddb5c2
[ "MIT" ]
20
2019-09-02T02:14:47.000Z
2022-02-23T23:13:50.000Z
src/mt-options.cpp
chrmoritz/lzma-native
313fb09ede27bed1c4e7f189b5fc99eadfddb5c2
[ "MIT" ]
7
2019-09-06T08:23:55.000Z
2021-03-19T11:59:39.000Z
node_modules/lzma-native/src/mt-options.cpp
96vksingh/nodejs_action
675a6bd8dfd3aa25c0863d1cec9597b71fbdac58
[ "MIT" ]
3
2019-09-22T20:57:13.000Z
2022-01-03T16:59:03.000Z
#include "liblzma-node.hpp" namespace lzma { MTOptions::MTOptions() : filters_(NULL), ok_(false) { } MTOptions::~MTOptions() { delete filters_; } MTOptions::MTOptions(Local<Object> opt) : filters_(NULL), ok_(true) { opts_.flags = 0; opts_.filters = NULL; opts_.block_size = Nan::To<int64_t>(Nan::Get(opt, NewString("blockSize")).ToLocalChecked()).ToChecked(); opts_.timeout = Nan::To<uint32_t>(Nan::Get(opt, NewString("timeout")).ToLocalChecked()) .FromMaybe(0); opts_.preset = Nan::To<uint32_t>(Nan::Get(opt, NewString("preset")).ToLocalChecked()) .FromMaybe(LZMA_PRESET_DEFAULT); opts_.check = (lzma_check)Nan::To<int32_t>(Nan::Get(opt, NewString("check")).ToLocalChecked()) .FromMaybe((int)LZMA_CHECK_CRC64); opts_.threads = Nan::To<uint32_t>(Nan::Get(opt, NewString("threads")).ToLocalChecked()) .FromMaybe(0); if (opts_.threads == 0) { opts_.threads = lzma_cputhreads(); } Local<Value> filters = Nan::Get(opt, NewString("filters")).ToLocalChecked(); if (filters->IsArray()) { filters_ = new FilterArray(Local<Array>::Cast(filters)); if (filters_->ok()) { opts_.filters = filters_->array(); } else { ok_ = false; } } } }
29.682927
106
0.657354
chrmoritz
d37c1e9430bcf7605b43ebd233675f37195dea3d
3,642
cpp
C++
src/GameOptionsManager.cpp
psobow/TicTacToeCpp
479ba81b9fcb37be4776ef528f0e8d81bed4245c
[ "MIT" ]
null
null
null
src/GameOptionsManager.cpp
psobow/TicTacToeCpp
479ba81b9fcb37be4776ef528f0e8d81bed4245c
[ "MIT" ]
null
null
null
src/GameOptionsManager.cpp
psobow/TicTacToeCpp
479ba81b9fcb37be4776ef528f0e8d81bed4245c
[ "MIT" ]
null
null
null
#include "../include/GameOptionsManager.hpp" GameOptionsManager* GameOptionsManager::instance = nullptr; GameOptionsManager* GameOptionsManager::getInstance() { if(instance == nullptr) { instance = new GameOptionsManager(); } return instance; } void GameOptionsManager::setGameStartingPlayer(const GameParticipant& PLAYER) { gameStartingPlayer = PLAYER; } void GameOptionsManager::switchHumanAndComputerChar() { char tempHumanChar = humanChar; humanChar = computerChar; computerChar = tempHumanChar; } void GameOptionsManager::setPointsRequiredForVictory(const int NEW_POINTS) { if (NEW_POINTS < MIN_POINTS_FOR_VICTORY || NEW_POINTS > boardSize) { std::string exceptionMessage = "Invalid new amount of points required for victory. Recived argument = " + std::to_string(NEW_POINTS) + "\n"; throw std::invalid_argument( exceptionMessage ); } pointsRequiredForVictory = NEW_POINTS; } void GameOptionsManager::setBoardSize(const int NEW_BOARD_SIZE) { if (NEW_BOARD_SIZE < MIN_BOARD_SIZE || NEW_BOARD_SIZE > MAX_BOARD_SIZE) { std::string exceptionMessage = "Invalid new board size. Recived argument = " + std::to_string(NEW_BOARD_SIZE) + "\n"; throw std::invalid_argument( exceptionMessage ); } boardSize = NEW_BOARD_SIZE; } const Participant GameOptionsManager::getEnumAssignedTo(const char CHAR) const { if ( (CHAR != EMPTY_SLOT_CHAR) && (CHAR != humanChar) && (CHAR != computerChar) ) { std::string exceptionMessage = "Invalid char. There is no Game Participant assigned to " + std::to_string(CHAR) + "\n"; throw std::invalid_argument( exceptionMessage ); } if (CHAR == humanChar) { return HUMAN; } else if (CHAR == computerChar) { return COMPUTER; } else { return NONE; } } const char GameOptionsManager::getCharAssignedTo(const Participant& PLAYER) const { if (PLAYER == NONE) { return EMPTY_SLOT_CHAR; } else if (PLAYER == HUMAN) { return humanChar; } else { return computerChar; } } const int GameOptionsManager::getDepthBound(const int BOARD_SIZE) const { switch (BOARD_SIZE) { case 3: return DEPTH_BOUND_3x3; case 4: return DEPTH_BOUND_4x4; case 5: return DEPTH_BOUND_5x5; case 6: return DEPTH_BOUND_6x6; case 7: return DEPTH_BOUND_7x7; case 8: return DEPTH_BOUND_8x8; case 9: return DEPTH_BOUND_9x9; case 10: return DEPTH_BOUND_10x10; default: break; } throw std::invalid_argument("Invalid argument. Recived argument = " + std::to_string(BOARD_SIZE) +"\n"); } const Participant GameOptionsManager::getGameStartingPlayer() const { return gameStartingPlayer; } const Participant GameOptionsManager::getOppositePlayer(const Participant& PLAYER) const { return static_cast<Participant>( PLAYER*(-1) ); } const int GameOptionsManager::getPointsRequiredForVictory() const { return pointsRequiredForVictory; } const int GameOptionsManager::getBoardSize() const { return boardSize; } const int GameOptionsManager::getMinBoardSize() const { return MIN_BOARD_SIZE; } const int GameOptionsManager::getMinPointsForVictory() const { return MIN_POINTS_FOR_VICTORY; } const int GameOptionsManager::getMaxBoardSize() const { return MAX_BOARD_SIZE; }
24.119205
127
0.654036
psobow
d382b5597aee79eda902a1f3a0059f942078e317
975
cpp
C++
chapter_1/ex-35.cpp
chwit/DSAA_by_CPP
5038de5229a098107e6861c17df088b8b85c711e
[ "BSD-2-Clause" ]
null
null
null
chapter_1/ex-35.cpp
chwit/DSAA_by_CPP
5038de5229a098107e6861c17df088b8b85c711e
[ "BSD-2-Clause" ]
null
null
null
chapter_1/ex-35.cpp
chwit/DSAA_by_CPP
5038de5229a098107e6861c17df088b8b85c711e
[ "BSD-2-Clause" ]
null
null
null
// // Created by user on 2019/4/10. // Copyright © 2019 user. All rights reserved. // #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; //next_permutation //只有排序之后的数组才能只用next_permutation获得全排列 int count_my = 0; //输出范围[start,end)内的全排列 template<typename T> void permutations(T list[], int k , int m) { //sort(list + k, list + m ); int num = m - k; int count = 1; for (int i = 2; i <= num; i++) // 计算总数 用 next & prev共同输出全排列 也可以判断数组是否相同 (用equal) count *= i; do { count_my++; count--; copy(list + k,list + m , ostream_iterator<T>(cout," ")); cout << endl; } while (next_permutation(list + k, list + m )); while (count) { count_my++; count--; copy(list + k, list + m, ostream_iterator<T>(cout, " ")); cout << endl; prev_permutation(list + k, list + m); } } int main() { int arr[] = { 1, 3, 2, 4, 5 }; permutations(arr, 0, 3); cout << count_my << endl; getchar(); getchar(); return 0; }
18.055556
83
0.610256
chwit
d383ec12679fb011994fb8de43f92751bf8d8534
1,595
hpp
C++
include/text_view_detail/basic_view.hpp
tahonermann/text_view
65740356488d0dd98b65f221c71c7b7377c813de
[ "MIT" ]
144
2015-10-10T10:12:53.000Z
2021-12-31T16:07:27.000Z
include/text_view_detail/basic_view.hpp
Quuxplusone/text_view
65740356488d0dd98b65f221c71c7b7377c813de
[ "MIT" ]
34
2016-01-22T03:52:53.000Z
2018-08-04T01:56:06.000Z
include/text_view_detail/basic_view.hpp
Quuxplusone/text_view
65740356488d0dd98b65f221c71c7b7377c813de
[ "MIT" ]
19
2016-02-10T11:29:20.000Z
2021-06-28T11:11:36.000Z
// Copyright (c) 2016, Tom Honermann // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #ifndef TEXT_VIEW_BASIC_VIEW_HPP // { #define TEXT_VIEW_BASIC_VIEW_HPP #include <utility> #include <experimental/ranges/concepts> namespace std { namespace experimental { inline namespace text { namespace text_detail { template<ranges::Iterator IT, ranges::Sentinel<IT> ST = IT> class basic_view : public ranges::view_base { public: using iterator = IT; using sentinel = ST; basic_view() = default; basic_view(IT first, ST last) : first{first}, last{last} {} template<typename IT2, typename ST2> requires ranges::Constructible<IT, IT2&&> && ranges::Constructible<ST, ST2&&> basic_view(IT2 first, ST2 last) : first(std::move(first)), last(std::move(last)) {} template<typename IT2, typename ST2> requires ranges::Constructible<IT, IT2&&> && ranges::Constructible<ST, ST2&&> basic_view(const basic_view<IT2, ST2> &o) : first(o.begin()), last(o.end()) {} IT begin() const { return first; } ST end() const { return last; } private: IT first = {}; ST last = {}; }; template<ranges::Iterator IT, ranges::Sentinel<IT> ST> auto make_basic_view(IT first, ST last) { return basic_view<IT, ST>{std::move(first), std::move(last)}; } } // namespace text_detail } // inline namespace text } // namespace experimental } // namespace std #endif // } TEXT_VIEW_BASIC_VIEW_HPP
24.538462
78
0.673981
tahonermann
d387a96b0da99eb463484c940d8f899aec583257
150
cpp
C++
tests/std/tests/VSO_0000000_c_math_functions/cmath.cpp
oktonion/STL
e2fce45b9ca899f3887b7fa48e24de95859a7b8e
[ "Apache-2.0" ]
2
2021-01-19T02:43:19.000Z
2021-11-20T05:21:42.000Z
tests/std/tests/VSO_0000000_c_math_functions/cmath.cpp
tapaswenipathak/STL
0d75fc5ab6684d4f6239879a6ec162aad0da860d
[ "Apache-2.0" ]
null
null
null
tests/std/tests/VSO_0000000_c_math_functions/cmath.cpp
tapaswenipathak/STL
0d75fc5ab6684d4f6239879a6ec162aad0da860d
[ "Apache-2.0" ]
4
2020-04-24T05:04:54.000Z
2020-05-17T22:48:58.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "type_asserts.hpp" #include <cmath>
25
59
0.733333
oktonion
d3898cc4b2eaeeb41b0bcae89c516391864463f8
1,553
cpp
C++
firmware/library/L3_HAL/test/buzzer_test.cpp
Jeremy-Chau/SJSU-Dev2
b3c0b008f9f19a12fe70d319760459b4b2111003
[ "Apache-2.0" ]
null
null
null
firmware/library/L3_HAL/test/buzzer_test.cpp
Jeremy-Chau/SJSU-Dev2
b3c0b008f9f19a12fe70d319760459b4b2111003
[ "Apache-2.0" ]
null
null
null
firmware/library/L3_HAL/test/buzzer_test.cpp
Jeremy-Chau/SJSU-Dev2
b3c0b008f9f19a12fe70d319760459b4b2111003
[ "Apache-2.0" ]
2
2018-07-27T20:48:40.000Z
2018-08-02T21:32:05.000Z
#include "L3_HAL/buzzer.hpp" #include "L1_Drivers/pwm.hpp" #include "L5_Testing/testing_frameworks.hpp" TEST_CASE("Testing buzzer", "[buzzer]") { // Create mock for PWM class Mock<PwmInterface> mock_pwm_pin; Fake( Method(mock_pwm_pin, Initialize), Method(mock_pwm_pin, SetDutyCycle), Method(mock_pwm_pin, SetFrequency), Method(mock_pwm_pin, GetDutyCycle), Method(mock_pwm_pin, GetFrequency)); PwmInterface & pwm = mock_pwm_pin.get(); // Instantiate buzzer test objects Buzzer test1(&pwm); SECTION("Check Initialize") { constexpr uint32_t kFrequency = 500; constexpr float kVolume = 0.0; test1.Initialize(); Verify( Method(mock_pwm_pin, Initialize).Using(500), Method(mock_pwm_pin, SetDutyCycle).Using(kVolume)), Method(mock_pwm_pin, SetFrequency).Using(kFrequency); } SECTION("Check Beep") { constexpr uint32_t kFrequency = 0; constexpr float kVolume = 0.0; test1.Beep(kFrequency, kVolume); float vol_error = kVolume - test1.GetVolume(); CHECK((-0.1f <= vol_error && vol_error <= 0.1f)); uint32_t freq_error = kFrequency - test1.GetFrequency(); CHECK(freq_error == 0); } SECTION("Check Stop") { constexpr uint32_t kFrequency = 500; constexpr float kVolume = 0.0; test1.Stop(); float vol_error = kVolume - test1.GetVolume(); CHECK((-0.1f <= vol_error && vol_error <= 0.1f)); } }
27.245614
65
0.62009
Jeremy-Chau
d39139f5437d8357fb6ff70daededd6f8024a64f
500
cpp
C++
ue5/Blink_game/Blink_game/PiDigitalOutput.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
ue5/Blink_game/Blink_game/PiDigitalOutput.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
ue5/Blink_game/Blink_game/PiDigitalOutput.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
#include "PiDigitalOutput.h" #include "PiIoManager.h" namespace pi_io { Pi_digital_output::Pi_digital_output(Pin pin) : pin_{ Pi_io_manager::instance().register_output(pin) } { } void Pi_digital_output::set_state(State state) { Pi_io_manager::instance().digital_write(pin_, state); } State Pi_digital_output::get_state() { return Pi_io_manager::instance().digital_read(pin_); } Pi_digital_output& Pi_digital_output::operator=(State rhs) { set_state(rhs); return *this; } }
18.518519
103
0.736
michivo
d39e2ce9546228306e6525f4563d98c23c74011a
3,217
cpp
C++
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Runtime.InteropServices // Name: UCOMIStream // C++ Typed Name: mscorlib::System::Runtime::InteropServices::UCOMIStream #include <gtest/gtest.h> #include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_UCOMIStream.h> #include <mscorlib/System/mscorlib_System_Byte.h> #include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_STATSTG.h> namespace mscorlib { namespace System { namespace Runtime { namespace InteropServices { //Public Methods Tests // Method Read // Signature: std::vector<mscorlib::System::Byte*> pv, mscorlib::System::Int32 cb, mscorlib::System::IntPtr pcbRead TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Read_Test) { } // Method Write // Signature: std::vector<mscorlib::System::Byte*> pv, mscorlib::System::Int32 cb, mscorlib::System::IntPtr pcbWritten TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Write_Test) { } // Method Seek // Signature: mscorlib::System::Int64 dlibMove, mscorlib::System::Int32 dwOrigin, mscorlib::System::IntPtr plibNewPosition TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Seek_Test) { } // Method SetSize // Signature: mscorlib::System::Int64 libNewSize TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,SetSize_Test) { } // Method CopyTo // Signature: mscorlib::System::Runtime::InteropServices::UCOMIStream pstm, mscorlib::System::Int64 cb, mscorlib::System::IntPtr pcbRead, mscorlib::System::IntPtr pcbWritten TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,CopyTo_Test) { } // Method Commit // Signature: mscorlib::System::Int32 grfCommitFlags TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Commit_Test) { } // Method Revert // Signature: TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Revert_Test) { } // Method LockRegion // Signature: mscorlib::System::Int64 libOffset, mscorlib::System::Int64 cb, mscorlib::System::Int32 dwLockType TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,LockRegion_Test) { } // Method UnlockRegion // Signature: mscorlib::System::Int64 libOffset, mscorlib::System::Int64 cb, mscorlib::System::Int32 dwLockType TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,UnlockRegion_Test) { } // Method Stat // Signature: mscorlib::System::Runtime::InteropServices::STATSTG pstatstg, mscorlib::System::Int32 grfStatFlag TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Stat_Test) { } // Method Clone // Signature: mscorlib::System::Runtime::InteropServices::UCOMIStream ppstm TEST(mscorlib_System_Runtime_InteropServices_UCOMIStream_Fixture,Clone_Test) { } } } } }
27.033613
178
0.71806
brunolauze
d3a15126bd4f8b80e79078193f3df6e00b0f4e7b
763
cpp
C++
src/lib/reorder.cpp
xuzijian629/pace2020
ec39d0dd193daf9fa1306ee8508a6f80fbab3c79
[ "MIT" ]
3
2020-06-12T09:17:33.000Z
2020-09-02T19:05:50.000Z
src/lib/reorder.cpp
xuzijian629/pace2020
ec39d0dd193daf9fa1306ee8508a6f80fbab3c79
[ "MIT" ]
null
null
null
src/lib/reorder.cpp
xuzijian629/pace2020
ec39d0dd193daf9fa1306ee8508a6f80fbab3c79
[ "MIT" ]
null
null
null
#include "graph.cpp" Graph reorder(const Graph& g, const vector<int>& to) { Graph ret; int n = g.n(); for (int i = 0; i < n; i++) { assert(g.nodes.test(i)); ret.add_node(to[i]); FOR_EACH(j, at(g.adj, i)) { ret.add_edge(to[i], to[j]); } } if (g.root != -1) ret.root = to[g.root]; return ret; } pair<vector<int>, vector<int>> find_good_order(const Graph& g) { int n = g.n(); vector<pair<int, int>> deg; for (int i = 0; i < n; i++) { deg.emplace_back(at(g.adj, i).count(), i); } sort(deg.rbegin(), deg.rend()); vector<int> to(n), back(n); for (int i = 0; i < n; i++) { int v = deg[i].second; to[v] = i; back[i] = v; } return make_pair(to, back); }
25.433333
65
0.496723
xuzijian629
d3a4b2fedbf139f9f34bc02019ee210dbf3eb967
5,781
cpp
C++
src/test/cases/multi_session.cpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
src/test/cases/multi_session.cpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
src/test/cases/multi_session.cpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <boost/uuid/uuid_io.hpp> #include "../test.hpp" #include "../../util/io.hpp" #include "../../util/util.hpp" #include "../../util/exception.hpp" #include "gen/isolevel_impls.hpp" namespace associative { namespace test { class Concurrent : public Test {}; TEST_F(Concurrent, IsolationUnsafe1) { auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); std::istringstream iss("content"); storeFile(file->getBlob("default")->getPath(true), iss); auto uuid = toString(file->uuid); env.commitSession(IsolationLevels::Full); auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.getFile(uuid); file1->removeBlob("default"); auto file2 = env2.getFile(uuid); iss.seekg(std::ios_base::beg); storeFile(file2->getBlob("default")->getPath(true), iss); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::BlobExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::BlobExclusive), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::Unsafe); ASSERT_THROW(env2.commitSession(IsolationLevels::Unsafe), CommitException) << "Expected exception"; env2.rollbackSession(); } TEST_F(Concurrent, IsolationUnsafe2) { auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); auto uuid = toString(file->uuid); env.commitSession(IsolationLevels::Full); auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.getFile(uuid); auto file2 = env2.getFile(uuid); auto blob = file2->getBlob("default"); file1->removeBlob("default"); env1.commitSession(IsolationLevels::Unsafe); std::istringstream iss("content"); storeFile(blob->getPath(true), iss); ASSERT_THROW(env2.commitSession(IsolationLevels::Unsafe), CommitException) << "Expected exception"; env2.rollbackSession(); } TEST_F(Concurrent, IsolationBlobExclusive) { auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); std::istringstream iss("content"); storeFile(file->getBlob("default")->getPath(true), iss); auto uuid = toString(file->uuid); env.commitSession(IsolationLevels::Full); auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.getFile(uuid); file1->addBlob("second", "text/plain"); auto file2 = env2.getFile(uuid); iss.seekg(std::ios_base::beg); storeFile(file2->getBlob("default")->getPath(true), iss); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::FileExclusive), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::BlobExclusive); env2.commitSession(IsolationLevels::Full); } TEST_F(Concurrent, IsolationFileExclusive) { auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.createFile(); file1->addBlob("default", "text/plain"); auto file2 = env2.createFile(); file2->addBlob("default", "text/plain"); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env1.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::AlmostFull), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::FileExclusive); env2.commitSession(IsolationLevels::Full); } TEST_F(Concurrent, IsolationAlmostFull) { auto& env1 = createBench()->env; auto& env2 = createBench()->env; env1.startSession(); env2.startSession(); auto file1 = env1.createFile(); file1->addBlob("default", "text/plain"); ASSERT_THROW(env1.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; ASSERT_THROW(env2.commitSession(IsolationLevels::Full), CommitException) << "Expected exception"; env1.commitSession(IsolationLevels::AlmostFull); env2.commitSession(IsolationLevels::Full); } TEST_F(Concurrent, IsolationFull) { // This test case is trivial (as already tested in single_session.cpp), // but is included here for completeness auto& env = createBench()->env; env.startSession(); auto file = env.createFile(); file->addBlob("default", "text/plain"); env.commitSession(IsolationLevels::Full); } }}
34.207101
107
0.749524
larsrh
d3a676ab524adbc844d2f332ab9f5ea0a3f57335
68,589
cpp
C++
tests/utils/numeric_utils_test.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
tests/utils/numeric_utils_test.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
tests/utils/numeric_utils_test.cpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, 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. /// /// Copyright holder is EMC Corporation /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "tests_shared.hpp" #include "utils/bit_utils.hpp" #include "utils/numeric_utils.hpp" #include <vector> #include <algorithm> namespace { template<typename T> iresearch::bstring encode(T value, size_t offset = 0) { typedef iresearch::numeric_utils::numeric_traits<T> traits_t; iresearch::bstring data; data.resize(traits_t::size()); traits_t::encode(traits_t::integral(value), &(data[0]), offset); return data; } } TEST(numeric_utils_test, encode32) { const irs::byte_type TYPE_MAGIC = 0; // 0 { const uint32_t value = 0; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 43 { const size_t shift = 43; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 1 byte { const uint32_t value = 0x7D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 1132 { const size_t shift = 1132; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 2 bytes { const uint32_t value = 0x3037; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0x30); expected.append(1, 0x37); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0x30); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // invalid shift = 54 { const size_t shift = 54; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 3 bytes { const uint32_t value = 0x44007D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]))); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0x44); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0x44); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0x44); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // invalid shift = 33 { const size_t shift = 33; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } // 4 bytes { const uint32_t value = 0x7FFFFEAF; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 8 { const size_t shift = 8; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); expected.append(1, 0xFF); expected.append(1, 0xFE); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 24 { const size_t shift = 24; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // invalid shift = 33 { const size_t shift = 33; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode32(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint32_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int32_t>::size()); actual.resize(irs::numeric_utils::encode32(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode32(actual.data())); } } } TEST(numeric_utils_test, i32_lexicographical_sort) { std::vector<int32_t> data = { -350, -761, -609, -343, 681, -915, -166, -727, 144, -464, 486, -527, 161, -616, -823, -283, -345, -988, 208, -550, 856, -235, 582, -357, 417, 565, -393, 658, 147, 266, 242, 990, -604, 686, 982, 287, 950, -566, 767, -25, 503, -214, 70, 351, 473, -531, -654, -795, 938, 634, -188, 437, 57, -808, -129, -793, 202, -671, -859, -808, 245, 71, -968, 533, -179, 771, -954, 839, -49, 776, -875, 761, -327, -947, 979, -129, -291, 835, 358, -796, -338, -168, -669, -181, -550, -368, 747, 321, -181, -243, -540, -974, -838, 266, -495, 77, 660, -911, -957, -418 }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); // sort values as a strings { irs::bstring lhsb, rhsb; lhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); rhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (int32_t lhs, int32_t rhs) { lhsb.resize(iresearch::numeric_utils::encode32(lhs, &(lhsb[0]))); rhsb.resize(iresearch::numeric_utils::encode32(rhs, &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, float_lexicographical_sort) { std::vector<float_t> data = { 651986.24597f, 0.f, 789897.54621f, 334163.97801f, 503825.00775f, 145063.42199f, 860891.64170f, 70621.40595f, 652100.77900f, 197530.50436f, 515243.79748f, 430713.86816f, 920883.39861f, 33127.12690f, 669809.53751f, 742514.67643f, 541261.20072f, 424864.54813f, -84206.11661f, 37734.94341f, 399434.40440f, 583076.69427f, 921670.79766f, 370855.67353f, 539653.46945f, 888530.51518f, 955485.29949f, 728637.62999f, 604241.69549f, 199548.03446f, 987841.11798f, 187679.83587f, 860653.96767f, 704908.54946f, 270492.27179f, 981837.20772f, 89069.58880f, 976493.74761f, 177264.69379f, 580679.70200f, 269226.75505f, -7565.20355f, 580326.52632f, 820924.88651f, 999188.46427f, 208690.17207f, -65341.05952f, 415085.10025f, 249832.76681f, 761120.91782f, 221577.50140f, 883788.22463f, 487001.46581f, 231184.95100f, 313349.23483f, 58377.55974f, -24389.93795f, -85784.41119f, 230454.79233f, 40357.24455f, 775261.89865f, 802026.18120f, 748156.61351f, 565290.75590f, std::numeric_limits<float_t>::max(), 59125.49834f, 81581.64508f, -77242.32905f, 358950.49929f, 927754.07961f, 816446.24556f, 491053.68666f, 25909.79241f, 319106.64948f, std::numeric_limits<float_t>::min(), 798202.10184f, 318100.23017f, 183748.53501f, 891857.49166f, 638973.58074f, -53220.76564f, 23770.88234f, 223292.54636f, 59219.16834f, -1*std::numeric_limits<float_t>::infinity(), 556780.22390f, 625542.69411f, 943141.14072f, 299615.24480f, -49206.87529f, 292463.48822f, 786073.54881f, 27863.51332f, 473998.82589f, std::numeric_limits<float_t>::infinity(), 391216.34299f, 945374.63819f, 958320.88699f, 826033.74749f, 439145.14628f, 132385.51939f, 420388.33719f, 878636.29916f, 164969.74829f, 763102.14175f }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); std::sort(data.begin(), data.end()); // sort values as a strings { iresearch::bstring lhsb, rhsb; lhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); rhsb.resize(iresearch::numeric_utils::numeric_traits<int32_t>::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (float_t lhs, float_t rhs) { lhsb.resize(iresearch::numeric_utils::encode32(iresearch::numeric_utils::ftoi32(lhs), &(lhsb[0]))); rhsb.resize(iresearch::numeric_utils::encode32(iresearch::numeric_utils::ftoi32(rhs), &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, i64_lexicographical_sort) { std::vector<int64_t> data = { 75916234875, 52789213189, -351958887,95319743962, 79430098384, -93388245157, -49766133093, -14684623510, 81939936346, -88743499960, 20121855753, 83100432533, 51334979222, -73041310283, 61053586489, -27283259777, 66875916011, 64196723717, -63245085177, 49356623092, 4831901977, -94997824110, 558743111, 86064753122, -20505155546, 97553550685, 4184837506, -87917522122, -18266405289, 72779316345, 78725060901, -37948627940, -48856097607, 53160149963, -71272992316, -20828322249, 9522187027, -84578726831, 12441908766, 17798626822, -20379673205, -18890364139, 2691328827, -26486115883, 68027701743, 91157000176, 67489735701, -65819861863, 32420845326, 35357628656, -352937797, 3730286026, -48575671214, -57132400233, -57931671060, 79274974121, 9443962937, 51250545543, -53668161995, 63749872762, -10243160821, 69057817471, -32302480156, 55309984087, 26821242343, -47858619974, -43658945958, 13882630371, -54803336237, -42915650818, 30843782668, 81271509976, -62481641673, 58881660576, -18924990310, -67739865224, 62103715004, 86468068247, 97226357283, 79135831106, 32583755567, -51070913529, 84103329088, 55669172603, -80203080540, 76458883725, 89479791488, 71316492715, 77391498575, -40379985779, 40912438277, -74300496300, 87642158905, -64141659318, 49343408029, 53715985320, -79770447588, -74497633642, -61100778565, 20399307283 }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); // sort values as a strings { irs::bstring lhsb, rhsb; lhsb.resize(iresearch::numeric_utils::numeric_traits<int64_t>::size()); rhsb.resize(iresearch::numeric_utils::numeric_traits<int64_t>::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (int64_t lhs, int64_t rhs) { lhsb.resize(iresearch::numeric_utils::encode64(lhs, &(lhsb[0]))); rhsb.resize(iresearch::numeric_utils::encode64(rhs, &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, double_lexicographical_sort) { std::vector<double_t> data = { 0., 317957780006.32197596427145, 533992104946.63198708865418, -444498986678.43033870609027, 993156979788.63351968519088, 609230681140.54886677327979, 171177411065.98517441469486, -940116899991.46242625613810, 72774954639.73607618349422, -217026020966.94801979090461, -925157835672.21734471256721, 767751105952.89203615528161, 598978092707.21771414727797, -655278929348.69924995521980, -557099107446.66080337327942, -727673216596.09359530550129, 155929101237.99420019518314, -798911902959.88316785538717, 584117345318.25284721248450, -181281342721.20955526885090, -884976572303.55617231854991, -737155568663.56896639967755, -259257466187.35485998324811, 724842924496.55147478755167, 992409605529.35004491794391, -427341238328.88027575280530, 957748176510.32850915115723, -927854884382.26975704648986, -295874505907.23869665862932, -298929529869.43047953277383, 107495609255.27271314303983, 102434974677.13196514040789, -526793124865.17854261453196, -986666726873.56673501132370, -105069548406.20492976447797, -810126205817.85505908441500, 502725540428.76024750469264, -86871683172.35618977451520, 734071867416.64626980975562, -777490837395.88541788788765, -488500977628.16631124735172, 463763000193.87295478669598, -226003491890.61834099265670, 761498090700.01267394982869, 798989307041.74065359017842, -905445250638.50230101426239, -602929648758.34512000826426, -196635976059.65844172037134, -68902930742.55014338649350, 863617225486.60693014348248, 297576823876.04230264017466, 997953300363.36244100861365, 30857690158.69949486046075, -443412200288.57337324347970, 219426915617.39282478456983, 104728098541.83723150838038, -475445743405.93337239973870, 772038568636.42044767570703, -340372866643.76634482469705, -84314886985.49330559814968, -413809077541.25496258086290, 125388728047.43644224826081, 999016783199.74652640509723, -689317751531.17149673922523, 438800651318.76647999452729, -458810955965.33778867001542, -86436450987.32619126668488, -331705479571.45864124012116, -183427201203.73517330909854, -519768203385.06633573447649, 517973236515.17426432816976, 502506143181.82046673345401, -789732965542.81048734803241, -919346901550.58489253306058, 10824521542.91072932207525, -745318840139.22831050084360, -32521082569.15634617635810, 705549213898.15826616164216, 980234109787.37944261514556, 941403018283.37973835104133, 361903082282.23728122293823, 559399746153.22414140832803, 64887538116.83856794463404, 531879426693.48764544980956, -767469304505.48851141030365, 454718537374.73419745207494, 26781561331.25608848932017, -802390430961.91735517322894, -323002730180.97632107370362, -849713418562.76309982070844, -439276315942.06966270789023, -222411432872.71793599832707, 125254418293.59830277673821, 62915394577.62399435864016, -250289681949.78762508825754, -818758496930.24461014673328, -168764751948.77234843968057, -418952390280.99569970788234, 6143003239.36296777770061, -683268292659.55290415303451, 448388662863.70375327007088, std::numeric_limits<double_t>::infinity(), -1*std::numeric_limits<double_t>::infinity(), std::numeric_limits<double_t>::max(), std::numeric_limits<double_t>::min() }; ASSERT_FALSE(std::is_sorted(data.begin(), data.end())); std::sort(data.begin(), data.end()); // sort values as a strings { typedef iresearch::numeric_utils::numeric_traits<double_t> traits_t; irs::bstring lhsb, rhsb; lhsb.resize(traits_t::size()); rhsb.resize(traits_t::size()); std::sort( data.begin(), data.end(), [&lhsb, &rhsb] (double_t lhs, double_t rhs) { lhsb.resize(traits_t::encode(traits_t::integral(lhs), &(lhsb[0]))); rhsb.resize(traits_t::encode(traits_t::integral(rhs), &(rhsb[0]))); return lhsb < rhsb; }); } ASSERT_TRUE(std::is_sorted(data.begin(), data.end())); } TEST(numeric_utils_test, encode64) { const irs::byte_type TYPE_MAGIC = 0x60; // 0 { const uint64_t value = 0; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 1 byte { const uint64_t value = 0x7D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 2 bytes { const uint64_t value = 0x3037; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x30); expected.append(1, 0x37); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 3 bytes { const uint64_t value = 0x44007D; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x44); expected.append(1, 0); expected.append(1, 0x7D); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x44); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 4 bytes { const uint64_t value = 0x7FFFFEAF; // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 5 bytes { const uint64_t value = uint64_t(0xCE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 6 bytes { const uint64_t value = uint64_t(0xFACE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); expected.append(1, 0xFA); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 7 bytes { const uint64_t value = uint64_t(0xEFFACE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); expected.append(1, 0xEF); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0x80); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } // 8 bytes { const uint64_t value = uint64_t(0x2AEFFACE7FFFFEAF); // shift = 0 { const size_t shift = 0; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); expected.append(1, 0xFE); expected.append(1, 0xAF); ASSERT_EQ(actual, expected); } // shift = 16 { const size_t shift = 16; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); expected.append(1, 0x7F); expected.append(1, 0xFF); ASSERT_EQ(actual, expected); } // shift = 32 { const size_t shift = 32; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); expected.append(1, 0xFA); expected.append(1, 0xCE); ASSERT_EQ(actual, expected); } // shift = 48 { const size_t shift = 48; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); expected.append(1, 0xEF); ASSERT_EQ(actual, expected); } // shift = 56 { const size_t shift = 56; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); expected.append(1, 0xAA); ASSERT_EQ(actual, expected); } // shift = 64 { const size_t shift = 64; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); } // shift = 65 { const size_t shift = 65; irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); irs::bstring expected; expected.append(1, TYPE_MAGIC + static_cast<irs::byte_type>(shift)); ASSERT_EQ(actual, expected); ASSERT_EQ(0, irs::numeric_utils::decode64(actual.data())); } for (size_t shift = 0; shift < irs::bits_required<uint64_t>(); ++shift) { irs::bstring actual; actual.resize(irs::numeric_utils::numeric_traits<int64_t>::size()); actual.resize(irs::numeric_utils::encode64(value, &(actual[0]), shift)); ASSERT_EQ(((value >> shift) << shift), irs::numeric_utils::decode64(actual.data())); } } } TEST(numeric_utils_test, int_traits) { typedef irs::numeric_utils::numeric_traits<int32_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(5, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT32_C(0)); ASSERT_EQ( INT32_C(0), traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, uint_traits) { typedef irs::numeric_utils::numeric_traits<uint32_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(5, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT32_C(0)); ASSERT_EQ( INT32_C(0), traits_t::decode(encoded.c_str()) ); } { traits_t::integral_t value(0x12345678); if constexpr (irs::is_big_endian()) { ASSERT_EQ(value, traits_t::hton(value)); ASSERT_EQ(value, traits_t::ntoh(value)); } else { ASSERT_NE(value, traits_t::hton(value)); ASSERT_NE(value, traits_t::ntoh(value)); ASSERT_EQ(value, traits_t::hton(traits_t::ntoh(value))); ASSERT_EQ(value, traits_t::ntoh(traits_t::hton(value))); } } } TEST(numeric_utils_test, long_traits) { typedef irs::numeric_utils::numeric_traits<int64_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(9, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT64_C(0)); ASSERT_EQ( INT64_C(0), traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, ulong_traits) { typedef irs::numeric_utils::numeric_traits<uint64_t> traits_t; typedef traits_t::integral_t type; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ(9, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(INT64_C(0)); ASSERT_EQ( INT64_C(0), traits_t::decode(encoded.c_str()) ); } { traits_t::integral_t value(0x1234567890ABCDEF); if constexpr (irs::is_big_endian()) { ASSERT_EQ(value, traits_t::hton(value)); ASSERT_EQ(value, traits_t::ntoh(value)); } else { ASSERT_NE(value, traits_t::hton(value)); ASSERT_NE(value, traits_t::ntoh(value)); ASSERT_EQ(value, traits_t::hton(traits_t::ntoh(value))); ASSERT_EQ(value, traits_t::ntoh(traits_t::hton(value))); } } } TEST(numeric_utils_test, float_t_traits) { typedef float_t type; typedef irs::numeric_utils::numeric_traits<type> traits_t; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::inf().c_str()) ); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::ninf().c_str()) ); ASSERT_EQ(5, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::infinity()); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(-1*std::numeric_limits<type>::infinity()); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode((float_t)0.f); ASSERT_EQ( 0.f, traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, double_t_traits) { typedef double_t type; typedef irs::numeric_utils::numeric_traits<type> traits_t; ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(traits_t::min().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(traits_t::max().c_str()) ); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::inf().c_str()) ); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(traits_t::ninf().c_str()) ); ASSERT_EQ(9, traits_t::size()); { auto encoded = encode(std::numeric_limits<type>::min()); ASSERT_EQ( std::numeric_limits<type>::min(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::max()); ASSERT_EQ( std::numeric_limits<type>::max(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(std::numeric_limits<type>::infinity()); ASSERT_EQ( std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode(-1*std::numeric_limits<type>::infinity()); ASSERT_EQ( -1*std::numeric_limits<type>::infinity(), traits_t::decode(encoded.c_str()) ); } { auto encoded = encode((double_t)0.); ASSERT_EQ( 0., traits_t::decode(encoded.c_str()) ); } } TEST(numeric_utils_test, float_traits) { typedef float type; typedef irs::numeric_utils::numeric_traits<type> traits_t; } TEST(numeric_utils_test, double_traits) { typedef double type; typedef irs::numeric_utils::numeric_traits<type> traits_t; } TEST(numeric_utils_test, long_double_traits) { typedef long double type; typedef irs::numeric_utils::numeric_traits<type> traits_t; }
35.030133
183
0.641488
geenen124
d3b3c82fc2ff57d1185046fa929d554d98864cae
8,855
cpp
C++
gameEngine/gameEngine/SceneDirector.cpp
ComputerScienceTrolls/simpleGameGL
81e25f690f5825bf633685e9d7d2771a3d61f4c7
[ "MIT" ]
null
null
null
gameEngine/gameEngine/SceneDirector.cpp
ComputerScienceTrolls/simpleGameGL
81e25f690f5825bf633685e9d7d2771a3d61f4c7
[ "MIT" ]
5
2017-10-06T21:39:20.000Z
2018-01-29T13:23:19.000Z
gameEngine/gameEngine/SceneDirector.cpp
ComputerScienceTrolls/simpleGameGL
81e25f690f5825bf633685e9d7d2771a3d61f4c7
[ "MIT" ]
null
null
null
#include "SceneDirector.h" #include <iostream> std::auto_ptr<SceneDirector> SceneDirector::instance; //default width and height int WIDTH = 800; int HEIGHT = 600; double lastTime = glfwGetTime(); int nbFrames = 0; //void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); SceneDirector::SceneDirector() { glfwInit(); //initiate openAl component alutInit(NULL, 0); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow(WIDTH, HEIGHT, "HelloWorld", nullptr, nullptr); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; glewInit(); glGetError(); // Call it once to catch glewInit() bug, all other errors are now from our application. ResourceManager::LoadShader("shaders/sprite.vs", "shaders/sprite.frag", nullptr, "sprite"); Shader temp1 = ResourceManager::GetShader("sprite"); Renderer = new SpriteRenderer(temp1); //Renderer = temp; glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(800), static_cast<GLfloat>(600), 0.0f, -1.0f, 1.0f); ResourceManager::GetShader("sprite").Use().SetInteger("sprite", 0); ResourceManager::GetShader("sprite").SetMatrix4("projection", projection); } /* void SceneDirector::Update(float delta) { currentScene->Update(delta); //check sensors for (int i = 0; i < sensors.size(); i++) { sensors.at(i)->sense(); } // Measure speed double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0) { // If last prinf() was more than 1 sec ago // printf and reset timer printf("%f ms/frame\n", 1000.0 / double(nbFrames)); nbFrames = 0; lastTime += 1.0; } } */ void SceneDirector::checkSensors() { for (int i = 0; i < sensors.size(); i++) { sensors.at(i)->sense(); } } void SceneDirector::pauseScene(AbstractScene * s) { //find scene given bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s == scenes.at(i)) { found = true; scenes[i]->setActive(false); } } if (!found) { std::cout << "pauseSence: no scene found"; } } void SceneDirector::unpauseScene(AbstractScene * s) { //find scene given bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s == scenes.at(i)) { found = true; scenes[i]->setActive(true); } } if (!found) { std::cout << "pauseSence: no scene found"; } } SceneDirector* SceneDirector::getInstance() { if (instance.get() == nullptr) { instance.reset(new SceneDirector()); } return instance.get(); } void SceneDirector::addScene(AbstractScene *s) { scenes.push_back(s); //if scenes is empy, make new scene the currentScene if (scenes.size() < 2) { currentScene = s; currentScene->setWindow(window); currentScene->setRenderer(Renderer); } } AbstractScene* SceneDirector::getScene(std::string) { return nullptr; } AbstractScene* SceneDirector::getScene(int i) { return scenes.at(i); } void SceneDirector::setSceneBackground(std::string n) { currentScene->setBackground(n.c_str()); } void SceneDirector::removeScene(std::string n) { //get index of collider int index = -1; for (int i = 0; i < this->scenes.size(); i++) { if (this->scenes[i]->getName() == n) { index = i; } } //if found remove it from the vector if (index != -1) { std::cout << "deleting " << scenes.at(index)->getName(); this->scenes.erase(scenes.begin() + index); } else { std::cout << "scene with the name of " << n << " not found"; } } void SceneDirector::removeScene(int index) { if (index > -1 && index <= sensors.size() - 1) { this->sensors.erase(sensors.begin() + index); } else { std::cout << "index is not in range"; } } //sets the given scene, if it's not already in scene list, add it void SceneDirector::setScene(AbstractScene *s) { currentScene->Stop(); currentScene = s; currentScene->setWindow(window); currentScene->setRenderer(Renderer); currentScene->Init(); currentScene->reset(); currentScene->Start(); bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s = scenes.at(i)) { found = true; } } if (!found) { scenes.push_back(s); } } //sets to scene, but only pauses old scene, if scene doens't exist in scenes, add it. void SceneDirector::setScenePause(AbstractScene * s) { //if scene is already the currentScene, do nothing if (currentScene != s) { currentScene->setActive(false); currentScene = s; currentScene->setWindow(window); currentScene->setRenderer(Renderer); currentScene->Start(); bool found = false; for (int i = 0; i < scenes.size(); i++) { if (s = scenes.at(i)) { found = true; } } if (!found) { scenes.push_back(s); } } } void SceneDirector::nextScene() { int currentIndex = -1; for (int i = 0; i < scenes.size(); i++) { if (currentScene == scenes.at(i)) { currentIndex = i; } } //make sure currentIndex and currentIndex+1 is in range if (currentIndex != -1 && (currentIndex) < scenes.size()-1) { //stop currentScene currentScene->Stop(); //assign new currentScene currentScene = scenes.at(currentIndex + 1); //init new currentScene currentScene->setWindow(window); currentScene->setRenderer(Renderer); //currentScene->Init(); currentScene->reset(); currentScene->Start(); } else { std::cout << "Next: there is no Scene to jump to"; std::cout << "\ncurrentIndex: " << currentIndex; std::cout << "\nsize: " << scenes.size(); } } void SceneDirector::previousScene() { int currentIndex = -1; for (int i = 0; i < scenes.size(); i++) { if (currentScene == scenes.at(i)) { currentIndex = i; } } //make sure currentIndex and currentIndex-1 is in range if (currentIndex != -1 && currentIndex - 1 > -1) { //stop currentScene currentScene->Stop(); //assign new currentScene currentScene = scenes.at(currentIndex - 1); //init new currentScene currentScene->setWindow(window); currentScene->setRenderer(Renderer); currentScene->Init(); currentScene->reset(); currentScene->Start(); } else { std::cout << "Previous: there is no Scene to jump to"; std::cout << "\ncurrentIndex: " << currentIndex; std::cout << "\nsize: " << scenes.size(); } } void SceneDirector::Start() { // OpenGL configuration glViewport(0, 0, 800, 600); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // DeltaTime variables GLfloat deltaTime = 0.0f; GLfloat lastFrame = 0.0f; //tell currentScene to set to active currentScene->Start(); while (!glfwWindowShouldClose(window)) { // Calculate delta time double currentFrame = glfwGetTime(); deltaTime = float(currentFrame) - lastFrame; lastFrame = float(currentFrame); glfwPollEvents(); // Update Game state this->Update(deltaTime); // Render glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); this->Render(); glfwSwapBuffers(window); } } void SceneDirector::Render() { currentScene->Render(); } void SceneDirector::addSensor(AbstractSensor * s) { sensors.push_back(s); } void SceneDirector::addObserver(AbstractObserver * o) { observers.push_back(o); } void SceneDirector::removeSensor(std::string name) { int index = -1; for (int i = 0; i < this->sensors.size(); i++) { if (this->sensors[i]->getName() == name) { index = i; } } //if found remove it from the vector if (index != -1) { std::cout << "deleting " << this->sensors.at(index)->getName(); this->sensors.erase(sensors.begin() + index); } else { std::cout << "Sensor with the name of " << name << " not found"; } } void SceneDirector::removeSensor(int index) { if (index > -1 && index <= sensors.size() - 1) { sensors.erase(sensors.begin() + index); } else { std::cout << "index is not in range"; } } void SceneDirector::removeObserver(std::string name) { //get index of collider int index = -1; for (int i = 0; i < observers.size(); i++) { if (observers[i]->getName() == name) { index = i; } } //if found remove it from the vector if (index != -1) { std::cout << "deleting " << observers.at(index)->getName(); observers.erase(observers.begin() + index); } else { std::cout << "observer with the name of " << name << " not found"; } } void SceneDirector::removeObserver(int index) { if (index > -1 && index <= sensors.size() - 1) { observers.erase(observers.begin() + index); } else { std::cout << "index is not in range"; } } size_t SceneDirector::getNumberOfScenes() { return scenes.size(); } AbstractScene* SceneDirector::getCurrentScene() { return this->currentScene; } SceneDirector::~SceneDirector() { glfwTerminate(); ResourceManager::Clear(); //delete items that are on heap that is used by openal alutExit(); }
19.809843
114
0.658724
ComputerScienceTrolls
d3b7e84eb305cec0b6ae45cfd9546f1a1dc425b1
3,515
hpp
C++
src/Base/Policies/DataStreamBuffer.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2017-02-17T13:01:13.000Z
2017-02-17T13:01:13.000Z
src/Base/Policies/DataStreamBuffer.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
null
null
null
src/Base/Policies/DataStreamBuffer.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2018-07-23T00:05:58.000Z
2018-07-23T00:05:58.000Z
/*! * \file DataStreamBuffer.hpp * \brief DataStream buffering policies * * \author mstefanc * \date 06-07-2010 */ #ifndef DATASTREAMBUFFER_HPP_ #define DATASTREAMBUFFER_HPP_ #include <queue> #include <stdexcept> namespace Base { /*! * Buffering policies for DataStream. * * Every buffering policy should have form: * \code * template <class T> * class PolicyName { * protected: * // store data in some internal container * void store(const T & t); * * // retrieve data from internal container * T retrieve(); * }; * \endcode * * There are some predefined simple policies (like FIFO queue, keeping only newest or oldest data). */ namespace DataStreamBuffer { /*! * \brief Buffering policy - FIFO queue. * * All items are stored in queue, so that none of them is missed during processing. */ template <class T> class Queue { public: bool empty() const { return buffer.empty(); } protected: /*! * Push data on the end of queue * \param t data to be stored */ void store(const T & t) { buffer.push(t); } /*! * Get first element from queue * \return First element from queue * \throw exception queue is empty */ T retrieve() { if (buffer.size() > 0) { T t = buffer.front(); buffer.pop(); return t; } else { /// \todo Throw correct exception throw std::runtime_error("Queue: Empty buffer!"); // throwing disabled until scopeLock will be implemented in DataStream } } private: //// FIFO queue std::queue<T> buffer; }; /*! * \brief Buffering policy - keep only the newest data. * * Only the newest data is remembered, when data comes before reading previous one, * older item is lost. */ template <class T> class Newest { public: /*! * Clears internal flags state */ Newest() { fresh = false; } bool empty() const { return !fresh; } protected: /*! * Remember new data. * \param t data to be remembered */ void store(const T & t) { item = t; fresh = true; } /*! * Return remembered data (if it's fresh). * * If there is no new data since last read, exception is thrown. * * \return remembered data * \throw exception there is no fresh data since last read */ T retrieve() { if (fresh) { fresh = false; return item; } else { /// \todo Throw correct exception throw std::runtime_error("Newest: Fresh data not available!"); } } private: /// newest data T item; /// data freshness flag bool fresh; }; /*! * \brief Buffering policy - keep only the oldest data * * Only the oldest data is remembered, when data comes before reading previous one, * newer item is lost. */ template <class T> class Oldest { public: /*! * Clears internal flags state */ Oldest() { fresh = false; } protected: /*! * Remember new data * * If there is older, unread data then new one is lost. * * \param t data to be remembered */ void store(const T & t) { if (!fresh) { item = t; fresh = true; } } /*! * Return remembered data (if it's fresh). * * If there is no data since last read, exception is thrown. * * \return remembered data * \throw exception there is no fresh data since last read */ T retrieve() { if (fresh) { fresh = false; return item; } else { /// \todo Throw correct exception throw std::runtime_error("Oldest: No data available!"); } } private: /// oldest data T item; /// data freshness flag bool fresh; }; } //: DataStreamBuffer } //: Base #endif /* DATASTREAMBUFFER_HPP_ */
17.84264
99
0.64239
mlaszko
d3b86882d6d10f4438be7e15f1ab5bc01bf2d4da
4,636
cpp
C++
Source/HardTime2/Private/Missions.cpp
ThomasWilliamWallace/PrisonGame
243ffd5d587086775c094d3dc72ff29987aa9bce
[ "MIT" ]
1
2018-12-30T15:35:50.000Z
2018-12-30T15:35:50.000Z
Source/HardTime2/Private/Missions.cpp
ThomasWilliamWallace/PrisonGame
243ffd5d587086775c094d3dc72ff29987aa9bce
[ "MIT" ]
null
null
null
Source/HardTime2/Private/Missions.cpp
ThomasWilliamWallace/PrisonGame
243ffd5d587086775c094d3dc72ff29987aa9bce
[ "MIT" ]
null
null
null
#include "Missions.h" #include "PlayerData.h" #include "SimWorld.h" #include "Constants.h" #include "ActorItem.h" MissionClass::MissionClass(RandomMission r, UPlayerData* playerPtr): MissionClass(playerPtr) {} MissionClass::MissionClass(UPlayerData* owner): m_mission(GetRandomMission()), m_owner(owner) { m_mission = EMissions::bringItemToRoom; m_itemType = EItemType::ball; m_locationClass = LocationClass(ELocations::gym); return; assert(m_owner != nullptr); switch (m_mission) { case EMissions::noMission: return; case EMissions::increaseAgility: m_objective = owner->pStats->getAgility(); break; case EMissions::increaseStrength: m_objective = owner->pStats->getStrength(); break; case EMissions::increaseIntelligence: m_objective = owner->pStats->getIntelligence(); break; case EMissions::bringItemToRoom: m_itemType = GetRandomItemType(); m_locationClass = GetRandomLocation(); return; default: ThrowException("Selected an invalid mission type."); } m_objective += 3; //todo ensure that the mission is achievable, ie 100 or below } MissionClass::MissionClass(EMissions mission, UPlayerData* owner, double objective): m_mission(mission), m_owner(owner), m_objective(objective) { assert(m_owner!=nullptr); } MissionClass::MissionClass(EMissions mission, UPlayerData* owner, EItemType itemType, ELocations location): m_mission(mission), m_owner(owner), m_itemType(itemType), m_locationClass(location) { assert(m_owner!=nullptr); } MissionClass::MissionClass(const MissionClass& missionClass): m_mission(missionClass.m_mission), m_owner(missionClass.m_owner), m_objective(missionClass.m_objective), m_itemType(missionClass.m_itemType), m_locationClass(missionClass.m_locationClass) { assert(m_owner!=nullptr); } bool MissionClass::IsMissionComplete(USimWorld &world) { switch (m_mission) { case EMissions::increaseAgility: return (m_objective <= m_owner->pStats->getAgility()); case EMissions::increaseStrength: return (m_objective <= m_owner->pStats->getStrength()); case EMissions::increaseIntelligence: return (m_objective <= m_owner->pStats->getIntelligence()); case EMissions::bringItemToRoom: for (auto &item : world.items) { if ((item->m_itemType == m_itemType) && (item->m_locationClass.location == m_locationClass.location) && (item->m_carryingPlayer == nullptr)) { return true; } } return false; case EMissions::noMission: return false; } return false; } std::string MissionClass::MissionNarrative() { switch (m_mission) { case EMissions::noMission: return "No Mission\n"; case EMissions::increaseAgility: return "Mission: " + m_owner->CharacterName() + " must " + MissionName() + " to " + FormatDouble(m_objective) + ". (current=" + FormatDouble(m_owner->pStats->getAgility()) + ")"; case EMissions::increaseStrength: return "Mission: " + m_owner->CharacterName() + " must " + MissionName() + " to " + FormatDouble(m_objective) + ". (current=" + FormatDouble(m_owner->pStats->getStrength()) + ")"; case EMissions::increaseIntelligence: return "Mission: " + m_owner->CharacterName() + " must " + MissionName() + " to " + FormatDouble(m_objective) + ". (current=" + FormatDouble(m_owner->pStats->getIntelligence()) + ")"; case EMissions::bringItemToRoom: return "Mission: " + m_owner->CharacterName() + " must bring a " + ItemTypeToString(m_itemType) + " to the " + m_locationClass.ToString() + "."; } ThrowException("ERROR: MISSION TYPE NOT RECOGNISED"); } std::string MissionClass::MissionName() { switch(m_mission) { case (EMissions::increaseAgility): return "increase agility"; case (EMissions::increaseStrength): return "increase strength"; case (EMissions::increaseIntelligence): return "increase intelligence"; case (EMissions::bringItemToRoom): return "bring item to room"; case (EMissions::noMission): return "no mission"; } ThrowException("UnrecognisedMission"); } EMissions GetRandomMission() { int random = rand() % 100; if (random<25) return EMissions::increaseStrength; else if (random<50) return EMissions::increaseAgility; else if (random<75) return EMissions::increaseIntelligence; else return EMissions::bringItemToRoom; }
31.972414
195
0.668464
ThomasWilliamWallace
d3c0eaa6d16dbbf92473213172a880fafb0628d8
742
hh
C++
restore_ios.hh
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
restore_ios.hh
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
restore_ios.hh
psaksa/git-junction
55cb940704d8d8dcf773e8917809a972c078976f
[ "MIT" ]
null
null
null
/* git-junction * Copyright (c) 2016-2017 by Pauli Saksa * * Licensed under The MIT License, see file LICENSE.txt in this source tree. */ #ifndef GIT_JUNCTION_RESTORE_IOS_HEADER #define GIT_JUNCTION_RESTORE_IOS_HEADER #include <ios> class restore_ios { std::ios &io; std::ios::fmtflags flags; std::ios::char_type fill; std::streamsize width; std::streamsize precision; public: restore_ios(std::ios &_io) : io{_io}, flags{io.flags()}, fill{io.fill()}, width{io.width()}, precision{io.precision()} { } ~restore_ios(void) { io.flags(flags); io.fill(fill); io.width(width); io.precision(precision); } }; #endif
18.55
76
0.59973
psaksa
d3c2cdd1cd9682a3a579a1692e817e5631ea6c7f
642
hpp
C++
lib/hargui/include/part.hpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
2
2020-09-11T18:11:10.000Z
2020-10-20T17:25:38.000Z
lib/hargui/include/part.hpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
null
null
null
lib/hargui/include/part.hpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
null
null
null
// // Created by Johannes on 17.07.2020. // #ifndef HAR_GUI_PART_HPP #define HAR_GUI_PART_HPP #include <gtkmm/box.h> #include <gtkmm/button.h> #include <gtkmm/image.h> #include <gtkmm/label.h> namespace har::gui_ { class part : public Gtk::Button { private: Gtk::Box _box; Gtk::Image _image; Gtk::Label _label; Cairo::RefPtr<Cairo::Surface> _surface; public: part(); void set_image(Glib::RefPtr<Gdk::Pixbuf> & pixbuf); void set_label(const std::string & label); ~part() noexcept override; }; } #endif //HAR_GUI_PART_HPP
18.882353
60
0.590343
Ocead
d3ca16f46de4c5008ef55d0175fe5df4c64b834a
699
hpp
C++
CPPMetal/Headers/CPPMetal.hpp
chromy/cppmetal
7acebf0519f119745e25a2b9eaac81889fb3a774
[ "MIT" ]
null
null
null
CPPMetal/Headers/CPPMetal.hpp
chromy/cppmetal
7acebf0519f119745e25a2b9eaac81889fb3a774
[ "MIT" ]
null
null
null
CPPMetal/Headers/CPPMetal.hpp
chromy/cppmetal
7acebf0519f119745e25a2b9eaac81889fb3a774
[ "MIT" ]
null
null
null
/* See LICENSE folder for this sample’s licensing information. Abstract: Header for C++ Metal wrapper */ #ifndef CPPMetal_hpp #define CPPMetal_hpp #include "CPPMetalBuffer.hpp" #include "CPPMetalCommandBuffer.hpp" #include "CPPMetalCommandQueue.hpp" #include "CPPMetalDevice.hpp" #include "CPPMetalDepthStencil.hpp" #include "CPPMetalDrawable.hpp" #include "CPPMetalLibrary.hpp" #include "CPPMetalPixelFormat.hpp" #include "CPPMetalRenderPass.hpp" #include "CPPMetalRenderCommandEncoder.hpp" #include "CPPMetalRenderPipeline.hpp" #include "CPPMetalTexture.hpp" #include "CPPMetalVertexDescriptor.hpp" #include "CPPMetalKitView.hpp" #include "CPPMetalKitTextureLoader.hpp" #endif // CPPMetal_hpp
24.964286
59
0.812589
chromy
d3ce4e217b620855f1d8e47c48be4f6c8dc802bc
355
cpp
C++
ex204042016.cpp
jcvasconcelos/praticando-exercicios-simples-git-c
24e7328ff6c6cb452acf2fad1e7a1789e2daaf42
[ "MIT" ]
null
null
null
ex204042016.cpp
jcvasconcelos/praticando-exercicios-simples-git-c
24e7328ff6c6cb452acf2fad1e7a1789e2daaf42
[ "MIT" ]
null
null
null
ex204042016.cpp
jcvasconcelos/praticando-exercicios-simples-git-c
24e7328ff6c6cb452acf2fad1e7a1789e2daaf42
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> int main() { int soma=10; float money=2.21; char letra='A'; double valor=2.01E6; printf("Valor da soma = %d\n", soma); //Mosta na tela o conteudo da variavel printf("Valor de Money = %f\n", money); printf("Valor de Letra = %c\n", letra); printf("Valor de valor = %e\n", valor); system("pause"); return 0; }
20.882353
77
0.642254
jcvasconcelos
d3d20adae2446f8d8b45f2833ac954436a55d9ea
11,970
cc
C++
tests/ticker.cc
hedzr/hicc
c2a33afec2ff1f79c42ed9f888ad091710e7ae60
[ "MIT" ]
null
null
null
tests/ticker.cc
hedzr/hicc
c2a33afec2ff1f79c42ed9f888ad091710e7ae60
[ "MIT" ]
null
null
null
tests/ticker.cc
hedzr/hicc
c2a33afec2ff1f79c42ed9f888ad091710e7ae60
[ "MIT" ]
null
null
null
// // Created by Hedzr Yeh on 2021/7/13. // // #define HICC_TEST_THREAD_POOL_DBGOUT 1 // #define HICC_ENABLE_THREAD_POOL_READY_SIGNAL 1 #include "hicc/hz-ticker.hh" #include "hicc/hz-x-class.hh" #include "hicc/hz-x-test.hh" #include <chrono> #include <iostream> #include <thread> hicc::debug::X x_global_var; namespace test { template<typename T> constexpr auto ZFN() { constexpr auto function = std::string_view{__FUNCTION_NAME__}; constexpr auto prefix = std::string_view{"auto ZFN() [T = "}; constexpr auto suffix = std::string_view{"]"}; constexpr auto start = function.find(prefix) + prefix.size(); constexpr auto end = function.rfind(suffix); std::string_view name = function.substr(start, (end - start)); return name.substr(0, (end - start)); // return function; } template<typename T> constexpr auto ZFS() { constexpr auto function = std::string_view{__FUNCTION_NAME__}; constexpr auto prefix = std::string_view{"auto ZFT() [T = "}; // constexpr auto suffix = std::string_view{"]"}; constexpr auto start = function.find(prefix) + prefix.size(); // constexpr auto end = function.rfind(suffix); return (unsigned long long) start; // function.substr(start, (end - start)); // return function; } template<typename T> constexpr auto ZFT() { constexpr auto function = std::string_view{__FUNCTION_NAME__}; // constexpr auto prefix = std::string_view{"auto ZFT() [T = "}; constexpr auto suffix = std::string_view{"]"}; // constexpr auto start = function.find(prefix) + prefix.size(); constexpr auto end = function.rfind(suffix); return (unsigned long long) end; // function.substr(start, (end - start)); // return function; } template<typename T> constexpr auto ZFZ() { // auto ZFZ() [T = std::__1::basic_string<char>] constexpr auto function = std::string_view{__FUNCTION_NAME__}; return function; } } // namespace test void test_type_name() { printf(">>Z '%s'\n", test::ZFZ<std::string>().data()); printf(">>Z '%s'\n", test::ZFN<std::string>().data()); printf(">>Z %llu, %llu\n", test::ZFS<std::string>(), test::ZFT<std::string>()); #ifndef _WIN32 printf(">>2 '%s'\n", hicc::debug::type_name_holder<std::string>::value.data()); printf(">>1 '%s'\n", hicc::debug::type_name_1<hicc::pool::conditional_wait_for_int>().data()); printf(">>> '%s'\n", hicc::debug::type_name<hicc::pool::conditional_wait_for_int>().data()); #endif auto fn = hicc::debug::type_name<std::string>(); std::string str{fn}; printf(">>> '%s'\n", str.c_str()); std::cout << hicc::debug::type_name<std::string>() << '\n'; std::cout << std::string(hicc::debug::type_name<std::string>()) << '\n'; printf(">>> %s\n", std::string(hicc::debug::type_name<std::string>()).c_str()); } void foo() { std::cout << x_global_var.c_str() << '\n'; std::this_thread::sleep_for(std::chrono::seconds(1)); } void test_thread_basics() { printf("> %s\n", __FUNCTION_NAME__); { std::thread t; std::cout << "- before starting, joinable: " << std::boolalpha << t.joinable() << '\n'; t = std::thread(foo); std::cout << "- after starting, joinable: " << t.joinable() << '\n'; t.join(); std::cout << "- after joining, joinable: " << t.joinable() << '\n'; } { unsigned int n = std::thread::hardware_concurrency(); std::cout << "- " << n << " concurrent _threads are supported.\n"; } } void foo1() { hicc_print("foo1 hit."); } void test_periodical_job() { namespace chr = hicc::chrono; namespace dtl = hicc::chrono::detail; using clock = std::chrono::system_clock; using time_point = clock::time_point; using namespace std::literals::chrono_literals; struct testcase { const char *desc; chr::anchors anchor; int offset; int ordinal; int times; time_point now, expected; }; #define CASE(desc, anchor, ofs) \ testcase { desc, anchor, ofs, 1, -1, time_point(), time_point() } #define CASE1(desc, anchor, ofs, ord) \ testcase { desc, anchor, ofs, ord, -1, time_point(), time_point() } #define CASE2(desc, anchor, ofs, ord, times) \ testcase { desc, anchor, ofs, ord, times, time_point(), time_point() } #define NOW_CASE(now_str, expected_str, desc, anchor, ofs) \ testcase { desc, anchor, ofs, 1, -1, hicc::chrono::parse_datetime(now_str), hicc::chrono::parse_datetime(expected_str) } for (auto const &t : { // Month NOW_CASE("2021-08-05", "2021-09-03", "day 3 every month", chr::anchors::Month, 3), NOW_CASE("2021-08-05", "2021-08-23", "day 23 every month", chr::anchors::Month, 23), NOW_CASE("2021-08-05", "2021-08-29", "day -3 every month", chr::anchors::Month, -3), NOW_CASE("2021-08-05", "2021-08-17", "day -15 every month", chr::anchors::Month, -15), NOW_CASE("2021-08-17", "2021-09-17", "day -15 every month", chr::anchors::Month, -15), // Year NOW_CASE("2021-08-05", "2022-08-03", "day 3 (this month) every year", chr::anchors::Year, 3), NOW_CASE("2021-08-05", "2021-08-23", "day 23 (this month) every year", chr::anchors::Year, 23), NOW_CASE("2021-08-05", "2021-12-29", "day -3 (this month) every year", chr::anchors::Year, -3), NOW_CASE("2021-08-05", "2021-12-17", "day -15 (this month) every year", chr::anchors::Year, -15), NOW_CASE("2021-08-18", "2021-12-17", "day -15 (this month) every year", chr::anchors::Year, -15), // FirstThirdOfMonth ... NOW_CASE("2021-08-05", "2021-09-03", "day 3 every first third of month", chr::anchors::FirstThirdOfMonth, 3), NOW_CASE("2021-08-05", "2021-08-08", "day 8 every first third of month", chr::anchors::FirstThirdOfMonth, 8), NOW_CASE("2021-08-05", "2021-08-08", "day -3 every first third of month", chr::anchors::FirstThirdOfMonth, -3), NOW_CASE("2021-08-05", "2021-09-04", "day -7 every first third of month", chr::anchors::FirstThirdOfMonth, -7), // MiddleThirdOfMonth ... NOW_CASE("2021-08-15", "2021-09-13", "day 3 every mid third of month", chr::anchors::MiddleThirdOfMonth, 3), NOW_CASE("2021-08-15", "2021-08-18", "day 8 every mid third of month", chr::anchors::MiddleThirdOfMonth, 8), NOW_CASE("2021-08-15", "2021-08-18", "day -3 every mid third of month", chr::anchors::MiddleThirdOfMonth, -3), NOW_CASE("2021-08-15", "2021-09-14", "day -7 every mid third of month", chr::anchors::MiddleThirdOfMonth, -7), // LastThirdOfMonth ... NOW_CASE("2021-08-25", "2021-09-23", "day 3 every last third of month", chr::anchors::LastThirdOfMonth, 3), NOW_CASE("2021-08-25", "2021-08-28", "day 8 every last third of month", chr::anchors::LastThirdOfMonth, 8), NOW_CASE("2021-08-25", "2021-08-29", "day -3 every last third of month", chr::anchors::LastThirdOfMonth, -3), NOW_CASE("2021-08-25", "2021-09-23", "day -9 every last third of month", chr::anchors::LastThirdOfMonth, -9), NOW_CASE("2021-08-22", "2021-08-23", "day -9 every last third of month", chr::anchors::LastThirdOfMonth, -9), }) { dtl::periodical_job pj(t.anchor, t.ordinal, t.offset, t.times, foo1); auto now = t.now; if (chr::duration_is_zero(now)) now = hicc::chrono::now(); else pj.last_pt = now; auto pt = pj.next_time_point(now); hicc_print("%40s: %s -> %s", t.desc, hicc::chrono::format_time_point_to_local(now).c_str(), hicc::chrono::format_time_point_to_local(pt).c_str()); auto tmp = t.expected; if (!chr::duration_is_zero(tmp)) { if (hicc::chrono::compare_date_part(pt, tmp) != 0) { hicc_print("%40s: ERROR: expecting %s but got %s", " ", hicc::chrono::format_time_point_to_local(tmp).c_str(), hicc::chrono::format_time_point_to_local(pt).c_str()); exit(-1); } } } #undef NOW_CASE } void test_timer() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count{1}; auto t = hicc::chrono::timer<>::get(); #if !HICC_ENABLE_THREAD_POOL_READY_SIGNAL std::this_thread::sleep_for(300ms); #endif hicc_print(" - start at: %s", hicc::chrono::format_time_point().c_str()); t->after(1us) .on([&count] { auto now = hicc::chrono::now(); hicc::pool::cw_setter cws(count); // std::time_t ct = std::time(0); // char *cc = ctime(&ct); printf(" - after [%02d]: %s\n", count.val(), hicc::chrono::format_time_point(now).c_str()); }) .build(); printf("count.wait()\n"); count.wait_for(); // t.clear(); printf("end of %s\n", __FUNCTION_NAME__); } void test_ticker() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count{16}; auto t = hicc::chrono::ticker<>::get(); #if !HICC_ENABLE_THREAD_POOL_READY_SIGNAL std::this_thread::sleep_for(300ms); #endif hicc_print(" - start at: %s", hicc::chrono::format_time_point().c_str()); t->every(1us) .on([&count]() { // auto now = hicc::chrono::now(); hicc::pool::cw_setter cws(count); printf(" - every [%02d]: %s\n", count.val(), hicc::chrono::format_time_point().c_str()); }) .build(); count.wait(); // t.clear(); printf("end of %s\n", __FUNCTION_NAME__); } void test_ticker_interval() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count2{4}; auto t = hicc::chrono::ticker<>::get([] { hicc_print(" - start at: %s", hicc::chrono::format_time_point().c_str()); }); t->interval(200ms) .on([&count2] { hicc::pool::cw_setter cws(count2); printf(" - interval [%02d]: %s\n", count2.val(), hicc::chrono::format_time_point().c_str()); }) .build(); count2.wait(); printf("end of %s\n", __FUNCTION_NAME__); } void test_alarmer() { using namespace std::literals::chrono_literals; hicc::debug::X x_local_var; hicc::pool::conditional_wait_for_int count2{4}; hicc::chrono::alarmer<>::super::get() ->every_month(3) .on([&count2] { auto now = hicc::chrono::now(); hicc::pool::cw_setter cws(count2); printf(" - alarmer [%02d]: %s\n", count2.val(), hicc::chrono::format_time_point(now).c_str()); }) .build(); printf("end of %s\n", __FUNCTION_NAME__); } int main() { // test_thread(); HICC_TEST_FOR(test_periodical_job); #if 1 HICC_TEST_FOR(test_type_name); HICC_TEST_FOR(test_thread_basics); HICC_TEST_FOR(test_timer); HICC_TEST_FOR(test_ticker); HICC_TEST_FOR(test_ticker_interval); HICC_TEST_FOR(test_alarmer); // using namespace std::literals::chrono_literals; // std::this_thread::sleep_for(200ns); // // { // std::time_t ct = std::time(0); // char *cc = ctime(&ct); // printf(". now: %s\n", cc); // } // { // auto t = std::time(nullptr); // auto tm = *std::localtime(&t); // std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << '\n'; // } #endif return 0; }
38.488746
181
0.578279
hedzr
d3d2a90e687b53ad00a51878e5c1bc5525580db2
2,913
hpp
C++
DefeatMonsterAICreateBaseProject/Skill.hpp
AinoMegumi/DefeatMonsterAICreateBaseProject
6666f55bec2ec42fc81a0a39fcd98d93af091676
[ "MIT" ]
null
null
null
DefeatMonsterAICreateBaseProject/Skill.hpp
AinoMegumi/DefeatMonsterAICreateBaseProject
6666f55bec2ec42fc81a0a39fcd98d93af091676
[ "MIT" ]
null
null
null
DefeatMonsterAICreateBaseProject/Skill.hpp
AinoMegumi/DefeatMonsterAICreateBaseProject
6666f55bec2ec42fc81a0a39fcd98d93af091676
[ "MIT" ]
null
null
null
#pragma once #include "Element.hpp" struct SkillA { SkillA() = default; SkillA(const std::string Name, const std::string Tag, int UseMP, const int BasePower, const std::string Description, const ElementInfo SkillElement, const std::string EffectGraphPath, const std::string EffectSoundPath, const bool Range, const bool ResurrectionEffect, const int SkillType, const int LessMP, const int AddBlendLevel) : Name(Name), Tag(Tag), UseMP(UseMP), BasePower(BasePower), Description(Description), SkillElement(SkillElement), EffectGraphPath(EffectGraphPath), EffectSoundPath(EffectSoundPath), Range(Range), ResurrectionEffect(ResurrectionEffect), SkillType(SkillType), LessMP(LessMP), AddBlendLevel(AddBlendLevel) {} std::string Name; // 名前 std::string Tag; // 識別タグ int UseMP; // 消費MP int BasePower; // 基本攻撃力 std::string Description; // 説明 ElementInfo SkillElement; // 属性(enum class値) std::string EffectGraphPath;// エフェクト画像のパス std::string EffectSoundPath;// エフェクトのサウンドパス bool Range; // 範囲効果フラグ bool ResurrectionEffect; // 復活効果の有無 int SkillType; // スキル種別(0:攻撃 1:回復 2:範囲回復) int LessMP; // 最低限必要なMP int AddBlendLevel; // 加算ブレンドのレベル bool operator == (const SkillA s) const { return this->Name == s.Name && this->UseMP == s.UseMP && this->BasePower == s.BasePower && this->Description == s.Description && this->SkillElement == s.SkillElement; } bool operator != (const SkillA s) const { return !this->operator==(s); } }; struct SkillW { SkillW() = default; SkillW(const std::wstring Name, const std::wstring Tag, int UseMP, const int BasePower, const std::wstring Description, const ElementInfo SkillElement, const std::wstring EffectGraphPath, const std::wstring EffectSoundPath, const bool Range, const bool ResurrectionEffect, const int SkillType, const int LessMP, const int AddBlendLevel) : Name(Name), Tag(Tag), UseMP(UseMP), BasePower(BasePower), Description(Description), SkillElement(SkillElement), EffectGraphPath(EffectGraphPath), EffectSoundPath(EffectSoundPath), Range(Range), ResurrectionEffect(ResurrectionEffect), SkillType(SkillType), LessMP(LessMP), AddBlendLevel(AddBlendLevel) {} std::wstring Name; // 名前 std::wstring Tag; // 識別タグ int UseMP; // 消費MP int BasePower; // 基本攻撃力 std::wstring Description; // 説明 ElementInfo SkillElement; // 属性(enum class値) std::wstring EffectGraphPath;// エフェクト画像のパス std::wstring EffectSoundPath;// エフェクトのサウンドパス bool Range; // 範囲効果フラグ bool ResurrectionEffect; // 復活効果の有無 int SkillType; // スキル種別(0:攻撃 1:回復 2:範囲回復) int LessMP; // 最低限必要なMP int AddBlendLevel; // 加算ブレンドのレベル bool operator == (const SkillW s) const { return this->Name == s.Name && this->UseMP == s.UseMP && this->BasePower == s.BasePower && this->Description == s.Description && this->SkillElement == s.SkillElement; } }; #if defined(UNICODE) typedef SkillW Skill; #else typedef SkillA Skill; #endif
50.224138
186
0.729832
AinoMegumi
d3d33631652acfc324a5eef9e1cb776de3d55a76
4,093
hpp
C++
include/xtomic/impl/hash_map_node_integral_key.hpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
include/xtomic/impl/hash_map_node_integral_key.hpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
include/xtomic/impl/hash_map_node_integral_key.hpp
mashavorob/lfds
3890472a8a9996ce35d9a28f185df4c2f219a2bd
[ "0BSD" ]
null
null
null
/* * hash_node_integral_key.hpp * * Created on: Feb 7, 2015 * Author: masha */ #ifndef INCLUDE_HASH_MAP_NODE_INTEGRAL_KEY_HPP_ #define INCLUDE_HASH_MAP_NODE_INTEGRAL_KEY_HPP_ #include <xtomic/quantum.hpp> #include "meta_utils.hpp" namespace xtomic { // Eclipse Luna does not recognize alignas keyword regardless of any settings // It seems Eclipse's developers do not admit the bug so the only way // to avoid annoying error marks these macro are used template<typename Key> struct align_by(2*sizeof(Key)) key_item { typedef key_item<Key> this_type; typedef typename get_int_by_size<sizeof(Key)>::type state_type; // states of the item (m_state field) enum { unused, // initial state pending,// key is valid, value is being constructed/deleted touched,// key is valid allocated,// key & value are valid }; // normal life cycle of an item in the hash table is: // // <after initialization> // 1. unused - initial state. Fields key and value have not been initialized // // <insert is in progress> // 2. pending - insert operation is in progress. // key is initialized // value is being constructed // // <first insert finished> // 3. allocated - ready to use, all fields are valid // // <first erase is in progress> // 4. pending - erase operation is in progress. // key is valid // value is being destroyed // // <first erase finished> // 5. touched - erase operation finished. // key is valid // value is destroyed // // <subsequent insert is in progress> // 6. pending - insert operation is in progress. // key is valid // value is being constructed // // <insert finished> // 7. allocated - exactly same as 3. key_item() : m_key(), m_state() { } key_item(const Key key, const state_type state) : m_key(key), m_state(state) { } key_item(const this_type & other) : m_key(other.m_key), m_state(other.m_state) { } key_item(const volatile this_type & other) : m_key(other.m_key), m_state(other.m_state) { } Key m_key; state_type m_state; }; template<typename Key, typename Value> class hash_node_integral_key { public: typedef Key key_type; typedef Value mapped_type; typedef hash_node_integral_key<key_type, mapped_type> this_class; typedef key_item<Key> key_item_type; typedef typename key_item_type::state_type state_type; private: hash_node_integral_key(const this_class&); // = delete; this_class& operator=(const this_class&); // = delete; public: hash_node_integral_key() : m_key(), m_refCount(0) { } const key_item_type getKey() const { return m_key; } void setKey(const key_type keyValue, const state_type stateValue) { m_key.m_key = keyValue; m_key.m_state = stateValue; } state_type getState() const { return m_key.m_state; } void setState(const state_type val) { thread_fence(barriers::release); m_key.m_state = val; } mapped_type* getValue() { return reinterpret_cast<mapped_type*>(m_value); } const mapped_type* getValue() const { return reinterpret_cast<const mapped_type*>(m_value); } bool atomic_cas(const key_item_type & expected, const key_item_type & newkey) { return xtomic::atomic_cas(m_key, expected, newkey); } void addRef() const { ++m_refCount; } void release() const { --m_refCount; } void waitForRelease() const { while (m_refCount.load(barriers::relaxed)) ; } private: volatile key_item_type m_key;char m_value[sizeof(mapped_type)] align_as(mapped_type); mutable xtomic::quantum<int> m_refCount; }; } #endif /* INCLUDE_HASH_MAP_NODE_INTEGRAL_KEY_HPP_ */
25.110429
89
0.623015
mashavorob
d3d576e1958a7c3ed1f9ead8e6193cec77f383b4
6,911
cpp
C++
exodus/libexodus/exodus/mvos2.cpp
exodusdb/exodus
b99dd39e826d5a56b6a807c14994ee8fc8970ff8
[ "MIT" ]
null
null
null
exodus/libexodus/exodus/mvos2.cpp
exodusdb/exodus
b99dd39e826d5a56b6a807c14994ee8fc8970ff8
[ "MIT" ]
null
null
null
exodus/libexodus/exodus/mvos2.cpp
exodusdb/exodus
b99dd39e826d5a56b6a807c14994ee8fc8970ff8
[ "MIT" ]
null
null
null
/* Copyright (c) 2009 [email protected] 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. */ // for sleep #include <thread> #include <chrono> #include <random> #include <unistd.h> //for getpid #include <exodus/mv.h> // to get whole environment extern char** environ; namespace exodus { void var::ossleep(const int milliseconds) const { THISIS("void var::ossleep(const int milliseconds) const") assertDefined(function_sig); // not needed if *this not used std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } // BOOST RANDOM // http://www.boost.org/doc/libs/1_38_0/libs/random/random_demo.cpp //// set the generator type to ... //// using RNG_typ = boost::minstd_rand; //using RNG_typ = boost::mt19937; //boost::thread_specific_ptr<RNG_typ> tss_random_base_generators; // //RNG_typ* get_random_base_generator() { // // get/init the base generator // RNG_typ* threads_random_base_generator = // tss_random_base_generators.get(); // if (!threads_random_base_generator) { // tss_random_base_generators.reset(new RNG_typ); // threads_random_base_generator = tss_random_base_generators.get(); // if (!threads_random_base_generator) // throw MVError("Could not create random number generator"); // // // seed to the os clock (secs since unix epoch) // // Caveat: std::time(0) is not a very good truly-random seed. // // logputl("Seeding random number generator to system clock"); // // decimal constants is unsigned only in C99" ie this number exceed max SIGNED // // integer // // (*threads_random_base_generator).seed(static_cast<unsigned // // int>(std::time(0)+2375472354)); // (*threads_random_base_generator) // .seed(static_cast<unsigned int>(std::time(0) + 2075472354)); // //(*thread_base_generator).seed(static_cast<unsigned int>(var().ostime().toInt())); // } // return threads_random_base_generator; //} using RNG_typ = std::mt19937; thread_local std::unique_ptr<RNG_typ> thread_RNG; // PickOS returns pseudo random integers in the range of 0-4 for rnd(5) var var::rnd() const { THISIS("var var::rnd() const") assertNumeric(function_sig); // Create a base generator per thread on the heap. Will be destroyed on thread termination. if (not thread_RNG.get()) var().initrnd(); int max = (*this).toInt() - 1; if (max < 0) return var(*this); // Define a integer range (0 to n-1) std::uniform_int_distribution<int> uniform_dist(0, max); // Generate a pseudo random number from the distribution using the seeded RNG return uniform_dist(*thread_RNG); //return x; } void var::initrnd() const { THISIS("void var::initrnd() const") assertDefined(function_sig); // Get a seed for the RNG uint64_t seed; if (this->unassigned()) { } else if (this->isnum()) { // Seed from number //seed = this->toLong(); seed = this->toInt(); } else if (var_typ & VARTYP_STR) { // Seed from string seed = 1; for (size_t ii = 0; ii < var_str.size(); ii++) seed *= var_str[ii]; // seed=MurmurHash64((char*)var_str.data(),int(var_str.size()*sizeof(char)),0); } else { // Seed from low resolution clock per second //seed.var_int = static_cast<unsigned int>(std::time(0) + 2'075'472'354); // Seed from high resolution clock seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); } // Set the new seed thread_RNG = std::make_unique<RNG_typ>(seed); } bool var::osgetenv(const char* envvarname) { THISIS("bool var::osgetenv(const char* envvarname)") assertDefined(function_sig); //assertStringMutator(function_sig); //ISSTRING(envvarname) // return whole environment if blank envvarname //if (envvarname.var_str.empty()) { if (*envvarname == 0) { var_str.clear(); //var_typ = VARTYP_STR; int i = 1; char* s = *environ; for (; s; i++) { // printf("%s\n", s); // var_str.append(boost::locale::conv::utf_to_utf<wchar_t>(s)); var_str.append(s); var_str.append("\n"); s = *(environ + i); } return true; } //TIP if you cant seem to osgetenv vars set in bash, then ensure you set them in bash with "export" //const char* cvalue = std::getenv(envvarname.var_str.c_str()); const char* cvalue = std::getenv(envvarname); if (cvalue == 0) { var_str.clear(); var_typ = VARTYP_STR; return false; } // *this = var(cvalue); var_str = cvalue; var_typ = VARTYP_STR; return true; } bool var::ossetenv(const char* envvarname) const { THISIS("bool var::ossetenv(const char* envvarname) const") assertString(function_sig); //ISSTRING(envvarname) //#ifdef _MSC_VER #ifndef setenv /* on windows this should be used BOOL WINAPI SetEnvironmentVariable(LPCTSTR lpName, LPCTSTR lpValue); */ // var("USING PUTENV").outputl(); // is this safe on windows?? // https://www.securecoding.cert.org/confluence/display/seccode/POS34-C.+Do+not+call+putenv()+with+a+pointer+to+an+automatic+variable+as+the+argument //std::string tempstr = envvarname.toString(); //tempstr += "="; //tempstr += toString(); // var(tempstr).outputl("temp std:string"); // std::cout<<tempstr<<" "<<tempstr.length()<<std::endl; // this will NOT work reliably since putenv will NOT COPY the local (i.e. temporary) // variable string //var("putenv " ^ var(tempstr) ).outputl(); //#pragma warning (disable : 4996) //const int result = putenv((char*)(tempstr.c_str())); //putenv("EXO_DATA=C:\\"); //std::cout<<getenv("EXO_DATA"); //char winenv[1024]; char* env = (char*)malloc(1024); //snprintf(env, 1024, "%s=%s", envvarname.var_str.c_str(), var_str.c_str()); snprintf(env, 1024, "%s=%s", envvarname, var_str.c_str()); //std::cout << winenv; int result = putenv(env); if (result == 0) return true; else return false; #else var("setenv " ^ envvarname ^ "=" ^ (*this)).outputl(); return setenv((char*)(envvarname.toString().c_str()), (char*)(toString().c_str()), 1); #endif } var var::ospid() const { //THISIS("var var::ospid() const") return getpid(); } } // namespace exodus
28.916318
150
0.70178
exodusdb
d3d74341214e42a6c90a87797b8fbaa336f66315
2,951
cpp
C++
exampleCreate/src/ofApp.cpp
armadillu/ofxTextureAtlas
b00b510acedc1211778b0f94b5a1c0753ea780d7
[ "MIT" ]
14
2015-03-31T03:33:34.000Z
2021-06-04T08:45:45.000Z
exampleCreate/src/ofApp.cpp
armadillu/ofxTextureAtlas
b00b510acedc1211778b0f94b5a1c0753ea780d7
[ "MIT" ]
1
2020-08-27T16:19:30.000Z
2020-08-27T16:53:43.000Z
exampleCreate/src/ofApp.cpp
armadillu/ofxTextureAtlas
b00b510acedc1211778b0f94b5a1c0753ea780d7
[ "MIT" ]
6
2015-08-05T20:45:19.000Z
2020-07-09T10:55:05.000Z
#include "ofApp.h" void ofApp::setup(){ ofSetFrameRate(60); ofSetVerticalSync(true); ofEnableAlphaBlending(); ofBackground(22); scale = 1.0; // LISTENERS ofAddListener(atlasCreator.eventAtlasCreationFinished, this, &ofApp::onAtlasCreationFinished); vector<string> fileList; ofDirectory d; d.allowExt("jpg"); d.listDir("images/cats"); //you are expected to put a ton of images in there. d.sort(); for(int i = 0; i < d.numFiles(); i++){ fileList.push_back(d.getPath(i)); } fileList.resize(MIN(500, fileList.size())); //lets limit the file list to 500 // CREATE ATLAS (+ callback to save) ////////////////////////// //create as many atlases as required to fit all those images in atlases of 4096 x 4096 //each image being 256 at the most. atlasCreator.createAtlases( fileList, 4096, //fbo/atlas size GL_RGB, //internal format ofVec2f(400,400), //maxItemSideSize 2.0, //padding true, //mipmaps -0.9 //mipmap bias ); } void ofApp::onAtlasCreationFinished(bool & arg){ //once atlases are created, save them to disk, so that we can load them next time //without having to recreate them atlasCreator.saveToDisk("textureCache", "png"); //save in a folder named "textureCache", in png format } void ofApp::update(){ float dt = 1./60.; } void ofApp::draw(){ ofDrawBitmapString("Progress: " + ofToString(atlasCreator.getPercentDone() * 100,1), 30, 50); if(atlasCreator.isCreating()){ //atlass construction process ofTexture * atlas = atlasCreator.getCurrentlyCreatedAtlas(); atlas->draw(0,0, ofGetHeight(), ofGetHeight()); ofDrawBitmapStringHighlight("Creating Atlas: " + ofToString(atlasCreator.getPercentDone(), 2) + "\n" + atlasCreator.getCurrentCreatingFileName(), 30, 30 ); } if(atlasCreator.isIdle() ){ int x = 0; for(int i = 0; i < atlasCreator.getNumAtlases(); i++){ ofFbo & fbo = atlasCreator.getAtlasAtIndex(i)->getFbo(); fbo.draw(ofGetMouseX() + x, ofGetMouseY(), fbo.getWidth() * scale, fbo.getHeight() * scale); x += fbo.getWidth() * scale; } } if(debug && atlasCreator.isIdle()){ ofClear(0); int x = 0; for(int i = 0; i < atlasCreator.getNumAtlases(); i++){ atlasCreator.getAtlasAtIndex(i)->drawDebug(ofGetMouseX() + x,ofGetMouseY()); x += atlasCreator.getAtlasAtIndex(i)->getFbo().getWidth(); } } } void ofApp::keyPressed(int key){ debug ^= true; } void ofApp::mouseScrolled( float x, float y ){ scale += y * 0.02; scale = ofClamp(scale, 0.02, 1.0); } void ofApp::keyReleased(int key){ } void ofApp::mouseMoved(int x, int y ){ } void ofApp::mouseDragged(int x, int y, int button){ } void ofApp::mousePressed(int x, int y, int button){ } void ofApp::mouseReleased(int x, int y, int button){ } void ofApp::windowResized(int w, int h){ } void ofApp::gotMessage(ofMessage msg){ } void ofApp::dragEvent(ofDragInfo dragInfo){ }
21.078571
103
0.657743
armadillu
d3de2fad0c36ff5e1de05d695371ae10e9d0cf5e
2,220
cpp
C++
test/framework/tMatcherFactory.cpp
xiaohongchen1991/clang-xform
bd0cf899760b53b24e10ca4baab3c4e281535b97
[ "MIT" ]
2
2020-02-18T18:09:45.000Z
2020-05-10T18:38:38.000Z
test/framework/tMatcherFactory.cpp
xiaohongchen1991/clang-xform
bd0cf899760b53b24e10ca4baab3c4e281535b97
[ "MIT" ]
null
null
null
test/framework/tMatcherFactory.cpp
xiaohongchen1991/clang-xform
bd0cf899760b53b24e10ca4baab3c4e281535b97
[ "MIT" ]
1
2020-02-18T18:09:48.000Z
2020-02-18T18:09:48.000Z
/* MIT License Copyright (c) 2019 Xiaohong Chen 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 "MatcherFactory.hpp" #include "MockMatchCallback.hpp" #include "gtest/gtest.h" namespace { std::unique_ptr<MatchCallbackBase> CreateMockMatchCallback(const std::string& id, clang::tooling::Replacements& replacements, std::vector<std::string> args) { return std::make_unique<MockMatchCallback>(id, replacements, std::move(args)); } } // end of anonymous namespace TEST(MatcherFactoryTest, CreateMatchCallback) { MatcherFactory& factory = MatcherFactory::Instance(); std::string id = "TestMatcherFactory"; // register new matcher factory.RegisterMatchCallback(id, CreateMockMatchCallback); clang::tooling::Replacements replacements; std::vector<std::string> args; // create MatchCallback EXPECT_TRUE(factory.CreateMatchCallback(id, replacements, args)); EXPECT_FALSE(factory.CreateMatchCallback("not_registered", replacements, args)); ASSERT_TRUE(factory.getMatcherMap().count(id)); EXPECT_TRUE(factory.getMatcherMap().at(id) == CreateMockMatchCallback); }
43.529412
102
0.735135
xiaohongchen1991
d3deb3e3c43d1ea4de8861e5764160d62eb9ba17
4,465
cpp
C++
test/swap.cpp
sieren/variant
99ef8fb19f5ea5f229587da3dd425a7d24c4fd80
[ "BSL-1.0" ]
564
2015-10-07T06:23:04.000Z
2022-03-25T17:17:49.000Z
test/swap.cpp
sieren/variant
99ef8fb19f5ea5f229587da3dd425a7d24c4fd80
[ "BSL-1.0" ]
76
2015-10-28T10:19:02.000Z
2021-08-17T02:28:36.000Z
test/swap.cpp
sieren/variant
99ef8fb19f5ea5f229587da3dd425a7d24c4fd80
[ "BSL-1.0" ]
88
2015-10-23T00:26:58.000Z
2022-03-03T09:47:27.000Z
// MPark.Variant // // Copyright Michael Park, 2015-2017 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <mpark/variant.hpp> #include <string> #include <gtest/gtest.h> #include "util.hpp" TEST(Swap, Same) { mpark::variant<int, std::string> v("hello"); mpark::variant<int, std::string> w("world"); // Check `v`. EXPECT_EQ("hello", mpark::get<std::string>(v)); // Check `w`. EXPECT_EQ("world", mpark::get<std::string>(w)); // Swap. using std::swap; swap(v, w); // Check `v`. EXPECT_EQ("world", mpark::get<std::string>(v)); // Check `w`. EXPECT_EQ("hello", mpark::get<std::string>(w)); } TEST(Swap, Different) { mpark::variant<int, std::string> v(42); mpark::variant<int, std::string> w("hello"); // Check `v`. EXPECT_EQ(42, mpark::get<int>(v)); // Check `w`. EXPECT_EQ("hello", mpark::get<std::string>(w)); // Swap. using std::swap; swap(v, w); // Check `v`. EXPECT_EQ("hello", mpark::get<std::string>(v)); // Check `w`. EXPECT_EQ(42, mpark::get<int>(w)); } #ifdef MPARK_EXCEPTIONS TEST(Swap, OneValuelessByException) { // `v` normal, `w` corrupted. mpark::variant<int, move_thrower_t> v(42), w(42); EXPECT_THROW(w = move_thrower_t{}, MoveConstruction); EXPECT_EQ(42, mpark::get<int>(v)); EXPECT_TRUE(w.valueless_by_exception()); // Swap. using std::swap; swap(v, w); // Check `v`, `w`. EXPECT_TRUE(v.valueless_by_exception()); EXPECT_EQ(42, mpark::get<int>(w)); } TEST(Swap, BothValuelessByException) { // `v`, `w` both corrupted. mpark::variant<int, move_thrower_t> v(42); EXPECT_THROW(v = move_thrower_t{}, MoveConstruction); mpark::variant<int, move_thrower_t> w(v); EXPECT_TRUE(v.valueless_by_exception()); EXPECT_TRUE(w.valueless_by_exception()); // Swap. using std::swap; swap(v, w); // Check `v`, `w`. EXPECT_TRUE(v.valueless_by_exception()); EXPECT_TRUE(w.valueless_by_exception()); } #endif TEST(Swap, DtorsSame) { struct Obj { Obj(size_t *dtor_count) : dtor_count_(dtor_count) {} Obj(const Obj &) = default; Obj(Obj &&) = default; ~Obj() { ++(*dtor_count_); } Obj &operator=(const Obj &) = default; Obj &operator=(Obj &&) = default; size_t *dtor_count_; }; // Obj size_t v_count = 0; size_t w_count = 0; { mpark::variant<Obj> v{&v_count}, w{&w_count}; using std::swap; swap(v, w); // Calls `std::swap(Obj &lhs, Obj &rhs)`, with which we perform: // ``` // { // Obj temp(move(lhs)); // lhs = move(rhs); // rhs = move(temp); // } `++v_count` from `temp::~Obj()`. // ``` EXPECT_EQ(1u, v_count); EXPECT_EQ(0u, w_count); } EXPECT_EQ(2u, v_count); EXPECT_EQ(1u, w_count); } namespace detail { struct Obj { Obj(size_t *dtor_count) : dtor_count_(dtor_count) {} Obj(const Obj &) = default; Obj(Obj &&) = default; ~Obj() { ++(*dtor_count_); } Obj &operator=(const Obj &) = default; Obj &operator=(Obj &&) = default; size_t *dtor_count_; }; // Obj static void swap(Obj &lhs, Obj &rhs) noexcept { std::swap(lhs.dtor_count_, rhs.dtor_count_); } } // namespace detail TEST(Swap, DtorsSameWithSwap) { size_t v_count = 0; size_t w_count = 0; { mpark::variant<detail::Obj> v{&v_count}, w{&w_count}; using std::swap; swap(v, w); // Calls `detail::swap(Obj &lhs, Obj &rhs)`, with which doesn't call any destructors. EXPECT_EQ(0u, v_count); EXPECT_EQ(0u, w_count); } EXPECT_EQ(1u, v_count); EXPECT_EQ(1u, w_count); } TEST(Swap, DtorsDifferent) { struct V { V(size_t *dtor_count) : dtor_count_(dtor_count) {} V(const V &) = default; V(V &&) = default; ~V() { ++(*dtor_count_); } V &operator=(const V &) = default; V &operator=(V &&) = default; size_t *dtor_count_; }; // V struct W { W(size_t *dtor_count) : dtor_count_(dtor_count) {} W(const W &) = default; W(W &&) = default; ~W() { ++(*dtor_count_); } W &operator=(const W &) = default; W &operator=(W &&) = default; size_t *dtor_count_; }; // W size_t v_count = 0; size_t w_count = 0; { mpark::variant<V, W> v{mpark::in_place_type_t<V>{}, &v_count}; mpark::variant<V, W> w{mpark::in_place_type_t<W>{}, &w_count}; using std::swap; swap(v, w); EXPECT_EQ(1u, v_count); EXPECT_EQ(2u, w_count); } EXPECT_EQ(2u, v_count); EXPECT_EQ(3u, w_count); }
25.514286
89
0.610974
sieren
d3e1c859769c49e51a6c38d76fa289fd7bff8304
24,184
cpp
C++
src/examples/commonExamples/persistenceExample/src/TestModel.cpp
MDE4CPP/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
12
2017-02-17T10:33:51.000Z
2022-03-01T02:48:10.000Z
src/examples/commonExamples/persistenceExample/src/TestModel.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
28
2017-10-17T20:23:52.000Z
2021-03-04T16:07:13.000Z
src/examples/commonExamples/persistenceExample/src/TestModel.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
22
2017-03-24T19:03:58.000Z
2022-03-31T12:10:07.000Z
/* * TestModel.cpp * * Created on: 23.06.2017 * Author: Alexander */ #include "TestModel.hpp" #include "ecore/EAnnotation.hpp" #include "ecore/EAttribute.hpp" #include "ecore/EClass.hpp" #include "ecore/EEnum.hpp" #include "ecore/EEnumLiteral.hpp" #include "ecore/EStringToStringMapEntry.hpp" #include "ecore/EOperation.hpp" #include "ecore/EReference.hpp" #include "ecore/ecoreFactory.hpp" #include "ecore/ecorePackage.hpp" #include "uml/umlPackage.hpp" #include "abstractDataTypes/SubsetUnion.hpp" using namespace testmodel; TestModel::TestModel() { } TestModel::~TestModel() { } std::shared_ptr<ecore::EPackage> TestModel::getMetaMetaPackage() { return ecore::ecorePackage::eInstance(); } std::shared_ptr<ecore::EObject> TestModel::createEcoreTestMetaModel() { std::shared_ptr<ecore::ecorePackage> package = ecore::ecorePackage::eInstance(); std::shared_ptr<ecore::ecoreFactory> factory = ecore::ecoreFactory::eInstance(); // Create package 'pck_UniModel' and set some default package information std::shared_ptr<ecore::EPackage> pck_UniModel = factory->createEPackage(); { pck_UniModel->setName("UniModelPackage"); pck_UniModel->setNsPrefix("Uni"); pck_UniModel->setNsURI("http://www.examples.org/Uni"); } // Create new subpackage 'pck_enum' and insert into package 'pck_UniModel' std::shared_ptr<ecore::EPackage> pck_enum(factory->createEPackage_in_ESuperPackage(pck_UniModel)); { { // set name and prefix of subpackage pck_enum->setName("EnumPackage"); pck_enum->setNsPrefix("enum"); } } // Create new subpackage and insert into package 'pck_UniModel' (alternative variant) std::shared_ptr<ecore::EPackage> pck_class(factory->createEPackage_in_ESuperPackage(pck_UniModel)); { { // set name and prefix of subpackage pck_class->setName("ClassPackage"); pck_class->setNsPrefix("cls"); } } // Create ENUMs that are used in classes std::shared_ptr<ecore::EEnum> enum_Geschlecht(factory->createEEnum_in_EPackage(pck_enum)); { enum_Geschlecht->setName("EnumGeschlecht"); // Create const attributes (literals) std::shared_ptr<Bag<ecore::EEnumLiteral>> list_ELiteral = enum_Geschlecht->getELiterals(); { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Geschlecht)); literal->setName("MAENNLICH"); literal->setLiteral("MAENNLICH"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Geschlecht)); literal->setName("WEIBLICH"); literal->setLiteral("WEIBLICH"); literal->setValue(1); } } std::shared_ptr<ecore::EEnum> enum_Verein(factory->createEEnum_in_EPackage(pck_enum)); { enum_Verein->setName("EnumVerein"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Verein)); literal->setName("BC"); literal->setLiteral("BC"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Verein)); literal->setName("BD"); literal->setLiteral("BD"); literal->setValue(1); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Verein)); literal->setName("BH"); literal->setLiteral("BH"); literal->setValue(2); } } std::shared_ptr<ecore::EEnum> enum_Position(factory->createEEnum_in_EPackage(pck_enum)); { enum_Position->setName("EnumPosition"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Position)); literal->setName("PROFESSOR"); literal->setLiteral("PROFESSOR"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Position)); literal->setName("WMA"); literal->setLiteral("WMA"); literal->setValue(1); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Position)); literal->setName("HIWI"); literal->setLiteral("HIWI"); literal->setValue(2); } } std::shared_ptr<ecore::EEnum> enum_StudentStatus(factory->createEEnum_in_EPackage(pck_enum)); { enum_StudentStatus->setName("EnumStudentStatus"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_StudentStatus)); literal->setName("BACHELOR"); literal->setLiteral("BACHELOR"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_StudentStatus)); literal->setName("MASTER"); literal->setLiteral("MASTER"); literal->setValue(1); } } std::shared_ptr<ecore::EEnum> enum_Veranstaltung(factory->createEEnum_in_EPackage(pck_enum)); { enum_Veranstaltung->setName("EnumVeranstaltung"); // Create const attributes (literals) { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Veranstaltung)); literal->setName("VORLESUNG"); literal->setLiteral("VORLESUNG"); literal->setValue(0); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Veranstaltung)); literal->setName("SEMINAR"); literal->setLiteral("SEMINAR"); literal->setValue(1); } { std::shared_ptr<ecore::EEnumLiteral> literal(factory->createEEnumLiteral_in_EEnum(enum_Veranstaltung)); literal->setName("PRAKTIKUM"); literal->setLiteral("PRAKTIKUM"); literal->setValue(2); } } // Create some classes with attributes, operations, compositions and association to each other std::shared_ptr<ecore::EClass> cls_UniModel(factory->createEClass_in_EPackage(pck_class)); { cls_UniModel->setName("UniModel"); cls_UniModel->setInterface(false); cls_UniModel->setAbstract(false); } std::shared_ptr<ecore::EClass> cls_Universitaet(factory->createEClass_in_EPackage(pck_class)); { cls_Universitaet->setName("Universitaet"); cls_Universitaet->setInterface(false); cls_Universitaet->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Universitaet)); attrib->setName("name"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Mensch(factory->createEClass_in_EPackage(pck_class)); { cls_Mensch->setName("Mensch"); cls_Mensch->setInterface(false); cls_Mensch->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mensch)); attrib->setName("lastname"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mensch)); attrib->setName("firstname"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mensch)); attrib->setName("sex"); attrib->setEType(enum_Geschlecht); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Person(factory->createEClass_in_EPackage(pck_class)); { cls_Person->setName("Person"); cls_Person->setInterface(true); cls_Person->setAbstract(false); // Add SuperType { std::shared_ptr<Bag<ecore::EClass>> list_ESuperTypes = cls_Person->getESuperTypes(); list_ESuperTypes->push_back(cls_Mensch); list_ESuperTypes->push_back(cls_Universitaet); // TODO this does not make sense, and is just for testing multiple ESuperTypes. } // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Person)); attrib->setName("id"); attrib->setEType(package->getEBigInteger_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } // Create operations, set their names and types { std::shared_ptr<ecore::EOperation> operation(factory->createEOperation_in_EContainingClass(cls_Person)); operation->setName("addVeranstaltung"); // Type: void operation->setEType(package->getEBoolean_Class()); operation->setOrdered(true); // default: ordered=true operation->setUnique(true); // default: unique=true operation->setLowerBound(0); operation->setUpperBound(1); // default: upperBound=1 { std::shared_ptr<ecore::EAnnotation> annotation(factory->createEAnnotation_in_EModelElement(operation)); annotation->setSource("http://sse.tu-ilmenau.de/codegen"); std::shared_ptr<Bag<ecore::EStringToStringMapEntry>> list_EStringToStringMapEntry = annotation->getDetails(); { std::shared_ptr<ecore::EStringToStringMapEntry> stringToStringMapEntry(factory->createEStringToStringMapEntry()); stringToStringMapEntry->setKey("body"); stringToStringMapEntry->setValue( " if (someOperation->getEContainingClass()->isSuperTypeOf(getEContainingClass()) &amp;&amp; (someOperation->getName()==getName()))&#xD;&#xA; {&#xD;&#xA; std::shared_ptr&lt; Bag&lt;ecore::EParameter> > parameters = getEParameters();&#xD;&#xA; std::shared_ptr&lt; Bag&lt;ecore::EParameter> > otherParameters = someOperation->getEParameters();&#xD;&#xA; if (parameters->size() == otherParameters->size())&#xD;&#xA; {&#xD;&#xA; for (Bag&lt;EParameter> ::iterator i = parameters->begin(), j = otherParameters->begin(); i != parameters->end(); ++i,++j )&#xD;&#xA; &#x9;{&#xD;&#xA; &#x9;std::shared_ptr&lt;EParameter> parameter = *i;&#xD;&#xA; &#x9;std::shared_ptr&lt;EParameter> otherParameter = *j;&#xD;&#xA; if (!(parameter->getEType().get() == otherParameter->getEType().get()))&#xD;&#xA; &#x9;&#x9;{&#xD;&#xA; return false;&#xD;&#xA; &#x9;&#x9;}&#xD;&#xA; &#x9;}&#xD;&#xA;&#x9;&#x9;}&#xD;&#xA;&#x9;&#x9;return true;&#xD;&#xA;&#x9;}"); list_EStringToStringMapEntry->push_back(stringToStringMapEntry); } } { std::shared_ptr<ecore::EAnnotation> annotation(factory->createEAnnotation_in_EModelElement(operation)); annotation->setSource("http://sse.tu-ilmenau.de/HansPeter"); std::shared_ptr<Bag<ecore::EStringToStringMapEntry>> list_EStringToStringMapEntry = annotation->getDetails(); { std::shared_ptr<ecore::EStringToStringMapEntry> stringToStringMapEntry(factory->createEStringToStringMapEntry()); stringToStringMapEntry->setKey("body"); stringToStringMapEntry->setValue("any source \n here is newline \t here is a tabulator"); list_EStringToStringMapEntry->push_back(stringToStringMapEntry); } } } { std::shared_ptr<ecore::EOperation> operation(factory->createEOperation_in_EContainingClass(cls_Person)); operation->setName("removeVeranstaltung"); // Type: void operation->setEType(package->getEChar_Class()); operation->setOrdered(true); // default: ordered=true operation->setUnique(true); // default: unique=true operation->setLowerBound(0); operation->setUpperBound(1); // default: upperBound=1 } } std::shared_ptr<ecore::EClass> cls_Mitarbeiter(factory->createEClass_in_EPackage(pck_class)); { cls_Mitarbeiter->setName("Mitarbeiter"); cls_Mitarbeiter->setInterface(false); cls_Mitarbeiter->setAbstract(false); // Add SuperType { std::shared_ptr<Bag<ecore::EClass>> list_ESuperTypes = cls_Mitarbeiter->getESuperTypes(); list_ESuperTypes->push_back(cls_Person); } // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mitarbeiter)); attrib->setName("position"); attrib->setEType(enum_Position); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mitarbeiter)); attrib->setName("gehalt"); attrib->setEType(package->getEFloat_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Mitarbeiter)); attrib->setName("office"); attrib->setEType(package->getEString_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Student(factory->createEClass_in_EPackage(pck_class)); { cls_Student->setName("Student"); cls_Student->setInterface(false); cls_Student->setAbstract(false); // Add SuperType { std::shared_ptr<Bag<ecore::EClass>> list_ESuperTypes = cls_Student->getESuperTypes(); list_ESuperTypes->push_back(cls_Person); } // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Student)); attrib->setName("status"); attrib->setEType(enum_StudentStatus); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Veranstaltung(factory->createEClass_in_EPackage(pck_class)); { cls_Veranstaltung->setName("Veranstaltung"); cls_Veranstaltung->setInterface(false); cls_Veranstaltung->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Veranstaltung)); attrib->setName("name"); attrib->setEType(enum_Veranstaltung); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Veranstaltung)); attrib->setName("maxTeilnehmer"); attrib->setEType(package->getEInt_Class()); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } std::shared_ptr<ecore::EClass> cls_Verein(factory->createEClass_in_EPackage(pck_class)); { cls_Verein->setName("Verein"); cls_Verein->setInterface(false); cls_Verein->setAbstract(false); // Create attributes, set their names and types { std::shared_ptr<ecore::EAttribute> attrib(factory->createEAttribute_in_EContainingClass(cls_Verein)); attrib->setName("name"); attrib->setEType(enum_Verein); attrib->setID(false); attrib->setOrdered(true); // default: ordered=true attrib->setUnique(true); // default: unique=true attrib->setLowerBound(0); attrib->setUpperBound(1); // default: upperBound=1 attrib->setChangeable(true); attrib->setVolatile(true); attrib->setTransient(false); attrib->setDefaultValueLiteral(""); attrib->setUnsettable(false); attrib->setDerived(false); } } // Create Compositions and Associations { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_UniModel)); reference->setName("universitaet"); reference->setEType(cls_Universitaet); reference->setContainment(true); // set reference as composition reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Universitaet)); reference->setName("person"); reference->setEType(cls_Person); reference->setContainment(true); // set reference as composition reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Universitaet)); reference->setName("veranstaltung"); reference->setEType(cls_Veranstaltung); reference->setContainment(true); // set reference as composition reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Person)); reference->setName("veranstaltung"); reference->setEType(cls_Veranstaltung); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Veranstaltung)); reference->setName("dozent"); reference->setEType(cls_Person); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Veranstaltung)); reference->setName("student"); reference->setEType(cls_Person); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } { { std::shared_ptr<ecore::EReference> reference(factory->createEReference_in_EContainingClass(cls_Student)); reference->setName("verein"); reference->setEType(cls_Verein); reference->setContainment(false); // set reference as association reference->setResolveProxies(true); // default: resolveProxies=true reference->setOrdered(true); // default: ordered=true reference->setUnique(true); // default: unique=true reference->setLowerBound(0); reference->setUpperBound(-1); // default: upperBound=1 reference->setChangeable(true); reference->setVolatile(true); reference->setTransient(false); reference->setDefaultValueLiteral(""); reference->setUnsettable(false); reference->setDerived(false); } } return std::dynamic_pointer_cast<ecore::EObject>(pck_UniModel); }
34.401138
1,069
0.724405
MDE4CPP
d3e2fdd3f504c29cb6ad9b28fd086f457d16fdb9
1,215
cpp
C++
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/bn/exp.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/bn/exp.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/crypto/bn/exp.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
/* unused */ #include <openssl/tmdiff.h> #include "bn_lcl.h" #ifdef OPENSSL_SYS_WINDOWS #include <stdio.h> #endif #define SIZE 256 #define NUM (8*8*8) #define MOD (8*8*8*8*8) main(argc,argv) int argc; char *argv[]; { BN_CTX ctx; BIGNUM a,b,c,r,rr,t,l; int j,i,size=SIZE,num=NUM,mod=MOD; char *start,*end; BN_MONT_CTX mont; double d,md; BN_MONT_CTX_init(&mont); BN_CTX_init(&ctx); BN_init(&a); BN_init(&b); BN_init(&c); BN_init(&r); start=ms_time_new(); end=ms_time_new(); while (size <= 1024*8) { BN_rand(&a,size,0,0); BN_rand(&b,size,1,0); BN_rand(&c,size,0,1); BN_mod(&a,&a,&c,&ctx); ms_time_get(start); for (i=0; i<10; i++) BN_MONT_CTX_set(&mont,&c,&ctx); ms_time_get(end); md=ms_time_diff(start,end); ms_time_get(start); for (i=0; i<num; i++) { /* bn_mull(&r,&a,&b,&ctx); */ /* BN_sqr(&r,&a,&ctx); */ BN_mod_exp_mont(&r,&a,&b,&c,&ctx,&mont); } ms_time_get(end); d=ms_time_diff(start,end)/* *50/33 */; TINYCLR_SSL_PRINTF("%5d bit:%6.2f %6d %6.4f %4d m_set(%5.4f)\n",size, d,num,d/num,(int)((d/num)*mod),md/10.0); num/=8; mod/=8; if (num <= 0) num=1; size*=2; } }
18.692308
72
0.566255
PervasiveDigital
d3e5ef0c6abd060d037184253795954185c0f745
269
cpp
C++
src/foreachprint.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
src/foreachprint.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
src/foreachprint.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <iostream> void print(int x) { std::cout << "print: "<< x << '\n'; } void printReverse(std::vector<int> v) { std::for_each(crbegin(v), crend(v), print); } int main(){ std::vector v{1,2,3,4,5}; printReverse(v); }
17.933333
45
0.613383
PeterSommerlad
d3e78bf353de3c32d39691300a33f6f236bb39ea
4,738
hpp
C++
include/freertos_cpp_util/object_pool/Object_pool.hpp
jacobschloss/freertos_cpp_util
8251809738922c84b1ce12db6a77000b73287a8b
[ "BSD-3-Clause" ]
5
2019-03-28T22:05:50.000Z
2022-03-29T16:20:01.000Z
include/freertos_cpp_util/object_pool/Object_pool.hpp
jacobschloss/freertos_cpp_util
8251809738922c84b1ce12db6a77000b73287a8b
[ "BSD-3-Clause" ]
null
null
null
include/freertos_cpp_util/object_pool/Object_pool.hpp
jacobschloss/freertos_cpp_util
8251809738922c84b1ce12db6a77000b73287a8b
[ "BSD-3-Clause" ]
1
2020-06-17T04:04:26.000Z
2020-06-17T04:04:26.000Z
/** * @brief Object_pool * @author Jacob Schloss <[email protected]> * @copyright Copyright (c) 2018 Jacob Schloss. All rights reserved. * @license Licensed under the 3-Clause BSD license. See LICENSE for details */ #pragma once #include "freertos_cpp_util/Queue_static_pod.hpp" #include "freertos_cpp_util/object_pool/Object_pool_node.hpp" #include "freertos_cpp_util/object_pool/Object_pool_base.hpp" #include <chrono> #include <type_traits> #include <utility> template< typename T, size_t LEN > class Object_pool : public Object_pool_base<T> { public: using typename Object_pool_base<T>::Aligned_T; using typename Object_pool_base<T>::Node_T; using typename Object_pool_base<T>::Heap_element_T; Object_pool() { for(size_t i = 0; i < LEN; i++) { Heap_element_T* const mem_ptr = &m_mem_node_pool[i]; mem_ptr->node = Node_T(this, reinterpret_cast<T*>( &(mem_ptr->val)) ); m_free_nodes.push_back(&mem_ptr->node); } } template<class Rep, class Period, typename... Args> T* try_allocate_for(const std::chrono::duration<Rep,Period>& duration, Args&&... args) { std::chrono::milliseconds duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration); return try_allocate_for_ticks(pdMS_TO_TICKS(duration_ms.count()), std::forward<Args>(args)...); } template<typename... Args> T* try_allocate_for_ticks(const TickType_t xTicksToWait, Args&&... args) { Node_T* node = nullptr; if(!m_free_nodes.pop_front(&node, xTicksToWait)) { return nullptr; } return node->allocate(std::forward<Args>(args)...); } template<typename... Args> T* try_allocate_isr(BaseType_t* const pxHigherPriorityTaskWoken, Args&&... args) { Node_T* node = nullptr; if(!m_free_nodes.pop_front_isr(&node, pxHigherPriorityTaskWoken)) { return nullptr; } return node->allocate(std::forward<Args>(args)...); } template<typename... Args> T* allocate(Args&&... args) { return try_allocate_for_ticks(0, std::forward<Args>(args)...); } class Node_T_deleter { public: void operator()(T* ptr) const { Node_T* node = Node_T::get_this_from_val_ptr(ptr); Object_pool_base<T>* pool = node->get_pool_ptr(); pool->deallocate(node); } }; typedef std::unique_ptr<T, Node_T_deleter> unique_node_ptr; class Node_T_deleter_isr { public: void operator()(T* ptr) const { Node_T* node = Node_T::get_this_from_val_ptr(ptr); Object_pool_base<T>* pool = node->get_pool_ptr(); pool->deallocate_isr(node); } }; typedef std::unique_ptr<T, Node_T_deleter_isr> isr_unique_node_ptr; template<typename... Args> unique_node_ptr try_allocate_for_ticks_unique(const TickType_t xTicksToWait, Args&&... args) { T* val = try_allocate_for_ticks(xTicksToWait, std::forward<Args>(args)...); return unique_node_ptr(val); } template<typename... Args> unique_node_ptr allocate_unique(Args&&... args) { T* val = allocate(std::forward<Args>(args)...); return unique_node_ptr(val); } template<typename... Args> isr_unique_node_ptr allocate_unique_isr(BaseType_t* const pxHigherPriorityTaskWoken, Args&&... args) { T* val = try_allocate_isr(pxHigherPriorityTaskWoken, std::forward<Args>(args)...); return isr_unique_node_ptr(val); } //the "best" deallocator //node must belong to this pool void deallocate(Node_T* const node) override { if(node == nullptr) { return; } node->deallocate(); // Object_pool_base<T>* pool = node->get_pool(); // if(pool != this) // { // //you tried to delete a foreign node // //that is bad // } if(!m_free_nodes.push_front(node)) { //this should never fail //very bad if this fails } } //look up the node based on the ptr //ptr must belong to this pool void deallocate(T* const ptr) override { if(ptr == nullptr) { return; } Node_T* node = Node_T::get_this_from_val_ptr(ptr); deallocate(node); } //the "best" deallocator //node must belong to this pool void deallocate_isr(Node_T* const node) override { if(node == nullptr) { return; } node->deallocate(); // Object_pool_base<T>* pool = node->get_pool(); // if(pool != this) // { // //you tried to delete a foreign node // //that is bad // } if(!m_free_nodes.push_front_isr(node)) { //this should never fail //very bad if this fails } } //look up the node based on the ptr //ptr must belong to this pool void deallocate_isr(T* const ptr) override { if(ptr == nullptr) { return; } Node_T* node = Node_T::get_this_from_val_ptr(ptr); deallocate_isr(node); } protected: //heap element: node and aligned storage std::array<Heap_element_T, LEN> m_mem_node_pool; //tracks free nodes Queue_static_pod<Node_T*, LEN> m_free_nodes; };
22.140187
106
0.695019
jacobschloss
d3e93b4a64afe604470a51fc7b70e85ea86ba495
1,670
hpp
C++
Source/Cerise/CR_Text.hpp
BubbleChien/Path
950f65b9fcd99bebf4cb5b20fecd3df085161912
[ "MIT" ]
1
2018-07-07T15:14:33.000Z
2018-07-07T15:14:33.000Z
Source/Cerise/CR_Text.hpp
BubbleChien/Path
950f65b9fcd99bebf4cb5b20fecd3df085161912
[ "MIT" ]
null
null
null
Source/Cerise/CR_Text.hpp
BubbleChien/Path
950f65b9fcd99bebf4cb5b20fecd3df085161912
[ "MIT" ]
null
null
null
#ifndef CR_TEXT_HPP #define CR_TEXT_HPP #include "./CR_Common.hpp" #include "./CR_Error.hpp" #include "./CR_Math.hpp" #include "./CR_Vector.hpp" namespace CR { class Text { CR_PRIVATE C2D_TextBuf m_buffer = nullptr; C2D_Text m_text; Vector m_pos; uint32_t m_color = 0xFFFFFFFF; float m_size = 1.0f; CR_PUBLIC void Init(uint32_t size); void Free(); void CenterAt(float x, float y); CR_PUBLIC inline ~Text(); inline void Clear(); inline void Append(const char* str); inline void SetPosition(float x, float y); inline void Move(float x, float y); inline void SetColor(uint32_t color); inline void SetSize(float s); inline void Render(); }; Text::~Text() { this->Free(); } void Text::Clear() { #if CR_DEV_BUILD if(m_buffer == nullptr) { Error::Show("Text has not been initialized."); return; } #endif C2D_TextBufClear(m_buffer); } void Text::Append(const char* str) { #if CR_DEV_BUILD if(m_buffer == nullptr) { Error::Show("Text has not been initialized."); return; } #endif C2D_TextParse(&m_text, m_buffer, str); } void Text::SetPosition(float x, float y) { m_pos.Set(Math::Pixel(x), Math::Pixel(y)); } void Text::Move(float x, float y) { m_pos.Move(x, y); } void Text::SetColor(uint32_t color) { m_color = color; } void Text::SetSize(float s) { m_size = s; } void Text::Render() { #if CR_DEV_BUILD if(m_buffer == nullptr) { Error::Show("Text has not been initialized."); return; } #endif C2D_DrawText(&m_text, CR_TEXT_FLAGS, m_pos.x, m_pos.y, 0.5f, m_size, m_size, m_color); } } #endif
11.678322
88
0.636527
BubbleChien
d3f6b620fb3cb66b4be843d879506f938c5cf2f0
16,727
cpp
C++
src/PropBindingDialog.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/PropBindingDialog.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/PropBindingDialog.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
#include "PropBindingDialog.h" #include <wx/dataview.h> #include <wx/statline.h> /////////////////////////////////////////////////////////////////////////// enum { ID_BIND = 100, ID_UNBIND }; BEGIN_EVENT_TABLE(PropBindingDialog, wxDialog) EVT_BUTTON(ID_BIND, PropBindingDialog::OnBindButton) EVT_BUTTON(ID_UNBIND, PropBindingDialog::OnUnbindButton) END_EVENT_TABLE() PropBindingSubscriberModelNode::PropBindingSubscriberModelNode ( PropBindingSubscriberModelNode* parent, const wxString &subscriber_name, Property * subscriber_prop, const wxString &binding, Property * observed_prop, bool is_container ) : m_parent ( parent ), m_subscriber_name ( subscriber_name ), m_subscriber ( subscriber_prop ), m_binding ( binding ), m_observed ( observed_prop ), m_container ( is_container ) { } PropBindingSubscriberModelNode::~PropBindingSubscriberModelNode ( ) { // free all our children nodes size_t count = m_children.GetCount(); for (size_t i = 0; i < count; i++) { PropBindingSubscriberModelNode *child = m_children[i]; delete child; } } void PropBindingSubscriberModelNode::UpdateNode ( ) { m_subscriber_name = m_subscriber->GetName ( ); Binding * binding = m_subscriber->GetBinding ( ); if ( binding ) { m_binding = binding->GetPropertyTypeName ( ); m_observed = binding->GetOtherProperty ( m_subscriber ); } else { m_binding = wxEmptyString; m_observed = NULL; } m_container = m_subscriber->IsContainer ( ); } PropBindingSubscriberModel::PropBindingSubscriberModel ( HeeksObj *obj ) { wxString str = obj->GetTitle ( ); if ( str.IsEmpty ( ) ) { str = obj->GetTypeString ( ); } m_root = new PropBindingSubscriberModelNode ( NULL, str, NULL, wxEmptyString, NULL, true ); for ( DomainObjectIterator it = obj->begin ( ); it != obj->end ( ); it++ ) { Property * prop = *it; if ( prop->IsBindable ( ) ) { PropBindingSubscriberModelNode* node; Binding * binding = prop->GetBinding ( ); if ( binding ) { wxString binding_type = binding->GetPropertyTypeName ( ); Property * observed = binding->GetOtherProperty ( prop ); node = new PropBindingSubscriberModelNode ( m_root, prop->GetName ( ), prop, binding_type, observed, prop->IsContainer ( ) ); } else { node = new PropBindingSubscriberModelNode ( m_root, prop->GetName ( ), prop, wxEmptyString, NULL, prop->IsContainer ( ) ); } m_root->Append ( node ); } } } PropBindingSubscriberModel::~PropBindingSubscriberModel ( ) { delete m_root; } void PropBindingSubscriberModel::GetValue ( wxVariant &variant, const wxDataViewItem &item, unsigned int col ) const { wxASSERT(item.IsOk()); PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) item.GetID(); switch (col) { case 0: variant = node->m_subscriber_name; break; case 1: if ( node->m_subscriber ) variant = node->m_subscriber->GetPropertyTypeName(); else variant = wxEmptyString; break; case 2: variant = node->m_binding; break; case 3: if ( node->m_observed ) { HeeksObj * obj = (HeeksObj*)node->m_observed->GetOwner(); wxString str = obj->GetTitle ( ); if ( str.IsEmpty ( ) ) { str = obj->GetTypeString ( ); } variant = str; } else variant = wxEmptyString; break; case 4: if ( node->m_observed ) variant = node->m_observed->GetName(); else variant = wxEmptyString; break; default: wxLogError ( "PropBindingSubscriberModel::GetValue: wrong column %d", col ); } } bool PropBindingSubscriberModel::SetValue ( const wxVariant &variant, const wxDataViewItem &item, unsigned int col ) { return false; } bool PropBindingSubscriberModel::IsEnabled ( const wxDataViewItem &item, unsigned int col ) const { return true; } wxDataViewItem PropBindingSubscriberModel::GetParent ( const wxDataViewItem &item ) const { // the invisible root node has no parent if (!item.IsOk()) return wxDataViewItem(0); PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) item.GetID(); if (node == m_root) return wxDataViewItem(0); return wxDataViewItem ( (void*) node->GetParent() ); } bool PropBindingSubscriberModel::IsContainer ( const wxDataViewItem &item ) const { if (!item.IsOk()) return true; PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) item.GetID(); return ( node->m_container ); } unsigned int PropBindingSubscriberModel::GetChildren ( const wxDataViewItem &parent, wxDataViewItemArray &array ) const { PropBindingSubscriberModelNode *node = (PropBindingSubscriberModelNode*) parent.GetID(); if (!node) { array.Add( wxDataViewItem( (void*) m_root ) ); return 1; } unsigned int count = node->GetChildren().GetCount(); for (unsigned int pos = 0; pos < count; pos++) { PropBindingSubscriberModelNode *child = node->GetChildren().Item ( pos ); array.Add( wxDataViewItem( (void*) child ) ); } return count; } PropBindingObservedModelNode::PropBindingObservedModelNode ( PropBindingObservedModelNode* parent, const wxString &observed_name, Property * observed_prop, bool is_container ) : m_parent ( parent ), m_observed_name ( observed_name ), m_observed ( observed_prop ), m_container ( is_container ) { } PropBindingObservedModelNode::~PropBindingObservedModelNode ( ) { // free all our children nodes size_t count = m_children.GetCount(); for (size_t i = 0; i < count; i++) { PropBindingObservedModelNode *child = m_children[i]; delete child; } } PropBindingObservedModel::PropBindingObservedModel ( HeeksObj *obj ) { wxString str = obj->GetTitle ( ); if ( str.IsEmpty ( ) ) { str = obj->GetTypeString ( ); } m_root = new PropBindingObservedModelNode ( NULL, str, NULL, true ); for ( DomainObjectIterator it = obj->begin ( ); it != obj->end ( ); it++ ) { Property * prop = *it; if ( prop->IsBindable ( ) ) { m_root->Append ( new PropBindingObservedModelNode ( m_root, prop->GetName ( ), prop, prop->IsContainer ( ) ) ); } } } PropBindingObservedModel::~PropBindingObservedModel ( ) { delete m_root; } void PropBindingObservedModel::GetValue ( wxVariant &variant, const wxDataViewItem &item, unsigned int col ) const { wxASSERT(item.IsOk()); PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) item.GetID(); switch (col) { case 0: variant = node->m_observed_name; break; case 1: if ( node->m_observed ) variant = node->m_observed->GetPropertyTypeName(); else variant = wxEmptyString; break; default: wxLogError ( "PropBindingObservedModel::GetValue: wrong column %d", col ); } } bool PropBindingObservedModel::SetValue ( const wxVariant &variant, const wxDataViewItem &item, unsigned int col ) { return false; } bool PropBindingObservedModel::IsEnabled ( const wxDataViewItem &item, unsigned int col ) const { return true; } wxDataViewItem PropBindingObservedModel::GetParent ( const wxDataViewItem &item ) const { // the invisible root node has no parent if (!item.IsOk()) return wxDataViewItem(0); PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) item.GetID(); if (node == m_root) return wxDataViewItem(0); return wxDataViewItem ( (void*) node->GetParent() ); } bool PropBindingObservedModel::IsContainer ( const wxDataViewItem &item ) const { if (!item.IsOk()) return true; PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) item.GetID(); return ( node->m_container ); } unsigned int PropBindingObservedModel::GetChildren ( const wxDataViewItem &parent, wxDataViewItemArray &array ) const { PropBindingObservedModelNode *node = (PropBindingObservedModelNode*) parent.GetID(); if (!node) { array.Add ( wxDataViewItem( (void*) m_root ) ); return 1; } unsigned int count = node->GetChildren().GetCount(); for (unsigned int pos = 0; pos < count; pos++) { PropBindingObservedModelNode *child = node->GetChildren().Item ( pos ); array.Add ( wxDataViewItem( (void*) child ) ); } return count; } PropBindingDialog::PropBindingDialog ( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog ( parent, id, title, pos, size, style), m_subscriber_model ( NULL ), m_observed_model ( NULL ) { this->SetSize ( wxSize ( 845, 480 ) ); // wxFlexGridSizer (int rows, int cols, int vgap, int hgap) wxFlexGridSizer* topSizer = new wxFlexGridSizer ( 4, 1, 0, 0 ); topSizer->AddGrowableCol ( 0 ); topSizer->AddGrowableRow ( 0 ); wxFlexGridSizer* gridSizer = new wxFlexGridSizer ( 1, 2, 0, 0 ); gridSizer->AddGrowableCol ( 0, 70 ); gridSizer->AddGrowableCol ( 1, 30 ); gridSizer->AddGrowableRow ( 0 ); prop1 = new wxDataViewCtrl ( this, wxID_ANY ); // Add (wxWindow *window, int proportion=0, int flag=0, int border=0, wxObject *userData=NULL) gridSizer->Add( prop1, 0, wxALL | wxEXPAND, 5 ); wxDataViewTextRenderer *text_renderer = new wxDataViewTextRenderer(); wxDataViewColumn* column; column = new wxDataViewColumn ( "subscriber", text_renderer, 0, 115, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "type", text_renderer, 1, 100, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "binding", text_renderer, 2, 95, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "observed", text_renderer, 3, 115, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); column = new wxDataViewColumn ( "property", text_renderer, 4, 115, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop1->AppendColumn ( column ); prop2 = new wxDataViewCtrl ( this, wxID_ANY ); gridSizer->Add ( prop2, 0, wxEXPAND | wxALL, 5 ); column = new wxDataViewColumn ( "observed", text_renderer, 0, 120, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop2->AppendColumn ( column ); column = new wxDataViewColumn ( "type", text_renderer, 1, 100, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE | wxDATAVIEW_COL_RESIZABLE ); prop2->AppendColumn ( column ); topSizer->Add ( gridSizer, 1, wxEXPAND | wxALL, 5 ); wxStaticBoxSizer *actionSizer = new wxStaticBoxSizer ( wxHORIZONTAL, this ); m_buttonBind = new wxButton ( actionSizer->GetStaticBox(), ID_BIND, _("Bind") ); actionSizer->Add ( m_buttonBind, 0, wxALL, 5 ); m_buttonUnbind = new wxButton ( actionSizer->GetStaticBox(), ID_UNBIND, _("Unbind") ); actionSizer->Add ( m_buttonUnbind, 0, wxALL, 5 ); actionSizer->Insert ( 0, 260, 0 ); actionSizer->Insert ( 1, 50, 0 ); topSizer->Add ( actionSizer, 1, wxEXPAND | wxALL, 5 ); m_staticline1 = new wxStaticLine ( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); topSizer->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); m_buttonSizer = new wxStdDialogButtonSizer ( ); m_buttonOK = new wxButton ( this, wxID_OK ); m_buttonSizer->AddButton ( m_buttonOK ); m_buttonSizer->Realize ( ); m_buttonSizer->SetMinSize ( wxSize ( -1, 40 ) ); topSizer->Add ( m_buttonSizer, 1, wxEXPAND, 5 ); this->SetSizer ( topSizer ); this->Layout ( ); this->Centre( wxBOTH ); } PropBindingDialog::~PropBindingDialog() { if ( m_subscriber_model ) { m_subscriber_model->DecRef(); } if ( m_observed_model ) { m_observed_model->DecRef(); } } void PropBindingDialog::ExpandSubscriberRecursive ( PropBindingSubscriberModel* model, wxDataViewItem& item ) { prop1->Expand ( item ); wxDataViewItemArray children; int count = model->GetChildren ( item, children ); for ( int i = 0; i < count; i++ ) { wxDataViewItem child = children[i]; ExpandSubscriberRecursive ( model, child ); } } void PropBindingDialog::AddSubscriberModel ( PropBindingSubscriberModel* model ) { m_subscriber_model = model; prop1->AssociateModel ( model ); wxDataViewItem root ( NULL ); ExpandSubscriberRecursive ( model, root ); wxGetApp().RegisterObserver ( this ); } void PropBindingDialog::ExpandObservedRecursive ( PropBindingObservedModel* model, wxDataViewItem& item ) { prop2->Expand ( item ); wxDataViewItemArray children; int count = model->GetChildren ( item, children ); for ( int i = 0; i < count; i++ ) { wxDataViewItem child = children[i]; ExpandObservedRecursive ( model, child ); } } void PropBindingDialog::AddObservedModel ( PropBindingObservedModel* model ) { m_observed_model = model; prop2->AssociateModel ( model ); wxDataViewItem root ( NULL ); ExpandObservedRecursive ( model, root ); } void PropBindingDialog::OnBindButton ( wxCommandEvent& event ) { wxDataViewItem selected1 = prop1->GetSelection ( ); if ( !selected1.IsOk ( ) ) { return; } PropBindingSubscriberModelNode* subscriber = (PropBindingSubscriberModelNode*) selected1.GetID ( ); wxDataViewItem selected2 = prop2->GetSelection ( ); if ( !selected2.IsOk ( ) ) { return; } PropBindingObservedModelNode* observed = (PropBindingObservedModelNode*) selected2.GetID ( ); new EqualityBinding ( subscriber->m_subscriber, observed->m_observed ); // At this point, the subscriber may be a completely new object. subscriber->UpdateNode ( ); m_subscriber_model->ItemChanged ( selected1 ); } void PropBindingDialog::OnUnbindButton ( wxCommandEvent& event ) { wxDataViewItem selected1 = prop1->GetSelection ( ); if ( !selected1.IsOk ( ) ) { return; } PropBindingSubscriberModelNode* subscriber = (PropBindingSubscriberModelNode*) selected1.GetID ( ); wxDataViewItem selected2 = prop2->GetSelection ( ); if ( !selected2.IsOk ( ) ) { return; } PropBindingObservedModelNode* observed = (PropBindingObservedModelNode*) selected2.GetID ( ); Binding * binding = observed->m_observed->GetBinding ( ); delete binding; } void PropBindingDialog::WhenMarkedListChanges ( bool selection_cleared, const std::list<HeeksObj*>* added_list, const std::list<HeeksObj*>* removed_list ) { if ( !added_list || added_list->empty ( ) ) { return; } HeeksObj* observed = added_list->back ( ); PropBindingObservedModel* observed_model = new PropBindingObservedModel ( observed ); this->AddObservedModel ( observed_model ); }
33.521042
147
0.609972
tapeguy
108cb9c126208baa6d96f4f71d32fac108adc580
1,440
cpp
C++
CF-Upsolving v001/Solutions/red_maple/A/main.cpp
gmeligio/axon_training
657f181b732265856c71e97697bfde2062744e5a
[ "MIT" ]
null
null
null
CF-Upsolving v001/Solutions/red_maple/A/main.cpp
gmeligio/axon_training
657f181b732265856c71e97697bfde2062744e5a
[ "MIT" ]
5
2019-04-30T22:31:36.000Z
2019-05-07T00:15:23.000Z
CF-Upsolving v001/Solutions/red_maple/A/main.cpp
gmeligio/axon_training
657f181b732265856c71e97697bfde2062744e5a
[ "MIT" ]
5
2019-05-01T05:08:43.000Z
2019-05-07T18:13:18.000Z
/* Date 05/12/2019 Brenda E Ramirez. */ /* Statement: */ #include <bits/stdc++.h> #include <limits.h> #include <algorithm> #include <numeric> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define endl '\n' using ll = long long; const int precision = 16; const int modulo = 1000000007; // 10^9 + 7 const ll lmodulo = 1000000007; // 10^9 + 7 const double EPS = 1e-9; void solveA() { int n; cin >> n; int pp = 0; int p = 0; ll ret = 0; while(n--) { int cur; cin >> cur; if(cur == p) { cout << "Infinite"; return; } if(pp == 3 and p == 1 and cur == 2) { ret += 2; } else { int tp = p; int tcur = cur; if(tp > tcur) swap(tp, tcur); if(tp == 2 and tcur == 3) { cout << "Infinite"; return; } else if(tp == 1 and tcur == 2) { ret += 3; } else if(tp == 1 and tcur == 3) { ret += 4; } } pp = p; p = cur; } cout <<"Finite" << endl << ret; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.precision(precision); cout.setf(ios_base::fixed); solveA(); return 0;
19.2
68
0.465278
gmeligio
108ee3df534bebc0f003c1a1d476c137aca231d1
23,882
cpp
C++
UDPEchoWithBroadcast/server.cpp
henry9836/UDPChat
8a31662236f8a223e7b73a2c5267999becc11837
[ "MIT" ]
1
2019-05-20T00:06:02.000Z
2019-05-20T00:06:02.000Z
UDPEchoWithBroadcast/server.cpp
henry9836/UDPChat
8a31662236f8a223e7b73a2c5267999becc11837
[ "MIT" ]
null
null
null
UDPEchoWithBroadcast/server.cpp
henry9836/UDPChat
8a31662236f8a223e7b73a2c5267999becc11837
[ "MIT" ]
null
null
null
// // (c) 2015 Media Design School // // File Name : server.cpp // Description : Does server work // Author : Henry Oliver // Mail : [email protected] // //Library Includes #include <WS2tcpip.h> #include <iostream> #include <utility> #include <thread> #include <chrono> #include <stdlib.h> #include <time.h> #include <math.h> //Local Includes #include "utils.h" #include "network.h" #include "consoletools.h" #include "socket.h" //Local Includes #include "server.h" //Global Temps std::string addrTmp = ""; CServer::CServer() :m_pcPacketData(0), m_pServerSocket(0) { ZeroMemory(&m_ClientAddress, sizeof(m_ClientAddress)); } CServer::~CServer() { delete m_pConnectedClients; m_pConnectedClients = 0; delete m_pServerSocket; m_pServerSocket = 0; delete m_pWorkQueue; m_pWorkQueue = 0; delete[] m_pcPacketData; m_pcPacketData = 0; } bool CServer::Initialise() { m_pcPacketData = new char[MAX_MESSAGE_LENGTH]; //Create a work queue to distribute messages between the main thread and the receive thread. m_pWorkQueue = new CWorkQueue<std::pair<sockaddr_in, std::string>>(); //Create a socket object m_pServerSocket = new CSocket(); //Get the port number to bind the socket to unsigned short _usServerPort = QueryPortNumber(DEFAULT_SERVER_PORT); //Initialise the socket to the local loop back address and port number if (!m_pServerSocket->Initialise(_usServerPort)) { return false; } //Qs 2: Create the map to hold details of all connected clients m_pConnectedClients = new std::map < std::string, TClientDetails >() ; return true; } bool CServer::AddClient(std::string _strClientName) { //TO DO : Add the code to add a client to the map here... for (auto it = m_pConnectedClients->begin(); it != m_pConnectedClients->end(); ++it) { //Check to see that the client to be added does not already exist in the map, if(it->first == ToString(m_ClientAddress)) { TPacket _packetToSend; std::string message = "Connection Refused: IP Already Exists"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, m_ClientAddress); return false; } //also check for the existence of the username if (it->second.m_strName == _strClientName) { TPacket _packetToSend; std::string message = "Connection Refused: User Already Exists"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, m_ClientAddress); return false; } } //Add the client to the map. TClientDetails _clientToAdd; _clientToAdd.m_strName = _strClientName; _clientToAdd.m_ClientAddress = this->m_ClientAddress; std::string _strAddress = ToString(m_ClientAddress); addrTmp = _strAddress; //Add security info _clientToAdd.SECURITY.authIP = _strAddress; _clientToAdd.SECURITY.authStatus = _clientToAdd.SECURITY.NOAUTH; _clientToAdd.SECURITY.authUser = _clientToAdd.m_strName; _clientToAdd.SECURITY.authUser = _clientToAdd.SECURITY.authUser.substr(1, _clientToAdd.SECURITY.authUser.length()); //get rid of padding _clientToAdd.SECURITY.key = 4 + rand() % 150; //Check for bad chars in security info std::string ENDLN = "$END"; size_t pos = _clientToAdd.SECURITY.authUser.find(ENDLN); while (pos != std::string::npos) { _clientToAdd.SECURITY.authUser.replace(pos, ENDLN.size(), ""); pos = _clientToAdd.SECURITY.authUser.find(ENDLN, pos + 0); } //Insert into the map m_pConnectedClients->insert(std::pair < std::string, TClientDetails > (_strAddress, _clientToAdd)); return true; } bool CServer::SendData(char* _pcDataToSend) { int _iBytesToSend = (int)strlen(_pcDataToSend) + 1; int iNumBytes = sendto( m_pServerSocket->GetSocketHandle(), // socket to send through. _pcDataToSend, // data to send _iBytesToSend, // number of bytes to send 0, // flags reinterpret_cast<sockaddr*>(&m_ClientAddress), // address to be filled with packet target sizeof(m_ClientAddress) // size of the above address struct. ); //iNumBytes; if (_iBytesToSend != iNumBytes) { std::cout << "There was an error in sending data from client to server" << std::endl; return false; } return true; } bool CServer::SendDataTo(char* _pcDataToSend, sockaddr_in _clientAdrress) { int _iBytesToSend = (int)strlen(_pcDataToSend) + 1; int iNumBytes = sendto( m_pServerSocket->GetSocketHandle(), // socket to send through. _pcDataToSend, // data to send _iBytesToSend, // number of bytes to send 0, // flags reinterpret_cast<sockaddr*>(&_clientAdrress), // address to be filled with packet target sizeof(_clientAdrress) // size of the above address struct. ); //iNumBytes; if (_iBytesToSend != iNumBytes) { std::cout << "There was an error in sending data from client to server" << std::endl; return false; } return true; } void CServer::ReceiveData(char* _pcBufferToReceiveData) { int iSizeOfAdd = sizeof(m_ClientAddress); int _iNumOfBytesReceived; int _iPacketSize; //Make a thread local buffer to receive data into char _buffer[MAX_MESSAGE_LENGTH]; while (true) { // pull off the packet(s) using recvfrom() _iNumOfBytesReceived = recvfrom( // pulls a packet from a single source... m_pServerSocket->GetSocketHandle(), // client-end socket being used to read from _buffer, // incoming packet to be filled MAX_MESSAGE_LENGTH, // length of incoming packet to be filled 0, // flags reinterpret_cast<sockaddr*>(&m_ClientAddress), // address to be filled with packet source &iSizeOfAdd // size of the above address struct. ); if (_iNumOfBytesReceived < 0) { int _iError = WSAGetLastError(); ErrorRoutines::PrintWSAErrorInfo(_iError); //return false; } else { _iPacketSize = static_cast<int>(strlen(_buffer)) + 1; strcpy_s(_pcBufferToReceiveData, _iPacketSize, _buffer); char _IPAddress[100]; inet_ntop(AF_INET, &m_ClientAddress.sin_addr, _IPAddress, sizeof(_IPAddress)); std::cout << "Server Received \"" << _pcBufferToReceiveData << "\" from " << _IPAddress << ":" << ntohs(m_ClientAddress.sin_port) << std::endl; //Push this packet data into the WorkQ m_pWorkQueue->push(std::make_pair(m_ClientAddress,_pcBufferToReceiveData)); } //std::this_thread::yield(); } //End of while (true) } void CServer::GetRemoteIPAddress(char *_pcSendersIP) { char _temp[MAX_ADDRESS_LENGTH]; int _iAddressLength; inet_ntop(AF_INET, &(m_ClientAddress.sin_addr), _temp, sizeof(_temp)); _iAddressLength = static_cast<int>(strlen(_temp)) + 1; strcpy_s(_pcSendersIP, _iAddressLength, _temp); } unsigned short CServer::GetRemotePort() { return ntohs(m_ClientAddress.sin_port); } std::string XOR(std::string input, int key, bool encode) { std::string output = ""; std::string split = "\\"; std::string tmpstr = ""; std::vector<int> toDecode; char decodeTMP; int position = 0; int xor = 0; if (encode) { int xor = 0; for (size_t i = 0; i < input.length(); i++) { xor = ((input.at(i)) ^ key); output += std::to_string(xor) + split; } } else { //decode for (size_t i = 0; i < input.length(); i++) { if (input.at(i) != split.at(0)) { tmpstr += input.at(i); } else { //std::cout << tmpstr << std::endl; toDecode.push_back(std::atoi(tmpstr.c_str())); tmpstr = ""; } } //std::cout << tmpstr << std::endl; toDecode.push_back(std::atoi(tmpstr.c_str())); tmpstr = ""; for (size_t k = 0; k < toDecode.size(); k++) { xor = (toDecode.at(k) ^ key); //decode decodeTMP = xor; //convert to ascii output += decodeTMP; //add to output } } return output; } void CServer::CheckPulse() { TPacket _packetToSend; std::string templ = "Ping"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if (((*m_pConnectedClients)[it->first].SECURITY.authStatus != (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHING) || (*m_pConnectedClients)[it->first].SECURITY.markedforDeath) { //only check authed clients std::string message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(KEEPALIVE, const_cast<char*>(message.c_str())); (*m_pConnectedClients)[it->first].m_bIsAlive = false; SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } } void CServer::DropTheDead(){ TPacket _packetToSend; std::string templ = ""; std::string message = ""; int amountremoved = 0; std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); while (it != (*m_pConnectedClients).end()) { if (((*m_pConnectedClients)[it->first].SECURITY.authStatus != (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHING) || (*m_pConnectedClients)[it->first].SECURITY.markedforDeath) { //only check authed clients if (!(*m_pConnectedClients)[it->first].m_bIsAlive) { templ += "$END User: " + (*m_pConnectedClients)[it->first].SECURITY.authUser + " disconnected (Timed Out)"; (*m_pConnectedClients).erase(it); it = (*m_pConnectedClients).begin(); } else { ++it; } } else {//otherwise if we are authing the client then check a flag to say client has taken at least one dead loop and if it is marked next time to drop it (*m_pConnectedClients)[it->first].SECURITY.markedforDeath = true; ++it; } } if (templ != "") { for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { //only authed clients can see msgs message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } } } void CServer::ProcessData(std::pair<sockaddr_in, std::string> dataItem) { TPacket _packetRecvd, _packetToSend; _packetRecvd = _packetRecvd.Deserialize(const_cast<char*>(dataItem.second.c_str())); switch (_packetRecvd.MessageType) { case INITCONN: { std::string message = ""; std::cout << "Server received a request to start a handshake" << std::endl; if (AddClient(_packetRecvd.MessageContent)) { //Qs 3: To DO : Add the code to do a handshake here //If this is first AUTH then we need create an xor challenge std::map<std::string, char> m; int key = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key; m_pConnectedClients->at(ToString(m_ClientAddress)).SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHING; message = "%" + XOR((dataItem.second.substr(2, dataItem.second.length()) + "#" + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b1) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b2) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b3) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b4)), key, true); //ADD XOR KEY ON int amountofch = static_cast<int>(floor(key / 10)); for (size_t i = 0; i < amountofch; i++) { int tmp = (48 + rand() % 78); char ctmp = tmp; message = ctmp + message; } _packetToSend.Serialize(AUTHCH, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); } else { std::cout << "Could not add user" << std::endl; } break; } case AUTHRE: { std::cout << "Server received a handshake response" << std::endl; std::string message = "ACCEPT"; std::string check = ""; //CHECK RESPONSE int key = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key; check = XOR(_packetRecvd.MessageContent, key, false); //decode if (check.find((*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser) != std::string::npos) { //correct response std::cout << "HANDSHAKE COMPLETED" << std::endl; _packetToSend.Serialize(AUTHRE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); message = MOTD + "Welcome to the chat " + (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + "$ENDUsers in Chat:"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { message += "$END [" + (*m_pConnectedClients)[it->first].SECURITY.authUser + "]"; } message += "$END"; _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE; (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.markedforDeath = false; //reset if was set by drop dead //Send to each user that user has joined chat std::string templ = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + " has connected to the chat!"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { std::string message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } else { //incorrect response std::cout << "HANDSHAKE FAILED" << std::endl; message = "REJECT"; _packetToSend.Serialize(AUTHRE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.NOAUTH; message = "QUIT"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); m_pConnectedClients->erase(ToString(m_ClientAddress)); //remove user from list } } case DATA: { if ((*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { std::string message = XOR(_packetRecvd.MessageContent, (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key, false); //decode std::cout << "Decoded: " << message << std::endl; message = message.substr(0, message.length()-1); //fix padding bool isCommand = false; if (message.length() >= 1){ //stop null strings from crashing server if (message.at(0) == COMMANDID.at(0)) { isCommand = true; } if (!isCommand){ //Chat //Send to each user message = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + "> " + message; std::string templ = message; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { //only authed clients can see msgs message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } } else { //Command if (message == COMMANDHELP) { message = HELP; } else if (message.find(COMMANDCHGMOTD) != std::string::npos) { if (message.length() > (COMMANDCHGMOTD.length() + 1)) { MOTD = message.substr(COMMANDCHGMOTD.length() + 1, message.length()); message = "motd changed to: " + MOTD; } } else if (message == COMMANDMOTD) { message = MOTD; } else if (message.find(COMMANDKICK) != std::string::npos) { if (message.length() > (COMMANDKICK.length() + 1)) { std::string target = message.substr(COMMANDKICK.length() + 1, message.length()); bool hasKicked = false; std::map<std::string, TClientDetails>::const_iterator targetLock; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authUser == target) { (*m_pConnectedClients)[it->first].SECURITY.authStatus = (*m_pConnectedClients)[it->first].SECURITY.NOAUTH; (*m_pConnectedClients)[it->first].SECURITY.markedforDeath = true; std::string message = XOR("You have been kicked from the server", (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); message = "QUIT"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); hasKicked = true; targetLock = it; } } if (hasKicked) { std::string templ = (*m_pConnectedClients)[targetLock->first].SECURITY.authUser + " has been kicked from the chat!"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { std::string message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } m_pConnectedClients->erase(targetLock); //remove user from list } else { std::string message = XOR("Could not find username", (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); } } } else if (message == COMMANDQUIT) { //CLOSE CONNECTION (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authStatus = (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.NOAUTH; //Deauth user message = "User: " + (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.authUser + " has disconnected (User Disconnect)"; std::string templ = message; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { if ((*m_pConnectedClients)[it->first].SECURITY.authStatus == (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.AUTHCOMPLETE) { //only authed clients can see msgs message = XOR(templ, (*m_pConnectedClients)[it->first].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[it->first].m_ClientAddress); } } message = "QUIT"; _packetToSend.Serialize(CLOSE, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); m_pConnectedClients->erase(ToString(m_ClientAddress)); //remove user from list } else if (message == COMMANDLIST) { message = "$ENDUsers in Chat:"; for (std::map<std::string, TClientDetails>::const_iterator it = (*m_pConnectedClients).begin(); it != (*m_pConnectedClients).end(); ++it) { message += "$END [" + (*m_pConnectedClients)[it->first].SECURITY.authUser + "]"; } message += "$END"; } else { message = "Unknown Command"; } message = XOR(message, (*m_pConnectedClients)[ToString(m_ClientAddress)].SECURITY.key, true); //encode _packetToSend.Serialize(DATA, const_cast<char*>(message.c_str())); SendDataTo(_packetToSend.PacketData, (*m_pConnectedClients)[ToString(m_ClientAddress)].m_ClientAddress); } } } else { std::string out = (std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b1) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b2) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b3) + "." + std::to_string(dataItem.first.sin_addr.S_un.S_un_b.s_b4)); std::cout << "CLIENT WAS BLOCKED FROM USING SERVER AS THEY ARE NOT AUTHED: " << out << std::endl; out = "REJECT"; _packetToSend.Serialize(AUTHRE, const_cast<char*>(out.c_str())); SendDataTo(_packetToSend.PacketData, dataItem.first); } break; } case BROADCAST: { std::cout << "Received a broadcast packet" << std::endl; //Just send out a packet to the back to the client again which will have the server's IP and port in it's sender fields std::string message = "<SERVER INFO>"; _packetToSend.Serialize(BROADCASTINIT, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); break; } case KEEPALIVEC: { std::string message = "<SERVER INFO>"; _packetToSend.Serialize(KEEPALIVEC, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); break; } case KEEPALIVE: { m_pConnectedClients->at(ToString(m_ClientAddress)).m_bIsAlive = true; //we have ping-pong break; } default: std::string message = "You are not authorised to connect to this server!"; //go from 0-10 and give error msg _packetToSend.Serialize(PACKERROR, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR1, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR2, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR3, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR4, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR5, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR6, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR7, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR8, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR9, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); _packetToSend.Serialize(PACKERROR10, const_cast<char*>(message.c_str())); SendData(_packetToSend.PacketData); break; } } CWorkQueue<std::pair<sockaddr_in, std::string>>* CServer::GetWorkQueue() { return m_pWorkQueue; }
39.15082
350
0.679549
henry9836
1090a9fb484f4c10c2600fd71d0ac46dc4b445c3
490
cpp
C++
engine/src/PhysicsEngine/API/ActivationListener.cpp
nuclearkevin/Strontium
88045e7ab50f614bbbcb8c283e2a7802fd435207
[ "MIT" ]
null
null
null
engine/src/PhysicsEngine/API/ActivationListener.cpp
nuclearkevin/Strontium
88045e7ab50f614bbbcb8c283e2a7802fd435207
[ "MIT" ]
null
null
null
engine/src/PhysicsEngine/API/ActivationListener.cpp
nuclearkevin/Strontium
88045e7ab50f614bbbcb8c283e2a7802fd435207
[ "MIT" ]
null
null
null
#include "PhysicsEngine/API/ActivationListener.h" // Project includes. #include "Core/Logs.h" // THIS MUST BE THREAD SAFE namespace Strontium::PhysicsEngine { ActivationListener::ActivationListener() { } ActivationListener::~ActivationListener() { } void ActivationListener::OnBodyActivated(const JPH::BodyID &inBodyID, JPH::uint64 inBodyUserData) { } void ActivationListener::OnBodyDeactivated(const JPH::BodyID &inBodyID, JPH::uint64 inBodyUserData) { } }
22.272727
96
0.738776
nuclearkevin
10a5e59cbd5f17b1323edd441eb4c343b699da6e
3,371
cpp
C++
utility/BoundingBox.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
utility/BoundingBox.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
utility/BoundingBox.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
#include "utility/BoundingBox.hpp" #include <algorithm> namespace math { BoundingBox::BoundingBox(const math::Vertex& min, const math::Vertex& max) { setCorners(min, max); } void BoundingBox::transform(const math::Matrix& mat) { float min = std::numeric_limits<float>::lowest(); float max = std::numeric_limits<float>::max(); math::Vertex newMin = {max, max, max}; math::Vertex newMax = {min, min, min}; math::Vertex corners[8]; getCorners(corners); for (auto& v : corners) { v = math::Vertex::Transform(v, mat); newMin = takeMinimum(newMin, v); newMax = takeMaximum(newMax, v); } setCorners(newMin, newMax); } void BoundingBox::setCorners(const math::Vertex& min, const math::Vertex& max) { MinCorner = min; MaxCorner = max; } void BoundingBox::getCorners(math::Vertex corners[8]) const { corners[0] = {MinCorner.X, MinCorner.Y, MinCorner.Z}; corners[1] = {MaxCorner.X, MinCorner.Y, MinCorner.Z}; corners[2] = {MaxCorner.X, MaxCorner.Y, MinCorner.Z}; corners[3] = {MinCorner.X, MaxCorner.Y, MinCorner.Z}; corners[4] = {MinCorner.X, MinCorner.Y, MaxCorner.Z}; corners[5] = {MaxCorner.X, MinCorner.Y, MaxCorner.Z}; corners[6] = {MaxCorner.X, MaxCorner.Y, MaxCorner.Z}; corners[7] = {MinCorner.X, MaxCorner.Y, MaxCorner.Z}; } void BoundingBox::connectWith(const BoundingBox& b) { MinCorner = takeMinimum(MinCorner, b.MinCorner); MaxCorner = takeMaximum(MaxCorner, b.MaxCorner); } void BoundingBox::update(const math::Vector3& v) { MinCorner.X = (std::min)(MinCorner.X, v.X); MaxCorner.X = (std::max)(MaxCorner.X, v.X); MinCorner.Y = (std::min)(MinCorner.Y, v.Y); MaxCorner.Y = (std::max)(MaxCorner.Y, v.Y); MinCorner.Z = (std::min)(MinCorner.Z, v.Z); MaxCorner.Z = (std::max)(MaxCorner.Z, v.Z); } float BoundingBox::getVolume() const { math::Vector3 e = MaxCorner - MinCorner; return e.X * e.Y * e.Z; } float BoundingBox::getSurfaceArea() const { math::Vector3 e = MaxCorner - MinCorner; return 2.0f * (e.X * e.Y + e.X * e.Z + e.Y * e.Z); } math::Vector3 BoundingBox::getCenter() const { return 0.5f * (MaxCorner + MinCorner); } math::Vector3 BoundingBox::getExtent() const { return 0.5f * (MaxCorner - MinCorner); } math::Vector3 BoundingBox::getVector() const { return MaxCorner - MinCorner; } const math::Vector3& BoundingBox::getMinimum() const { return MinCorner; } const math::Vector3& BoundingBox::getMaximum() const { return MaxCorner; } bool BoundingBox::intersect2d(const BoundingBox& b) const { if (MaxCorner.X < b.MinCorner.X) return false; if (MinCorner.X > b.MaxCorner.X) return false; if (MaxCorner.Y < b.MinCorner.Y) return false; if (MinCorner.Y > b.MaxCorner.Y) return false; return true; } bool BoundingBox::intersect(const BoundingBox& b) const { if (!intersect2d(b)) return false; if (MaxCorner.Z < b.MinCorner.Z) return false; if (MinCorner.Z > b.MaxCorner.Z) return false; return true; // boxes overlap } std::ostream& operator<<(std::ostream& o, const BoundingBox& b) { o << b.MinCorner << b.MaxCorner; return o; } std::istream& operator>>(std::istream& i, BoundingBox& b) { i >> b.MinCorner >> b.MaxCorner; return i; } } // namespace math
23.573427
78
0.643429
coolzoom
10a7f4d0f9d6cf651919cc9afaa9a60453cf2f31
595
hpp
C++
include/cvtools.hpp
Biblbrox/point-cloud-annotation-tool
66947974914243af8e5f1bb622ffaa93c2fdb47d
[ "MIT" ]
null
null
null
include/cvtools.hpp
Biblbrox/point-cloud-annotation-tool
66947974914243af8e5f1bb622ffaa93c2fdb47d
[ "MIT" ]
null
null
null
include/cvtools.hpp
Biblbrox/point-cloud-annotation-tool
66947974914243af8e5f1bb622ffaa93c2fdb47d
[ "MIT" ]
null
null
null
#ifndef CVTOOLS_HPP #define CVTOOLS_HPP #include <opencv2/imgproc.hpp> #include <algorithm> namespace cvtools { /** * Add border to image * @param mat * @param borderSize * @return */ cv::Mat addBorder(const cv::Mat& mat, int borderSize); /** * Calculate truncation of rect in image coordinates. * @param mat * @param rect * @param mat * @param rect * @param imgPos * @return float from 0 to 1x */ float calcTruncated(const cv::Mat& mat, const cv::Rect& rect, const cv::Point& imgPos); }; #endif //CVTOOLS_HPP
19.833333
91
0.610084
Biblbrox
10a831ddd2342ec7a67a532f9ed465005f71bc9e
4,561
cpp
C++
Source/Game/MainMenuState.cpp
Fiskmans/Old_Betsy
6610586165250d21de9b9efb57b4e8e56e82ecdf
[ "MIT" ]
3
2021-05-06T19:54:20.000Z
2021-05-06T21:15:50.000Z
Source/Game/MainMenuState.cpp
Fiskmans/Old_Betsy
6610586165250d21de9b9efb57b4e8e56e82ecdf
[ "MIT" ]
null
null
null
Source/Game/MainMenuState.cpp
Fiskmans/Old_Betsy
6610586165250d21de9b9efb57b4e8e56e82ecdf
[ "MIT" ]
null
null
null
#include "pch.h" #include "MainMenuState.h" #include "GraphicEngine.h" #include "DirectX11Framework.h" #include "SpriteInstance.h" #include <Xinput.h> #include "AssetManager.h" #include "GamlaBettan\Scene.h" MainMenuState::MainMenuState(bool aShouldDeleteOnPop) : BaseState(aShouldDeleteOnPop), Observer( { MessageType::InputMouseMoved }), myStateInitData{ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } { SetUpdateThroughEnabled(false); SetDrawThroughEnabled(false); myBackground = nullptr; myMousePointer = nullptr; } MainMenuState::~MainMenuState() { Deactivate(); for (Button* button : myButtons) { delete button; } myButtons.clear(); delete myMousePointer; delete myBackground; WIPE(*this); } void MainMenuState::Update(const float aDeltaTime) { if (myGameStateToStart) { myGameStateToStart->PreSetup(aDeltaTime); } #if DIRECTTOGAME static bool first = true; if (first) { myPlayButton.TriggerOnPressed(); first = false; } #endif } void MainMenuState::RecieveMessage(const Message& aMessage) { if (aMessage.myMessageType == MessageType::InputMouseMoved) { myMousePointer->SetPosition(*reinterpret_cast<const V2f*>(aMessage.myData)); } } bool MainMenuState::Init(InputManager* aInputManager, SpriteFactory* aSpritefactory, LightLoader* aLightLoader, DirectX11Framework* aFramework, AudioManager* aAudioManager, SpriteRenderer* aSpriteRenderer) { myIsMain = true; myMousePointer = aSpritefactory->CreateSprite("ui/mouse.dds"); myStateInitData.myFrameWork = aFramework; myStateInitData.myInputManager = aInputManager; myStateInitData.myLightLoader = aLightLoader; myStateInitData.mySpriteFactory = aSpritefactory; myStateInitData.myAudioManager = aAudioManager; myStateInitData.mySpriteRenderer = aSpriteRenderer; InitLayout(aSpritefactory); return true; } void MainMenuState::Render(CGraphicsEngine* aGraphicsEngine) { aGraphicsEngine->RenderFrame(); } void MainMenuState::Activate() { for (Button* button : myButtons) { button->Enable(); } Scene::GetInstance().AddToScene(myMousePointer); Scene::GetInstance().AddToScene(myBackground); } void MainMenuState::Deactivate() { for (Button* button : myButtons) { button->Disable(); } Scene::GetInstance().RemoveFromScene(myMousePointer); Scene::GetInstance().RemoveFromScene(myBackground); } void MainMenuState::Unload() { } void MainMenuState::InitLayout(SpriteFactory* aSpritefactory) { FiskJSON::Object& root = AssetManager::GetInstance().GetJSON("menu/MainMenuLayout.json").GetAsJSON(); std::string imagesPath = root["ImagesPath"].Get<std::string>(); myBackground = aSpritefactory->CreateSprite(imagesPath + "\\" + root["GameTitleImage"]["name"].Get<std::string>()); myBackground->SetPosition({ root["GameTitleImage"]["PosX"].Get<float>(), root["GameTitleImage"]["PosY"].Get<float>() }); myBackground->SetUVMinMaxInTexels(V2f(0, 0), V2f(1920.f, 1080.f)); myBackground->SetDepth(1.f); myBackground->SetSize(V2f(1, 1)); Button* playButton = new Button(); Button* exitButton = new Button(); playButton->Init(imagesPath, root["StartButton"]["name"].Get<std::string>(), { root["StartButton"]["PosX"].Get<float>(), root["StartButton"]["PosY"].Get<float>() }, V2f(0.545f, 1.f), aSpritefactory); exitButton->Init(imagesPath, root["ExitButton"]["name"].Get<std::string>(), { root["ExitButton"]["PosX"].Get<float>(), root["ExitButton"]["PosY"].Get<float>() }, V2f(0.545f, 1.f), aSpritefactory); if (!myGameStateToStart) { myGameStateToStart = CreateGameState(0); } playButton->SetOnPressedFunction([this]() -> void { Message message; message.myMessageType = MessageType::PushState; if (myGameStateToStart) { message.myData = myGameStateToStart; myGameStateToStart = nullptr; } else { message.myData = CreateGameState(0); } PostMaster::GetInstance().SendMessages(message); }); exitButton->SetOnPressedFunction([this]() -> void { bool mainState = true; PostMaster::GetInstance().SendMessages(MessageType::PopState,&mainState); }); myButtons.push_back(playButton); myButtons.push_back(exitButton); } GameState* MainMenuState::CreateGameState(const int& aStartLevel) { GameState* state = new GameState(); if (state->Init(myStateInitData.myInputManager, myStateInitData.mySpriteFactory, myStateInitData.myLightLoader, myStateInitData.myFrameWork, myStateInitData.myAudioManager, myStateInitData.mySpriteRenderer) == false) { delete state; return nullptr; } state->SetMain(true); state->LoadLevel(aStartLevel); return state; }
25.338889
201
0.740627
Fiskmans
10a8f11069f0035c59ae3fdba72c2e7128d7aee0
426
cpp
C++
AtCoder/ABC187/C.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
AtCoder/ABC187/C.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
AtCoder/ABC187/C.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; unordered_set<string> sSet; string s; for(int i = 0; i < n; ++i){ cin >> s; sSet.insert(s); } string answer = "satisfiable"; for(string s: sSet){ if(sSet.count("!" + s)){ answer = s; break; } } cout << answer; return 0; }
16.384615
35
0.42723
Tudor67
10aa0375a751f008a6f77356abc3511d7bcce66f
2,125
cpp
C++
tests/quasiquote_tests.cpp
rosholger/Lispis
16eaa785580b5ea2b1ff5a0e0c6e9f006af9b1bd
[ "MIT" ]
3
2017-05-02T14:50:18.000Z
2020-04-22T08:11:31.000Z
tests/quasiquote_tests.cpp
rosholger/Lispis
16eaa785580b5ea2b1ff5a0e0c6e9f006af9b1bd
[ "MIT" ]
null
null
null
tests/quasiquote_tests.cpp
rosholger/Lispis
16eaa785580b5ea2b1ff5a0e0c6e9f006af9b1bd
[ "MIT" ]
null
null
null
#include "tests.h" TEST(quoteEqualQuasiquote) { TEST_SETUP; RUN_STR(q, s1, "'(a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923)))"); RUN_STR(qq, s2, "(quasiquote (a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923))))"); t_assert("quote equals quasiquote", deepEqual(q, qq) && s1 && s2); } TEST(quoteEqualQuasiquoteUnquote) { TEST_SETUP; RUN_STR(q, s1, "'(a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923)))"); RUN_STR(qq, s2, "(let! t '(23 + 8545 . a))" "(quasiquote (a b c 1 (unquote t)" "(((aksf ag) asd) . (asd 923))))"); t_assert("quote equals quasiquote", deepEqual(q, qq) && s1 && s2); } TEST(quoteEqualQuasiquoteUnquoteSplice) { TEST_SETUP; RUN_STR(q, s1, "'(asd sasd asd dass sasd ads asd " " a b c 1 (23 + 8545 . a) (((aksf ag) asd) . (asd 923)))"); RUN_STR(qq, s2, "(let! t '(23 + 8545 . a))" "(let! t2 '((((aksf ag) asd) . (asd 923))))" "(quasiquote (asd sasd asd dass sasd ads asd " " a b c 1 (unquote t)" "(unquote-splice t2)))"); t_assert("quote equals quasiquote", deepEqual(q, qq) && s1 && s2); } // Thinks that define! is a function, that is a LARGE bug TEST(quasiquoteDefine) { TEST_SETUP; #if 1 RUN_STR(res, s, "(quasiquote (a (unquote (define! a 1))))" "a"); t_assert("unquoted define", unpackInt(res) == 1 && s); #else t_assert("unquoted define", false); #endif } TEST(quasiquoteNestingBasic) { TEST_SETUP; RUN_STR(res1, s1, "(let! a 1) ``,a"); RUN_STR(res2, s2, "`(quasiquote (unquote a))"); t_assert("basic quasiquote nesting", (s1 && s2 && deepEqual(res1, res2))); } TEST(quasiquoteNestingUnquote) { TEST_SETUP; RUN_STR(res1, s1, "(let! a 1) ``,,a"); RUN_STR(res2, s2, "`(quasiquote (unquote 1))"); t_assert("quasiquote unquote nesting", (s1 && s2 && deepEqual(res1, res2))); }
31.25
84
0.505412
rosholger
10b8f89c528690f720871e29821ceb9ba01ef0c6
647
cpp
C++
array.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
array.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
array.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int size = 5; //Initialize array int Roll_Number[] = {100,101,102,103,104}; //print array for (int i = 0; i < size; i++){ //Access element at index i cout << Roll_Number[i] << " "; } cout << endl; // Update values of array element at index 3 and 4 Roll_Number[3] = 22222; Roll_Number[4] = 33333; cout << "Values of array after updation: " << endl; //Print updated values of array for (int i = 0; i < size; i++){ //Access elements of array at index i cout << Roll_Number[i] << " "; } cout << endl; }
23.962963
55
0.553323
gptakhil
10bd4ffae98d8423d847bcb6d83ad774bbf2ea9f
312
cpp
C++
src/StraightEnemyMove.cpp
yubeneko/Shooting_2D
614476bd9fec654535e05e349b122d076ccd76e5
[ "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
1
2022-03-18T08:16:22.000Z
2022-03-18T08:16:22.000Z
src/StraightEnemyMove.cpp
yubeneko/Shooting_2D
614476bd9fec654535e05e349b122d076ccd76e5
[ "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
src/StraightEnemyMove.cpp
yubeneko/Shooting_2D
614476bd9fec654535e05e349b122d076ccd76e5
[ "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
#include "StraightEnemyMove.h" #include "Actor.h" StraightEnemyMove::StraightEnemyMove(Actor* owner, int updateOrder) : Component(owner, updateOrder) { } void StraightEnemyMove::Update(float deltaTime) { glm::vec2 pos = mOwner->GetPosition(); pos.x += mRightSpeed * deltaTime; mOwner->SetPosition(pos); }
20.8
67
0.746795
yubeneko
10c8eec391aeb73be4da1128f631c31763b58841
2,154
cpp
C++
Official Windows Platform Sample/Windows 8.1 desktop samples/[C++]-Windows 8.1 desktop samples/Input Method Editor (IME) sample/C++/SampleIME/DisplayAttributeProvider.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/IME/cpp/SampleIME/DisplayAttributeProvider.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Samples/IME/cpp/SampleIME/DisplayAttributeProvider.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "Private.h" #include "globals.h" #include "SampleIME.h" #include "DisplayAttributeInfo.h" #include "EnumDisplayAttributeInfo.h" //+--------------------------------------------------------------------------- // // ITfDisplayAttributeProvider::EnumDisplayAttributeInfo // //---------------------------------------------------------------------------- STDAPI CSampleIME::EnumDisplayAttributeInfo(__RPC__deref_out_opt IEnumTfDisplayAttributeInfo **ppEnum) { CEnumDisplayAttributeInfo* pAttributeEnum = nullptr; if (ppEnum == nullptr) { return E_INVALIDARG; } *ppEnum = nullptr; pAttributeEnum = new (std::nothrow) CEnumDisplayAttributeInfo(); if (pAttributeEnum == nullptr) { return E_OUTOFMEMORY; } *ppEnum = pAttributeEnum; return S_OK; } //+--------------------------------------------------------------------------- // // ITfDisplayAttributeProvider::GetDisplayAttributeInfo // //---------------------------------------------------------------------------- STDAPI CSampleIME::GetDisplayAttributeInfo(__RPC__in REFGUID guidInfo, __RPC__deref_out_opt ITfDisplayAttributeInfo **ppInfo) { if (ppInfo == nullptr) { return E_INVALIDARG; } *ppInfo = nullptr; // Which display attribute GUID? if (IsEqualGUID(guidInfo, Global::SampleIMEGuidDisplayAttributeInput)) { *ppInfo = new (std::nothrow) CDisplayAttributeInfoInput(); if ((*ppInfo) == nullptr) { return E_OUTOFMEMORY; } } else if (IsEqualGUID(guidInfo, Global::SampleIMEGuidDisplayAttributeConverted)) { *ppInfo = new (std::nothrow) CDisplayAttributeInfoConverted(); if ((*ppInfo) == nullptr) { return E_OUTOFMEMORY; } } else { return E_INVALIDARG; } return S_OK; }
26.268293
125
0.579851
zzgchina888
10c9bbf2a00f59dc3739a171357a9ac3b6af25c7
136
cpp
C++
cppcode/cpp execise/day02/main.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day02/main.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day02/main.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; extern "C" int add (int, int); int main (void) { cout << add (123, 456) << endl; return 0; }
17
32
0.632353
jiedou
10cedd7e2501814e0a6470110e97c6e2f2154d6f
547
cpp
C++
Example/Network/Http/Http/ConnectionMgr.cpp
chenyu2202863/iocpframework
292fbf820af0d96b1d3be18d3616dce3e421f9c2
[ "FSFAP" ]
51
2015-01-28T08:50:43.000Z
2022-02-28T02:31:47.000Z
Example/Network/Http/Http/ConnectionMgr.cpp
lvyong1943/iocpframework
292fbf820af0d96b1d3be18d3616dce3e421f9c2
[ "FSFAP" ]
1
2016-09-26T06:38:44.000Z
2016-10-16T11:42:02.000Z
Example/Network/Http/Http/ConnectionMgr.cpp
lvyong1943/iocpframework
292fbf820af0d96b1d3be18d3616dce3e421f9c2
[ "FSFAP" ]
52
2015-01-10T08:28:52.000Z
2021-10-30T12:10:23.000Z
#include "stdafx.h" #include "ConnectionMgr.h" namespace http { void ConnectionMgr::Start(const ConnectionPtr &c) { { AutoLock lock(lock_); connections_.insert(c); } c->Start(); } void ConnectionMgr::Stop(const ConnectionPtr &c) { { AutoLock lock(lock_); connections_.erase(c); } c->Stop(); } void ConnectionMgr::StopAll() { std::for_each(connections_.begin(), connections_.end(), std::tr1::bind(&Connection::Stop, std::placeholders::_1)); { AutoLock lock(lock_); connections_.clear(); } } }
14.394737
61
0.645338
chenyu2202863
10d4060ff81c8fe4932b765600f9bb22f9bb92db
41,288
cpp
C++
agent/browser/ie/pagetest/TestState.cpp
LeeLiangze/web_test
50ce21afb153b105569e31ef08ddc098743208e5
[ "IJG" ]
null
null
null
agent/browser/ie/pagetest/TestState.cpp
LeeLiangze/web_test
50ce21afb153b105569e31ef08ddc098743208e5
[ "IJG" ]
null
null
null
agent/browser/ie/pagetest/TestState.cpp
LeeLiangze/web_test
50ce21afb153b105569e31ef08ddc098743208e5
[ "IJG" ]
null
null
null
/* Copyright (c) 2005-2007, AOL, LLC. 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 company 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 "StdAfx.h" #include "TestState.h" #include <atlutil.h> #include <Mmsystem.h> #include "Psapi.h" CTestState::CTestState(void): hTimer(0) ,lastBytes(0) ,lastCpuIdle(0) ,lastCpuKernel(0) ,lastCpuUser(0) ,lastTime(0) ,imageCount(0) ,lastImageTime(0) ,lastRealTime(0) ,cacheCleared(false) ,heartbeatEvent(NULL) { // Load the ad regular expressions from disk. LoadAdPatterns(); } CTestState::~CTestState(void) { if( heartbeatEvent ) CloseHandle(heartbeatEvent); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CTestState::Reset(void) { __super::Reset(); EnterCriticalSection(&cs); currentState = READYSTATE_UNINITIALIZED; painted = false; SetBrowserWindowUpdated(true); LeaveCriticalSection(&cs); } /*----------------------------------------------------------------------------- Do all of the startup checks and evaluations -----------------------------------------------------------------------------*/ void CTestState::DoStartup(CString& szUrl, bool initializeDoc) { USES_CONVERSION; CString msg; if( !active && available ) { msg.Format(_T("[Pagetest] *** DoStartup() - '%s'\n"), (LPCTSTR)szUrl); OutputDebugString(msg); bool ok = true; CheckABM(); domElementId.Empty(); domRequest.Empty(); domRequestType = END; endRequest.Empty(); if( interactive ) { checkOpt = true; if( runningScript ) { CString szEventName = szUrl; // default this to the url for right now if( !script_eventName.IsEmpty() ) szEventName = script_eventName; domElementId = script_domElement; domRequest = script_domRequest; domRequestType = script_domRequestType; endRequest = script_endRequest; if( script_timeout != -1 ) timeout = script_timeout; if( script_activity_timeout ) activityTimeout = script_activity_timeout; if( !szEventName.IsEmpty() && szEventName == somEventName ) ok = false; else somEventName = szEventName; } } else { // load the automation settings from the registry CRegKey key; if( key.Open(HKEY_CURRENT_USER, _T("Software\\America Online\\SOM"), KEY_READ | KEY_WRITE) == ERROR_SUCCESS ) { CString szEventName = szUrl; // default this to the url for right now TCHAR buff[100000]; ULONG len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("EventName"), buff, &len) == ERROR_SUCCESS ) szEventName = buff; if( runningScript ) { if( script_active ) { if( !script_eventName.IsEmpty() ) { if( szEventName.IsEmpty() ) szEventName = script_eventName; else { if( !szEventName.Replace(_T("%STEP%"), (LPCTSTR)script_eventName) ) szEventName += CString(_T("_")) + script_eventName; } } domElementId = script_domElement; domRequest = script_domRequest; domRequestType = script_domRequestType; endRequest = script_endRequest; } else ok = false; } else { len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("DOM Element ID"), buff, &len) == ERROR_SUCCESS ) if( lstrlen(buff) ) domElementId = buff; key.DeleteValue(_T("DOM Element ID")); } len = sizeof(buff) / sizeof(TCHAR); logFile.Empty(); if( key.QueryStringValue(_T("IEWatchLog"), buff, &len) == ERROR_SUCCESS ) logFile = buff; len = sizeof(buff) / sizeof(TCHAR); linksFile.Empty(); if( key.QueryStringValue(_T("Links File"), buff, &len) == ERROR_SUCCESS ) linksFile = buff; key.DeleteValue(_T("Links File")); len = sizeof(buff) / sizeof(TCHAR); s404File.Empty(); if( key.QueryStringValue(_T("404 File"), buff, &len) == ERROR_SUCCESS ) s404File = buff; key.DeleteValue(_T("404 File")); len = sizeof(buff) / sizeof(TCHAR); htmlFile.Empty(); if( key.QueryStringValue(_T("HTML File"), buff, &len) == ERROR_SUCCESS ) htmlFile = buff; key.DeleteValue(_T("HTML File")); len = sizeof(buff) / sizeof(TCHAR); cookiesFile.Empty(); if( key.QueryStringValue(_T("Cookies File"), buff, &len) == ERROR_SUCCESS ) cookiesFile = buff; key.DeleteValue(_T("Cookies File")); // if we're running a script, the block list will come from the script if( !runningScript ) { len = sizeof(buff) / sizeof(TCHAR); blockRequests.RemoveAll(); if( key.QueryStringValue(_T("Block"), buff, &len) == ERROR_SUCCESS ) { CString block = buff; int pos = 0; CString token = block.Tokenize(_T(" "), pos); while( pos >= 0 ) { token.Trim(); blockRequests.AddTail(token); token = block.Tokenize(_T(" "), pos); } } key.DeleteValue(_T("Block")); } len = sizeof(buff) / sizeof(TCHAR); basicAuth.Empty(); if( key.QueryStringValue(_T("Basic Auth"), buff, &len) == ERROR_SUCCESS ) { basicAuth = buff; script_basicAuth = buff; } key.DeleteValue(_T("Basic Auth")); if( ok ) { if( runningScript ) logUrl[0]=0; else { len = _countof(logUrl); key.QueryStringValue(_T("URL"), logUrl, &len); } key.QueryDWORDValue(_T("Cached"), cached); includeObjectData = 1; key.QueryDWORDValue(_T("Include Object Data"), includeObjectData); saveEverything = 0; key.QueryDWORDValue(_T("Save Everything"), saveEverything); captureVideo = 0; key.QueryDWORDValue(_T("Capture Video"), captureVideo); checkOpt = 1; key.QueryDWORDValue(_T("Check Optimizations"), checkOpt); ignoreSSL = 0; key.QueryDWORDValue(_T("ignoreSSL"), ignoreSSL); blockads = 0; key.QueryDWORDValue(_T("blockads"), blockads); pngScreenShot = 0; key.QueryDWORDValue(_T("pngScreenShot"), pngScreenShot); imageQuality = JPEG_DEFAULT_QUALITY; key.QueryDWORDValue(_T("imageQuality"), imageQuality); imageQuality = max(JPEG_DEFAULT_QUALITY, min(100, imageQuality)); bodies = 0; key.QueryDWORDValue(_T("bodies"), bodies); htmlbody = 0; key.QueryDWORDValue(_T("htmlbody"), htmlbody); keepua = 0; key.QueryDWORDValue(_T("keepua"), keepua); minimumDuration = 0; key.QueryDWORDValue(_T("minimumDuration"), minimumDuration); clearShortTermCacheSecs = 0; key.QueryDWORDValue(_T("clearShortTermCacheSecs"), clearShortTermCacheSecs); noHeaders = 0; key.QueryDWORDValue(_T("No Headers"), noHeaders); noImages = 0; key.QueryDWORDValue(_T("No Images"), noImages); len = sizeof(buff) / sizeof(TCHAR); customHost.Empty(); if( key.QueryStringValue(_T("Host"), buff, &len) == ERROR_SUCCESS ) customHost = buff; if( !heartbeatEvent ) { len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("Heartbeat Event"), buff, &len) == ERROR_SUCCESS ) heartbeatEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, buff); } if( heartbeatEvent ) SetEvent(heartbeatEvent); if( !runningScript ) { len = _countof(descriptor); key.QueryStringValue(_T("Descriptor"), descriptor, &len); // delete values that shouldn't be re-used key.DeleteValue(_T("Descriptor")); key.DeleteValue(_T("URL")); key.DeleteValue(_T("Cached")); key.DeleteValue(_T("Save Everything")); key.DeleteValue(_T("ignoreSSL")); key.DeleteValue(_T("Host")); } len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("customRules"), buff, &len) == ERROR_SUCCESS && len > 1 ) { CString rules = buff; int pos = 0; CString rule = rules.Tokenize(_T("\n"), pos); while (pos >= 0) { rule = rule.Trim(); if (rule.GetLength()) { int separator = rule.Find(_T('=')); if (separator > 0) { CString name = rule.Left(separator).Trim(); rule = rule.Mid(separator + 1).Trim(); int separator = rule.Find(_T('\t')); if (separator > 0) { CString mime = rule.Left(separator).Trim(); rule = rule.Mid(separator + 1).Trim(); if (name.GetLength() && mime.GetLength() && rule.GetLength()) { CCustomRule newrule; newrule.name = name; newrule.mime = mime; newrule.regex = rule; customRules.AddTail(newrule); } } } } rule = rules.Tokenize(_T("\n"), pos); } } customMetrics.RemoveAll(); len = sizeof(buff) / sizeof(TCHAR); if( key.QueryStringValue(_T("customMetricsFile"), buff, &len) == ERROR_SUCCESS && len > 1 ) { HANDLE hFile = CreateFile(buff, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (hFile != INVALID_HANDLE_VALUE) { DWORD custom_len = GetFileSize(hFile, NULL); if (custom_len) { char * custom_metrics = (char *)malloc(custom_len + 1); char * decoded = (char *)malloc(custom_len + 1); if (custom_metrics && decoded) { custom_metrics[custom_len] = 0; DWORD bytes = 0; if (ReadFile(hFile, custom_metrics, custom_len, &bytes, 0) && bytes == custom_len) { char * line = strtok(custom_metrics, "\r\n"); while (line) { CStringA metric_line(line); int divider = metric_line.Find(":"); if (divider > 0) { CCustomMetric metric; metric.name = (LPCTSTR)CA2T((LPCSTR)metric_line.Left(divider)); CStringA code = metric_line.Mid(divider + 1); int nDestLen = custom_len; if (Base64Decode((LPCSTR)code, code.GetLength(), (BYTE*)decoded, &nDestLen) && nDestLen) { decoded[nDestLen] = 0; metric.code = (LPCTSTR)CA2T(decoded); customMetrics.AddTail(metric); } } line = strtok(NULL, "\r\n"); } } free(decoded); free(custom_metrics); } } CloseHandle(hFile); } } key.DeleteValue(_T("Basic Auth")); // make sure the event name has changed // this is to prevent a page with navigate script on it // from adding test entries to the log file if( !szEventName.IsEmpty() && szEventName == somEventName ) { msg.Format(_T("[Pagetest] *** Ingoring event, event name has not changed - '%s'\n"), (LPCTSTR)somEventName); OutputDebugString(msg); ok = false; } else somEventName = szEventName; } key.Close(); } else ok = false; // load iewatch settings if( ok ) { if( script_activity_timeout ) activityTimeout = script_activity_timeout; if( key.Open(HKEY_CURRENT_USER, _T("SOFTWARE\\AOL\\ieWatch"), KEY_READ) == ERROR_SUCCESS ) { if( runningScript && script_timeout != -1 ) timeout = script_timeout; else key.QueryDWORDValue(_T("Timeout"), timeout); key.Close(); } if( key.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\AOL\\ieWatch"), KEY_READ) == ERROR_SUCCESS ) { key.QueryDWORDValue(_T("Include Header"), includeHeader); key.Close(); } } #ifdef _DEBUG timeout = timeout * 10; #endif } // Delete short lifetime cache elements if configured (Blaze patch) // TODO: replace this with proper cache aging if we can figure out how to do it if( ok && cached && clearShortTermCacheSecs > 0 ) ClearShortTermCache(clearShortTermCacheSecs); // clear the cache if necessary (extra precaution) if( ok && !cached && !cacheCleared ) { HANDLE hEntry; DWORD len, entry_size = 0; GROUPID id; INTERNET_CACHE_ENTRY_INFO * info = NULL; HANDLE hGroup = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, 0, 0, &id, 0); if (hGroup) { do { len = entry_size; hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, id, info, &len, NULL, NULL, NULL); if (!hEntry && GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, id, info, &len, NULL, NULL, NULL); } } if (hEntry && info) { bool ok = true; do { DeleteUrlCacheEntry(info->lpszSourceUrlName); len = entry_size; if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { ok = false; } } } else { ok = false; } } } while (ok); } if (hEntry) { FindCloseUrlCache(hEntry); } DeleteUrlCacheGroup(id, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, 0); } while(FindNextUrlCacheGroup(hGroup, &id,0)); FindCloseUrlCache(hGroup); } len = entry_size; hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, 0, info, &len, NULL, NULL, NULL); if (!hEntry && GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { hEntry = FindFirstUrlCacheEntryEx(NULL, 0, 0xFFFFFFFF, 0, info, &len, NULL, NULL, NULL); } } if (hEntry && info) { bool ok = true; do { DeleteUrlCacheEntry(info->lpszSourceUrlName); len = entry_size; if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { if (!FindNextUrlCacheEntryEx(hEntry, info, &len, NULL, NULL, NULL)) { ok = false; } } } else { ok = false; } } } while (ok); } if (hEntry) { FindCloseUrlCache(hEntry); } len = entry_size; hEntry = FindFirstUrlCacheEntry(NULL, info, &len); if (!hEntry && GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { hEntry = FindFirstUrlCacheEntry(NULL, info, &len); } } if (hEntry && info) { bool ok = true; do { DeleteUrlCacheEntry(info->lpszSourceUrlName); len = entry_size; if (!FindNextUrlCacheEntry(hEntry, info, &len)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && len) { entry_size = len; info = (INTERNET_CACHE_ENTRY_INFO *)realloc(info, len); if (info) { if (!FindNextUrlCacheEntry(hEntry, info, &len)) { ok = false; } } } else { ok = false; } } } while (ok); } if (hEntry) { FindCloseUrlCache(hEntry); } if (info) free(info); cacheCleared = true; } if( ok ) { // check for any machine-wide overrides CRegKey keyMachine; if( keyMachine.Open(HKEY_LOCAL_MACHINE, _T("Software\\America Online\\Pagetest"), KEY_READ) == ERROR_SUCCESS ) { DWORD val = checkOpt; if( ERROR_SUCCESS == keyMachine.QueryDWORDValue(_T("Check Optimizations"), val) ) checkOpt = val; keyMachine.Close(); } // parse any test options that came in on the url ParseTestOptions(); msg.Format(_T("[Pagetest] *** DoStartup() - Starting measurement - '%s'\n"), (LPCTSTR)somEventName); OutputDebugString(msg); // create the dialog if we need to Create(); // delete any old data Reset(); // track the document that everything belongs to if( initializeDoc ) { EnterCriticalSection(&cs); currentDoc = nextDoc; nextDoc++; LeaveCriticalSection(&cs); } EnterCriticalSection(&cs); active = true; available = false; reportSt = NONE; // collect the starting TCP stats GetTcpStatistics(&tcpStatsStart); // keep the activity tracking up to date QueryPerfCounter(lastRequest); lastActivity = lastRequest; startTime = CTime::GetCurrentTime(); url = szUrl; GetCPUTime(startCPU, startCPUtotal); LeaveCriticalSection(&cs); StartTimer(1, 100); } } else { msg.Format(_T("[Pagetest] *** DoStartup() - event dropped because we are already active or not available - '%s'\n"), (LPCTSTR)szUrl); OutputDebugString(msg); } } /*----------------------------------------------------------------------------- See if the test is complete -----------------------------------------------------------------------------*/ void CTestState::CheckComplete() { ATLTRACE(_T("[Pagetest] - Checking to see if the test is complete\n")); if( heartbeatEvent ) SetEvent(heartbeatEvent); if( active ) { CString buff; bool expired = false; bool done = false; __int64 now; QueryPerfCounter(now); DWORD elapsed = (DWORD)((now - start) / freq); bool keepOpen = false; if (minimumDuration && elapsed < minimumDuration) keepOpen = true; // only do the request checking if we're actually active if( active ) { EnterCriticalSection(&cs); // has our timeout expired? if( !keepOpen && timeout && start ) { if( elapsed > timeout ) { buff.Format(_T("[Pagetest] - Test timed out (timout set to %d sec)\n"), timeout); OutputDebugString(buff); expired = true; } else { ATLTRACE(_T("[Pagetest] - Elapsed test time: %d sec\n"), elapsed); } } else { ATLTRACE(_T("[Pagetest] - Start time not logged yet\n")); } LeaveCriticalSection(&cs); // see if the DOM element we're interested in appeared yet CheckDOM(); // only exit if there isn't an outstanding doc or request if( !keepOpen && ((lastRequest && !currentDoc) || expired || forceDone || errorCode) ) { done = forceDone || errorCode != 0; if( !done ) { // count the number of open wininet requests EnterCriticalSection(&cs); openRequests = 0; POSITION pos = winInetRequestList.GetHeadPosition(); while( pos ) { CWinInetRequest * r = winInetRequestList.GetNext(pos); if( r && r->valid && !r->end ) { ATLTRACE(_T("[Pagetest] (0x%p) %s%s\n"), r->hRequest, r->host, r->object); openRequests++; } } LeaveCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - %d openRequests"), openRequests); // did the DOM element arrive yet (if we're looking for one?) if( (domElement || (domElementId.IsEmpty() && domRequest.IsEmpty())) && requiredRequests.IsEmpty() && !script_waitForJSDone ) { // see if we are done (different logic if we're in abm mode or not) if( abm ) { DWORD elapsed = now > lastActivity && lastActivity ? (DWORD)((now - lastActivity ) / (freq / 1000)) : 0; DWORD elapsedRequest = now > lastRequest && lastRequest ? (DWORD)((now - lastRequest ) / (freq / 1000)) : 0; if ( (!openRequests && elapsed > activityTimeout) || // no open requests and it's been longer than 2 seconds since the last request (!openRequests && elapsedRequest > REQUEST_ACTIVITY_TIMEOUT) || // no open requests and it's been longer than 30 seconds since the last traffic on the wire (openRequests && elapsedRequest > FORCE_ACTIVITY_TIMEOUT) ) // open requests but it's been longer than 60 seconds since the last one (edge case) that touched the wire { done = true; expired = false; OutputDebugString(_T("[Pagetest] ***** Measured as Web 2.0\n")); } } else { if( lastDoc ) // make sure we actually measured a document - shouldn't be possible to not be set but just to be safe { DWORD elapsed = (DWORD)((now - lastDoc) / (freq / 1000)); if( elapsed > DOC_TIMEOUT ) { done = true; expired = false; OutputDebugString(_T("[Pagetest] ***** Measured as Web 1.0\n")); } } } } } else { buff.Format(_T("[Pagetest] - Force exit. Error code = %d (0x%08X)\n"), errorCode, errorCode); OutputDebugString(buff); } } } if ( !keepOpen && (expired || done) ) { CString buff; buff.Format(_T("[Pagetest] ***** Page Done\n") _T("[Pagetest] Document ended: %0.3f sec\n") _T("[Pagetest] Last Activity: %0.3f sec\n") _T("[Pagetest] DOM Element: %0.3f sec\n"), !endDoc ? 0.0 : (double)(endDoc-start) / (double)freq, !lastRequest ? 0.0 : (double)(lastRequest-start) / (double)freq, !domElement ? 0.0 : (double)(domElement-start) / (double)freq); OutputDebugString(buff); // see if we are combining multiple script steps (in which case we need to start again) if( runningScript && script_combineSteps && script_combineSteps != 1 && !script.IsEmpty() ) { if( script_combineSteps > 1 ) script_combineSteps--; // do some basic resetting end = 0; lastRequest = 0; lastActivity = 0; endDoc = 0; ContinueScript(false); } else { GetCPUTime(endCPU, endCPUtotal); // keep track of the end time in case there wasn't a document if( !end || abm ) end = lastRequest; // put some text on the browser window to indicate we're done double sec = (start && end > start) ? (double)(end - start) / (double)freq: 0; if( !expired ) reportSt = TIMER; else reportSt = QUIT_NOEND; RepaintWaterfall(); // kill the background timer if( hTimer ) { DeleteTimerQueueTimer(NULL, hTimer, NULL); hTimer = 0; timeEndPeriod(1); } // get a screen shot of the fully loaded page if( saveEverything ) { FindBrowserWindow(); screenCapture.Capture(hBrowserWnd, CapturedImage::FULLY_LOADED); } // write out any results (this will also kill the timer) FlushResults(); } } } } /*----------------------------------------------------------------------------- See if the browser's readystate has changed -----------------------------------------------------------------------------*/ void CTestState::CheckReadyState(void) { if (!m_spChromeFrame) { // figure out the old state (first non-complete browser window) EnterCriticalSection(&cs); READYSTATE oldState = READYSTATE_COMPLETE; POSITION pos = browsers.GetHeadPosition(); while( pos && oldState == READYSTATE_COMPLETE ) { CBrowserTracker tracker = browsers.GetNext(pos); if( tracker.state != READYSTATE_COMPLETE ) oldState = tracker.state; } // update the state for all browsers in this thread CAtlList<CComPtr<IWebBrowser2>> browsers2; pos = browsers.GetHeadPosition(); while( pos ) { POSITION oldPos = pos; CBrowserTracker tracker = browsers.GetNext(pos); if(tracker.browser && tracker.threadId == GetCurrentThreadId()) tracker.browser->get_ReadyState(&(browsers.GetAt(oldPos).state)); } // see what the new state is READYSTATE newState = READYSTATE_COMPLETE; pos = browsers.GetHeadPosition(); while( pos && newState == READYSTATE_COMPLETE ) { CBrowserTracker tracker = browsers.GetNext(pos); if( tracker.state != READYSTATE_COMPLETE ) newState = tracker.state; } LeaveCriticalSection(&cs); if( newState != oldState ) { currentState = newState; CString state; switch(currentState) { case READYSTATE_UNINITIALIZED: state = "Uninitialized"; break; case READYSTATE_LOADING: state = "Loading"; break; case READYSTATE_LOADED: state = "Loaded"; break; case READYSTATE_INTERACTIVE: state = "Interactive"; break; case READYSTATE_COMPLETE: { state = "Complete"; // force a DocumentComplete in case we never got notified if( active && currentDoc ) DocumentComplete(url); } break; default: state = "Unknown"; break; } CString buff; buff.Format(_T("Browser ReadyState changed to %s\n"), (LPCTSTR)state); StatusUpdate(buff); OutputDebugString(buff); } } } /*----------------------------------------------------------------------------- Check to see if a specific DOM element we're looking for has been loaded yet -----------------------------------------------------------------------------*/ void CTestState::CheckDOM(void) { // don't bother if we already found it if(!domElementId.IsEmpty() && !domElement && startRender) { if( FindDomElementByAttribute(domElementId) ) { QueryPerfCounter(domElement); lastRequest = lastActivity = domElement; CString buff; buff.Format(_T("[Pagetest] * DOM Element ID '%s' appeared\n"), (LPCTSTR)domElementId); OutputDebugString(buff); if( saveEverything ) { FindBrowserWindow(); screenCapture.Capture(hBrowserWnd, CapturedImage::DOM_ELEMENT); } } } } /*----------------------------------------------------------------------------- Check to see if anything was drawn to the screen -----------------------------------------------------------------------------*/ void CTestState::PaintEvent(int x, int y, int width, int height) { if (active) { SetBrowserWindowUpdated(true); CheckWindowPainted(); } } /*----------------------------------------------------------------------------- Check to see if anything was drawn to the screen -----------------------------------------------------------------------------*/ void CTestState::CheckWindowPainted() { if( active && !painted && hBrowserWnd && ::IsWindow(hBrowserWnd) && BrowserWindowUpdated() ) { // grab a screen shot of the window GdiFlush(); screenCapture.Lock(); SetBrowserWindowUpdated(false); __int64 now; QueryPerfCounter(now); const DWORD START_RENDER_MARGIN = 30; // grab a screen shot CapturedImage captured_img(hBrowserWnd,CapturedImage::START_RENDER); captured_img._capture_time.QuadPart = now; CxImage img; if (captured_img.Get(img) && img.GetWidth() > START_RENDER_MARGIN * 2 && img.GetHeight() > START_RENDER_MARGIN * 2) { int bpp = img.GetBpp(); if (bpp >= 15) { int height = img.GetHeight(); int width = img.GetWidth(); // 24-bit gets a fast-path where we can just compare full rows if (bpp <= 24 ) { DWORD row_bytes = 3 * (width - (START_RENDER_MARGIN * 2)); char * white = (char *)malloc(row_bytes); if (white) { memset(white, 0xFFFFFFFF, row_bytes); for (DWORD row = START_RENDER_MARGIN; row < height - START_RENDER_MARGIN && !painted; row++) { char * image_bytes = (char *)img.GetBits(row) + START_RENDER_MARGIN; if (memcmp(image_bytes, white, row_bytes)) painted = true; } free (white); } } else { for (DWORD row = START_RENDER_MARGIN; row < height - START_RENDER_MARGIN && !painted; row++) { for (DWORD x = START_RENDER_MARGIN; x < width - START_RENDER_MARGIN && !painted; x++) { RGBQUAD pixel = img.GetPixelColor(x, row, false); if (pixel.rgbBlue != 255 || pixel.rgbRed != 255 || pixel.rgbGreen != 255) painted = true; } } } } } if (painted) { startRender = now; OutputDebugString(_T("[Pagetest] * Render Start (Painted)")); screenCapture._captured_images.AddTail(captured_img); } else captured_img.Free(); screenCapture.Unlock(); } } /*----------------------------------------------------------------------------- Parse the test options string -----------------------------------------------------------------------------*/ void CTestState::ParseTestOptions() { TCHAR buff[4096]; if( !testOptions.IsEmpty() ) { int pos = 0; do { // commands are separated by & just like query parameters CString token = testOptions.Tokenize(_T("&"), pos); if( token.GetLength() ) { int index = token.Find(_T('=')); if( index > 0 ) { CString command = token.Left(index).Trim(); if( command.GetLength() ) { // any values need to be escaped since it is passed in on the url so un-escape it CString tmp = token.Mid(index + 1); DWORD len; if( AtlUnescapeUrl((LPCTSTR)tmp, buff, &len, _countof(buff)) ) { CString value = buff; value = value.Trim(); // now handle the actual command if( !command.CompareNoCase(_T("ptBlock")) ) { // block the specified request blockRequests.AddTail(value); } if( !command.CompareNoCase(_T("ptAds")) ) { // block aol-specific ad calls if( !value.CompareNoCase(_T("none")) || !value.CompareNoCase(_T("block")) ) { blockRequests.AddTail(_T("adsWrapper.js")); blockRequests.AddTail(_T("adsWrapperAT.js")); blockRequests.AddTail(_T("adsonar.js")); blockRequests.AddTail(_T("sponsored_links1.js")); blockRequests.AddTail(_T("switcher.dmn.aol.com")); } } } } } } }while( pos >= 0 ); } // see if the DOM element was really a DOM request in hiding if( domElementId.GetLength() ) { int pos = 0; CString action = domElementId.Tokenize(_T("="), pos).Trim(); if( pos != -1 ) { CString val = domElementId.Tokenize(_T("="), pos).Trim(); if( val.GetLength() ) { if( !action.CompareNoCase(_T("RequestEnd")) ) { domRequest = val; domRequestType = END; domElementId.Empty(); } else if( !action.CompareNoCase(_T("RequestTTFB")) ) { domRequest = val; domRequestType = TTFB; domElementId.Empty(); } else if( !action.CompareNoCase(_T("RequestStart")) ) { domRequest = val; domRequestType = START; domElementId.Empty(); } } } } } VOID CALLBACK BackgroundTimer(PVOID lpParameter, BOOLEAN TimerOrWaitFired) { if( lpParameter ) ((CTestState *)lpParameter)->BackgroundTimer(); } /*----------------------------------------------------------------------------- Measurement is starting, kick off the background stuff -----------------------------------------------------------------------------*/ void CTestState::StartMeasuring(void) { // create thee background timer to fire every 100ms if( !hTimer && saveEverything && (!runningScript || script_logData) ) { lastBytes = 0; lastCpuIdle = 0; lastCpuKernel = 0; lastCpuUser = 0; lastTime = 0; imageCount = 0; lastImageTime = 0; lastRealTime = 0; SetBrowserWindowUpdated(true); // now find just the browser control FindBrowserWindow(); if( hMainWindow ) { ::SetWindowPos(hMainWindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); ::UpdateWindow(hMainWindow); } timeBeginPeriod(1); CreateTimerQueueTimer(&hTimer, NULL, ::BackgroundTimer, this, 100, 100, WT_EXECUTEDEFAULT); // Force a grab/stats capture now BackgroundTimer(); } } /*----------------------------------------------------------------------------- Do the 100ms periodic checking -----------------------------------------------------------------------------*/ void CTestState::BackgroundTimer(void) { // queue up a message in case we're having timer problems CheckStuff(); FindBrowserWindow(); // timer will only be running while we're active EnterCriticalSection(&csBackground); const DWORD imageIncrements = 20; // allow for X screen shots at each increment __int64 now; QueryPerfCounter(now); if( active ) { CProgressData data; data.sampleTime = now; DWORD ms = 0; if( start && now > start ) ms = (DWORD)((now - start) / msFreq); // round to the closest 100ms data.ms = ((ms + 50) / 100) * 100; // don't re-do everything if we get a burst of timer callbacks if( data.ms != lastTime || !lastTime ) { DWORD msElapsed = 0; if( data.ms > lastTime ) msElapsed = data.ms - lastTime; double elapsed = 0; if( now > lastRealTime && lastRealTime) elapsed = (double)(now - lastRealTime) / (double)freq; lastRealTime = now; // figure out the bandwidth if (elapsed > 0) { double bits = (bwBytesIn - lastBytes) * 8; data.bpsIn = (DWORD)(bits / elapsed); } // calculate CPU utilization FILETIME idle, kernel, user; if( GetSystemTimes( &idle, &kernel, &user) ) { ULARGE_INTEGER k, u, i; k.LowPart = kernel.dwLowDateTime; k.HighPart = kernel.dwHighDateTime; u.LowPart = user.dwLowDateTime; u.HighPart = user.dwHighDateTime; i.LowPart = idle.dwLowDateTime; i.HighPart = idle.dwHighDateTime; if( lastCpuIdle || lastCpuKernel || lastCpuUser ) { __int64 idle = i.QuadPart - lastCpuIdle; __int64 kernel = k.QuadPart - lastCpuKernel; __int64 user = u.QuadPart - lastCpuUser; int cpu_utilization = (int)((((kernel + user) - idle) * 100) / (kernel + user)); data.cpu = max(min(cpu_utilization, 100), 0); } lastCpuIdle = i.QuadPart; lastCpuKernel = k.QuadPart; lastCpuUser = u.QuadPart; } // get the memory use (working set - task-manager style) PROCESS_MEMORY_COUNTERS mem; mem.cb = sizeof(mem); if( GetProcessMemoryInfo(GetCurrentProcess(), &mem, sizeof(mem)) ) data.mem = mem.WorkingSetSize / 1024; // interpolate across multiple time periods if( msElapsed > 100 ) { DWORD chunks = msElapsed / 100; for( DWORD i = 1; i < chunks; i++ ) { CProgressData d; d.ms = lastTime + (i * 100); d.cpu = data.cpu; // CPU time was already spread over the period d.bpsIn = data.bpsIn / chunks; // split bandwidth evenly across the time slices d.mem = data.mem; // just assign them all the same memory use (could interpolate but probably not worth it) progressData.AddTail(d); } data.bpsIn /= chunks; // bandwidth is the only measure in the main chunk that needs to be adjusted } bool grabImage = false; if( !lastImageTime ) { if( captureVideo && hBrowserWnd && IsWindow(hBrowserWnd) ) grabImage = true; } else if( painted && captureVideo && hBrowserWnd && IsWindow(hBrowserWnd) && BrowserWindowUpdated() ) { // see what time increment we are in // we go from 0.1 second to 1 second to 5 second intervals // as we get more and more screen shots DWORD minTime = 100; if( imageCount >= imageIncrements ) minTime = 1000; if( imageCount >= imageIncrements * 2 ) minTime = 5000; if( data.ms > lastImageTime && (data.ms - lastImageTime) >= minTime ) grabImage = true; } if( grabImage ) { ATLTRACE(_T("[Pagetest] - Grabbing video frame : %d ms\n"), data.ms); if( painted ) SetBrowserWindowUpdated(false); screenCapture.Capture(hBrowserWnd, CapturedImage::VIDEO); imageCount++; lastImageTime = data.ms; if( !lastImageTime ) lastImageTime = 1; } progressData.AddTail(data); lastTime = data.ms; } lastBytes = bwBytesIn; } LeaveCriticalSection(&csBackground); } /*----------------------------------------------------------------------------- Delete any cache items with a lifetime less than cacheTTL -----------------------------------------------------------------------------*/ #define RATIO_100NANO_TO_SECOND ((_int64)10000000) void CTestState::ClearShortTermCache(DWORD cacheTTL) { DWORD cacheEntryInfoBufferSizeInitial = 0; DWORD cacheEntryInfoBufferSize = 0; DWORD dwError; LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry; HANDLE hCacheDir; // Determine the size of the first entry, if it exists hCacheDir = FindFirstUrlCacheEntry(NULL,0,&cacheEntryInfoBufferSizeInitial); if (hCacheDir == NULL && GetLastError() == ERROR_NO_MORE_ITEMS) return; // Get the current time in a large integer (seems like a weird way to do it, but that's what MSDN dictates...) SYSTEMTIME curSysTime; GetSystemTime(&curSysTime); FILETIME curFileTime; SystemTimeToFileTime(&curSysTime, &curFileTime); ULONGLONG curTimeSecs = ((((ULONGLONG) curFileTime.dwHighDateTime) << 32) + curFileTime.dwLowDateTime) / RATIO_100NANO_TO_SECOND; // Read the first entry cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cacheEntryInfoBufferSize); hCacheDir = FindFirstUrlCacheEntry(NULL, lpCacheEntry, &cacheEntryInfoBufferSizeInitial); // Iterate the current and next entries BOOL retVal = (hCacheDir != NULL); while(retVal) { cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize; // Find out the current time in secs ULONGLONG cacheItemTimeSecs = ((((ULONGLONG) lpCacheEntry->ExpireTime.dwHighDateTime) << 32) + lpCacheEntry->ExpireTime.dwLowDateTime) / RATIO_100NANO_TO_SECOND; // If the item expires in less than the given limit, delete it if (cacheItemTimeSecs < (curTimeSecs + cacheTTL)) DeleteUrlCacheEntry(lpCacheEntry->lpszSourceUrlName); // Get the next record retVal = FindNextUrlCacheEntry(hCacheDir, lpCacheEntry, &cacheEntryInfoBufferSizeInitial); if (!retVal) { // If we have no more items, break dwError = GetLastError(); if (dwError == ERROR_NO_MORE_ITEMS) { break; } // Otherwise, if the error was insufficient buffer, increase the buffer size if (dwError == ERROR_INSUFFICIENT_BUFFER && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize) { cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; // Re-allocate to a larger size lpCacheEntry = (LPINTERNET_CACHE_ENTRY_INFO)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, lpCacheEntry, cacheEntryInfoBufferSize); if (lpCacheEntry) retVal = FindNextUrlCacheEntry(hCacheDir, lpCacheEntry, &cacheEntryInfoBufferSizeInitial); } else break; } } HeapFree(GetProcessHeap(),0,lpCacheEntry); // Cleanup the cache dir handle FindCloseUrlCache(hCacheDir); }
32.080808
176
0.582034
LeeLiangze
10dd4e7e6d0f6ae718e21b3a1b8397eefce814a0
8,859
cpp
C++
esp-at/UnifiedAtEvent.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
2
2020-03-05T12:59:06.000Z
2020-03-11T02:58:53.000Z
esp-at/UnifiedAtEvent.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
null
null
null
esp-at/UnifiedAtEvent.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
null
null
null
#define private public #include"Uart.h" #include"UnifiedAtEvent.h" #include"Utilities.h" #include"UnifiedBackTask.h" #define T_US 1000000.0 #define T_MS 1000.0 #define ESP_BIT_RATE 115200 #define ESP_BYTE_RATE (1.0 * ESP_BIT_RATE / 11) #define MAX_DESIRED 50.0 #define COST(bytes) uint32_t(T_US / ESP_BYTE_RATE * (bytes)) #define ei else if #define es else #define self (*(EspStateBar *)handle) volatile bool isUseRtosMemory = false; void * memoryAlloc(size_t size){ void * ptr; if (isUseRtosMemory == false){ if (ptr = malloc(size)){ return ptr; } } Rtos::malloc(& ptr, size); return ptr; } void memoryFree(void * ptr){ if (isUseRtosMemory == false){ free(ptr); } else{ Rtos::free(ptr); } } void * operator new(size_t size) { return memoryAlloc(size); } void * operator new[](size_t size) { return memoryAlloc(size); } void operator delete(void * ptr) { memoryFree(ptr); } void operator delete[](void * ptr) { memoryFree(ptr); } namespace{ #ifdef USE_ESP32_AT_SERIAL #define PIN_RX auto & com = Serial; #elif defined USE_ESP32_AT_SERIAL2 #define PIN_RX auto & com = Serial2; #elif defined USE_ESP32_AT_SERIAL1 #define PIN_RX auto & com = Serial1; #endif volatile bool ipdMode = false; } #ifdef PIN_RX // void sendSignal(void * serial, char chr){ // if (serial != & com){ // return; // } // // debug("%c", chr); // // static uint64_t word = 0; // // uint64_t want = '+' << 32 | 'I' << 24 | 'P' << 16 | 'D' << 8 | ':'; // // auto flag = (want & word) == want && ipdMode == false; // // word = word << 8 | chr; // // Rtos::giveFromISR(esp.semaWaitRx); // // com.rxBuffer.clear(); // // uint32_t size; // // Rtos::queueSize(esp.rxQueue, & size); // // Rtos::queueSendFromISR(esp.rxQueue, chr); // } int EspStateBar::available(){ return com.available(); } int EspStateBar::read(){ return com.read(); } void EspStateBar::begin(){ com.begin(ESP_BIT_RATE); } void EspStateBar::write(Text value){ com.print(value.c_str()); } void EspStateBar::txBin(uint8_t const * buffer, size_t length){ com.write(buffer, length); } // default: // - wifi multi-connection // - close echo // - show IPD remote ip:port void EspStateBar::reset(){ wifi.reset(); tx("ATE0"); flush(); waitFlag(); tx("AT+CIPMUX=1"); flush(); waitFlag(); tx("AT+CIPDINFO=1"); flush(); waitFlag(); } #else int EspStateBar::available(){ return -1; } int EspStateBar::read(){ return -1; } void EspStateBar::begin(){} void EspStateBar::write(Text value){} void EspStateBar::reset(){} #endif EspStateBar esp; struct TokenEventPair{ typedef std::function<void(EspStateBar &, Text &)> Invoke; const char * token; Invoke invoke; }; std::initializer_list<TokenEventPair> responesMap = { { "ready", [](EspStateBar & esp, Text &){ esp.reset(); esp.whenReset(); } }, { "WIFI CONNECTED", [](EspStateBar & esp, Text &){ esp.wifi.state = WifiConnected; esp.wifi.whenStateChanged(); } }, { "WIFI GOT IP", [](EspStateBar & esp, Text &){ esp.wifi.state = WifiGotIp; esp.wifi.whenStateChanged(); } }, { "WIFI DISCONNECT", [](EspStateBar & esp, Text &){ esp.wifi.state = WifiDisconnect; esp.wifi.whenStateChanged(); } }, { "smartconfig connected wifi", [](EspStateBar & esp, Text &){ esp.smart.state = Success; esp.smart.whenRising(); } }, { "smartconfig connect Fail", [](EspStateBar & esp, Text &) { esp.smart.state = Fail; esp.smart.whenRising(); } }, { "OK", [](EspStateBar & esp, Text &) { if (esp.wait == WaitWifiScan){ esp.wifi.whenScanFinished(); } esp.wait = WaitNothing; esp.flag = Success; Rtos::give(esp.semaWaitCmd); // for waitFlag Rtos::give(esp.semaWaitCmd); // for tx } }, { "ERROR", [](EspStateBar & esp, Text &) { if (esp.wait == WaitWifiScan){ esp.wifi.whenScanFailed(); } esp.wait = WaitNothing; esp.flag = Fail; Rtos::give(esp.semaWaitCmd); // for waitFlag Rtos::give(esp.semaWaitCmd); // for tx } }, { "+IPD", [](EspStateBar & esp, Text & resp){ int32_t id; Ipd ipd; // +5 to skip "+IPD," esp.rx(resp.c_str() + 5, & id, & ipd.length, & ipd.ip, & ipd.port); ipd.data = std::shared_ptr<uint8_t>(new uint8_t[ipd.length]); ipd.i = 0; for (int32_t i = 0; i < ipd.length; i++){ if (esp.available()){ ipd.data.get()[i] = esp.read(); } es{ Rtos::delayus(COST(ipd.length - i)); } } ipdMode = false; esp.wifi.packet[id].push(ipd); esp.wifi.packId = id; esp.wifi.whenReceivePacket(); } }, }; Text EspStateBar::readUntil(char * token){ std::vector<char> buf; char c; while(true){ while (available() <= 0){ Rtos::delayms(1); } c = read(); buf.push_back(c); // debug("%c", c); if (strchr(token, c) != nullptr){ buf.push_back('\0'); return Text(& buf.front()); } } } void EspStateBar::eventHandler(){ while (true) { Text && resp = readUntil(':', '\n'); if (resp.length() == 0){ continue; } // first for (auto & event : responesMap) { if (resp.startsWith(event.token)) { event.invoke(this[0], resp); break; } } // second analysis analysis.invoke(resp); } } Result EspStateBar::waitFlag(uint32_t ms) { Rtos::take(semaWaitCmd, Rtos::msToTicks(ms)); return flag; } // setup and loop code block extern void body(); // FREE RTOS IDLE function extern "C" void vApplicationIdleHook(){} // ESP-LIB function extern bool __attribute__((weak)) _start_network_event_task(){} void fore(void * handle) { _start_network_event_task(); self.begin(); self.reset(); body(); } void back(void * handle){ self.eventHandler(); } void espAtShell(){ esp.run(); while(1); } void EspStateBar::run(){ isUseRtosMemory = true; Rtos::createSemaphore(& semaWaitCmd, 2 /*max*/, 1 /*for send first cmd.*/); Rtos::createThread(& taskBack, "ESP-BG", back, this, 1024, 1 /*priority*/); Rtos::createThread(& taskFore, "ESP-FG", fore, this, 2048, 1); Rtos::scheduler(); } //void atWifiScanSubfunction(Text current){ // auto & list = esp.wifi.apList; // list.clear(); // // auto lastIndexOf = [](const char * line, char chr, size_t times){ // for (int i = strlen(line); i-- > 0; ){ // if (line[i] != chr){ // continue; // } // if (--times == 0){ // return i; // } // } // return -1; // }; // // while (current.startsWith("+CWLAP:")){ // // char line[] = "+CWLAP:(3,\"POT\",-AL00a\",-53,\"12:34:56:78:9a:bc\",1)"; // char * line = (char *)current.c_str(); // char * p = nullptr; // char * t; // int32_t mac[6]; //need 32bit when use sscanf // int32_t ecn; // int32_t rssi; // int32_t channel; // // p = line + lastIndexOf(line, ',', 3); // // sscanf(line, "+CWLAP:" "(%d,", & ecn); // sscanf(p + 1, "%d,\"%x:%x:%x:%x:%x:%x\",%d", // & rssi, // & mac[0], // & mac[1], // & mac[2], // & mac[3], // & mac[4], // & mac[5], // & channel // ); // // //replace '\"' to '\0' // p[0] = ','; // p[-1] = '\0'; // // WifiApItem info; // info.ecn = ecn; // info.ssid = strchr(line, ',') + 2; //skip ',' '\"' // info.rssi = rssi; // copy<uint8_t, int32_t>(info.bssid, mac, 6); // info.channel = channel; // list.push_back(info); // current = readLine(); // } // // if (esp.wifi.whenFinishScan){ // esp.wifi.whenFinishScan(); // } //} //
25.604046
88
0.493397
PowerfulCat
10eaed4fcb6f417e0d2208c7552c84365d5f32a0
6,111
hpp
C++
extension/parquet/include/thrift_tools.hpp
hannes/duckdb
4a24d71edecc7c0018eb3860d2e104cfe90462b6
[ "MIT" ]
null
null
null
extension/parquet/include/thrift_tools.hpp
hannes/duckdb
4a24d71edecc7c0018eb3860d2e104cfe90462b6
[ "MIT" ]
null
null
null
extension/parquet/include/thrift_tools.hpp
hannes/duckdb
4a24d71edecc7c0018eb3860d2e104cfe90462b6
[ "MIT" ]
null
null
null
#pragma once #include <list> #include "thrift/protocol/TCompactProtocol.h" #include "thrift/transport/TBufferTransports.h" #include "duckdb.hpp" #ifndef DUCKDB_AMALGAMATION #include "duckdb/common/file_system.hpp" #include "duckdb/common/allocator.hpp" #endif namespace duckdb { // A ReadHead for prefetching data in a specific range struct ReadHead { ReadHead(idx_t location, uint64_t size) : location(location), size(size) {}; // Hint info idx_t location; uint64_t size; // Current info unique_ptr<AllocatedData> data; bool data_isset = false; idx_t GetEnd() const { return size + location; } void Allocate(Allocator &allocator) { data = allocator.Allocate(size); } }; // Comparator for ReadHeads that are either overlapping, adjacent, or within ALLOW_GAP bytes from each other struct ReadHeadComparator { static constexpr uint64_t ALLOW_GAP = 1 << 14; // 16 KiB bool operator()(const ReadHead *a, const ReadHead *b) const { auto a_start = a->location; auto a_end = a->location + a->size; auto b_start = b->location; if (a_end <= NumericLimits<idx_t>::Maximum() - ALLOW_GAP) { a_end += ALLOW_GAP; } return a_start < b_start && a_end < b_start; } }; // Two-step read ahead buffer // 1: register all ranges that will be read, merging ranges that are consecutive // 2: prefetch all registered ranges struct ReadAheadBuffer { ReadAheadBuffer(Allocator &allocator, FileHandle &handle, FileOpener &opener) : allocator(allocator), handle(handle), file_opener(opener) { } // The list of read heads std::list<ReadHead> read_heads; // Set for merging consecutive ranges std::set<ReadHead *, ReadHeadComparator> merge_set; Allocator &allocator; FileHandle &handle; FileOpener &file_opener; idx_t total_size = 0; // Add a read head to the prefetching list void AddReadHead(idx_t pos, uint64_t len, bool merge_buffers = true) { // Attempt to merge with existing if (merge_buffers) { ReadHead new_read_head {pos, len}; auto lookup_set = merge_set.find(&new_read_head); if (lookup_set != merge_set.end()) { auto existing_head = *lookup_set; auto new_start = MinValue<idx_t>(existing_head->location, new_read_head.location); auto new_length = MaxValue<idx_t>(existing_head->GetEnd(), new_read_head.GetEnd()) - new_start; existing_head->location = new_start; existing_head->size = new_length; return; } } read_heads.emplace_front(ReadHead(pos, len)); total_size += len; auto &read_head = read_heads.front(); if (merge_buffers) { merge_set.insert(&read_head); } if (read_head.GetEnd() > handle.GetFileSize()) { throw std::runtime_error("Prefetch registered for bytes outside file"); } } // Returns the relevant read head ReadHead *GetReadHead(idx_t pos) { for (auto &read_head : read_heads) { if (pos >= read_head.location && pos < read_head.GetEnd()) { return &read_head; } } return nullptr; } // Prefetch all read heads void Prefetch() { for (auto &read_head : read_heads) { read_head.Allocate(allocator); if (read_head.GetEnd() > handle.GetFileSize()) { throw std::runtime_error("Prefetch registered requested for bytes outside file"); } handle.Read(read_head.data->get(), read_head.size, read_head.location); read_head.data_isset = true; } } }; class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTransport<ThriftFileTransport> { public: static constexpr uint64_t PREFETCH_FALLBACK_BUFFERSIZE = 1000000; ThriftFileTransport(Allocator &allocator, FileHandle &handle_p, FileOpener &opener, bool prefetch_mode_p) : handle(handle_p), location(0), allocator(allocator), ra_buffer(ReadAheadBuffer(allocator, handle_p, opener)), prefetch_mode(prefetch_mode_p) { } uint32_t read(uint8_t *buf, uint32_t len) { auto prefetch_buffer = ra_buffer.GetReadHead(location); if (prefetch_buffer != nullptr && location - prefetch_buffer->location + len <= prefetch_buffer->size) { D_ASSERT(location - prefetch_buffer->location + len <= prefetch_buffer->size); if (!prefetch_buffer->data_isset) { prefetch_buffer->Allocate(allocator); handle.Read(prefetch_buffer->data->get(), prefetch_buffer->size, prefetch_buffer->location); prefetch_buffer->data_isset = true; } memcpy(buf, prefetch_buffer->data->get() + location - prefetch_buffer->location, len); } else { if (prefetch_mode && len < PREFETCH_FALLBACK_BUFFERSIZE && len > 0) { Prefetch(location, MinValue<uint64_t>(PREFETCH_FALLBACK_BUFFERSIZE, handle.GetFileSize() - location)); auto prefetch_buffer_fallback = ra_buffer.GetReadHead(location); D_ASSERT(location - prefetch_buffer_fallback->location + len <= prefetch_buffer_fallback->size); memcpy(buf, prefetch_buffer_fallback->data->get() + location - prefetch_buffer_fallback->location, len); } else { handle.Read(buf, len, location); } } location += len; return len; } // Prefetch a single buffer void Prefetch(idx_t pos, uint64_t len) { RegisterPrefetch(pos, len, false); FinalizeRegistration(); PrefetchRegistered(); } // Register a buffer for prefixing void RegisterPrefetch(idx_t pos, uint64_t len, bool can_merge = true) { ra_buffer.AddReadHead(pos, len, can_merge); } // Prevents any further merges, should be called before PrefetchRegistered void FinalizeRegistration() { ra_buffer.merge_set.clear(); } // Prefetch all previously registered ranges void PrefetchRegistered() { ra_buffer.Prefetch(); } void ClearPrefetch() { ra_buffer.read_heads.clear(); ra_buffer.merge_set.clear(); } void SetLocation(idx_t location_p) { location = location_p; } idx_t GetLocation() { return location; } idx_t GetSize() { return handle.file_system.GetFileSize(handle); } private: FileHandle &handle; idx_t location; Allocator &allocator; // Multi-buffer prefetch ReadAheadBuffer ra_buffer; // Whether the prefetch mode is enabled. In this mode the DirectIO flag of the handle will be set and the parquet // reader will manage the read buffering. bool prefetch_mode; }; } // namespace duckdb
29.1
116
0.727377
hannes
10eff848446dd52b65ad267dfb5b9e40a5bd8131
16,275
hpp
C++
packages/utility/archive/src/Utility_HDF5OArchiveImpl_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/archive/src/Utility_HDF5OArchiveImpl_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/archive/src/Utility_HDF5OArchiveImpl_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_HDF5OArchiveImpl_def.hpp //! \author Alex Robinson //! \brief HDF5 output archive implementation class definition //! //---------------------------------------------------------------------------// #ifndef UTILITY_HDF5_OARCHIVE_IMPL_DEF_HPP #define UTILITY_HDF5_OARCHIVE_IMPL_DEF_HPP // Std Lib Includes #include <sstream> // FRENSIE Includes #include "Utility_TypeNameTraits.hpp" #include "Utility_LoggingMacros.hpp" #include "Utility_DesignByContract.hpp" namespace Utility{ // Constructor template<typename Archive> HDF5OArchiveImpl<Archive>::HDF5OArchiveImpl( const std::string& hdf5_filename, unsigned flags ) : boost::archive::detail::common_oarchive<Archive>( flags ), HDF5CommonArchive( hdf5_filename, ((flags & HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE) ? HDF5File::OVERWRITE : HDF5File::READ_WRITE ) ), d_object_count( 0 ), d_group_count( 0 ), d_group_stack(), d_next_object_is_attribute( false ) { this->init( flags ); } // Initialize the archive template<typename Archive> void HDF5OArchiveImpl<Archive>::init( unsigned flags ) { // Add a header to the archive if( !(flags & boost::archive::no_header ) ) { try{ this->writeToGroupAttribute( this->getPropertiesDir(), this->getSignatureAttributeName(), std::string(boost::archive::BOOST_ARCHIVE_SIGNATURE()) ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "The archive signature could not be " "set in hdf5 archive " << this->getFilename() << "!" ); try{ this->writeToGroupAttribute<unsigned>( this->getPropertiesDir(), this->getVersionAttributeName(), boost::archive::BOOST_ARCHIVE_VERSION() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "The archive version could not be set " "in hdf5 archive " << this->getFilename() << "!" ); } // Create the group that will contain all serialized data this->createGroup( this->getDataDir() ); // Create the group that will contain links to tracked objects this->createGroup( this->getTrackedObjectsDir() ); // Create the group that will contain the hierarchical information // associated with the serialized objects this->createGroup( this->getTreeDir() ); } // Save opaque object template<typename Archive> inline void HDF5OArchiveImpl<Archive>::save_binary( const void* address, std::size_t count ) { this->saveImpl( address, count ); } #ifdef BOOST_SERIALIZATION_ARRAY_WRAPPER_AVAILABLE // Save an array template<typename Archive> template<typename ValueType> inline void HDF5OArchiveImpl<Archive>::save_array( const boost::serialization::array_wrapper<ValueType>& a, unsigned int ) { this->saveImpl( a.address(), a.count() ); } #endif // Start a save template<typename Archive> void HDF5OArchiveImpl<Archive>::save_start( const char* name ) { // if( name ) // { // FRENSIE_LOG_TAGGED_NOTIFICATION( name, "started" ); // } this->startHDF5Group( name ); } // Finish a save template<typename Archive> void HDF5OArchiveImpl<Archive>::save_end( const char* name ) { // if( name ) // { // FRENSIE_LOG_TAGGED_NOTIFICATION( name, "finished" ); // } this->endHDF5Group(); } // Intercept any type that is not a name-value pair or an attribute here /*! \details This method should never be called as it will cause a compilation * error (by design). To avoid this method, only serialize your types using * the boost::serialization::nvp wrapper. */ template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::save_override( const T& t, int ) { testStaticPrecondition((boost::serialization::is_wrapper<T>::type::value)); // This should never be called #ifdef USE_OLD_BOOST_ARCHIVE_OVERRIDE this->CommonOArchive::save_override( t, 0 ); #else this->CommonOArchive::save_override( t ); #endif } // Save a type that is wrapped in a boost::serialization::nvp template<typename Archive> template<typename T> inline void HDF5OArchiveImpl<Archive>::save_override( const boost::serialization::nvp<T>& t, int ) { this->save_start( t.name() ); this->saveIntercept(t.const_value(), typename std::conditional<IsTuple<T>::value && Utility::HDF5TypeTraits<T>::IsSpecialized::value,std::true_type,std::false_type>::type()); this->save_end( t.name() ); } // Save a boost::archive::object_id_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::object_id_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "object id type: " ); unsigned object_id = t; this->writeToCurrentGroupAttribute( "object_id", &object_id, 1 ); this->linkTrackedObject( object_id ); d_next_object_is_attribute = true; this->save( object_id ); } // Save a boost::archive::object_reference_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::object_reference_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "object reference type: " ); unsigned object_reference = t; this->writeToCurrentGroupAttribute( "object_reference", &object_reference, 1 ); this->linkTrackedObjectReference( object_reference ); d_next_object_is_attribute = true; this->save( object_reference ); } // Save a boost::archive::version_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::version_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "version type: " ); unsigned version = t; this->writeToCurrentGroupAttribute( "version", &version, 1 ); d_next_object_is_attribute = true; this->save( version ); } // Save a boost::archive::class_id_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_id_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "class id type: " ); size_t class_id = t; this->writeToCurrentGroupAttribute( "class_id", &class_id, 1 ); d_next_object_is_attribute = true; this->save( class_id ); } // Save a boost::archive::class_id_optional_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_id_optional_type& t, int ) { // Ignore the writing of this type - it is not needed by this archive type // Note: this implementation of this method is similar to the implementation // of the equivalent method for other archive types. #if 0 size_t class_id_optional = t; this->writeToCurrentGroupAttribute( "class_id_optional", &class_id_optional, 1 ); d_next_object_is_attribute = true; this->save( class_id_optional ); #endif } // Save a boost::archive::class_id_reference_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_id_reference_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "class id reference type: " ); size_t class_id_reference = t; this->writeToCurrentGroupAttribute( "class_id_reference", &class_id_reference, 1 ); d_next_object_is_attribute = true; this->save( class_id_reference ); } // Save a boost::archive::class_name_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::class_name_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "class name type: " ); const std::string class_name( t ); this->writeToCurrentGroupAttribute( "class_name", &class_name, 1 ); d_next_object_is_attribute = true; this->save( class_name ); } // Save a boost::archive::tracking_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save_override( const boost::archive::tracking_type& t, int ) { //FRENSIE_LOG_PARTIAL_NOTIFICATION( "tracking type: " ); this->writeToCurrentGroupAttribute( "class_tracking", &t.t, 1 ); d_next_object_is_attribute = true; this->save( t.t ); } // Save any type with a Utility::HDF5TypeTraits specialization template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::save( const T& t ) { this->saveImpl( &t, 1 ); } // Save a wide string template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const wchar_t& t ) { THROW_HDF5_ARCHIVE_EXCEPTION( "Wide chars are not currently supported!" ); } // Save a wide string template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const std::wstring& t ) { THROW_HDF5_ARCHIVE_EXCEPTION( "Wide strings are not currently supported!" ); } // Save a boost::serialization::collection_size_type template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const boost::serialization::collection_size_type& t ) { size_t collection_size = t; this->save( collection_size ); } // Save a boost::serialization::item_version_type attribute template<typename Archive> void HDF5OArchiveImpl<Archive>::save( const boost::serialization::item_version_type& t ) { unsigned version = t; this->save( version ); } // Write to current group attribute template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::writeToCurrentGroupAttribute( const std::string& attribute_name, const T* const data, const size_t size ) { std::ostringstream full_attribute_name; full_attribute_name << attribute_name << "_d" << d_object_count; try{ this->writeToGroupAttribute( this->getTreeObjectPath(), full_attribute_name.str(), data, size ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not write data to group attribute " << this->getTreeObjectPath() << ":" << full_attribute_name.str() << "!" ); } // Intercept a type that is about to be saved template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveIntercept( const T& t, std::true_type is_fast_serializable_tuple ) { this->save(t); } // Intercept a type that is about to be saved template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveIntercept( const T& t, std::false_type is_fast_serializable_tuple ) { #if USE_OLD_BOOST_ARCHIVE_OVERRIDE this->CommonOArchive::save_override( t, 0 ); #else this->CommonOArchive::save_override( t ); #endif } // Save implementation template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveImpl( const T* data, size_t count ) { try{ this->saveImpl( this->getObjectDataPath( d_object_count ), data, count ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not save data for primitive " "object " << d_object_count << " of type " << Utility::typeName<T>() << "!" ); } // Save implementation (object data set path already determined) template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveImpl( const std::string& object_data_set_path, const T* data, size_t count ) { //FRENSIE_LOG_NOTIFICATION( object_data_set_path << " (" << Utility::typeName<T>() << ")" ); this->writeToDataSet( object_data_set_path, data, count ); this->linkDataAndUpdateObjectCount(); } // Save container implementation template<typename Archive> template<typename T> void HDF5OArchiveImpl<Archive>::saveContainerImpl( const T& container ) { std::string object_data_set_path = this->getObjectDataPath( d_object_count ); try{ this->saveImpl( object_data_set_path, container.data(), container.size() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not save data for container " "object " << d_object_count << " of type " << Utility::typeName<T>() << "!" ); } // Start an hdf5 group template<typename Archive> void HDF5OArchiveImpl<Archive>::startHDF5Group( const char* group_name ) { std::ostringstream full_group_name; if( group_name == NULL ) full_group_name << "_g" << d_group_count; else full_group_name << group_name << "_g" << d_group_count; d_group_stack.push_back( full_group_name.str() ); this->createGroup( this->getTreeObjectPath() ); ++d_group_count; } // End an hdf5 group template<typename Archive> void HDF5OArchiveImpl<Archive>::endHDF5Group() { d_group_stack.pop_back(); } // Get the tree object path template<typename Archive> std::string HDF5OArchiveImpl<Archive>::getTreeObjectPath() const { std::ostringstream oss; oss << this->getTreeDir(); GroupStack::const_iterator it = d_group_stack.begin(); GroupStack::const_iterator end = d_group_stack.end(); while( it != end ) { oss << "/" << *it; ++it; } return oss.str(); } // Link the data object template<typename Archive> void HDF5OArchiveImpl<Archive>::linkDataObject() { if( !d_next_object_is_attribute ) { std::ostringstream link_path; link_path << this->getTreeObjectPath() << "/<data>_d" << d_object_count; const std::string object_path = this->getObjectDataPath( d_object_count ); try{ this->createHardLink( object_path, link_path.str() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not create a link with path " << link_path.str() << " to data object " << d_object_count << " at " << object_path << "!" ); } d_next_object_is_attribute = false; } // Link the tracked object template<typename Archive> void HDF5OArchiveImpl<Archive>::linkTrackedObject( unsigned object ) { const std::string link_path = this->getTrackedObjectsPath( object ); const std::string object_path = this->getTreeObjectPath(); try{ this->createSoftLink( object_path, link_path ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not create a link with path " << link_path << " to data object " << object << " at " << object_path << "!" ); } // Link the tracked object reference template<typename Archive> void HDF5OArchiveImpl<Archive>::linkTrackedObjectReference( unsigned object_reference ) { std::ostringstream link_path; link_path << this->getTreeObjectPath() << "/<reference>_o" << object_reference; const std::string object_path = this->getTrackedObjectsPath( object_reference ); try{ this->createSoftLink( object_path, link_path.str() ); } HDF5_FILE_EXCEPTION_CATCH_RETHROW( "Could not create a link with path " << link_path.str() << " to data object " << object_reference << " at " << object_path << "!" ); } // Link the data and update the object count template<typename Archive> void HDF5OArchiveImpl<Archive>::linkDataAndUpdateObjectCount() { this->linkDataObject(); ++d_object_count; } } // end Utility namespace #endif // end UTILITY_HDF5_OARCHIVE_IMPL_DEF_HPP //---------------------------------------------------------------------------// // end Utility_HDF5OArchiveImpl_def.hpp //---------------------------------------------------------------------------//
31.97446
176
0.642949
bam241
10f1a471a36c3904f10641621de29965b79e4415
553
cpp
C++
source/RTTR.cpp
xzrunner/js
4d1387c8561884c585dd86e4e0f21885eeada1ec
[ "MIT" ]
null
null
null
source/RTTR.cpp
xzrunner/js
4d1387c8561884c585dd86e4e0f21885eeada1ec
[ "MIT" ]
null
null
null
source/RTTR.cpp
xzrunner/js
4d1387c8561884c585dd86e4e0f21885eeada1ec
[ "MIT" ]
null
null
null
#include "js/RTTR.h" namespace detail { extern std::string rttr_to_rapidjson(rttr::instance obj, const std::string& dir_path); extern bool rttr_from_rapidjson(const std::string& json, const std::string& dir_path, rttr::instance obj); } namespace js { std::string RTTR::ToRapidJson(rttr::instance obj, const std::string& dir_path) { return detail::rttr_to_rapidjson(obj, dir_path); } bool RTTR::FromRapidJson(const std::string& json, const std::string& dir_path, rttr::instance obj) { return detail::rttr_from_rapidjson(json, dir_path, obj); } }
23.041667
106
0.75226
xzrunner
10f40c81e8745dbd133d965258c2b4484ef30fc1
2,630
cpp
C++
src/tools/loop_stats/src/LoopStats_InductionVariables.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
null
null
null
src/tools/loop_stats/src/LoopStats_InductionVariables.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
null
null
null
src/tools/loop_stats/src/LoopStats_InductionVariables.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
null
null
null
/* * Copyright 2019 - 2020 Angelo Matni, Simone Campanoni * * 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 "LoopStats.hpp" using namespace llvm; using namespace llvm::noelle; void LoopStats::collectStatsOnNoelleIVs (Hot *profiles, LoopDependenceInfo &LDI, Stats *statsForLoop) { auto loopStructure = LDI.getLoopStructure(); auto ivManager = LDI.getInductionVariableManager(); auto ivs = ivManager->getInductionVariables(*loopStructure); statsForLoop->numberOfIVs = ivs.size(); for (auto iv : ivs) { auto phiNode = iv->getLoopEntryPHI(); statsForLoop->numberOfDynamicIVs += profiles->getTotalInstructions(phiNode); } auto GIV = ivManager->getLoopGoverningIVAttribution(*loopStructure); if (GIV != nullptr){ statsForLoop->isGovernedByIV = 1; statsForLoop->numberOfDynamicGovernedIVs = profiles->getTotalInstructions(GIV->getHeaderCmpInst()); } return ; } void LoopStats::collectStatsOnLLVMIVs (Hot *profiles, ScalarEvolution &SE, Loop &llvmLoop, Stats *statsForLoop) { /* * Note: LLVM does not provide a way to collect all instructions used in computing IVs */ for (auto &phi : llvmLoop.getHeader()->phis()) { bool llvmLoopValidForInductionAnalysis = phi.getBasicBlockIndex(llvmLoop.getLoopPreheader()) >= 0; if (llvmLoopValidForInductionAnalysis && llvmLoop.isAuxiliaryInductionVariable(phi, SE)) { statsForLoop->numberOfIVs++; } statsForLoop->numberOfDynamicIVs = profiles->getTotalInstructions(&phi); } auto governingIV = llvmLoop.getInductionVariable(SE); if (governingIV != nullptr){ statsForLoop->isGovernedByIV = 1; } return ; }
46.964286
435
0.759696
SusanTan
10f491ead11c97c3bec0a5dbf3c1c72f4db6b4bb
763
cpp
C++
Source/Core/TornadoEngine/Components/Logic/ObjectInstanceEndHandlerBuilderSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
27
2015-01-08T08:26:29.000Z
2019-02-10T03:18:05.000Z
Source/Core/TornadoEngine/Components/Logic/ObjectInstanceEndHandlerBuilderSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
1
2017-04-05T02:02:14.000Z
2017-04-05T02:02:14.000Z
Source/Core/TornadoEngine/Components/Logic/ObjectInstanceEndHandlerBuilderSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
17
2015-01-18T02:50:01.000Z
2019-02-08T21:00:53.000Z
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [[email protected], [email protected]] See for more information LICENSE.md. */ #include "ObjectInstanceEndHandlerBuilderSystem.h" #include "Modules.h" #include "LogicModule.h" #include "HandlerCallCollector.h" using namespace nsLogicWrapper; void TObjectInstanceEndHandlerBuilderSystem::Reactive(nsECSFramework::TEntityID eid, const nsLogicWrapper::TObjectInstanceEndHandlerComponent* pC) { auto handler = pC->handler; if (handler == nullptr) { return; } auto handlerCallCollector = nsTornadoEngine::Modules()->HandlerCalls(); handlerCallCollector->Add([handler, eid]() { handler->Handle(eid); }); }
26.310345
147
0.711664
RamilGauss
10f5def95557eea3f8b793b27399968598c2b537
5,503
cpp
C++
TommyGun/Plugins/CodeEditor/PaletteParser/fPaletteParserOptions.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/Plugins/CodeEditor/PaletteParser/fPaletteParserOptions.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/Plugins/CodeEditor/PaletteParser/fPaletteParserOptions.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
#pragma link "KSpinEdit" /*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include "pch.h" #pragma hdrstop //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" #pragma link "KXmlInfo" //--------------------------------------------------------------------------- using namespace Scorpio; using namespace PaletteParser; //--------------------------------------------------------------------------- TfrmPaletteParserOptions *frmPaletteParserOptions = NULL; //--------------------------------------------------------------------------- __fastcall TfrmPaletteParserOptions::TfrmPaletteParserOptions(TComponent* Owner) : TForm(Owner) , m_pPlugin(NULL) { } //--------------------------------------------------------------------------- HRESULT __fastcall TfrmPaletteParserOptions::Initialize(ZXPlugin* pPlugin) { RL_HRESULT(S_OK); m_pPlugin = pPlugin; String Prefix; regScorpio->Read("PaletteParser", "Prefix", Prefix); int iState = 0; if (regScorpio->Read("PaletteParser", "NumberBase", iState)) { switch(iState) { case 1: radZXPaletteParserHexidecimal->Checked = true; break; case 2: radZXPaletteParserBinary->Checked = true; break; case 0: default: radZXPaletteParserDecimal->Checked = true; } } if (Prefix.Trim() != "") { edtNumericalPrefix->Text = Prefix; } return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall TfrmPaletteParserOptions::Release(void) { RL_HRESULT(S_OK); return hResult; } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radZXPaletteParserDecimalClick(TObject *Sender) { edtNumericalPrefix->Text = ""; regScorpio->Write("PaletteParser", "NumberBase", 0); } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radZXPaletteParserHexidecimalClick(TObject *Sender) { edtNumericalPrefix->Text = "$"; regScorpio->Write("PaletteParser", "NumberBase", 1); } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radZXPaletteParserBinaryClick(TObject *Sender) { edtNumericalPrefix->Text = "%"; regScorpio->Write("PaletteParser", "NumberBase", 2); } //--------------------------------------------------------------------------- String __fastcall TfrmPaletteParserOptions::NumToStr(unsigned char iNum) { String sNum = ""; String sPrefix = frmPaletteParserOptions->edtNumericalPrefix->Text.Trim(); if (radZXPaletteParserDecimal->Checked) { sNum = " " + IntToStr(iNum); sNum = sPrefix + sNum.SubString(sNum.Length() - 2, 3); } else if (radZXPaletteParserHexidecimal->Checked) { sNum = "00" + IntToHex(iNum, 2); sNum = sPrefix + sNum.SubString(sNum.Length() - 1, 2); } else if (radZXPaletteParserBinary->Checked) { sNum = sPrefix; unsigned char bitmask = 0x80; for (int i = 0; i < 8; i++) { sNum += iNum & bitmask ? "1" : "0"; bitmask >>= 1; } } return sNum; } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::edtLabelPrefixChange(TObject *Sender) { lblExample->Caption = edtLabelPrefix->Text + "MyLabel" + edtLabelPostfix->Text; } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::edtNumericalPrefixChange(TObject *Sender) { regScorpio->Write("PaletteParser", "Prefix", edtNumericalPrefix->Text); } //--------------------------------------------------------------------------- void __fastcall TfrmPaletteParserOptions::radSourceCodeAsmClick(TObject *Sender) { lblPrefix->Enabled = radSourceCodeAsm->Checked; edtPrefix->Enabled = radSourceCodeAsm->Checked; chkSourceCodeUseLabel->Enabled = radSourceCodeAsm->Checked; lblLabelPrefix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; lblLabelPostfix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; edtLabelPrefix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; edtLabelPostfix->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; lblExample->Enabled = radSourceCodeAsm->Checked && chkSourceCodeUseLabel->Checked; } //---------------------------------------------------------------------------
39.028369
98
0.466291
tonyt73
10fbc17be7c46cd179d7c469a97ba04bef88412a
2,689
cpp
C++
3rdParty/Aria/src/ArTransform.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
3rdParty/Aria/src/ArTransform.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
3rdParty/Aria/src/ArTransform.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2015 Adept Technology, Inc. Copyright (C) 2016 Omron Adept Technologies, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at [email protected] or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ #include "ArExport.h" #include "ariaOSDef.h" #include "ArTransform.h" AREXPORT void ArTransform::doTransform(std::list<ArPose *> *poseList) { std::list<ArPose *>::iterator it; ArPose *pose; for (it = poseList->begin(); it != poseList->end(); it++) { pose = (*it); *pose = doTransform(*pose); } } AREXPORT void ArTransform::doTransform(std::list<ArPoseWithTime *> *poseList) { std::list<ArPoseWithTime *>::iterator it; ArPoseWithTime *pose; for (it = poseList->begin(); it != poseList->end(); it++) { pose = (*it); *pose = doTransform(*pose); } } /** @param pose the coord system from which we transform to abs world coords */ AREXPORT void ArTransform::setTransform(ArPose pose) { myTh = pose.getTh(); myCos = ArMath::cos(-myTh); mySin = ArMath::sin(-myTh); myX = pose.getX(); myY = pose.getY(); } /** @param pose1 transform this into pose2 @param pose2 transform pose1 into this */ AREXPORT void ArTransform::setTransform(ArPose pose1, ArPose pose2) { myTh = ArMath::subAngle(pose2.getTh(), pose1.getTh()); myCos = ArMath::cos(-myTh); mySin = ArMath::sin(-myTh); myX = pose2.getX() - (myCos * pose1.getX() + mySin * pose1.getY()); myY = pose2.getY() - (myCos * pose1.getY() - mySin * pose1.getX()); } AREXPORT void ArTransform::setTransformLowLevel(double x, double y, double th) { myTh = th; myCos = ArMath::cos(-myTh); mySin = ArMath::sin(-myTh); myX = x; myY = y; }
29.877778
78
0.693938
bellonemauro
10ff9243ff70b7edce6d99b3edda04c3ee82e67b
1,737
cpp
C++
scenewidget.cpp
predmach/vtk_realsense
4139a86b07ced908ce5b4b9f3089a4fb9fa6a532
[ "Apache-2.0" ]
103
2017-04-01T06:10:08.000Z
2022-03-23T03:13:49.000Z
scenewidget.cpp
JoyPoint/Qt-VTK-viewer
51ee2c4b99982c2798fd99ba89212940861768ac
[ "Apache-2.0" ]
9
2018-04-04T16:14:10.000Z
2021-01-24T15:20:58.000Z
scenewidget.cpp
JoyPoint/Qt-VTK-viewer
51ee2c4b99982c2798fd99ba89212940861768ac
[ "Apache-2.0" ]
35
2017-01-25T01:48:47.000Z
2022-03-27T07:39:30.000Z
#include "scenewidget.h" #include <vtkCamera.h> #include <vtkDataSetMapper.h> #include <vtkGenericOpenGLRenderWindow.h> #include <vtkProperty.h> #include <vtkRenderWindowInteractor.h> SceneWidget::SceneWidget(QWidget* parent) : QVTKOpenGLNativeWidget(parent) { vtkNew<vtkGenericOpenGLRenderWindow> window; setRenderWindow(window.Get()); // Camera vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New(); camera->SetViewUp(0, 1, 0); camera->SetPosition(0, 0, 10); camera->SetFocalPoint(0, 0, 0); // Renderer m_renderer = vtkSmartPointer<vtkRenderer>::New(); m_renderer->SetActiveCamera(camera); m_renderer->SetBackground(0.5, 0.5, 0.5); renderWindow()->AddRenderer(m_renderer); } void SceneWidget::addDataSet(vtkSmartPointer<vtkDataSet> dataSet) { // Actor vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); // Mapper vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(dataSet); actor->SetMapper(mapper); m_renderer->AddActor(actor); m_renderer->ResetCamera(dataSet->GetBounds()); renderWindow()->Render(); } void SceneWidget::removeDataSet() { vtkActor* actor = m_renderer->GetActors()->GetLastActor(); if (actor != nullptr) { m_renderer->RemoveActor(actor); } renderWindow()->Render(); } void SceneWidget::zoomToExtent() { // Zoom to extent of last added actor vtkSmartPointer<vtkActor> actor = m_renderer->GetActors()->GetLastActor(); if (actor != nullptr) { m_renderer->ResetCamera(actor->GetBounds()); } renderWindow()->Render(); }
27.140625
89
0.671272
predmach
8007346c8b0fb80fbfd2d8e50fe82ff5e8d7cf77
1,083
cpp
C++
EmerCert/MainWindow.cpp
emercoin-scratch/EmerCert
9d17b363dd0e9d6feb07c62ee385e585d9a72dee
[ "BSD-2-Clause" ]
2
2018-11-12T16:22:44.000Z
2021-04-24T03:08:24.000Z
EmerCert/MainWindow.cpp
emercoin-scratch/EmerCert
9d17b363dd0e9d6feb07c62ee385e585d9a72dee
[ "BSD-2-Clause" ]
1
2018-07-09T22:20:45.000Z
2021-03-20T05:00:55.000Z
EmerCert/MainWindow.cpp
emercoin-scratch/EmerCert
9d17b363dd0e9d6feb07c62ee385e585d9a72dee
[ "BSD-2-Clause" ]
3
2018-10-06T20:35:05.000Z
2020-11-26T00:15:45.000Z
#include "pch.h" #include "MainWindow.h" #include "InfoCardsWidget.h" #include "ManageSslPage.h" #include "ManageDnsPage.h" #include "EnumerDialog.h" #include "DiplomaWidget.h" #include "DpoWidget.h" #include "AboutWidget.h" MainWindow::MainWindow(QWidget *parent): QTabWidget(parent) { setWindowTitle(tr("EmerCert Manager ") + QCoreApplication::applicationVersion()); add(new ManageSslPage); add(new InfoCardsWidget); add(new ManageDnsPage); add(new DpoWidget); add(new DiplomaWidget); #ifdef _DEBUG add(new EnumerDialog); #endif add(new AboutWidget); setIconSize({32, 32}); auto quit = new QAction(tr("Quit")); quit->setShortcut(QKeySequence("Ctrl+Q")); connect(quit, &QAction::triggered, qApp, &QCoreApplication::quit); addAction(quit); QSettings sett; int index = sett.value("MainWindow.tabIndex", 0).toInt(); index = qBound(0, index, count()-1); setCurrentIndex(index); } void MainWindow::add(QWidget *w) { addTab(w, w->windowIcon(), w->windowTitle()); } MainWindow::~MainWindow() { QSettings sett; sett.setValue("MainWindow.tabIndex", currentIndex()); }
27.075
82
0.730379
emercoin-scratch
800950a892025477a88272510d8be9b29912b92c
4,415
cpp
C++
qgeotiledmappingmanagerenginegooglemaps.cpp
mfbernardes/googlemaps
7ce7124b385b2ebac0f72c38b094f436d4fe5c58
[ "MIT" ]
123
2016-07-18T07:53:34.000Z
2022-02-21T20:30:27.000Z
qgeotiledmappingmanagerenginegooglemaps.cpp
mfbernardes/googlemaps
7ce7124b385b2ebac0f72c38b094f436d4fe5c58
[ "MIT" ]
30
2016-07-18T07:55:30.000Z
2022-03-06T02:03:24.000Z
qgeotiledmappingmanagerenginegooglemaps.cpp
mfbernardes/googlemaps
7ce7124b385b2ebac0f72c38b094f436d4fe5c58
[ "MIT" ]
66
2016-09-17T12:41:41.000Z
2021-12-28T16:39:48.000Z
#include "QtLocation/private/qgeocameracapabilities_p.h" #include "qgeotiledmappingmanagerenginegooglemaps.h" #include "qgeotiledmapgooglemaps.h" #include "qgeotilefetchergooglemaps.h" #include "QtLocation/private/qgeotilespec_p.h" #if QT_VERSION < QT_VERSION_CHECK(5,6,0) #include <QStandardPaths> #include "QtLocation/private/qgeotilecache_p.h" #else #include "QtLocation/private/qgeofiletilecache_p.h" #endif #include <QDebug> #include <QDir> #include <QVariant> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QJsonDocument> #include <QtCore/qmath.h> #include <QtCore/qstandardpaths.h> QT_BEGIN_NAMESPACE QGeoTiledMappingManagerEngineGooglemaps::QGeoTiledMappingManagerEngineGooglemaps(const QVariantMap &parameters, QGeoServiceProvider::Error *error, QString *errorString) : QGeoTiledMappingManagerEngine() { Q_UNUSED(error); Q_UNUSED(errorString); QGeoCameraCapabilities capabilities; capabilities.setMinimumZoomLevel(0.0); capabilities.setMaximumZoomLevel(21.0); setCameraCapabilities(capabilities); int tile = parameters.value(QStringLiteral("googlemaps.maps.tilesize"), 256).toInt(); setTileSize(QSize(tile, tile)); QList<QGeoMapType> types; #if QT_VERSION < QT_VERSION_CHECK(5,9,0) types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1); types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2); types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3); types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4); #elif QT_VERSION < QT_VERSION_CHECK(5,10,0) types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps"); types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps"); types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps"); types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps"); #else types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps", capabilities, parameters); types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps", capabilities, parameters); types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps", capabilities, parameters); types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps", capabilities, parameters); #endif setSupportedMapTypes(types); QGeoTileFetcherGooglemaps *fetcher = new QGeoTileFetcherGooglemaps(parameters, this, tileSize()); setTileFetcher(fetcher); if (parameters.contains(QStringLiteral("googlemaps.cachefolder"))) m_cacheDirectory = parameters.value(QStringLiteral("googlemaps.cachefolder")).toString(); const int szCache = 100 * 1024 * 1024; #if QT_VERSION < QT_VERSION_CHECK(5,6,0) if (m_cacheDirectory.isEmpty()) m_cacheDirectory = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("googlemaps"); QGeoTileCache *tileCache = createTileCacheWithDir(m_cacheDirectory); if (tileCache) tileCache->setMaxDiskUsage(szCache); #else if (m_cacheDirectory.isEmpty()) m_cacheDirectory = QAbstractGeoTileCache::baseCacheDirectory() + QLatin1String("googlemaps"); QAbstractGeoTileCache *tileCache = new QGeoFileTileCache(m_cacheDirectory); tileCache->setMaxDiskUsage(szCache); setTileCache(tileCache); #endif *error = QGeoServiceProvider::NoError; errorString->clear(); } QGeoTiledMappingManagerEngineGooglemaps::~QGeoTiledMappingManagerEngineGooglemaps() { } QGeoMap *QGeoTiledMappingManagerEngineGooglemaps::createMap() { return new QGeoTiledMapGooglemaps(this); } QT_END_NAMESPACE
45.515464
176
0.752435
mfbernardes
800a5d7416a13180aafa1398d84598e65c192f5a
5,508
cpp
C++
Src/lunaui/launcher/gfx/scrollingsurface.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/lunaui/launcher/gfx/scrollingsurface.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/lunaui/launcher/gfx/scrollingsurface.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "scrollingsurface.h" #include "pixmapobject.h" #include "dimensionsglobal.h" #include <QPainter> #include <QDebug> ScrollingSurface::ScrollingSurface(const QRectF& geometry) : ScrollableObject(geometry) , m_qp_surfacePmo(0) { } //virtual ScrollingSurface::~ScrollingSurface() { } void ScrollingSurface::resetTargetRectValid() { m_targetRect = QRect(m_screenGeom.x(), m_screenGeom.y(), m_maxSourceRectWidth, m_maxSourceRectHeight); } //TODO: pixmap management - deletion of unused when new ones are set void ScrollingSurface::setPixmapObject(PixmapObject * p_pmo) { m_qp_surfacePmo = p_pmo; if (p_pmo) { setFlag(QGraphicsItem::ItemHasNoContents,false); setSourceContentGeom(DimensionsGlobal::realRectAroundRealPoint(QSizeF(p_pmo->size()))); } else { setFlag(QGraphicsItem::ItemHasNoContents,true); m_sourceRect = QRect(0,0,0,0); setSourceContentGeom(QRectF(0,0,0,0)); //TODO: TEST: see setSourceContentGeom. clean this up m_targetRect = QRect(0,0,0,0); } update(m_boundingRect); } bool ScrollingSurface::testAndtranslateScrollSurfacePointToPixmapPoint(const QPointF& pointF,QPoint& r_translatedPoint) { // QPoint point = pointF.toPoint(); // if (m_targetRect.contains(point)) // { // //ask the pixmapobject to map this for me // r_translatedPoint = m_qp_surfacePmo->translatePaintTargetPointToPixmapPoint(point,m_sourceRect,m_targetRect); // //qDebug() << __PRETTY_FUNCTION__ << ": point: " << point << " , pixmap point: " << r_translatedPoint; // return true; // } // //qDebug() << __PRETTY_FUNCTION__ << ": point: " << point << " is not contained in the target paint rect " << m_targetRect; return false; } //virtual qint32 ScrollingSurface::scrollValue() const { if (m_overscrollVal) return m_overscrollVal; //else not in overscroll, return the top y of the source rect return m_sourceRect.top(); } //virtual qint32 ScrollingSurface::rawScrollValue() const { return m_sourceRect.top(); } //virtual void ScrollingSurface::setScrollValue(qint32 v) { //qDebug() << __FUNCTION__ << " " << v; if ((v >= 0) && (v < m_overscrollBottomStart)) { //no overscroll...somewhere in the middle of things m_sourceRect.setY(v); m_sourceRect.setHeight(m_maxSourceRectHeight); resetTargetRectValid(); m_overscrollVal = 0; } else if (v < 0) { //Negative values: set it to overscroll from top. //the source rect is shrunk, with the shrinking coming from the bottom of the rect m_sourceRect.setY(0); m_sourceRect.setHeight(qMax(0,m_screenGeom.height()+v)); m_targetRect.setY(m_screenGeom.top() + qMin(-v,m_screenGeom.height())); m_targetRect.setHeight(m_sourceRect.height()); m_overscrollVal = v; } else { //TODO: PIXEL-ALIGN QSize sourceSize = m_sourceGeom.size().toSize(); //Positive value > m_overscrollBottomStart //the source rect is shrunk, with the shrinking coming from the top qint32 va = qMin(v,sourceSize.height()); m_sourceRect.setY(va); m_sourceRect.setHeight(sourceSize.height()-va); m_targetRect.setY(m_screenGeom.top()); m_targetRect.setHeight(m_sourceRect.height()); m_overscrollVal = v; } update(m_boundingRect); } ////public Q_SLOTS: /* * * These geom change functions are empty on purpose...see .h file * */ //virtual void ScrollingSurface::slotSourceGeomChanged(const QRectF& newGeom) { } //virtual void ScrollingSurface::slotSourceContentSizeChanged(const QSizeF& newContentSize) { } //virtual void ScrollingSurface::slotSourceContentSizeChanged(const QSize& newContentSize) { } ////protected: //virtual void ScrollingSurface::setSourceContentGeom(const QRectF& newContentGeom) { m_sourceGeom = newContentGeom; //TODO: PIXEL-ALIGN QSize sourceSize = m_sourceGeom.size().toSize(); m_maxSourceRectWidth = qMin(sourceSize.width(),m_screenGeom.width()); m_maxSourceRectHeight = qMin(sourceSize.height(),m_screenGeom.height()); m_sourceRect = QRect(0,0,m_maxSourceRectWidth,m_maxSourceRectHeight); m_targetRect = QRect(m_screenGeom.x(), m_screenGeom.y(), m_maxSourceRectWidth, m_maxSourceRectHeight); m_overscrollBottomStart = qMax(0,sourceSize.height()-m_screenGeom.height()); } //virtual void ScrollingSurface::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget) { //ASSUMES m_qp_surfacePmo is valid; the ItemHasNoContents should have been set otherwise QPen sp = painter->pen(); painter->setPen(Qt::green); painter->drawRect(m_screenGeom); painter->setPen(sp); // painter->drawPixmap(m_screenGeom.x(),m_screenGeom.y(), // m_screenGeom.width(),m_screenGeom.height(), // (*(*m_qp_surfacePmo)),m_sourceRect.x(),m_sourceRect.y(), // m_sourceRect.width(),m_sourceRect.height()); //COMMENTED TO TEST OUT HUGE PIXMAP // painter->drawPixmap(m_targetRect, // (*(*m_qp_surfacePmo)), // m_sourceRect); // m_qp_surfacePmo->paint(painter,m_targetRect,m_sourceRect); }
27.402985
127
0.741649
ericblade
80187f641b4aaa50fe7b57d6a3437056fcfe5292
3,443
hpp
C++
source/gameos/include/linkedlist.hpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/gameos/include/linkedlist.hpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/gameos/include/linkedlist.hpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
#pragma once //===========================================================================// // File: LinkedList.hpp // // Contents: Linked list routines // //---------------------------------------------------------------------------// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// class gosLink { public: gosLink* Next; gosLink* Prev; PVOID linkData; public: gosLink() { linkData = 0; Next = 0; Prev = 0; } gosLink(PVOID ptr) { linkData = ptr; Next = 0; Prev = 0; } virtual ~gosLink() { Next = 0; Prev = 0; } gosLink* GetNext() { return (gosLink*)linkData; } }; template <class T> class LinkedList { public: gosLink* m_Head; int32_t m_Size; public: LinkedList() { m_Head = 0; m_Size = 0; }; LinkedList(T ptr) { gosLink* newlink = (gosLink*)malloc(sizeof(gosLink)); m_Head = newlink; m_Head->Next = 0; m_Size = 1; }; ~LinkedList() { while (m_Head != 0) Del((T)m_Head->linkData); }; void Add(T ptr) { gosLink* newlink = (gosLink*)malloc(sizeof(gosLink)); newlink->linkData = ptr; newlink->Next = 0; newlink->Prev = 0; if (m_Head == 0) { m_Head = newlink; newlink->Next = 0; newlink->Prev = 0; } else { gosLink* tmp = m_Head; while (tmp->Next != 0) tmp = tmp->Next; tmp->Next = newlink; newlink->Next = 0; newlink->Prev = tmp; } m_Size += 1; } void Del(T ptr) { if (!m_Head) // YIK - Why does it need this! (Delete All surfaces used // to crash) return; gosLink* tmp = m_Head; if (tmp->linkData == (PVOID)ptr) { m_Head = tmp->Next; tmp->Prev = 0; m_Size -= 1; memset(tmp, 0, sizeof(tmp)); free(tmp); } else { gosLink* target; while (tmp->Next != 0) { if (tmp->Next->linkData == (PVOID)ptr) { target = tmp->Next; tmp->Next = target->Next; if (target->Next) target->Next->Prev = tmp; m_Size -= 1; free(target); memset(tmp, 0, sizeof(tmp)); return; } else { tmp = (gosLink*)tmp->Next; } } } } int32_t Size() { return m_Size; } T Get(int32_t index) { gosLink* tmp = m_Head; if (tmp == 0) { return 0; } while (index && tmp->Next) { tmp = tmp->Next; index--; } if (index != 0) { return 0; } else { return (T)tmp->linkData; } } }; template <class T> class LinkedListIterator { public: gosLink* m_Iterator; LinkedList<T>* m_List; public: LinkedListIterator(LinkedList<T>* list) { m_Iterator = list->m_Head; m_List = list; } ~LinkedListIterator() {} T Head() { m_Iterator = m_List->m_Head; if (m_List->m_Head == 0) return 0; return (T)((gosLink*)m_List->m_Head)->linkData; } T Tail() { m_Iterator = m_List->m_Head; if (!m_Iterator) return 0; while (m_Iterator->Next != 0) { m_Iterator = m_Iterator->Next; } return (T)((gosLink*)m_Iterator)->linkData; } T ReadAndNext() { gosLink* tmp = m_Iterator; if (tmp == 0) return (T)0; m_Iterator = m_Iterator->Next; return (T)((gosLink*)tmp)->linkData; } T ReadAndPrev() { gosLink* tmp = m_Iterator; if (tmp == 0) return (T)0; m_Iterator = m_Iterator->Prev; return (T)((gosLink*)tmp)->linkData; } T Next() { m_Iterator = m_Iterator->Next; if (m_Iterator == 0) return 0; return (T)m_Iterator->linkData; } };
16.960591
79
0.533256
mechasource
801aeba9d2d56daefc70741d6ed771cfe48bdc37
748
cpp
C++
经典算法练习题/翻转单词顺序序列.cpp
anbingxu666/WangDao-DataStructure
70dcd76c1e26852d659a01358ecb90b8eec2e2ba
[ "Apache-2.0" ]
382
2019-08-09T12:46:46.000Z
2022-03-31T08:38:48.000Z
经典算法练习题/翻转单词顺序序列.cpp
anbingxu666/WangDao-DataStructure
70dcd76c1e26852d659a01358ecb90b8eec2e2ba
[ "Apache-2.0" ]
1
2019-09-04T05:45:49.000Z
2020-12-17T12:02:22.000Z
经典算法练习题/翻转单词顺序序列.cpp
anbingxu666/WangDao-DataStructure
70dcd76c1e26852d659a01358ecb90b8eec2e2ba
[ "Apache-2.0" ]
86
2019-09-04T05:44:34.000Z
2022-03-08T05:06:00.000Z
// // Created by newLion on 2020-06-10. // #include <string> using namespace std; string ReverseSentence(string str) { if (str.empty()) return str; int i = 0, sz = str.size(); while (i < sz && str[i] == ' ') ++i; if (i == sz) return str; string ret = ""; //结果数组 string tmp = ""; //临时结果 bool hasstr = false; for (int i = sz - 1; i >= 0; --i) { // 合并一个单词 if (str[i] != ' ') { tmp = str[i] + tmp;; hasstr = true; } // 找到一个单词,将单词合并到结果串中 else if (str[i] == ' ' && hasstr) { ret = ret + tmp + " "; tmp = ""; hasstr = false; } } if (tmp != "") ret += tmp; return ret; }
19.684211
43
0.410428
anbingxu666
801e695b82291b98dbf5ec53ba811eb4107efb67
496
cpp
C++
Factory/examples/src/Derivee2.cpp
PhDunski/KoalaToolbox
ca2e46f886fe254324344ab0ddb612d1daa71e81
[ "MIT" ]
null
null
null
Factory/examples/src/Derivee2.cpp
PhDunski/KoalaToolbox
ca2e46f886fe254324344ab0ddb612d1daa71e81
[ "MIT" ]
null
null
null
Factory/examples/src/Derivee2.cpp
PhDunski/KoalaToolbox
ca2e46f886fe254324344ab0ddb612d1daa71e81
[ "MIT" ]
null
null
null
/** @file Derivee1.cpp * * Fournit la définition des fonctions membres de la classe Derivee2 * * Ce fichier permet de tester les classes de création d'objet au départ * de listes de paramètres à transmettre au constructeur * @author koala01 * @version 1.0 * @date 2013/12/15 */ #include <Derivee2.hpp> #include <iostream> void Derivee2::print() const{ std::cout<<"Derivee2 :" <<" str = "<< str_ <<" color : "<<color_<<std::endl; }
27.555556
74
0.610887
PhDunski
801f8b1416f4ea01aa775d1e7c0bdfa5ea0c6a27
39,876
cpp
C++
src/NetProtocol/Base/nNetConnector.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Base/nNetConnector.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Base/nNetConnector.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
#include <netprotocol.h> N::NetConnector:: NetConnector (void) : NetTalk ( ) { setParameter ( "Running" , true ) ; setParameter ( "Stopped" , true ) ; setParameter ( "ReadStopped" , true ) ; setParameter ( "WriteStopped" , true ) ; setParameter ( "Block" , false ) ; } N::NetConnector::~NetConnector (void) { } void N::NetConnector::Prepared (int flags) { } void N::NetConnector::Started (int flags) { } void N::NetConnector::Finished (int flags) { } bool N::NetConnector::AssignHost(void) { return false ; } bool N::NetConnector::BothChannels (void) { bool listening = false ; bool duty = false ; bool sleeping = true ; int state = 0 ; //////////////////////////////////////////////////////////////////////////// duty = Parameters [ "Running" ] . toBool ( ) ; setParameter ( "Stopped" , false ) ; setParameter ( "ReadStopped" , false ) ; setParameter ( "WriteStopped" , false ) ; //////////////////////////////////////////////////////////////////////////// if ( Parameters.contains("State" ) ) { state = Parameters [ "State" ] .toInt ( ) ; } else setParameter ( "State" , state ) ; ; //////////////////////////////////////////////////////////////////////////// AccessTime ( ) ; while ( duty ) { state = Parameters [ "State" ] .toInt ( ) ; switch ( state ) { case 0 : state = 101 ; sleeping = false ; setParameter ( "State" , state ) ; Prepend ( ) ; Prepared ( 3 ) ; AccessTime ( ) ; break ; case 101 : state = 102 ; sleeping = true ; AssignHost ( ) ; setParameter ( "State" , state ) ; AccessTime ( ) ; break ; case 102 : sleeping = true ; if ( Connect ( ) ) { state = 103 ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 103 : sleeping = true ; if ( isConnected ( 100 ) ) { state = 401 ; listening = true ; Started ( 3 ) ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 201 : sleeping = true ; listening = true ; if ( ReadChunk ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 202 : sleeping = true ; listening = true ; if ( ReadLine ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 203 : sleeping = true ; listening = true ; if ( ReadStructure ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 301 : sleeping = true ; listening = true ; if ( WriteCommand ( ) ) { state = 302 ; } else { state = 303 ; } ; setParameter ( "State" , state ) ; break ; case 302 : sleeping = true ; Interpreter -> Actions ( ) ; AccessTime ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 303 : sleeping = true ; Interpreter -> Actions ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 304 : sleeping = true ; state = 401 ; setParameter ( "State" , state ) ; break ; case 401 : sleeping = true ; if ( Interpreter->Data(NetProtocol::Output).size() > 0 ) { state = 301 ; } else if ( Interpreter -> contains ( "State" ) ) { Interpreter -> Actions ( ) ; state = Interpreter -> value ( "State" ) . toInt ( ) ; switch ( state ) { case 0 : state = 901 ; break ; case 1 : state = 201 ; break ; case 2 : state = 202 ; break ; case 3 : state = 203 ; break ; } ; } ; setParameter ( "State" , state ) ; break ; case 901 : sleeping = true ; listening = false ; Close ( ) ; state = 999 ; setParameter ( "State" , state ) ; break ; case 911 : Time :: msleep ( 10 ) ; break ; case 999 : if ( Parameters . contains ( "Running" ) && Parameters [ "Running" ] . toBool ( ) ) { bool retry = false ; bool Forever = false ; //////////////////////////////////////////////////////////////////// if ( Parameters . contains ( "Forever" ) ) { Forever = Parameters [ "Forever" ] . toBool ( ) ; } ; if ( Forever ) { retry = true ; } else { if ( Parameters.contains("Retry") ) { if ( Parameters["Trying"].toInt()<Parameters["Retry"].toInt()) { retry = true ; } ; } ; } ; //////////////////////////////////////////////////////////////////// if ( retry ) { state = 101 ; setParameter ( "Trying" , Parameters["Trying"].toInt() + 1 ) ; Time :: msleep ( 500 ) ; } else { duty = false ; } ; } else { duty = false ; } ; setParameter ( "State" , state ) ; break ; default : break ; } ; SyncTime ( ) ; Intermediate ( sleeping , duty ) ; } ; //////////////////////////////////////////////////////////////////////////// if ( listening ) Close ( ) ; Finished ( 3 ) ; setParameter ( "Stopped" , true ) ; setParameter ( "ReadStopped" , true ) ; setParameter ( "WriteStopped" , true ) ; AutoDeletion ( ) ; //////////////////////////////////////////////////////////////////////////// return true ; } bool N::NetConnector::ReadChannel (void) { bool listening = false ; bool duty = false ; bool sleeping = true ; int state = 0 ; //////////////////////////////////////////////////////////////////////////// duty = Parameters [ "Running" ] . toBool ( ) ; setParameter ( "Stopped" , false ) ; setParameter ( "ReadStopped" , false ) ; //////////////////////////////////////////////////////////////////////////// if ( Parameters.contains("State" ) ) { state = Parameters [ "State" ] .toInt ( ) ; } else setParameter ( "State" , state ) ; ; //////////////////////////////////////////////////////////////////////////// AccessTime ( ) ; while ( duty ) { state = Parameters [ "State" ] .toInt ( ) ; switch ( state ) { case 0 : state = 101 ; sleeping = false ; setParameter ( "State" , state ) ; Prepend ( ) ; Prepared ( 1 ) ; AccessTime ( ) ; break ; case 101 : state = 102 ; sleeping = true ; AssignHost ( ) ; AccessTime ( ) ; setParameter ( "State" , state ) ; break ; case 102 : sleeping = true ; if ( Connect ( ) ) { state = 103 ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 103 : sleeping = true ; if ( isConnected ( 100 ) ) { state = 401 ; listening = true ; Started ( 1 ) ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 201 : sleeping = true ; if ( ReadChunk ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 202 : sleeping = true ; if ( ReadLine ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 203 : sleeping = true ; if ( ReadStructure ( ) ) { AccessTime ( ) ; } else { } ; state = 401 ; setParameter ( "State" , state ) ; break ; case 401 : sleeping = true ; if ( Interpreter -> contains ( "State" ) ) { Interpreter -> Actions ( ) ; state = Interpreter -> value ( "State" ) . toInt ( ) ; switch ( state ) { case 0 : state = 901 ; break ; case 1 : state = 201 ; break ; case 2 : state = 202 ; break ; case 3 : state = 203 ; break ; } ; } ; setParameter ( "State" , state ) ; break ; case 901 : sleeping = true ; listening = false ; Close ( ) ; state = 999 ; setParameter ( "State" , state ) ; break ; case 911 : Time :: msleep ( 10 ) ; break ; case 999 : if ( Parameters . contains ( "Running" ) && Parameters [ "Running" ] . toBool ( ) ) { bool retry = false ; bool Forever = false ; //////////////////////////////////////////////////////////////////// if ( Parameters . contains ( "Forever" ) ) { Forever = Parameters [ "Forever" ] . toBool ( ) ; } ; if ( Forever ) { retry = true ; } else { if ( Parameters.contains("Retry") ) { if ( Parameters["Trying"].toInt()<Parameters["Retry"].toInt()) { retry = true ; } ; } ; } ; //////////////////////////////////////////////////////////////////// if ( retry ) { state = 101 ; setParameter ( "Trying" , Parameters["Trying"].toInt() + 1 ) ; Time :: msleep ( 500 ) ; } else { duty = false ; } ; } else { duty = false ; } ; setParameter ( "State" , state ) ; break ; default : break ; } ; SyncTime ( ) ; Intermediate ( sleeping , duty ) ; } ; //////////////////////////////////////////////////////////////////////////// if ( listening ) Close ( ) ; Finished ( 1 ) ; setParameter ( "ReadStopped" , true ) ; if ( Parameters["WriteStopped"].toBool() ) setParameter("Stopped",true) ; AutoDeletion ( ) ; return true ; } bool N::NetConnector::WriteChannel (void) { bool listening = false ; bool duty = false ; bool sleeping = true ; int state = 0 ; //////////////////////////////////////////////////////////////////////////// duty = Parameters [ "Running" ] . toBool ( ) ; setParameter ( "Stopped" , false ) ; setParameter ( "WriteStopped" , false ) ; //////////////////////////////////////////////////////////////////////////// if ( Parameters.contains("State" ) ) { state = Parameters [ "State" ] .toInt ( ) ; } else setParameter ( "State" , state ) ; ; //////////////////////////////////////////////////////////////////////////// AccessTime ( ) ; while ( duty ) { state = Parameters [ "State" ] .toInt ( ) ; switch ( state ) { case 0 : state = 101 ; sleeping = false ; setParameter ( "State" , state ) ; Prepend ( ) ; Prepared ( 2 ) ; AccessTime ( ) ; break ; case 101 : state = 102 ; sleeping = true ; AssignHost ( ) ; AccessTime ( ) ; setParameter ( "State" , state ) ; break ; case 102 : sleeping = true ; if ( Connect ( ) ) { state = 103 ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 103 : sleeping = true ; if ( isConnected ( 100 ) ) { state = 401 ; listening = true ; Started ( 2 ) ; AccessTime ( ) ; } else { state = 901 ; } ; setParameter ( "State" , state ) ; break ; case 301 : sleeping = true ; if ( WriteCommand ( ) ) { state = 302 ; } else { state = 303 ; } ; setParameter ( "State" , state ) ; break ; case 302 : sleeping = true ; Interpreter -> Actions ( ) ; AccessTime ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 303 : sleeping = true ; Interpreter -> Actions ( ) ; state = 304 ; setParameter ( "State" , state ) ; break ; case 304 : sleeping = true ; state = 401 ; setParameter ( "State" , state ) ; break ; case 401 : sleeping = true ; if ( Interpreter->Data(NetProtocol::Output).size() > 0 ) { state = 301 ; } ; setParameter ( "State" , state ) ; break ; case 901 : sleeping = true ; listening = false ; Close ( ) ; state = 999 ; setParameter ( "State" , state ) ; break ; case 911 : Time :: msleep ( 10 ) ; break ; case 999 : if ( Parameters . contains ( "Running" ) && Parameters [ "Running" ] . toBool ( ) ) { bool retry = false ; bool Forever = false ; //////////////////////////////////////////////////////////////////// if ( Parameters . contains ( "Forever" ) ) { Forever = Parameters [ "Forever" ] . toBool ( ) ; } ; if ( Forever ) { retry = true ; } else { if ( Parameters.contains("Retry") ) { if ( Parameters["Trying"].toInt()<Parameters["Retry"].toInt()) { retry = true ; } ; } ; } ; //////////////////////////////////////////////////////////////////// if ( retry ) { state = 101 ; setParameter ( "Trying" , Parameters["Trying"].toInt() + 1 ) ; Time :: msleep ( 500 ) ; } else { duty = false ; } ; } else { duty = false ; } ; setParameter ( "State" , state ) ; break ; default : break ; } ; SyncTime ( ) ; Intermediate ( sleeping , duty ) ; } ; //////////////////////////////////////////////////////////////////////////// if ( listening ) Close ( ) ; Finished ( 2 ) ; setParameter ( "WriteStopped" , true ) ; if ( Parameters["ReadStopped"].toBool() ) setParameter("Stopped",true) ; AutoDeletion ( ) ; return true ; } bool N::NetConnector::AtChannel(int channels) { switch ( channels ) { case 1: return ReadChannel ( ) ; case 2: return WriteChannel ( ) ; case 3: return BothChannels ( ) ; } ; return false ; }
72.766423
78
0.150717
Vladimir-Lin
801fef50c23a6a0c2913d39e520a90f5ca9013fa
9,340
cpp
C++
src/bindings/Scriptdev2/scripts/northrend/naxxramas/boss_faerlina.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/bindings/Scriptdev2/scripts/northrend/naxxramas/boss_faerlina.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/scripts/northrend/naxxramas/boss_faerlina.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2011 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Faerlina SD%Complete: 50 SDComment: SDCategory: Naxxramas EndScriptData */ #include "precompiled.h" #include "naxxramas.h" enum { SAY_GREET = -1533009, SAY_AGGRO = -1533010, SAY_ENRAGE1 = -1533011, SAY_ENRAGE2 = -1533012, SAY_ENRAGE3 = -1533013, SAY_SLAY1 = -1533014, SAY_SLAY2 = -1533015, SAY_DEATH = -1533016, EMOTE_BOSS_GENERIC_FRENZY = -1000005, //SOUND_RANDOM_AGGRO = 8955, //soundId containing the 4 aggro sounds, we not using this SPELL_POSIONBOLT_VOLLEY = 28796, H_SPELL_POSIONBOLT_VOLLEY = 54098, SPELL_FRENZY = 28798, H_SPELL_FRENZY = 54100, SPELL_RAINOFFIRE = 28794, //Not sure if targeted AoEs work if casted directly upon a pPlayer H_SPELL_RAINOFFIRE = 58936, SPELL_FIREBALL = 54095, SPELL_FIREBALL_H = 54096, SPELL_WIDOWS_EMBRACE = 28732, NPC_NAXXRAMAS_WORSHIPPER = 16506, NPC_NAXXRAMAS_FOLLOWER = 16505, }; struct MANGOS_DLL_DECL boss_faerlinaAI : public ScriptedAI { boss_faerlinaAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); m_bHasTaunted = false; Reset(); } instance_naxxramas* m_pInstance; bool m_bIsRegularMode; uint32 m_uiPoisonBoltVolleyTimer; uint32 m_uiRainOfFireTimer; uint32 m_uiEnrageTimer; bool m_bHasTaunted; void Reset() { m_uiPoisonBoltVolleyTimer = urand(14000, 15000); m_uiRainOfFireTimer = urand(6000, 8000); m_uiEnrageTimer = urand(60000, 80000); std::list<Creature*> lUnitList; GetCreatureListWithEntryInGrid(lUnitList, m_creature, NPC_NAXXRAMAS_WORSHIPPER, 100.0f); if (!lUnitList.empty()) for(std::list<Creature*>::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) if ((*iter)->isDead()) (*iter)->Respawn(); lUnitList.clear(); GetCreatureListWithEntryInGrid(lUnitList, m_creature, NPC_NAXXRAMAS_FOLLOWER, 100.0f); if (!lUnitList.empty()) for(std::list<Creature*>::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) if ((*iter)->isDead()) (*iter)->Respawn(); } void Aggro(Unit* pWho) { DoScriptText(SAY_AGGRO, m_creature); m_creature->SetInCombatWithZone(); std::list<Creature*> lUnitList; GetCreatureListWithEntryInGrid(lUnitList, m_creature, NPC_NAXXRAMAS_WORSHIPPER, 100.0f); if (!lUnitList.empty()) for (std::list<Creature*>::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) (*iter)->AI()->AttackStart(pTarget); else (*iter)->AI()->AttackStart(pWho); m_creature->CallForHelp(20); if (m_pInstance) m_pInstance->SetData(TYPE_FAERLINA, IN_PROGRESS); } void MoveInLineOfSight(Unit* pWho) { if (!m_bHasTaunted && pWho->GetTypeId() == TYPEID_PLAYER && m_creature->IsWithinDistInMap(pWho, 80.0f)) { DoScriptText(SAY_GREET, m_creature); m_bHasTaunted = true; } ScriptedAI::MoveInLineOfSight(pWho); } void KilledUnit(Unit* pVictim) { DoScriptText(urand(0, 1)?SAY_SLAY1:SAY_SLAY2, m_creature); } void JustDied(Unit* pKiller) { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_FAERLINA, DONE); } void JustReachedHome() { if (m_pInstance) m_pInstance->SetData(TYPE_FAERLINA, FAIL); } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // Poison Bolt Volley if (m_uiPoisonBoltVolleyTimer < uiDiff) { if (!m_creature->HasAura(SPELL_WIDOWS_EMBRACE)) DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_POSIONBOLT_VOLLEY : H_SPELL_POSIONBOLT_VOLLEY); m_uiPoisonBoltVolleyTimer = urand(14000, 15000); } else m_uiPoisonBoltVolleyTimer -= uiDiff; // Rain Of Fire if (m_uiRainOfFireTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) DoCastSpellIfCan(pTarget, m_bIsRegularMode ? SPELL_RAINOFFIRE : H_SPELL_RAINOFFIRE); m_uiRainOfFireTimer = urand(6000, 8000); } else m_uiRainOfFireTimer -= uiDiff; //Enrage_Timer if (m_uiEnrageTimer < uiDiff) { switch (urand(0, 2)) { case 0: DoScriptText(SAY_ENRAGE1, m_creature); break; case 1: DoScriptText(SAY_ENRAGE2, m_creature); break; case 2: DoScriptText(SAY_ENRAGE3, m_creature); break; } m_creature->MonsterTextEmote("%s goes into a frenzy!", 0, true); DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_FRENZY : H_SPELL_FRENZY); m_uiEnrageTimer = urand(60000, 80000); } else m_uiEnrageTimer -= uiDiff; DoMeleeAttackIfReady(); } }; struct MANGOS_DLL_DECL mob_worshipperAI : public ScriptedAI { mob_worshipperAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_naxxramas* m_pInstance; bool m_bIsRegularMode; uint32 m_uiFireball_Timer; void Reset() { m_uiFireball_Timer = 0; } void Aggro(Unit *pWho) { if (m_pInstance) { if (Creature* pFaerlina = m_creature->GetMap()->GetCreature(m_pInstance->GetData64(NPC_FAERLINA))) if (pFaerlina->isAlive() && !pFaerlina->getVictim()) pFaerlina->AI()->AttackStart(pWho); } } void JustDied(Unit* pKiller) { if (m_pInstance) if (Creature* pFaerlina = m_creature->GetMap()->GetCreature(m_pInstance->GetData64(NPC_FAERLINA))) if ((pFaerlina->HasAura(SPELL_FRENZY) || pFaerlina->HasAura(H_SPELL_FRENZY)) && (m_creature->GetDistance2d(pFaerlina) <= 10.0f)) { pFaerlina->RemoveAurasDueToSpell(m_bIsRegularMode ? SPELL_FRENZY : H_SPELL_FRENZY); if (SpellEntry* pSpell = (SpellEntry*)GetSpellStore()->LookupEntry(SPELL_WIDOWS_EMBRACE)) { pSpell->EffectImplicitTargetA[0] = TARGET_SELF; pSpell->EffectImplicitTargetB[0] = 0; pSpell->EffectImplicitTargetA[1] = TARGET_SELF; pSpell->EffectImplicitTargetB[1] = 0; pFaerlina->CastSpell(pFaerlina, pSpell, true); pFaerlina->MonsterTextEmote("%s is affected by Widow's Embrace!", 0, true); } } } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiFireball_Timer < uiDiff) { DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_FIREBALL : SPELL_FIREBALL_H); m_uiFireball_Timer = 5000 + rand()%3000; } else m_uiFireball_Timer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_mob_worshipper(Creature* pCreature) { return new mob_worshipperAI(pCreature); } CreatureAI* GetAI_boss_faerlina(Creature* pCreature) { return new boss_faerlinaAI(pCreature); } void AddSC_boss_faerlina() { Script* NewScript; NewScript = new Script; NewScript->Name = "boss_faerlina"; NewScript->GetAI = &GetAI_boss_faerlina; NewScript->RegisterSelf(); NewScript = new Script; NewScript->Name = "mob_worshipper"; NewScript->GetAI = &GetAI_mob_worshipper; NewScript->RegisterSelf(); }
33.238434
144
0.611563
mfooo
802fbb6528162c2b00424ecf1be9bbd263fc6648
13,922
cpp
C++
examples/basic/pipelines.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
1
2017-08-17T15:28:24.000Z
2017-08-17T15:28:24.000Z
examples/basic/pipelines.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
null
null
null
examples/basic/pipelines.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
null
null
null
/* * Vulkan Example - Using different pipelines in one single renderpass * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkanExampleBase.h" // Vertex layout for this example std::vector<vkx::VertexLayout> vertexLayout = { vkx::VertexLayout::VERTEX_LAYOUT_POSITION, vkx::VertexLayout::VERTEX_LAYOUT_NORMAL, vkx::VertexLayout::VERTEX_LAYOUT_UV, vkx::VertexLayout::VERTEX_LAYOUT_COLOR }; static vk::PhysicalDeviceFeatures features = [] { vk::PhysicalDeviceFeatures features; features.wideLines = VK_TRUE; return features; }(); class VulkanExample : public vkx::ExampleBase { public: struct { vk::PipelineVertexInputStateCreateInfo inputState; std::vector<vk::VertexInputBindingDescription> bindingDescriptions; std::vector<vk::VertexInputAttributeDescription> attributeDescriptions; } vertices; struct { vkx::MeshBuffer cube; } meshes; vkx::UniformData uniformDataVS; // Same uniform buffer layout as shader struct UboVS { glm::mat4 projection; glm::mat4 modelView; glm::vec4 lightPos = glm::vec4(0.0f, 2.0f, 1.0f, 0.0f); } uboVS; vk::PipelineLayout pipelineLayout; vk::DescriptorSet descriptorSet; vk::DescriptorSetLayout descriptorSetLayout; struct { vk::Pipeline phong; vk::Pipeline wireframe; vk::Pipeline toon; } pipelines; VulkanExample() : vkx::ExampleBase(ENABLE_VALIDATION) { camera.setZoom(-10.5f); camera.setRotation({ -25.0f, 15.0f, 0.0f }); enableTextOverlay = true; title = "Vulkan Example - vk::Pipeline state objects"; } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class device.destroyPipeline(pipelines.phong); if (deviceFeatures.fillModeNonSolid) { device.destroyPipeline(pipelines.wireframe); } device.destroyPipeline(pipelines.toon); device.destroyPipelineLayout(pipelineLayout); device.destroyDescriptorSetLayout(descriptorSetLayout); meshes.cube.destroy(); device.destroyBuffer(uniformDataVS.buffer); device.freeMemory(uniformDataVS.memory); } void updateDrawCommandBuffer(const vk::CommandBuffer& cmdBuffer) { cmdBuffer.setScissor(0, vkx::rect2D(size)); cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr); cmdBuffer.bindVertexBuffers(VERTEX_BUFFER_BIND_ID, meshes.cube.vertices.buffer, { 0 }); cmdBuffer.bindIndexBuffer(meshes.cube.indices.buffer, 0, vk::IndexType::eUint32); // Left : Solid colored vk::Viewport viewport = vkx::viewport((float)size.width / 3, (float)size.height, 0.0f, 1.0f); cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.phong); cmdBuffer.drawIndexed(meshes.cube.indexCount, 1, 0, 0, 0); // Center : Toon viewport.x += viewport.width; cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.toon); cmdBuffer.setLineWidth(2.0f); cmdBuffer.drawIndexed(meshes.cube.indexCount, 1, 0, 0, 0); auto lineWidthGranularity = deviceProperties.limits.lineWidthGranularity; auto lineWidthRange = deviceProperties.limits.lineWidthRange; if (deviceFeatures.fillModeNonSolid) { // Right : Wireframe viewport.x += viewport.width; cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.wireframe); cmdBuffer.drawIndexed(meshes.cube.indexCount, 1, 0, 0, 0); } } void loadMeshes() { meshes.cube = loadMesh(getAssetPath() + "models/treasure_smooth.dae", vertexLayout, 1.0f); } void setupVertexDescriptions() { // Binding description vertices.bindingDescriptions.resize(1); vertices.bindingDescriptions[0] = vkx::vertexInputBindingDescription(VERTEX_BUFFER_BIND_ID, vkx::vertexSize(vertexLayout), vk::VertexInputRate::eVertex); // Attribute descriptions // Describes memory layout and shader positions vertices.attributeDescriptions.resize(4); // Location 0 : Position vertices.attributeDescriptions[0] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 0, vk::Format::eR32G32B32Sfloat, 0); // Location 1 : Color vertices.attributeDescriptions[1] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 1, vk::Format::eR32G32B32Sfloat, sizeof(float) * 3); // Location 3 : Texture coordinates vertices.attributeDescriptions[2] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 2, vk::Format::eR32G32Sfloat, sizeof(float) * 6); // Location 2 : Normal vertices.attributeDescriptions[3] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 3, vk::Format::eR32G32B32Sfloat, sizeof(float) * 8); vertices.inputState = vk::PipelineVertexInputStateCreateInfo(); vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size(); vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size(); vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); } void setupDescriptorPool() { std::vector<vk::DescriptorPoolSize> poolSizes = { vkx::descriptorPoolSize(vk::DescriptorType::eUniformBuffer, 1) }; vk::DescriptorPoolCreateInfo descriptorPoolInfo = vkx::descriptorPoolCreateInfo(poolSizes.size(), poolSizes.data(), 2); descriptorPool = device.createDescriptorPool(descriptorPoolInfo); } void setupDescriptorSetLayout() { std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Vertex shader uniform buffer vkx::descriptorSetLayoutBinding( vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eVertex, 0) }; vk::DescriptorSetLayoutCreateInfo descriptorLayout = vkx::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), setLayoutBindings.size()); descriptorSetLayout = device.createDescriptorSetLayout(descriptorLayout); vk::PipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vkx::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); pipelineLayout = device.createPipelineLayout(pPipelineLayoutCreateInfo); } void setupDescriptorSet() { vk::DescriptorSetAllocateInfo allocInfo = vkx::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); descriptorSet = device.allocateDescriptorSets(allocInfo)[0]; std::vector<vk::WriteDescriptorSet> writeDescriptorSets = { // Binding 0 : Vertex shader uniform buffer vkx::writeDescriptorSet( descriptorSet, vk::DescriptorType::eUniformBuffer, 0, &uniformDataVS.descriptor) }; device.updateDescriptorSets(writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { vk::PipelineInputAssemblyStateCreateInfo inputAssemblyState = vkx::pipelineInputAssemblyStateCreateInfo(vk::PrimitiveTopology::eTriangleList, vk::PipelineInputAssemblyStateCreateFlags(), VK_FALSE); vk::PipelineRasterizationStateCreateInfo rasterizationState = vkx::pipelineRasterizationStateCreateInfo(vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise); vk::PipelineColorBlendAttachmentState blendAttachmentState = vkx::pipelineColorBlendAttachmentState(); vk::PipelineColorBlendStateCreateInfo colorBlendState = vkx::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); vk::PipelineDepthStencilStateCreateInfo depthStencilState = vkx::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, vk::CompareOp::eLessOrEqual); vk::PipelineViewportStateCreateInfo viewportState = vkx::pipelineViewportStateCreateInfo(1, 1); vk::PipelineMultisampleStateCreateInfo multisampleState = vkx::pipelineMultisampleStateCreateInfo(vk::SampleCountFlagBits::e1); std::vector<vk::DynamicState> dynamicStateEnables = { vk::DynamicState::eViewport, vk::DynamicState::eScissor, vk::DynamicState::eLineWidth, }; vk::PipelineDynamicStateCreateInfo dynamicState = vkx::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), dynamicStateEnables.size()); std::array<vk::PipelineShaderStageCreateInfo, 2> shaderStages; // Phong shading pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelines/phong.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelines/phong.frag.spv", vk::ShaderStageFlagBits::eFragment); vk::GraphicsPipelineCreateInfo pipelineCreateInfo = vkx::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); // We are using this pipeline as the base for the other pipelines (derivatives) // vk::Pipeline derivatives can be used for pipelines that share most of their state // Depending on the implementation this may result in better performance for pipeline // switchting and faster creation time pipelineCreateInfo.flags = vk::PipelineCreateFlagBits::eAllowDerivatives; // Textured pipeline pipelines.phong = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; // All pipelines created after the base pipeline will be derivatives pipelineCreateInfo.flags = vk::PipelineCreateFlagBits::eDerivative; // Base pipeline will be our first created pipeline pipelineCreateInfo.basePipelineHandle = pipelines.phong; // It's only allowed to either use a handle or index for the base pipeline // As we use the handle, we must set the index to -1 (see section 9.5 of the specification) pipelineCreateInfo.basePipelineIndex = -1; // Toon shading pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelines/toon.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelines/toon.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.toon = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; // Non solid rendering is not a mandatory Vulkan feature if (deviceFeatures.fillModeNonSolid) { // vk::Pipeline for wire frame rendering rasterizationState.polygonMode = vk::PolygonMode::eLine; shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelines/wireframe.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelines/wireframe.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.wireframe = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; } } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Create the vertex shader uniform buffer block uniformDataVS = createUniformBuffer(uboVS); updateUniformBuffers(); } void updateUniformBuffers() { uboVS.projection = glm::perspective(glm::radians(60.0f), (float)(size.width / 3.0f) / (float)size.height, 0.001f, 256.0f); uboVS.modelView = camera.matrices.view; uniformDataVS.copy(uboVS); } void prepare() { ExampleBase::prepare(); loadMeshes(); setupVertexDescriptions(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); updateDrawCommandBuffers(); prepared = true; } void render() override { if (!prepared) return; draw(); } void viewChanged() override { updateUniformBuffers(); } void getOverlayText(vkx::TextOverlay *textOverlay) override { textOverlay->addText("Phong shading pipeline", (float)size.width / 6.0f, size.height - 35.0f, vkx::TextOverlay::alignCenter); textOverlay->addText("Toon shading pipeline", (float)size.width / 2.0f, size.height - 35.0f, vkx::TextOverlay::alignCenter); textOverlay->addText("Wireframe pipeline", size.width - (float)size.width / 6.5f, size.height - 35.0f, vkx::TextOverlay::alignCenter); } }; RUN_EXAMPLE(VulkanExample)
42.445122
147
0.690777
ChristophLGDV
803281f2c8659764d6d54a8f9605c242e4bce664
8,435
cxx
C++
PHOS/DA/PHSGAINda.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PHOS/DA/PHSGAINda.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PHOS/DA/PHSGAINda.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/* contact: [email protected] link: see comments in the $ALICE_ROOT/PHOS/AliPHOSRcuDA1.cxx reference run: /alice/data/2009/LHC09b_PHOS/000075883/raw/09000075883017.20.root run type: PHYSICS DA type: MON number of events needed: 1000 input files: Mod0RCU0.data Mod0RCU1.data Mod0RCU2.data Mod0RCU3.data Mod1RCU0.data Mod1RCU1.data Mod1RCU2.data Mod1RCU3.data Mod2RCU0.data Mod2RCU1.data Mod2RCU2.data Mod2RCU3.data Mod3RCU0.data Mod3RCU1.data Mod3RCU2.data Mod3RCU3.data Mod4RCU0.data Mod4RCU1.data Mod4RCU2.data Mod4RCU3.data zs.txt Output files: PHOS_Calib_Total.root contains cumulative statistics for a number of runs. Trigger types used: PHYSICS */ #include "event.h" #include "monitor.h" extern "C" { #include "daqDA.h" } #include <stdio.h> #include <stdlib.h> #include <TSystem.h> #include <TROOT.h> #include <TPluginManager.h> #include "AliRawReader.h" #include "AliRawReaderDate.h" #include "AliPHOSRcuDA1.h" #include "AliPHOSRawFitterv0.h" #include "AliCaloAltroMapping.h" #include "AliCaloRawStreamV3.h" #include "AliLog.h" /* Main routine Arguments: 1- monitoring data source */ int main(int argc, char **argv) { gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); AliLog::SetGlobalDebugLevel(0) ; AliLog::SetGlobalLogLevel(AliLog::kFatal); int status; if (argc!=2) { printf("Wrong number of arguments\n"); return -1; } /* Retrieve ZS parameters from DAQ DB */ const char* zsfile = "zs.txt"; int failZS = daqDA_DB_getFile(zsfile, zsfile); Int_t offset,threshold; if(!failZS) { FILE *f = fopen(zsfile,"r"); int scan = fscanf(f,"%d %d",&offset,&threshold); } /* Retrieve mapping files from DAQ DB */ const char* mapFiles[20] = { "Mod0RCU0.data", "Mod0RCU1.data", "Mod0RCU2.data", "Mod0RCU3.data", "Mod1RCU0.data", "Mod1RCU1.data", "Mod1RCU2.data", "Mod1RCU3.data", "Mod2RCU0.data", "Mod2RCU1.data", "Mod2RCU2.data", "Mod2RCU3.data", "Mod3RCU0.data", "Mod3RCU1.data", "Mod3RCU2.data", "Mod3RCU3.data", "Mod4RCU0.data", "Mod4RCU1.data", "Mod4RCU2.data", "Mod4RCU3.data" }; for(Int_t iFile=0; iFile<20; iFile++) { int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]); if(failed) { printf("Cannot retrieve file %s from DAQ DB. Exit.\n",mapFiles[iFile]); return -1; } } /* Open mapping files */ AliAltroMapping *mapping[20]; TString path = "./"; path += "Mod"; TString path2; TString path3; Int_t iMap = 0; for(Int_t iMod = 0; iMod < 5; iMod++) { path2 = path; path2 += iMod; path2 += "RCU"; for(Int_t iRCU=0; iRCU<4; iRCU++) { path3 = path2; path3 += iRCU; path3 += ".data"; mapping[iMap] = new AliCaloAltroMapping(path3.Data()); iMap++; } } /* define data source : this is argument 1 */ status=monitorSetDataSource( argv[1] ); if (status!=0) { printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status)); return -1; } /* declare monitoring program */ status=monitorDeclareMp( __FILE__ ); if (status!=0) { printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status)); return -1; } /* define wait event timeout - 1s max */ monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); /* init some counters */ int nevents_physics=0; int nevents_total=0; AliRawReader *rawReader = NULL; AliPHOSRcuDA1* dAs[5]; for(Int_t iMod=0; iMod<5; iMod++) { dAs[iMod] = 0; } Float_t e[64][56][2]; Float_t t[64][56][2]; for(Int_t iX=0; iX<64; iX++) { for(Int_t iZ=0; iZ<56; iZ++) { for(Int_t iGain=0; iGain<2; iGain++) { e[iX][iZ][iGain] = 0.; t[iX][iZ][iGain] = 0.; } } } Int_t cellX = -1; Int_t cellZ = -1; Int_t nBunches = 0; Int_t sigStart, sigLength; Int_t caloFlag; /* main loop (infinite) */ for(;;) { struct eventHeaderStruct *event; eventTypeType eventT; /* check shutdown condition */ if (daqDA_checkShutdown()) {break;} /* get next event (blocking call until timeout) */ status=monitorGetEventDynamic((void **)&event); if (status==MON_ERR_EOF) { printf ("End of File detected\n"); break; /* end of monitoring file has been reached */ } if (status!=0) { printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)); break; } /* retry if got no event */ if (event==NULL) { continue; } /* use event - here, just write event id to result file */ eventT=event->eventType; if (eventT==PHYSICS_EVENT) { rawReader = new AliRawReaderDate((void*)event); AliCaloRawStreamV3 stream(rawReader,"PHOS",mapping); AliPHOSRawFitterv0 fitter; fitter.SubtractPedestals(kTRUE); // assume that data is non-ZS if(!failZS) { fitter.SubtractPedestals(kFALSE); fitter.SetAmpOffset(offset); fitter.SetAmpThreshold(threshold); } while (stream.NextDDL()) { while (stream.NextChannel()) { /* Retrieve ZS parameters from data*/ if(failZS) { short value = stream.GetAltroCFG1(); bool ZeroSuppressionEnabled = (value >> 15) & 0x1; bool AutomaticBaselineSubtraction = (value >> 14) & 0x1; if(ZeroSuppressionEnabled) { offset = (value >> 10) & 0xf; threshold = value & 0x3ff; fitter.SubtractPedestals(kFALSE); fitter.SetAmpOffset(offset); fitter.SetAmpThreshold(threshold); } } cellX = stream.GetCellX(); cellZ = stream.GetCellZ(); caloFlag = stream.GetCaloFlag(); // 0=LG, 1=HG, 2=TRU if(caloFlag!=0 && caloFlag!=1) continue; //TRU data! // In case of oscillating signals with ZS, //a channel can have several bunches. nBunches = 0; while (stream.NextBunch()) { nBunches++; if (nBunches > 1) continue; sigStart = stream.GetStartTimeBin(); sigLength = stream.GetBunchLength(); fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag); fitter.Eval(stream.GetSignals(),sigStart,sigLength); } // End of NextBunch() if (nBunches != 1) continue; e[cellX][cellZ][caloFlag] = fitter.GetEnergy(); t[cellX][cellZ][caloFlag] = fitter.GetTime(); } if(stream.GetModule()<0 || stream.GetModule()>4) continue; if(dAs[stream.GetModule()]) dAs[stream.GetModule()]->FillHistograms(e,t); else { dAs[stream.GetModule()] = new AliPHOSRcuDA1(stream.GetModule(),-1,0); dAs[stream.GetModule()]->FillHistograms(e,t); } for(Int_t iX=0; iX<64; iX++) { for(Int_t iZ=0; iZ<56; iZ++) { for(Int_t iGain=0; iGain<2; iGain++) { e[iX][iZ][iGain] = 0.; t[iX][iZ][iGain] = 0.; } } } } // da1.FillHistograms(e,t); // //da1.UpdateHistoFile(); delete rawReader; nevents_physics++; } nevents_total++; /* free resources */ free(event); /* exit when last event received, no need to wait for TERM signal */ if (eventT==END_OF_RUN) { printf("EOR event detected\n"); break; } } for(Int_t i = 0; i < 20; i++) delete mapping[i]; /* Be sure that all histograms are saved */ char h2name[80]; char totfile[80]; //Write the Total file (accumulated statistics for number of runs) sprintf(totfile,"PHOS_Calib_Total.root"); TFile * ftot = new TFile(totfile,"recreate"); // if (!ftot->IsZombie()){ // printf("Updating file %s.\n",ftot->GetName()); // for(Int_t iMod=0; iMod<5; iMod++) { // if(!dAs[iMod]) continue; // printf("DA1 for module %d detected.\n",iMod); // for(Int_t iX=0; iX<64; iX++) { // for(Int_t iZ=0; iZ<56; iZ++) { // for(Int_t iGain=0; iGain<2; iGain++) { // sprintf(h2name,"%d_%d_%d_%d",iMod,iX,iZ,iGain); // TH2F* h2tot = (TH2F*)ftot->Get(h2name); // const TH2F* h2run = dAs[iMod]->GetTimeEnergyHistogram(iX,iZ,iGain); // Time vs Energy // if(!h2tot && h2run) h2run->Write(); // if(h2tot && h2run) { h2tot->Add(h2run); h2tot->Write(h2tot->GetName(),TObject::kWriteDelete); } // } // } // } // } // } ftot->Close(); /* Store output files to the File Exchange Server */ daqDA_FES_storeFile(totfile,"AMPLITUDES"); return status; }
25.104167
299
0.617427
AllaMaevskaya
80394afa90cf9774eeef2235550b565ee8bc07fa
2,805
hpp
C++
Ruken/Source/Include/Build/Config.hpp
Renondedju/Ruken
2b2944b0c7aabf0f921f4daafc45eb01e592d825
[ "MIT" ]
6
2020-09-12T19:16:49.000Z
2022-03-17T14:10:16.000Z
Ruken/Source/Include/Build/Config.hpp
Renondedju/Ruken
2b2944b0c7aabf0f921f4daafc45eb01e592d825
[ "MIT" ]
1
2021-11-15T10:13:17.000Z
2021-11-15T10:13:17.000Z
Ruken/Source/Include/Build/Config.hpp
Renondedju/Ruken
2b2944b0c7aabf0f921f4daafc45eb01e592d825
[ "MIT" ]
3
2020-09-03T16:41:35.000Z
2022-01-24T09:35:55.000Z
/* * MIT License * * Copyright (c) 2019-2020 Basile Combet, Philippe Yi * * 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 NON INFRINGEMENT. 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. */ #pragma once // ------------------------------ // Global Settings #define RUKEN_CONFIG_LEVEL_DEBUG 0 #define RUKEN_CONFIG_LEVEL_RELEASE 1 #ifndef NDEBUG #define RUKEN_CONFIG_LEVEL RUKEN_CONFIG_LEVEL_DEBUG #define RUKEN_CONFIG_DEBUG #define RUKEN_CONFIG_STR "Debug" #else #define RUKEN_CONFIG_LEVEL RUKEN_CONFIG_LEVEL_RELEASE #define RUKEN_CONFIG_RELEASE #define RUKEN_CONFIG_STR "Release" #endif #define RUKEN_DEBUG if constexpr(RUKEN_CONFIG_LEVEL == RUKEN_CONFIG_LEVEL_DEBUG) #define RUKEN_RELEASE if constexpr(RUKEN_CONFIG_LEVEL == RUKEN_CONFIG_LEVEL_RELEASE) // ------------------------------ // Threading #if !defined(no_multithread) && defined(__STDCPP_THREADS__) && !defined(RUKEN_REQUEST_SINGLE_THREADED_BUILD) #define RUKEN_MULTITHREAD_ENABLED #define RUKEN_MULTITHREAD_STATUS_STR "Enabled" #else #define RUKEN_MULTITHREAD_DISABLED #define RUKEN_MULTITHREAD_STATUS_STR "Disabled" #endif // ------------------------------ // Resource management #if defined(RUKEN_CONFIG_DEBUG) #define RUKEN_RESOURCE_MANIFEST_STORE_IDENTIFIER #endif // ------------------------------ // ECS // Sets the maximum number of components allowed by the ECS, keep this number // as low as possible. Must be a power of 2 with a minimum of 8. #define RUKEN_MAX_ECS_COMPONENTS 64 // ------------------------------ // Logging #if !defined(RUKEN_REQUEST_SILENT_BUILD) #define RUKEN_LOGGING_ENABLED #define RUKEN_LOGGING_STATUS_STR "Enabled" #else #define RUKEN_LOGGING_DISABLED #define RUKEN_LOGGING_STATUS_STR "Disabled" #endif
35.0625
108
0.714795
Renondedju
803a544d85582452b50445351d82a42e9d22c0eb
11,855
cpp
C++
r_mux/source/r_muxer.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
r_mux/source/r_muxer.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
r_mux/source/r_muxer.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
#include "r_mux/r_muxer.h" #include "r_mux/r_format_utils.h" #include "r_utils/r_string_utils.h" #include "r_utils/r_exception.h" #include <stdexcept> using namespace std; using namespace r_mux; using namespace r_utils; using namespace r_utils::r_std_utils; AVCodecID r_mux::encoding_to_av_codec_id(const string& codec_name) { auto lower_codec_name = r_string_utils::to_lower(codec_name); if(lower_codec_name == "h264") return AV_CODEC_ID_H264; else if(lower_codec_name == "h265" || lower_codec_name == "hevc") return AV_CODEC_ID_HEVC; else if(lower_codec_name == "mp4a-latm") return AV_CODEC_ID_AAC_LATM; else if(lower_codec_name == "mpeg4-generic") return AV_CODEC_ID_AAC; else if(lower_codec_name == "pcmu") return AV_CODEC_ID_PCM_MULAW; R_THROW(("Unknown codec name.")); } r_muxer::r_muxer(const std::string& path, bool output_to_buffer) : _path(path), _output_to_buffer(output_to_buffer), _buffer(), _fc([](AVFormatContext* fc){avformat_free_context(fc);}), _video_stream(nullptr), _audio_stream(nullptr), _needs_finalize(false), _video_bsf([](AVBSFContext* bsf){av_bsf_free(&bsf);}), _audio_bsf([](AVBSFContext* bsf){av_bsf_free(&bsf);}) { avformat_alloc_output_context2(&_fc.raw(), NULL, NULL, _path.c_str()); if(!_fc) R_THROW(("Unable to create libavformat output context")); if(_fc.get()->oformat->flags & AVFMT_GLOBALHEADER) _fc.get()->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; _fc.get()->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; } r_muxer::~r_muxer() { if(_needs_finalize) finalize(); } void r_muxer::add_video_stream(AVRational frame_rate, AVCodecID codec_id, uint16_t w, uint16_t h, int profile, int level) { auto codec = avcodec_find_encoder(codec_id); if(!codec) R_THROW(("Unable to find encoder stream.")); _video_stream = avformat_new_stream(_fc.get(), codec); if(!_video_stream) R_THROW(("Unable to allocate AVStream.")); _video_stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; _video_stream->codecpar->codec_id = codec_id; _video_stream->codecpar->width = w; _video_stream->codecpar->height = h; _video_stream->codecpar->format = AV_PIX_FMT_YUV420P; _video_stream->codecpar->profile = profile; _video_stream->codecpar->level = level; _video_stream->time_base.num = frame_rate.den; _video_stream->time_base.den = frame_rate.num; } void r_muxer::add_audio_stream(AVCodecID codec_id, uint8_t channels, uint32_t sample_rate) { auto codec = avcodec_find_encoder(codec_id); _audio_stream = avformat_new_stream(_fc.get(), codec); if(!_audio_stream) R_THROW(("Unable to allocate AVStream")); _audio_stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; _audio_stream->codecpar->codec_id = codec_id; _audio_stream->codecpar->channels = channels; _audio_stream->codecpar->sample_rate = sample_rate; _audio_stream->time_base.num = 1; _audio_stream->time_base.den = sample_rate; } void r_muxer::set_video_bitstream_filter(const std::string& filter_name) { const AVBitStreamFilter *filter = av_bsf_get_by_name(filter_name.c_str()); if(!filter) R_THROW(("Unable to find bitstream filter.")); auto ret = av_bsf_alloc(filter, &_video_bsf.raw()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_alloc()")); ret = avcodec_parameters_copy(_video_bsf.get()->par_in, _video_stream->codecpar); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); ret = av_bsf_init(_video_bsf.get()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_init()")); ret = avcodec_parameters_copy(_video_stream->codecpar, _video_bsf.get()->par_out); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); } void r_muxer::set_audio_bitstream_filter(const std::string& filter_name) { const AVBitStreamFilter *filter = av_bsf_get_by_name(filter_name.c_str()); if(!filter) R_THROW(("Unable to find bitstream filter.")); auto ret = av_bsf_alloc(filter, &_audio_bsf.raw()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_alloc()")); ret = avcodec_parameters_copy(_audio_bsf.get()->par_in, _audio_stream->codecpar); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); ret = av_bsf_init(_audio_bsf.get()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_init()")); ret = avcodec_parameters_copy(_audio_stream->codecpar, _audio_bsf.get()->par_out); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); } void r_muxer::set_video_extradata(const std::vector<uint8_t>& ed) { if(!ed.empty()) { if(_video_stream->codecpar->extradata) av_free(_video_stream->codecpar->extradata); _video_stream->codecpar->extradata = (uint8_t*)av_malloc(ed.size()); memcpy(_video_stream->codecpar->extradata, &ed[0], ed.size()); _video_stream->codecpar->extradata_size = (int)ed.size(); } } void r_muxer::set_audio_extradata(const std::vector<uint8_t>& ed) { if(!ed.empty()) { if(_audio_stream->codecpar->extradata) av_free(_audio_stream->codecpar->extradata); _audio_stream->codecpar->extradata = (uint8_t*)av_malloc(ed.size()); memcpy(_audio_stream->codecpar->extradata, &ed[0], ed.size()); _audio_stream->codecpar->extradata_size = (int)ed.size(); } } void r_muxer::open() { if(_fc.get()->nb_streams < 1) R_THROW(("Please add a stream before opening this muxer.")); if(_output_to_buffer) { int res = avio_open_dyn_buf(&_fc.get()->pb); if(res < 0) R_THROW(("Unable to allocate a memory IO object: %s", ff_rc_to_msg(res).c_str())); } else { int res = avio_open(&_fc.get()->pb, _path.c_str(), AVIO_FLAG_WRITE); if(res < 0) R_THROW(("Unable to open output io context: %s", ff_rc_to_msg(res).c_str())); } int res = avformat_write_header(_fc.get(), NULL); if(res < 0) R_THROW(("Unable to write header to output file: %s", ff_rc_to_msg(res).c_str())); _needs_finalize = true; } static void _get_packet_defaults(AVPacket* pkt) { pkt->buf = nullptr; pkt->pts = AV_NOPTS_VALUE; pkt->dts = AV_NOPTS_VALUE; pkt->data = nullptr; pkt->size = 0; pkt->stream_index = 0; pkt->flags = 0; pkt->side_data = nullptr; pkt->side_data_elems = 0; pkt->duration = 0; pkt->pos = -1; } void r_muxer::write_video_frame(uint8_t* p, size_t size, int64_t input_pts, int64_t input_dts, AVRational input_time_base, bool key) { if(_fc.get()->pb == nullptr) R_THROW(("Please call open() before writing frames.")); raii_ptr<AVPacket> input_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(input_pkt.get()); input_pkt.get()->stream_index = _video_stream->index; input_pkt.get()->data = p; input_pkt.get()->size = (int)size; input_pkt.get()->pts = av_rescale_q(input_pts, input_time_base, _video_stream->time_base); input_pkt.get()->dts = av_rescale_q(input_dts, input_time_base, _video_stream->time_base); input_pkt.get()->flags |= (key)?AV_PKT_FLAG_KEY:0; if(_video_bsf) { int res = av_bsf_send_packet(_video_bsf.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to send packet to bitstream filter: %s", ff_rc_to_msg(res).c_str())); while(res == 0) { raii_ptr<AVPacket> output_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(output_pkt.get()); res = av_bsf_receive_packet(_video_bsf.get(), output_pkt.get()); if(res == 0) { res = av_interleaved_write_frame(_fc.get(), output_pkt.get()); if(res < 0) R_THROW(("Unable to write frame to output file: %s", ff_rc_to_msg(res).c_str())); } else if(res == AVERROR(EAGAIN)) { // no output packet, needs more input break; } else R_THROW(("Unable to receive packet from bitstream filter: %s", ff_rc_to_msg(res).c_str())); } } else { int res = av_interleaved_write_frame(_fc.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to write video frame to output file: %s", ff_rc_to_msg(res).c_str())); } } void r_muxer::write_audio_frame(uint8_t* p, size_t size, int64_t input_pts, AVRational input_time_base) { if(_fc.get()->pb == nullptr) R_THROW(("Please call open() before writing frames.")); if(_fc.get()->pb == nullptr) R_THROW(("Please call open() before writing frames.")); raii_ptr<AVPacket> input_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(input_pkt.get()); input_pkt.get()->stream_index = _audio_stream->index; input_pkt.get()->data = p; input_pkt.get()->size = (int)size; input_pkt.get()->pts = av_rescale_q(input_pts, input_time_base, _audio_stream->time_base); input_pkt.get()->dts = input_pkt.get()->pts; input_pkt.get()->flags = AV_PKT_FLAG_KEY; if(_audio_bsf) { int res = av_bsf_send_packet(_audio_bsf.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to send packet to bitstream filter: %s", ff_rc_to_msg(res).c_str())); while(res == 0) { raii_ptr<AVPacket> output_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(output_pkt.get()); res = av_bsf_receive_packet(_audio_bsf.get(), output_pkt.get()); if(res == 0) { res = av_interleaved_write_frame(_fc.get(), output_pkt.get()); if(res < 0) R_THROW(("Unable to write frame to output file: %s", ff_rc_to_msg(res).c_str())); } else if(res == AVERROR(EAGAIN)) { // no output packet, needs more input break; } else R_THROW(("Unable to receive packet from bitstream filter: %s", ff_rc_to_msg(res).c_str())); } } else { int res = av_interleaved_write_frame(_fc.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to write audio frame to output file: %s", ff_rc_to_msg(res).c_str())); } } void r_muxer::finalize() { if(_needs_finalize) { _needs_finalize = false; int res = av_write_trailer(_fc.get()); if(res < 0) R_THROW(("Unable to write trailer to output file: %s", ff_rc_to_msg(res).c_str())); if(_output_to_buffer) { raii_ptr<uint8_t> fileBytes([](uint8_t* p){av_freep(p);}); int fileSize = avio_close_dyn_buf(_fc.get()->pb, &fileBytes.raw()); _buffer.resize(fileSize); memcpy(&_buffer[0], fileBytes.get(), fileSize); } else { int res = avio_close(_fc.get()->pb); if(res < 0) R_THROW(("Unable to close output io context: %s", ff_rc_to_msg(res).c_str())); } } } const uint8_t* r_muxer::buffer() const { if(!_output_to_buffer) R_THROW(("Please only call buffer() on muxers configured to output to buffer.")); return &_buffer[0]; } size_t r_muxer::buffer_size() const { if(!_output_to_buffer) R_THROW(("Please only call buffer_size() on muxers configured to output to buffer.")); return _buffer.size(); }
33.394366
132
0.640489
TroyDL
803b5ca8edd0c5610516eab4a496ee6f3a4dc479
356
cpp
C++
MonkeyDelivery/Src/Control/NextStateCommand.cpp
miggon23/TheUnnamedGame
8b8fbf232772d5de90fb8646129afa5e8b11608e
[ "MIT" ]
7
2022-02-04T08:57:33.000Z
2022-03-06T12:54:05.000Z
MonkeyDelivery/Src/Control/NextStateCommand.cpp
miggon23/MonkeyDelivery
8b8fbf232772d5de90fb8646129afa5e8b11608e
[ "MIT" ]
79
2022-02-01T15:25:51.000Z
2022-03-30T22:17:20.000Z
MonkeyDelivery/Src/Control/NextStateCommand.cpp
miggon23/MonkeyDelivery
8b8fbf232772d5de90fb8646129afa5e8b11608e
[ "MIT" ]
null
null
null
#include "NextStateCommand.h" #include "./States/State.h" bool NextStateCommand::parse(SDL_Event& event) { if (event.type == SDL_KEYDOWN) { SDL_Keycode key = event.key.keysym.sym; if (key == SDLK_SPACE) { return true; } } return false; } void NextStateCommand::execute() { game->getState()->next(); }
17.8
47
0.601124
miggon23
d9b753fc62ef4f6f56ad748549c6d03dfbd436ef
25
cpp
C++
TOD1/SoundEmitter.cpp
Michael0ne/TOD_tools
0e55b28b7001d8b7ce7c0e0811f27682349b41c9
[ "FSFAP" ]
20
2020-01-15T22:00:23.000Z
2022-02-07T05:32:09.000Z
TOD1/SoundEmitter.cpp
Michael0ne/TOD_tools
0e55b28b7001d8b7ce7c0e0811f27682349b41c9
[ "FSFAP" ]
2
2021-02-26T15:13:49.000Z
2021-11-28T17:35:05.000Z
TOD1/SoundEmitter.cpp
Michael0ne/TOD_tools
0e55b28b7001d8b7ce7c0e0811f27682349b41c9
[ "FSFAP" ]
1
2020-05-07T18:41:50.000Z
2020-05-07T18:41:50.000Z
#include "SoundEmitter.h"
25
25
0.8
Michael0ne
d9b7937809b3d4c193c135c9dee0c3585b0d2253
5,655
cpp
C++
Plugins/CaptionMod/BaseUI.cpp
DrAbcrealone/MetaHookSv
db8306d325590a380a458758c8518519cab01891
[ "MIT" ]
31
2021-01-20T08:12:48.000Z
2022-03-29T16:47:50.000Z
Plugins/CaptionMod/BaseUI.cpp
DrAbcrealone/MetaHookSv
db8306d325590a380a458758c8518519cab01891
[ "MIT" ]
118
2021-02-04T17:57:48.000Z
2022-03-31T13:03:21.000Z
Plugins/CaptionMod/BaseUI.cpp
DrAbcrealone/MetaHookSv
db8306d325590a380a458758c8518519cab01891
[ "MIT" ]
13
2021-01-21T01:43:19.000Z
2022-03-15T04:51:19.000Z
#include <metahook.h> #include "BaseUI.h" #include <VGUI\IScheme.h> #include <VGUI\ILocalize.h> #include <VGUI\ISurface.h> #include <VGUI\IInput.h> #include "FontTextureCache.h" #include <IEngineSurface.h> #include "vgui_internal.h" #include "IKeyValuesSystem.h" #include "exportfuncs.h" #include "engfuncs.h" namespace vgui { bool VGui_InitInterfacesList(const char *moduleName, CreateInterfaceFn *factoryList, int numFactories); } void (__fastcall *m_pfnCBaseUI_Initialize)(void *pthis, int, CreateInterfaceFn *factories, int count); void (__fastcall *m_pfnCBaseUI_Start)(void *pthis, int, struct cl_enginefuncs_s *engineFuncs, int interfaceVersion); void (__fastcall *m_pfnCBaseUI_Shutdown)(void *pthis, int); int (__fastcall *m_pfnCBaseUI_Key_Event)(void *pthis, int, int down, int keynum, const char *pszCurrentBinding); void (__fastcall *m_pfnCBaseUI_CallEngineSurfaceProc)(void *pthis, int, void *hwnd, unsigned int msg, unsigned int wparam, long lparam); void (__fastcall *m_pfnCBaseUI_Paint)(void *pthis, int, int x, int y, int right, int bottom); void (__fastcall *m_pfnCBaseUI_HideGameUI)(void *pthis, int); void (__fastcall *m_pfnCBaseUI_ActivateGameUI)(void *pthis, int); bool (__fastcall *m_pfnCBaseUI_IsGameUIVisible)(void *pthis, int); void (__fastcall *m_pfnCBaseUI_HideConsole)(void *pthis, int); void (__fastcall *m_pfnCBaseUI_ShowConsole)(void *pthis, int); class CBaseUI : public IBaseUI { public: virtual void Initialize(CreateInterfaceFn *factories, int count); virtual void Start(struct cl_enginefuncs_s *engineFuncs, int interfaceVersion); virtual void Shutdown(void); virtual int Key_Event(int down, int keynum, const char *pszCurrentBinding); virtual void CallEngineSurfaceProc(void *hwnd, unsigned int msg, unsigned int wparam, long lparam); virtual void Paint(int x, int y, int right, int bottom); virtual void HideGameUI(void); virtual void ActivateGameUI(void); virtual bool IsGameUIVisible(void); virtual void HideConsole(void); virtual void ShowConsole(void); }; static CBaseUI s_BaseUI; IBaseUI *baseuifuncs; IGameUIFuncs *gameuifuncs; extern vgui::ISurface *g_pSurface; extern vgui::ISchemeManager *g_pScheme; extern IKeyValuesSystem *g_pKeyValuesSystem; extern IEngineSurface *staticSurface; static BOOL s_LoadingClientFactory = false; void CBaseUI::Initialize(CreateInterfaceFn *factories, int count) { //Patch ClientFactory if(!g_IsClientVGUI2 && *gCapFuncs.pfnClientFactory == NULL) { *gCapFuncs.pfnClientFactory = NewClientFactory; s_LoadingClientFactory = true; } m_pfnCBaseUI_Initialize(this, 0, factories, count); s_LoadingClientFactory = false; HINTERFACEMODULE hVGUI2 = (HINTERFACEMODULE)GetModuleHandle("vgui2.dll"); if(hVGUI2) { CreateInterfaceFn fnVGUI2CreateInterface = Sys_GetFactory(hVGUI2); g_pScheme = (vgui::ISchemeManager *)fnVGUI2CreateInterface(VGUI_SCHEME_INTERFACE_VERSION, NULL); g_pKeyValuesSystem = (IKeyValuesSystem *)fnVGUI2CreateInterface(KEYVALUESSYSTEM_INTERFACE_VERSION, NULL); } g_pSurface = (vgui::ISurface *)factories[0](VGUI_SURFACE_INTERFACE_VERSION, NULL); staticSurface = (IEngineSurface *)factories[0](ENGINE_SURFACE_VERSION, NULL); KeyValuesSystem_InstallHook(); Surface_InstallHook(); Scheme_InstallHook(); GameUI_InstallHook(); } void CBaseUI::Start(struct cl_enginefuncs_s *engineFuncs, int interfaceVersion) { m_pfnCBaseUI_Start(this, 0, engineFuncs, interfaceVersion); } void CBaseUI::Shutdown(void) { m_pfnCBaseUI_Shutdown(this, 0); } int CBaseUI::Key_Event(int down, int keynum, const char *pszCurrentBinding) { return m_pfnCBaseUI_Key_Event(this, 0, down, keynum, pszCurrentBinding); } void CBaseUI::CallEngineSurfaceProc(void *hwnd, unsigned int msg, unsigned int wparam, long lparam) { m_pfnCBaseUI_CallEngineSurfaceProc(this, 0, hwnd, msg, wparam, lparam); } void CBaseUI::Paint(int x, int y, int right, int bottom) { m_pfnCBaseUI_Paint(this, 0, x, y, right, bottom); } void CBaseUI::HideGameUI(void) { m_pfnCBaseUI_HideGameUI(this, 0); } void CBaseUI::ActivateGameUI(void) { m_pfnCBaseUI_ActivateGameUI(this, 0); } bool CBaseUI::IsGameUIVisible(void) { return m_pfnCBaseUI_IsGameUIVisible(this, 0); } void CBaseUI::HideConsole(void) { m_pfnCBaseUI_HideConsole(this, 0); } void CBaseUI::ShowConsole(void) { m_pfnCBaseUI_ShowConsole(this, 0); } void BaseUI_InstallHook(void) { CreateInterfaceFn fnCreateInterface = g_pMetaHookAPI->GetEngineFactory(); baseuifuncs = (IBaseUI *)fnCreateInterface(BASEUI_INTERFACE_VERSION, NULL); gameuifuncs = (IGameUIFuncs *)fnCreateInterface(VENGINE_GAMEUIFUNCS_VERSION, NULL); //Search CBaseUI::Initialize for ClientFactory if (g_iEngineType == ENGINE_SVENGINE) { #define CLIENTFACTORY_SIG_SVENGINE "\x83\xC4\x0C\x83\x3D" DWORD *vft = *(DWORD **)baseuifuncs; DWORD addr = (DWORD)g_pMetaHookAPI->SearchPattern((void *)vft[1], 0x200, CLIENTFACTORY_SIG_SVENGINE, Sig_Length(CLIENTFACTORY_SIG_SVENGINE)); Sig_AddrNotFound(ClientFactory); gCapFuncs.pfnClientFactory = (void *(**)(void))*(DWORD *)(addr + 5); DWORD *pVFTable = *(DWORD **)&s_BaseUI; g_pMetaHookAPI->VFTHook(baseuifuncs, 0, 1, (void *)pVFTable[1], (void **)&m_pfnCBaseUI_Initialize); } else { #define CLIENTFACTORY_SIG "\xCC\xA1\x2A\x2A\x2A\x2A\x85\xC0\x74" DWORD *vft = *(DWORD **)baseuifuncs; DWORD addr = (DWORD)g_pMetaHookAPI->SearchPattern((void *)vft[1], 0x200, CLIENTFACTORY_SIG, Sig_Length(CLIENTFACTORY_SIG)); Sig_AddrNotFound(ClientFactory); gCapFuncs.pfnClientFactory = (void *(**)(void))*(DWORD *)(addr + 2); DWORD *pVFTable = *(DWORD **)&s_BaseUI; g_pMetaHookAPI->VFTHook(baseuifuncs, 0, 1, (void *)pVFTable[1], (void **)&m_pfnCBaseUI_Initialize); } }
33.070175
143
0.774536
DrAbcrealone
d9b84a0b3afa685a84f54b3760a003bfa5cc9178
2,398
cc
C++
capstone.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
1
2021-06-26T05:32:43.000Z
2021-06-26T05:32:43.000Z
capstone.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
2
2019-10-14T06:46:43.000Z
2019-10-18T04:34:20.000Z
capstone.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
null
null
null
#include "capstone.h" #include <functional> #include <iomanip> #include <iostream> #include <memory> #include <string> using namespace std; using namespace std::placeholders; Capstone::Capstone(csh handle, const uint8_t* code, size_t size, uint64_t address) { this->handle = handle; this->code = code; this->size = size; this->address = address; } Capstone::~Capstone() { cs_close(&handle); } /* discard the consts here to match the vendor signature */ Capstone::const_iterator::const_iterator(const Capstone& c) : handle(c.handle), insn(cs_malloc(c.handle)), code(const_cast<const uint8_t*>(c.code)), size(c.size), address(c.address) {} Capstone::const_iterator::const_iterator() : handle(0), insn(NULL), code(NULL), size(0), address(0) {} /* copy will allocate additional memory */ Capstone::const_iterator::const_iterator(const const_iterator& c) : handle(c.handle), insn(cs_malloc(c.handle)), code(c.code), size(c.size), address(c.address) {} Capstone::const_iterator::~const_iterator() { if (insn) { cs_free(insn, 1); insn = NULL; } } const cs_insn& Capstone::const_iterator::operator*() const { return *insn; } Capstone::const_iterator& Capstone::const_iterator::operator++() { if (size == 0) { code = NULL; return *this; } // cout << "cs_disasm_iter(" << hex << handle << "," << (unsigned int)*code << "," << size << "," << address << ")" << // endl; bool i_sz = cs_disasm_iter(handle, &code, &size, &address, insn); // if it fails, reset to end() if (!i_sz) { size = 0; code = NULL; } return *this; } /* postfix is notably less efficient since it allocates a cs_insn each time */ Capstone::const_iterator Capstone::const_iterator::operator++(int) { const_iterator old(*this); operator++(); return old; } long operator-(Capstone::const_iterator const& lhs, Capstone::const_iterator const& rhs) { return lhs.code - rhs.code; } bool operator==(Capstone::const_iterator const& lhs, Capstone::const_iterator const& rhs) { return lhs.code == rhs.code && lhs.size == rhs.size; } bool operator!=(Capstone::const_iterator const& lhs, Capstone::const_iterator const& rhs) { return !(lhs == rhs); } Capstone::const_iterator Capstone::begin() const { return Capstone::const_iterator(*this); } Capstone::const_iterator Capstone::end() const { return Capstone::const_iterator(); }
26.351648
120
0.675146
justinleona
d9bbd6d6f04f630898221d3c4142a9d7d015d8d6
12,223
cc
C++
src/xi_nub.cc
michaeljclark/xi
f8370784d8d92dad535a9ad2c30bf6b6b9eda87f
[ "ISC" ]
3
2020-12-17T14:38:23.000Z
2021-03-11T10:27:55.000Z
src/xi_nub.cc
michaeljclark/xi
f8370784d8d92dad535a9ad2c30bf6b6b9eda87f
[ "ISC" ]
null
null
null
src/xi_nub.cc
michaeljclark/xi
f8370784d8d92dad535a9ad2c30bf6b6b9eda87f
[ "ISC" ]
null
null
null
/* * xi_nub - atomically create child process hosting static function. * * Copyright (c) 2020 Michael Clark <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "xi_common.h" #include "sha256.h" #include <cstdlib> #include <cinttypes> #include <vector> #include <algorithm> #include <threads.h> using string = std::string; template <typename T> using vector = std::vector<T>; struct xi_nub_ctx { string app_name; string user_name; string home_path; string profile_path; void *user_data; }; struct xi_nub_agent { xi_nub_ctx *ctx; vector<string> args; xi_nub_platform_desc listen_sock; vector<xi_nub_ch> ch; }; struct xi_nub_ch { xi_nub_ctx *ctx; xi_nub_agent *agent; xi_nub_platform_desc sock; void *user_data; }; /* * profile directory */ #if defined OS_WINDOWS const char *profile_template = "%s\\%s"; #elif defined OS_MACOS const char *profile_template = "%s/Library/Application Support/%s"; #elif defined OS_LINUX || defined OS_FREEBSD const char *profile_template = "%s/.config/%s"; #endif #if defined OS_WINDOWS static void xi_nub_find_dirs(xi_nub_ctx *ctx) { char profile_path_tmp[MAXPATHLEN]; ctx->user_name = _windows_getenv("USERNAME"); ctx->home_path = _windows_getenv("HOMEPATH"); string appdata = _windows_getenv("APPDATA"); snprintf(profile_path_tmp, MAX_PATH, profile_template, appdata.c_str(), ctx->app_name.c_str()); ctx->profile_path = profile_path_tmp; } #endif #if defined OS_POSIX static void xi_nub_find_dirs(xi_nub_ctx *ctx) { char profile_path_tmp[MAXPATHLEN]; struct passwd *p = getpwuid(getuid()); ctx->user_name = p->pw_name; ctx->home_path = p->pw_dir; snprintf(profile_path_tmp, MAXPATHLEN, profile_template, ctx->home_path.c_str(), ctx->app_name.c_str()); ctx->profile_path = profile_path_tmp; } #endif /* * convert command-line argument to a vector */ static vector<string> _get_args(int argc, const char **argv) { vector<string> args; for (size_t i = 0; i < argc; i++) { if (i == 0 && strcmp(argv[0], "<self>") == 0) { args.push_back(_executable_path()); } else { args.push_back(argv[i]); } } return args; } static char** _get_argv(vector<string> vec) { size_t alloc_size = (vec.size() + 1) * sizeof(char*); for (auto &s : vec) alloc_size += s.size() + 1; char **arr = (char **)malloc(alloc_size); char *data = (char*)&arr[vec.size() + 1]; for (size_t i = 0; i < vec.size(); i++) { arr[i] = data; memcpy(data, vec[i].data(), vec[i].size()); data[vec[i].size()] = 0; data += vec[i].size() + 1; } arr[vec.size()] = 0; return (char**)arr; } struct _argument_hash { unsigned char hash[32]; }; static _argument_hash _get_args_hash(vector<string> vec) { _argument_hash ah; sha256_ctx ctx; sha256_init(&ctx); for (auto &s : vec) { sha256_update(&ctx, s.c_str(), s.size() + 1); } sha256_final(&ctx, ah.hash); return ah; } static string _to_hex(const unsigned char *in, size_t in_len) { size_t o = 0, l = in_len << 1; char *buf = (char*)alloca(l + 1); for (size_t i = 0, o = 0; i < in_len; i++) { o+= snprintf(buf+o, l + 1 - o, "%02" PRIx8, in[i]); } return string(buf, l); } static string _get_nub_addr(xi_nub_ctx *ctx, vector<string> vec) { _argument_hash ah = _get_args_hash(vec); return ctx->app_name + string("-") + _to_hex(ah.hash, sizeof(ah.hash)); } /* * nub agent */ xi_nub_agent* xi_nub_agent_new(xi_nub_ctx *ctx, int argc, const char **argv) { xi_nub_agent *agent = new xi_nub_agent(); agent->ctx = ctx; agent->args = _get_args(argc, argv); _debug_func("agent=%p\n", agent); return agent; } void xi_nub_agent_destroy(xi_nub_agent *agent) { delete agent; } /* * nub server */ static void xi_nub_wake_all_waiters(xi_nub_ctx *ctx) { char sem_file[MAXPATHLEN]; const char* profile_path = xi_nub_ctx_get_profile_path(ctx); snprintf(sem_file, sizeof(sem_file), "%s%s", profile_path, PATH_SEPARATOR "semaphore"); auto f = _open_file(sem_file, file_open_existing, file_read_write); if (f.has_error()) return; /* no lock file */ char buf[1024]; xi_nub_result r = _read(&f, buf, sizeof(buf)); size_t num_waiters = (size_t)(r.bytes >> 2); uint32_t *p = (uint32_t*)buf; for (size_t i = 0; i < num_waiters; i++) { uint32_t pid = *p++; char sem_name[16]; snprintf(sem_name, sizeof(sem_name), "%s-%u", ctx->app_name.c_str(), pid); xi_nub_platform_semaphore sem = _semaphore_open(sem_name); if (sem.has_error()) { _panic("error: _semaphore_open: error_code=%d\n", sem.error_code()); } _debug_func("semaphore=%s *** signal ***\n", sem_name); _semaphore_signal(&sem); _semaphore_unlink(sem_name); _semaphore_close(&sem); } _close(&f); _delete_file(sem_file); } void xi_nub_agent_accept(xi_nub_agent *agent, int nthreads, xi_nub_accept_cb cb) { string pipe_addr = _get_nub_addr(agent->ctx, agent->args); agent->listen_sock = _listen_socket_create(pipe_addr.c_str()); if (agent->listen_sock.has_error()) { _panic("error: listen_socket_create failed: error=%d\n", agent->listen_sock.error_code()); } _debug_func("listening sock=%s\n", agent->listen_sock.identity()); xi_nub_wake_all_waiters(agent->ctx); /* TODO: create agent thread */ for (;;) { xi_nub_ch ch{ agent->ctx, agent, _listen_socket_accept(agent->listen_sock) }; _debug_func("accepted sock=%s\n", ch.sock.identity()); if (ch.sock.has_error()) { cb(&ch, ch.sock.error_code()); } else { cb(&ch, xi_nub_success); } /* TODO - implement server shutdown */ } } /* * nub client */ struct xi_name_object { char name[MAXPATHLEN]; }; struct xi_nub_ticket { uint32_t ticket; uint32_t pid; bool is_leader; xi_name_object obj; }; static xi_nub_ticket xi_nub_get_ticket(xi_nub_ctx *ctx) { xi_name_object obj; const char* profile_path = xi_nub_ctx_get_profile_path(ctx); snprintf(obj.name, sizeof(obj.name), "%s%s", profile_path, PATH_SEPARATOR "semaphore"); bool is_leader = false; auto f = _open_file(obj.name, file_create_new, file_append); if (f.has_error()) { f = _open_file(obj.name, file_open_existing, file_append); } else { is_leader = true; } uint32_t pid = (uint32_t)_get_processs_id(); _write(&f, &pid, sizeof(pid)); xi_nub_result off = _get_file_offset(&f); uint32_t ticket = (uint32_t)off.bytes >> 2; _close(&f); _debug("%s: ticket=%u, is_leader=%u, pid=%u, file=%s\n", __func__, ticket, is_leader, pid, obj.name); return xi_nub_ticket{ticket, pid, is_leader, obj }; } static void xi_nub_sleep_on_ticket(xi_nub_ctx *ctx, xi_nub_ticket ticket) { char sem_name[16]; snprintf(sem_name, sizeof(sem_name), "%s-%u", ctx->app_name.c_str(), ticket.pid); xi_nub_platform_semaphore sem = _semaphore_create(sem_name); if (sem.has_error()) { _panic("error: _semaphore_create: error_code=%d\n", sem.error_code()); } _debug_func("semaphore=%s *** created ***\n", sem_name); _semaphore_wait(&sem, 15000); #if defined OS_WINDOWS _thread_sleep(100); #endif _debug_func("semaphore=%s *** woke up ***\n", sem_name); } void xi_nub_agent_connect(xi_nub_agent *agent, int nthreads, xi_nub_connect_cb cb) { string pipe_addr = _get_nub_addr(agent->ctx, agent->args); xi_nub_ch ch{ agent->ctx, agent, _client_socket_connect(pipe_addr.c_str()) }; _debug_func("sock=%s\n", ch.sock.identity()); /* TODO: create agent thread */ /* if we get a socket error, we try to launch a new server */ if (ch.sock.has_error()) { _close(&ch.sock); /* get an atomic launch ticket, first caller is the leader */ xi_nub_ticket ticket = xi_nub_get_ticket(agent->ctx); /* launch a server if we are the leader */ if (ticket.is_leader) { char **argv = _get_argv(agent->args); int argc = (int)agent->args.size(); xi_nub_os_process p = _create_process(argc, (const char**)argv); free(argv); } /* wait for server to wake us up */ xi_nub_sleep_on_ticket(agent->ctx, ticket); /* attempt to reconnect */ ch.sock = _client_socket_connect(pipe_addr.c_str()); if (ch.sock.has_error()) { cb(&ch, ch.sock.error_code()); } else { cb(&ch, xi_nub_success); } } else { cb(&ch, xi_nub_success); } } /* * nub channel io */ void xi_nub_io_read(xi_nub_ch *ch, void *buf, size_t len, xi_nub_read_cb cb) { xi_nub_result result = _read(&ch->sock, buf, len); _debug_func("sock=%s, len=%zu: ret=%zd, error=%d\n", ch->sock.identity(), len, result.bytes, result.error); if (cb) cb(ch, result.error, buf, result.bytes); } void xi_nub_io_write(xi_nub_ch *ch, void *buf, size_t len, xi_nub_write_cb cb) { xi_nub_result result = _write(&ch->sock, buf, len); _debug_func("sock=%s, len=%zu: ret=%zd, error=%d\n", ch->sock.identity(), len, result.bytes, result.error); if (cb) cb(ch, result.error, buf, result.bytes); } void xi_nub_io_close(xi_nub_ch *ch, xi_nub_close_cb cb) { bool is_server = ch->agent->listen_sock.desc_type() == xi_nub_desc_type_pipe_listen; xi_nub_result result = is_server ? _disconnect(&ch->sock) : _close(&ch->sock); _debug_func("sock=%s: ret=%zd, error=%d\n", ch->sock.identity(), result.bytes, result.error); if (cb) cb(ch, result.error); } const char* xi_nub_io_get_identity(xi_nub_ch *ch) { return ch->sock.identity(); } /* * nub accessors */ static xi_nub_ctx *global_nub_ctx; void xi_nub_io_set_user_data(xi_nub_ch *ch, void *data) { ch->user_data = data; } void* xi_nub_io_get_user_data(xi_nub_ch *ch) { return ch->user_data; } xi_nub_agent* xi_nub_io_get_agent(xi_nub_ch *ch) { return ch->agent; } xi_nub_ctx* xi_nub_io_get_context(xi_nub_ch *ch) { return ch->ctx; } void xi_nub_ctx_set_user_data(xi_nub_ctx *ctx, void *data) { ctx->user_data = data; } void* xi_nub_ctx_get_user_data(xi_nub_ctx *ctx) { return ctx->user_data; } const char* xi_nub_ctx_get_profile_path(xi_nub_ctx *ctx) { return ctx->profile_path.c_str(); } xi_nub_ctx* xi_nub_ctx_get_initial_context() { return global_nub_ctx; } /* * nub context */ static void xi_nub_init(xi_nub_ctx *ctx, const char *app_name) { /* find user profile directory */ ctx->app_name = app_name; xi_nub_find_dirs(ctx); /* create profile directory if it does not exist */ if (!_directory_exists(ctx->profile_path.c_str())) { if(!_make_directory(ctx->profile_path.c_str())) { _panic("error: _make_directory failed: %s\n", ctx->profile_path.c_str()); } } #if defined OS_POSIX /* install handler to cleanup on exit */ _install_signal_handler(); #endif } xi_nub_ctx* xi_nub_ctx_create(const char *app_name) { xi_nub_ctx *ctx; ctx = new xi_nub_ctx(); xi_nub_init(ctx, app_name); if (!global_nub_ctx) { global_nub_ctx = ctx; } return ctx; } void xi_nub_ctx_destroy(xi_nub_ctx *ctx) { delete ctx; }
26.98234
94
0.647468
michaeljclark
d9bdf03336aea3a8efe4f5bcbd3197263a397a62
1,843
cpp
C++
plugins/opengl/src/sdl/context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/sdl/context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/sdl/context.cpp
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) #include <sge/opengl/backend/context.hpp> #include <sge/opengl/backend/current.hpp> #include <sge/opengl/backend/current_unique_ptr.hpp> #include <sge/opengl/sdl/context.hpp> #include <sge/opengl/sdl/current.hpp> #include <sge/renderer/exception.hpp> #include <sge/window/object.hpp> #include <sge/window/object_ref.hpp> #include <awl/backends/sdl/window/object.hpp> #include <fcppt/make_unique_ptr.hpp> #include <fcppt/text.hpp> #include <fcppt/unique_ptr_to_base.hpp> #include <fcppt/cast/dynamic.hpp> #include <fcppt/optional/to_exception.hpp> #include <fcppt/config/external_begin.hpp> #include <SDL_video.h> #include <fcppt/config/external_end.hpp> sge::opengl::sdl::context::context(sge::window::object_ref const _window) : sge::opengl::backend::context{}, window_{ fcppt::optional::to_exception( fcppt::cast::dynamic<awl::backends::sdl::window::object>(_window.get().awl_object()), [] { return sge::renderer::exception{ FCPPT_TEXT("Window passed to sdl::context is not an SDL window.")}; }) .get()}, context_{SDL_GL_CreateContext(&this->window_.get().get().get())} { } sge::opengl::sdl::context::~context() { SDL_GL_DeleteContext(this->context_); } sge::opengl::backend::current_unique_ptr sge::opengl::sdl::context::activate() { return fcppt::unique_ptr_to_base<sge::opengl::backend::current>( fcppt::make_unique_ptr<sge::opengl::sdl::current>(this->window_, this->context_)); } void sge::opengl::sdl::context::deactivate(sge::opengl::backend::current_unique_ptr &&) {}
38.395833
99
0.686923
cpreh
d9bf04ef6338d62f898bf95d48d7996a7644a4b4
696
hpp
C++
webmock/api/application.hpp
mrk21/cpp-webmock
13a7b8362e2e84d47de45071956a43ac3005c58a
[ "MIT" ]
1
2021-05-01T15:05:47.000Z
2021-05-01T15:05:47.000Z
webmock/api/application.hpp
mrk21/cpp-webmock
13a7b8362e2e84d47de45071956a43ac3005c58a
[ "MIT" ]
13
2015-01-02T11:59:58.000Z
2015-01-19T05:27:06.000Z
webmock/api/application.hpp
mrk21/cpp-webmock
13a7b8362e2e84d47de45071956a43ac3005c58a
[ "MIT" ]
null
null
null
#ifndef WEBMOCK_API_APPLICATION_HPP #define WEBMOCK_API_APPLICATION_HPP #include <webmock/core/request.hpp> #include <webmock/core/stub_registry.hpp> #include <functional> namespace webmock { namespace api { struct application { using stub_not_found_callback_type = std::function<void(core::request const &)>; core::stub_registry registry; struct { struct { stub_not_found_callback_type callback; bool is_connecting_to_net = false; } stub_not_found; } config; }; inline application & app() { static application instance; return instance; } }} #endif
24
88
0.632184
mrk21
d9c1c68ac81d35cb9e64bcafae2a489d45d035df
412
cpp
C++
Private/TB_GameMode.cpp
larsjsol/UE4_TurnBased
547a601cbeacec5b8380ec480b2764dd1822aedb
[ "MIT" ]
7
2015-02-13T23:07:00.000Z
2022-03-04T08:01:04.000Z
Private/TB_GameMode.cpp
larsjsol/UE4_TurnBased
547a601cbeacec5b8380ec480b2764dd1822aedb
[ "MIT" ]
null
null
null
Private/TB_GameMode.cpp
larsjsol/UE4_TurnBased
547a601cbeacec5b8380ec480b2764dd1822aedb
[ "MIT" ]
2
2019-06-25T06:38:18.000Z
2022-03-04T04:06:35.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "UE4_TurnBased.h" #include "TB_PlayerController.h" #include "TB_GameState.h" #include "TB_GameMode.h" ATB_GameMode::ATB_GameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PlayerControllerClass = ATB_PlayerController::StaticClass(); GameStateClass = ATB_GameState::StaticClass(); }
21.684211
78
0.791262
larsjsol
d9c48862fa5ed07ac1b2a037ddcfd936d469c912
1,130
hpp
C++
include/primer/result.hpp
cbeck88/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
14
2016-07-27T18:14:47.000Z
2018-06-15T19:54:10.000Z
include/primer/result.hpp
garbageslam/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
5
2016-11-01T23:20:35.000Z
2016-11-29T21:09:53.000Z
include/primer/result.hpp
cbeck88/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
2
2021-02-07T03:42:22.000Z
2021-02-10T14:12:00.000Z
// (C) Copyright 2015 - 2018 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once /*** * Signaling object used to indicate how to terminate a lua function call. */ #include <primer/base.hpp> PRIMER_ASSERT_FILESCOPE; #include <primer/expected.hpp> namespace primer { //[ primer_result // Tag used by the user to indicate a yield. struct yield { int n_; }; // Helper object: Represents a return or yield signal. struct return_or_yield { int n_; bool is_return_; bool is_valid() const { return n_ >= 0; } }; // Result object class result { expected<return_or_yield> payload_; public: // Ctors (implicit for ease of use) result(int i) : payload_(return_or_yield{i, true}) {} result(yield y) : payload_(return_or_yield{y.n_, false}) {} result(error e) : payload_(e) {} // Accessor const expected<return_or_yield> & get_payload() const & { return payload_; } expected<return_or_yield> & get_payload() & { return payload_; } }; //] } // end namespace primer
20.178571
80
0.69292
cbeck88
d9c7fb61a4bcddf1a828f1f705d83b9910670b6e
188
hpp
C++
cracking/minmax/note2.hpp
ancientscience/ancientscience.github.io
2c8e3c6a8017164fd86fabaaa3343257cea54405
[ "MIT" ]
null
null
null
cracking/minmax/note2.hpp
ancientscience/ancientscience.github.io
2c8e3c6a8017164fd86fabaaa3343257cea54405
[ "MIT" ]
null
null
null
cracking/minmax/note2.hpp
ancientscience/ancientscience.github.io
2c8e3c6a8017164fd86fabaaa3343257cea54405
[ "MIT" ]
null
null
null
std::reverse_iterator( first_min_element(v.begin(), v.end(), std::less<int>())) == last_max_element(v.rbegin(), v.rend(), std::greater<int>())
26.857143
41
0.515957
ancientscience
d9cbfc4923dbb225bdd48cd9da3b08dd90957b05
419
cpp
C++
week1/project1/b/main.cpp
Arnarish/3ViknaPizzaD-t
65e214dfccd7932c25082206fc2f9a360d7efa07
[ "MIT" ]
null
null
null
week1/project1/b/main.cpp
Arnarish/3ViknaPizzaD-t
65e214dfccd7932c25082206fc2f9a360d7efa07
[ "MIT" ]
null
null
null
week1/project1/b/main.cpp
Arnarish/3ViknaPizzaD-t
65e214dfccd7932c25082206fc2f9a360d7efa07
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> using namespace std; int main(void) { string text; ofstream fout; fout.open("very_important_text.txt", ios::app); while (true) { cout << "Write whatever you wish, and it will be saved!" << endl; getline(cin, text); if (text[0] == '\\') { break; } fout << text << endl; } return 0; }
18.217391
73
0.539379
Arnarish
d9d0cd085c7da60b01c1d68ada67354e99ab1129
3,458
hpp
C++
src/tesseract/regression/LeastSquares.hpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
3
2015-01-09T08:15:28.000Z
2019-05-24T08:34:04.000Z
src/tesseract/regression/LeastSquares.hpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
null
null
null
src/tesseract/regression/LeastSquares.hpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2014 Soumyajit De * * 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. */ #ifndef LEAST_SQUARES_H__ #define LEAST_SQUARES_H__ #include <tesseract/base/types.h> namespace tesseract { /** * Enum for defining which of the methods are to be used for solving * the least square problem instance */ enum LeastSquareMethod { LS_SVD, LS_QR, LS_NORMAL }; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined systems \f$Ax=b\f$. */ template <typename T, enum LeastSquareMethod> struct LeastSquares; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined system \f$Ax=b\f$ * using Jacobi SVD. */ template <typename T> struct LeastSquares<T, LS_SVD> { /** * Solves the over-determined system \f$Ax=b\f$. * @param A matrix \f$A\f$ * @param b vector \f$b\f$ * @param result result vector \f$x\f$ */ void solve(const Eigen::Ref<const Matrix<T>>& A, const Eigen::Ref<const Vector<T>>& b, Eigen::Ref<Vector<T>> result) const { result = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b); } }; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined system \f$Ax=b\f$ * using Householder QR decomposition. */ template <typename T> struct LeastSquares<T, LS_QR> { /** * Solves the over-determined system \f$Ax=b\f$. * @param A matrix \f$A\f$ * @param b vector \f$b\f$ * @param result result vector \f$x\f$ */ void solve(const Eigen::Ref<const Matrix<T>>& A, const Eigen::Ref<const Vector<T>>& b, Eigen::Ref<Vector<T>> result) const { result = A.colPivHouseholderQr().solve(b); } }; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined system \f$Ax=b\f$ * using \f$x=(A^T.A)^{-1}(A^T.b)\f$. */ template <typename T> struct LeastSquares<T, LS_NORMAL> { /** * Solves the over-determined system \f$Ax=b\f$. * @param A matrix \f$A\f$ * @param b vector \f$b\f$ * @param result result vector \f$x\f$ */ void solve(const Eigen::Ref<const Matrix<T>>& A, const Eigen::Ref<const Vector<T>>& b, Eigen::Ref<Vector<T>> result) const { result = (A.transpose() * A).ldlt().solve(A.transpose() * b); } }; } #endif // LEAST_SQUARES_H__
29.555556
87
0.707634
lambday
d9d0edfb4fc17c65fea6cc6e8f0bfcd9762bb869
5,514
cpp
C++
ELM_GUI_lib/ELM_GUI_lib/Device.cpp
therealddx/EagleLibraryManager
bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8
[ "MIT" ]
null
null
null
ELM_GUI_lib/ELM_GUI_lib/Device.cpp
therealddx/EagleLibraryManager
bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8
[ "MIT" ]
null
null
null
ELM_GUI_lib/ELM_GUI_lib/Device.cpp
therealddx/EagleLibraryManager
bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8
[ "MIT" ]
null
null
null
#include "Stdafx.h" #include "Device.h" namespace ELM_GUI_lib { Device::Device() { p = Package(); s = Symbol(); name = ""; XMLtext = ""; } Device::Device(std::string d_name) { /* <deviceset name="DUMMY"> <gates> </gates> <devices> <device name=""> <technologies> <technology name=""/> </technologies> </device> </devices> </deviceset> */ name = d_name; p = Package(name); s = Symbol(name); XMLtext = XMLParse::generateTag(XMLParse::XML_TAGS::DEVICESET_START, name); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::GATES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::GATES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICE_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::TECHNOLOGIES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::TECHNOLOGY)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::TECHNOLOGIES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICE_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICESET_END)); } Device::Device(std::string d_name, std::string d_XMLtext) { p = Package(d_name); s = Symbol(d_name); name = d_name; XMLtext = d_XMLtext; } void Device::compileXML(std::vector<std::string> padNames) { XMLtext = XMLParse::generateTag(XMLParse::DEVICESET_START, name); XMLtext.append(XMLParse::generateTag(XMLParse::GATES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::GATE, name)); XMLtext.append(XMLParse::generateTag(XMLParse::GATES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICE_START, name)); XMLtext.append(XMLParse::generateTag(XMLParse::CONNECTS_START)); for (std::string cur_name : padNames) XMLtext.append(XMLParse::generateTag(XMLParse::CONNECT, cur_name)); XMLtext.append(XMLParse::generateTag(XMLParse::CONNECTS_END)); XMLtext.append(XMLParse::generateTag(XMLParse::TECHNOLOGIES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::TECHNOLOGY)); XMLtext.append(XMLParse::generateTag(XMLParse::TECHNOLOGIES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICE_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICESET_END)); } //Generates 2xN Device. Device::Device( std::string d_name, std::vector<std::string> padNames, double d_space_x, double d_space_y, double d_dim_x, double d_dim_y, int N ) { Package p_new(d_name, padNames, d_space_x, d_space_y, d_dim_x, d_dim_y, N); //Package p_new(d_name); p = p_new; Symbol s_new(d_name, padNames, N*2); //Symbol s_new(d_name); s = s_new; name = d_name; compileXML(padNames); //Grouping pins will have to be presented as an option. //One example deviceset connection looks like this: // <deviceset name="VCO_805-900MHZ"> // <gates> // <gate name="G$1" symbol="VCO_805-900MHZ" x="60.96" y="5.08"/> // </gates> // <devices> // <device name="" package="VCO_805-900MHZ"> // <connects> // <connect gate="G$1" pin="GND" pad="GND0 GND1 GND2 GND3 GND4 GND5 GND6 GND7 GND8 GND9 GND10 GND11 GND12"/> // <connect gate="G$1" pin="RF" pad="RF"/> // <connect gate="G$1" pin="VCC" pad="VCC"/> // <connect gate="G$1" pin="VT" pad="VT"/> // </connects> // <technologies> // <technology name=""/> // </technologies> // </device> // </devices> // </deviceset> } //Generate RA. Device::Device( std::string d_name, std::vector<std::string> d_padNames, double d_REF, int d_N, double d_padW, double d_padL, double d_padSpace, double d_centeredSquarePad_DIM, double d_cornerSquarePads_REF, double d_cornerSquarePads_DIM ) { Package p_new( d_name, d_padNames, d_REF, d_N, d_padW, d_padL, d_padSpace, d_centeredSquarePad_DIM, d_cornerSquarePads_REF, d_cornerSquarePads_DIM ); //Package p_new(d_name); p = p_new; Symbol s_new(d_name, d_padNames, p.numPads); //Symbol s_new(d_name); s = s_new; name = d_name; compileXML(d_padNames); } //Generate RxR. Device::Device( std::string d_name, std::vector<std::string> d_padNames, int d_N_rows, int* d_N_pads, double* d_padX, double* d_padY, double* d_padSpace, //length N_rows double* d_horizontalOffset, double* d_verticalOffset //length N_rows - 1 ) { Package p_new( d_name, d_padNames, d_N_rows, d_N_pads, d_padX, d_padY, d_padSpace, //length N_rows d_horizontalOffset, d_verticalOffset //length N_rows - 1 ); //Package p_new(d_name); p = p_new; Symbol s_new(d_name, d_padNames, p.numPads); //Symbol s_new(d_name); s = s_new; name = d_name; compileXML(d_padNames); } Device::Device(const Device& orig) { } Device::~Device() { } Device * Device::makeDummyDevices(std::vector<std::string> nameList) { int numDummyDevices = nameList.size(); Device * dummyDeviceList = new Device[numDummyDevices]; for (int n = 0; n < numDummyDevices; n++) { dummyDeviceList[n] = Device(nameList[n]); } return dummyDeviceList; } }
27.989848
113
0.673377
therealddx
d9d2a919f762ee2e36c64e4a2f3895827fc9c5ef
432
hpp
C++
src/lib/PageDownloader.hpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
src/lib/PageDownloader.hpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
src/lib/PageDownloader.hpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
#ifndef PAGEDOWNLOADER_HPP_R1YIYM0U #define PAGEDOWNLOADER_HPP_R1YIYM0U #include "bmrk_fwd.hpp" #include <string> #include <future> namespace bmrk { /** * Download a document from a remote url */ class PageDownloader { public: /** * \return a future with the downloaded document */ virtual Future<String> load(const String& url) const; }; } /* bmrk */ #endif /* end of include guard: PAGEDOWNLOADER_HPP_R1YIYM0U */
18.782609
62
0.722222
alepez
d9d4e63d8d4b6c32e7e6c337834673972631e779
881
cpp
C++
test/training_data/plag_original_codes/arc105_a_17340899_625_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/arc105_a_17340899_625_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/arc105_a_17340899_625_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/arc105/tasks/arc105_a A - Fourtune CookiesEditorial Time Limit : 2 sec / Memory Limit : 1024 MB 配点 : 200 点 */ #include <iostream> using namespace std; /* -------------------- ここまでテンプレ -------------------- */ int main() { bool ans = 0; int a, b, c, d; cin >> a >> b >> c >> d; ans |= (a) == (b + c + d); ans |= (a + b) == (c + d); ans |= (a + c) == (b + d); ans |= (a + d) == (b + c); ans |= (a + b + c) == (d); ans |= (a + b + d) == (c); ans |= (a + c + d) == (b); ans |= (a + b + c + d) == 0; ans |= (b) == (a + c + d); ans |= (b + c) == (a + d); ans |= (b + d) == (a + c); ans |= (b + c + d) == (a); ans |= (c) == (a + b + d); ans |= (c + d) == (a + b); ans |= (d) == (a + b + c); if (ans) cout << "Yes" << endl; else cout << "No" << endl; }
24.472222
60
0.351873
xryuseix
d9d8aecc63c2ce097ee4d081d7b66de84f8aa770
288
cpp
C++
lib/except.cpp
kenavolic/nforce
34ca3ad924047f47c22c1db332b2da3885c5eed4
[ "Apache-2.0" ]
1
2019-05-01T19:13:02.000Z
2019-05-01T19:13:02.000Z
lib/except.cpp
kenavolic/nforce
34ca3ad924047f47c22c1db332b2da3885c5eed4
[ "Apache-2.0" ]
null
null
null
lib/except.cpp
kenavolic/nforce
34ca3ad924047f47c22c1db332b2da3885c5eed4
[ "Apache-2.0" ]
null
null
null
#include "nforce/core/except.h" namespace n4 { //------------------------------------- // Public nexcept::nexcept(const std::string &str, status_type s) : std::exception{}, m_status{s} {} status_type nexcept::status() const noexcept { return m_status; } } // namespace n4
26.181818
66
0.579861
kenavolic
d9d8ec9ad576d4e46bf8f3fa0027ec24fd06096c
2,552
cpp
C++
backend/Sensors/Sensor.cpp
Sorong/Smarrium
dc3a6b8e0d428e01b936679a8ca221c2b610b0f6
[ "MIT" ]
null
null
null
backend/Sensors/Sensor.cpp
Sorong/Smarrium
dc3a6b8e0d428e01b936679a8ca221c2b610b0f6
[ "MIT" ]
null
null
null
backend/Sensors/Sensor.cpp
Sorong/Smarrium
dc3a6b8e0d428e01b936679a8ca221c2b610b0f6
[ "MIT" ]
null
null
null
#include "./backend/Sensors/Sensor.h" #include <QDebug> Sensor::Sensor(int interval) { this->_id = QUuid::createUuid(); this->_interval = interval; this->lastCheckedHour = -1; start(interval); connect(this, SIGNAL(timeout()), this, SLOT(intervallElapsed())); //eventValueLog = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; //TODO: Remove me } const QString &Sensor::toString() { return this->name; } QUuid Sensor::getUuid() { return this->_id; } void Sensor::intervallElapsed(){ sensors_event_t* event = new sensors_event_t(); this->getEvent(event); logEvent(event); emit newSensorEvent(event); } void Sensor::fillLog(float val) { for (int i = 0; i < 24; i++) { this->eventValueLog.push_back(val); qDebug() << "Logeintrag erstellt"; } } int Sensor::getInterval(){ return this->_interval; } void Sensor::setInterval(int interval){ stop(); start(interval); } QString Sensor::getId(){ return this->_id.toString(); } void Sensor::logEvent(sensors_event_t *event){ float value = 0; switch(event->type){ case SENSOR_TYPE_IRTEMPERATURE: value = event->irTemperature; break; case SENSOR_TYPE_LIGHT: value = event->light; break; case SENSOR_TYPE_MOISTURE: value = event->moisture; break; case SENSOR_TYPE_RELATIVE_HUMIDITY: value = event->relative_humidity; break; case SENSOR_TYPE_TEMPERATURE: value = event->temperature; break; case SENSOR_TYPE_UV: value = event->uv; break; default: return; } qDebug() << "Intervall elapsed: " << value << "Sensor: " << this->getSort(); int currentHour = QTime::currentTime().hour(); if(this->lastCheckedHour == -1) { this->fillLog(value); this->lastCheckedHour = currentHour; return; } if(this->lastCheckedHour < currentHour || currentHour == 0){ qDebug() << "Logeintrag erstellt"; if(eventValueLog.size() == 24){ this->eventValueLog.pop_front(); this->eventValueLog.push_back(value); } else{ this->eventValueLog.push_back(value); } this->lastCheckedHour = currentHour; } } QList<qreal> Sensor::getEventValueLog(){ return this->eventValueLog; } float Sensor::getLastEventValue(){ if(this->eventValueLog.isEmpty()){ return 0; } else{ return this->eventValueLog.last(); } }
21.445378
116
0.604232
Sorong
d9e3e4a0826be431fa25cbbe29a862edbe9ed409
3,014
cpp
C++
1521/c.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1521/c.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1521/c.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <unordered_map> #include <vector> #include <cassert> #include <algorithm> #include <chrono> #include <random> using namespace std; void solve() { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); unordered_map<int, int> mp; int n; cin >> n; // Initial phase. cout << "? " << 1 << " " << 1 << " " << 2 << " " << n - 1 << "\n"; int max_1_2; int min_1_2; int num; cin >> max_1_2; cout << "? " << 1 << " " << 2 << " " << 1 << " " << n - 1 << "\n"; cin >> num; max_1_2 = max(max_1_2, num); cout << "? " << 1 << " " << 2 << " " << 1 << " " << max_1_2 - 1 << "\n"; cin >> num; // p1 < p2 => result is p2 - 1 int cur_unknown_idx; int max_known = max_1_2; if (num == max_known - 1) { mp[max_known] = 2; cur_unknown_idx = 1; } else { // p1 > p2 otherwise. mp[max_known] = 1; cur_unknown_idx = 2; } // Get second cout << "? " << 2 << " " << cur_unknown_idx << " " << mp[max_known] << " " << 1 << "\n"; cin >> min_1_2; if (min_1_2 == max(2, max_known)) { cout << "? " << 1 << " " << mp[max_known] << " " << cur_unknown_idx << " " << n - 1 << "\n"; cin >> max_1_2; mp[max_1_2] = cur_unknown_idx; max_known = max(max_known, max_1_2); } else { mp[min_1_2] = cur_unknown_idx; max_known = max(max_known, min_1_2); } // The first and second are known. // find the others vector<int> indices; for (int i = 3; i <= n; ++i) { indices.push_back(i); } shuffle(indices.begin(), indices.end(), std::default_random_engine(seed)); for (int i = 3; i <= n; ++i) { // still don't know n - i + 1 numbers int cnt_less_unknown = max_known - (i - 1); int cnt_greater_unknown = n - max_known + 1; int idx = indices[i - 3]; // chances are we'll encounter the number that is less! if (cnt_less_unknown > cnt_greater_unknown) { cout << "? 2 " << idx << " " << mp[max_known] << " " << 1 << endl; cin >> min_1_2; if (min_1_2 == max_known) { // ops, bad luck! cout << "? 1 " << mp[max_known] << " " << idx << " " << n - 1 << endl; cin >> max_1_2; mp[max_1_2] = idx; max_known = max(max_known, max_1_2); } else { mp[min_1_2] = idx; } } else { // chances are we'll encounter the number that is greater cout << "? 1 " << mp[max_known] << " " << idx << " " << n - 1 << endl; cin >> max_1_2; if (max_1_2 == min(max_known, n - 1)) { // ops, bad luck! cout << "? 2 " << idx << " " << mp[max_known] << " " << 1 << endl; cin >> min_1_2; mp[min_1_2] = idx; } else { mp[max_1_2] = idx; max_known = max(max_known, max_1_2); } } } vector<int> ans(n, 0); for (auto [num, idx]: mp) { ans[idx - 1] = num; } cout << "! "; for (auto el: ans) { cout << el << " "; } cout << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } cout.flush(); return 0; }
25.982759
96
0.500664
vladshablinsky
d9e50470ee21ab61a147555aaf145938bc90c2df
16,993
cpp
C++
shimmer/src/configuration.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
shimmer/src/configuration.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
shimmer/src/configuration.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
#include "configuration.h" #include "common/env.h" #include "common/file.h" #include "common/json.h" #include <sstream> namespace shimmer { const common::logger& config::logger = common::logger::get ( "shimmer::config" ); nlohmann::json config::merge ( const nlohmann::json& a, const nlohmann::json& b ) { auto merged = b.flatten(); for ( const auto& prop : a.items() ) { if ( !prop.value().is_null() ) merged[prop.key()] = prop.value(); } return merged.unflatten(); } nlohmann::json config::from_environment() { nlohmann::json conf = nlohmann::json::object(); auto evars = common::env::find_all ( std::regex ( "^SHIMMER_.*" ) ); if ( !evars.empty() ) { for ( auto& evar : evars ) { auto key = evar.first.substr ( 8, evar.first.length() ); key = common::str::replace ( key, "_", "/" ); key = common::str::lower ( key ); conf["/" + key] = evar.second; } conf = conf.unflatten(); } logger.debug ( "Environment config: {}", conf.dump ( 2 ) ); return conf; } nlohmann::json config::from_file ( const std::string& path ) { auto conf = nlohmann::json ( common::file::read_all ( path ) ); logger.debug ( "File config ({}): {}", path, conf.dump ( 2 ) ); return nlohmann::json ( conf ); } config config::create() { config conf = from_environment(); if ( !conf.general.config_dirs.empty() ) { try { auto config_file = common::file::find ( "shimmer.conf", conf.general.config_dirs ); conf = merge ( from_file ( config_file ), conf ); } catch ( const std::exception& ex ) { logger.warn ( "Failed to load config file:\n{}", ex.what() ); } } logger.debug ( "Shimmer configuration: {}", nlohmann::json ( conf ).dump ( 2 ) ); return conf; } template<typename T> void set_property ( T& property, const nlohmann::json& json, const std::string& field ) { try { property = json.at ( field ).get<T>(); } catch ( const nlohmann::json::exception& ex ) { if ( ex.id == 403 ) {} else { config::logger.warn ( "Unable to set config property: {} -> {}\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } catch ( const std::exception& ex ) { config::logger.warn ( "Unable to set config property: {} -> {}\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } template<> void set_property ( unsigned int& property, const nlohmann::json& json, const std::string& field ) { try { auto value = json.at ( field ); if ( value.is_string() ) { value = std::stof ( value.get<std::string>() ); } property = value.get<unsigned int>(); } catch ( const nlohmann::json::exception& jex ) { if ( jex.id == 403 ) {} else { config::logger.warn ( "Unable to set config property: {} -> {}\n{}", field, json.at ( field ).dump(), jex.what() ); } } catch ( const std::exception& ex ) { config::logger.warn ( "Unable to set config property: {} -> {}\nExpected an unsigned integer.\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } template<> void set_property ( float& property, const nlohmann::json& json, const std::string& field ) { try { auto value = json.at ( field ); if ( value.is_string() ) { value = std::stof ( value.get<std::string>() ); } property = value.get<float>(); } catch ( const nlohmann::json::exception& jex ) { if ( jex.id == 403 ) {} else { config::logger.warn ( "Unable to set config property: {} -> {}\n{}", field, json.at ( field ).dump(), jex.what() ); } } catch ( const std::exception& ex ) { config::logger.warn ( "Unable to set config property: {} -> {}\nExpected a float.\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } config::mapping_exception::mapping_exception( const std::string& property, const std::string& value, const std::vector<std::string>& expected ) : runtime_error ( "Could not map value: '" + property + "' => '" + value + "'; expected one of the following: [" + common::str::join ( expected, ", " ) + "]." ) {} std::string to_string ( const enum config::logging::level& level ) { switch ( level ) { case config::logging::level::debug: return "debug"; case config::logging::level::error: return "error"; case config::logging::level::fatal: return "fatal"; case config::logging::level::info: return "info"; case config::logging::level::off: return "off"; case config::logging::level::trace: return "trace"; case config::logging::level::warning: return "warning"; } return "warning"; } std::string to_string ( const enum config::logging::output& output ) { switch ( output ) { case config::logging::output::console: return "console"; case config::logging::output::file: return "file"; } return "console"; } std::string to_string ( const enum config::video::filter& filter ) { switch ( filter ) { case config::video::filter::linear: return "linear"; case config::video::filter::nearest: return "nearest"; } return "nearest"; } std::string to_string ( const enum config::video::aspect& aspect ) { switch ( aspect ) { case config::video::aspect::custom: return "custom"; case config::video::aspect::original: return "original"; case config::video::aspect::stretch: return "stretch"; case config::video::aspect::zoom: return "zoom"; } return "original"; } std::string to_string ( const enum config::video::shape::type& shape ) { switch ( shape ) { case config::video::shape::type::lens: return "lens"; case config::video::shape::type::rectangle: return "rectangle"; } return "rectangle"; } void from_string ( enum config::logging::level& level, const std::string& str ) { if ( str.compare ( "debug" ) == 0 ) { level = config::logging::level::debug; } else if ( str.compare ( "error" ) == 0 ) { level = config::logging::level::error; } else if ( str.compare ( "fatal" ) == 0 ) { level = config::logging::level::fatal; } else if ( str.compare ( "info" ) == 0 ) { level = config::logging::level::info; } else if ( str.compare ( "off" ) == 0 ) { level = config::logging::level::off; } else if ( str.compare ( "trace" ) == 0 ) { level = config::logging::level::trace; } else if ( str.compare ( "warning" ) == 0 ) { level = config::logging::level::warning; } else { throw config::mapping_exception ( "config::logging::level", str, { "trace", "debug", "info", "warning", "error", "fatal", "off" } ); } } void from_string ( enum config::logging::output& output, const std::string& str ) { if ( str.compare ( "console" ) == 0 ) { output = config::logging::output::console; } else if ( str.compare ( "file" ) == 0 ) { output = config::logging::output::file; } else { throw config::mapping_exception ( "config::logging::output", str, { "console", "file" } ); } } void from_string ( enum config::video::filter& filter, const std::string& str ) { if ( str.compare ( "linear" ) == 0 ) { filter = config::video::filter::linear; } else if ( str.compare ( "nearest" ) == 0 ) { filter = config::video::filter::nearest; } else { throw config::mapping_exception ( "config::video::filter", str, { "linear", "nearest" } ); } } void from_string ( enum config::video::aspect& aspect, const std::string& str ) { if ( str.compare ( "custom" ) == 0 ) { aspect = config::video::aspect::custom; } else if ( str.compare ( "original" ) == 0 ) { aspect = config::video::aspect::original; } else if ( str.compare ( "stretch" ) == 0 ) { aspect = config::video::aspect::stretch; } else if ( str.compare ( "zoom" ) == 0 ) { aspect = config::video::aspect::zoom; } else { throw config::mapping_exception ( "config::video::aspect", str, { "custom", "original", "stretch", "zoom" } ); } } void from_string ( enum config::video::shape::type& shape, const std::string& str ) { if ( str.compare ( "lens" ) == 0 ) { shape = config::video::shape::type::lens; } else if ( str.compare ( "rectangle" ) == 0 ) { shape = config::video::shape::type::rectangle; } else { throw config::mapping_exception ( "config::video::shape::type", str, { "lens", "rectangle" } ); } } void to_json ( nlohmann::json& json, const config& config ) { json = { { "general", config.general }, { "input", config.input }, { "logging", config.logging }, { "video", config.video }, }; } void from_json ( const nlohmann::json& json, config& config ) { set_property ( config.general, json, "general" ); set_property ( config.input, json, "input" ); set_property ( config.logging, json, "logging" ); set_property ( config.video, json, "video" ); } void to_json ( nlohmann::json& json, const struct config::general& general ) { json = { { "config_dirs", general.config_dirs }, { "data_dirs", general.data_dirs }, { "font_dirs", general.font_dirs }, { "image_dirs", general.image_dirs }, { "shaders_dirs", general.shader_dirs }, }; } void from_json ( const nlohmann::json& json, struct config::general& general ) { set_property ( general.config_dirs, json, "config_dirs" ); set_property ( general.data_dirs, json, "data_dirs" ); set_property ( general.font_dirs, json, "font_dirs" ); set_property ( general.image_dirs, json, "image_dirs" ); set_property ( general.shader_dirs, json, "shader_dirs" ); } void to_json ( nlohmann::json& json, const struct config::input& input ) { json = { { "grab", input.grab } }; } void from_json ( const nlohmann::json& json, struct config::input& input ) { set_property ( input.grab, json, "grab" ); } void to_json ( nlohmann::json& json, const struct config::logging& logging ) { json = { { "level", logging.level }, { "output", logging.output }, { "file", logging.file } }; } void from_json ( const nlohmann::json& json, struct config::logging& logging ) { set_property ( logging.level, json, "level" ); set_property ( logging.output, json, "output" ); set_property ( logging.file, json, "file" ); } void to_json ( nlohmann::json& json, const enum config::logging::level& level ) { json = to_string ( level ); } void from_json ( const nlohmann::json& json, enum config::logging::level& level ) { from_string ( level, json ); } void to_json ( nlohmann::json& json, const enum config::logging::output& output ) { json = to_string ( output ); } void from_json ( const nlohmann::json& json, enum config::logging::output& output ) { from_string ( output, json ); } void to_json ( nlohmann::json& json, const struct config::video& video ) { json = { { "aspect", video.aspect }, { "custom_aspect", video.custom_aspect }, { "filter", video.filter }, { "font", video.font }, { "limiter", video.limiter }, { "shader", video.shader }, { "shape", video.shape } }; } void from_json ( const nlohmann::json& json, struct config::video& video ) { set_property ( video.aspect, json, "aspect" ); set_property ( video.custom_aspect, json, "custom_aspect" ); set_property ( video.filter, json, "filter" ); set_property ( video.font, json, "font" ); set_property ( video.limiter, json, "limiter" ); set_property ( video.shader, json, "shader" ); set_property ( video.shape, json, "shape" ); } void to_json ( nlohmann::json& json, const enum config::video::aspect& aspect ) { json = to_string ( aspect ); } void from_json ( const nlohmann::json& json, enum config::video::aspect& aspect ) { from_string ( aspect, json ); } void to_json ( nlohmann::json& json, const enum config::video::filter& filter ) { json = to_string ( filter ); } void from_json ( const nlohmann::json& json, enum config::video::filter& filter ) { from_string ( filter, json ); } void to_json ( nlohmann::json& json, const struct config::video::limiter& limiter ) { json = { { "rate", limiter.rate }, { "samples", limiter.samples } }; } void from_json ( const nlohmann::json& json, struct config::video::limiter& limiter ) { set_property ( limiter.rate, json, "rate" ); set_property ( limiter.samples, json, "samples" ); } void to_json ( nlohmann::json& json, const struct config::video::shader& shader ) { json = { { "fragment", shader.fragment }, { "scale", shader.scale }, { "vertex", shader.vertex } }; } void from_json ( const nlohmann::json& json, struct config::video::shader& shader ) { set_property ( shader.fragment, json, "fragment" ); set_property ( shader.scale, json, "scale" ); set_property ( shader.vertex, json, "vertex" ); } void to_json ( nlohmann::json& json, const struct config::video::shape& shape ) { json = { { "type", shape.type }, { "lens", shape.lens } }; } void from_json ( const nlohmann::json& json, struct config::video::shape& shape ) { set_property ( shape.lens, json, "lens" ); set_property ( shape.type, json, "type" ); } void to_json ( nlohmann::json& json, const struct config::video::shape::lens& lens ) { json = { { "curve", lens.curve }, { "quality", lens.quality } }; } void from_json ( const nlohmann::json& json, struct config::video::shape::lens& lens ) { set_property ( lens.curve, json, "curve" ); set_property ( lens.quality, json, "quality" ); } void to_json ( nlohmann::json& json, const enum config::video::shape::type& type ) { json = to_string ( type ); } void from_json ( const nlohmann::json& json, enum config::video::shape::type& type ) { from_string ( type, json ); } } // namespace shimmer
31.009124
100
0.496852
jasbok
d9e897debb36785021c3255d4f5a1bdb1e3c0111
3,126
hpp
C++
cm730controller/include/cm730controller/cm730controller.hpp
threeal/ros2_cm730
2f5e3a60395405c4af6dcfb5a7c5a56ede921b09
[ "Apache-2.0" ]
1
2020-09-27T04:33:53.000Z
2020-09-27T04:33:53.000Z
cm730controller/include/cm730controller/cm730controller.hpp
threeal/ros2_cm730
2f5e3a60395405c4af6dcfb5a7c5a56ede921b09
[ "Apache-2.0" ]
null
null
null
cm730controller/include/cm730controller/cm730controller.hpp
threeal/ros2_cm730
2f5e3a60395405c4af6dcfb5a7c5a56ede921b09
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Bold Hearts // // 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 CM730CONTROLLER__CM730CONTROLLER_HPP_ #define CM730CONTROLLER__CM730CONTROLLER_HPP_ #include <rclcpp/rclcpp.hpp> #include <cm730driver_msgs/srv/write.hpp> #include <cm730driver_msgs/srv/bulk_read.hpp> #include <cm730driver_msgs/srv/sync_write.hpp> #include <cm730controller_msgs/msg/cm730_info.hpp> #include <cm730controller_msgs/msg/mx28_info_array.hpp> #include <cm730controller_msgs/msg/mx28_command.hpp> #include <map> #include "cm730controller/visibility_control.h" namespace cm730controller { class Cm730Controller : public rclcpp::Node { public: Cm730Controller(); virtual ~Cm730Controller(); private: // Convenience types using Write = cm730driver_msgs::srv::Write; using BulkRead = cm730driver_msgs::srv::BulkRead; using SyncWrite = cm730driver_msgs::srv::SyncWrite; using CM730Info = cm730controller_msgs::msg::CM730Info; using MX28InfoArray = cm730controller_msgs::msg::MX28InfoArray; using MX28Command = cm730controller_msgs::msg::MX28Command; using CM730EepromTable = cm730controller_msgs::msg::CM730EepromTable; using MX28EepromTable = cm730controller_msgs::msg::MX28EepromTable; using WriteClient = rclcpp::Client<Write>; using BulkReadClient = rclcpp::Client<BulkRead>; using SyncWriteClient = rclcpp::Client<SyncWrite>; // Clients for CM730 driver services WriteClient::SharedPtr writeClient_; BulkReadClient::SharedPtr bulkReadClient_; SyncWriteClient::SharedPtr syncWriteClient_; // Subscribers rclcpp::Subscription<MX28Command>::SharedPtr mx28CommandSub_; std::mutex mx28CommandMutex_; MX28Command::SharedPtr mx28Command_; // Publishers rclcpp::Publisher<CM730Info>::SharedPtr cm730InfoPub_; rclcpp::Publisher<MX28InfoArray>::SharedPtr mx28InfoPub_; // Static info CM730EepromTable::SharedPtr staticCm730Info_; std::map<uint8_t, MX28EepromTable::SharedPtr> staticMx28Info_; // Timer for main loop rclcpp::TimerBase::SharedPtr loopTimer_; void powerOn(); void readStaticInfo(); void handleStaticInfo(BulkReadClient::SharedFuture response); void startLoop(); void handleDynamicInfo(BulkReadClient::SharedFuture response); void writeCommands(); template<typename TCommand> typename TCommand::SharedPtr grabCommand(typename TCommand::SharedPtr & cmd, std::mutex & mutex) { std::lock_guard<std::mutex> lock{mutex}; if (cmd == nullptr) { return nullptr; } auto grab = cmd; cmd.reset(); return grab; } }; } // namespace cm730controller #endif // CM730CONTROLLER__CM730CONTROLLER_HPP_
30.647059
98
0.769354
threeal
d9ecd7a377e127ff44518c0ae390d90fed546d81
2,134
cpp
C++
SensorPi/src/ui.cpp
tfrec-kalcsits/SensorSystem
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
[ "MIT" ]
2
2018-06-30T06:05:29.000Z
2021-08-24T22:34:19.000Z
SensorPi/src/ui.cpp
tfrec-kalcsits/SensorSystem
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
[ "MIT" ]
13
2018-07-07T00:11:08.000Z
2018-09-05T02:49:11.000Z
SensorPi/src/ui.cpp
tfrec-kalcsits/SensorSystem
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
[ "MIT" ]
null
null
null
#include <sensorpi/ui.h> #include <wiringPi.h> #include <mcp23017.h> #include <lcd.h> //functions taken from lcd-adafruit.c in wiringPi namespace sensorsystem { static void setBacklightColour (int colour) { colour &= 7 ; digitalWrite (AF_RED, !(colour & 1)) ; digitalWrite (AF_GREEN, !(colour & 2)) ; digitalWrite (AF_BLUE, !(colour & 4)) ; } static int adafruitLCDSetup (int colour) { int i ; pinMode (AF_RED, OUTPUT) ; pinMode (AF_GREEN, OUTPUT) ; pinMode (AF_BLUE, OUTPUT) ; setBacklightColour (colour) ; for (i = 0 ; i <= 4 ; ++i) { pinMode (AF_BASE + i, INPUT) ; pullUpDnControl (AF_BASE + i, PUD_UP) ; } pinMode (AF_RW, OUTPUT) ; digitalWrite (AF_RW, LOW) ; return lcdInit (2, 16, 4, AF_RS, AF_E, AF_DB4,AF_DB5,AF_DB6,AF_DB7, 0,0,0,0) ; } int initLCD() { mcp23017Setup(AF_BASE, 0x20); return adafruitLCDSetup(7); } void initMainScreen(int handle) { lcdClear(handle); lcdHome(handle); lcdPuts(handle, "A:"); lcdPosition(handle, 0, 1); lcdPuts(handle, "O: L:"); } void printMainScreenMeasurements(int handle, float ambient, float object, float lux) { lcdPosition(handle, 2, 0); lcdPrintf(handle, "%.2f", ambient); lcdPosition(handle, 2, 1); lcdPrintf(handle, "%.2f", object); lcdPosition(handle, 10,1); lcdPrintf(handle, "%.1f", lux); } bool isButtonPressed(int handle, uint8_t button) { return digitalRead(button) == LOW; } void waitForRelease(int handle) { while(isButtonPressed(handle, AF_UP) || isButtonPressed(handle, AF_DOWN) || isButtonPressed(handle, AF_LEFT) || isButtonPressed(handle, AF_RIGHT) || isButtonPressed(handle, AF_SELECT)); } uint8_t waitForInput(int handle) { for(;;) { if(isButtonPressed(handle, AF_UP)) return AF_UP; if(isButtonPressed(handle, AF_DOWN)) return AF_DOWN; if(isButtonPressed(handle, AF_RIGHT)) return AF_RIGHT; if(isButtonPressed(handle, AF_LEFT)) return AF_LEFT; if(isButtonPressed(handle, AF_SELECT)) return AF_SELECT; } } }
22
84
0.636364
tfrec-kalcsits
d9ed3409b8c5e807cd7ef53aff859ba86be8cffa
9,126
cpp
C++
src/bkGL/vao/VertexAttributePointer.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
4
2018-12-08T15:35:38.000Z
2021-08-06T03:23:06.000Z
src/bkGL/vao/VertexAttributePointer.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
src/bkGL/vao/VertexAttributePointer.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * 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 <algorithm> #include <string> #include <bkGL/vao/VertexAttributePointer.h> #include <bkGL/gl_type_traits.h> namespace bk { //==================================================================================================== //===== MEMBERS //==================================================================================================== class VertexAttributePointer::Impl { public: GLuint id; GLenum value_type; GLboolean normalized; // GL_FALSE / GL_TRUE std::string name; Impl(GLuint id, GLenum value_type, bool normalized, std::string name) : id(id), value_type(value_type), normalized(normalized ? GL_TRUE : GL_FALSE), name(name) { /* do nothing */ } Impl(const Impl&) = default; Impl(Impl&&) noexcept = default; ~Impl() = default; [[maybe_unused]] Impl& operator=(const Impl&) = default; [[maybe_unused]] Impl& operator=(Impl&&) noexcept = default; }; //==================================================================================================== //===== CONSTRUCTORS & DESTRUCTOR //==================================================================================================== /// @{ -------------------------------------------------- CTOR VertexAttributePointer::VertexAttributePointer() : VertexAttributePointer(0, GL_FLOAT, false, "var") { /* do nothing */ } VertexAttributePointer::VertexAttributePointer(GLuint id, GLenum value_type, bool normalized, std::string name) : _pdata(id, value_type, normalized, name) { /* do nothing */ } VertexAttributePointer::VertexAttributePointer(const self_type&) = default; VertexAttributePointer::VertexAttributePointer(self_type&&) noexcept = default; /// @} /// @{ -------------------------------------------------- DTOR VertexAttributePointer::~VertexAttributePointer() = default; /// @} //==================================================================================================== //===== GETTER //==================================================================================================== /// @{ -------------------------------------------------- GET ID GLuint VertexAttributePointer::id() const { return _pdata->id; } /// @} /// @{ -------------------------------------------------- GET NUMEL GLint VertexAttributePointer::numel() const { return gl_numel(_pdata->value_type); } /// @} /// @{ -------------------------------------------------- GET VALUE_TYPE GLenum VertexAttributePointer::value_type() const { return _pdata->value_type; } /// @} /// @{ -------------------------------------------------- GET SIZE IN BYTES GLsizei VertexAttributePointer::size_in_bytes() const { return gl_size_in_bytes(_pdata->value_type); } /// @} /// @{ -------------------------------------------------- GET NORMALIZED GLboolean VertexAttributePointer::is_normalized() const { return _pdata->normalized; } /// @} /// @{ -------------------------------------------------- GET NAME const std::string& VertexAttributePointer::name() const { return _pdata->name; } /// @} //==================================================================================================== //===== SETTER //==================================================================================================== /// @{ -------------------------------------------------- OPERATOR = auto VertexAttributePointer::operator=(const self_type& other) -> self_type& = default; auto VertexAttributePointer::operator=(self_type&&) noexcept -> self_type& = default; /// @} /// @{ -------------------------------------------------- SET VALUE TYPE void VertexAttributePointer::set_value_type(GLenum type) { _pdata->value_type = type; } void VertexAttributePointer::set_value_type_BYTE() { set_value_type(GL_BYTE); } void VertexAttributePointer::set_value_type_UNSIGNED_BYTE() { set_value_type(GL_UNSIGNED_BYTE); } void VertexAttributePointer::set_value_type_SHORT() { set_value_type(GL_SHORT); } void VertexAttributePointer::set_value_type_UNSIGNED_SHORT() { set_value_type(GL_UNSIGNED_SHORT); } void VertexAttributePointer::set_value_type_INT_VEC2() { set_value_type(GL_INT_VEC2); } void VertexAttributePointer::set_value_type_INT_VEC3() { set_value_type(GL_INT_VEC3); } void VertexAttributePointer::set_value_type_INT_VEC4() { set_value_type(GL_INT_VEC4); } void VertexAttributePointer::set_value_type_INT() { set_value_type(GL_INT); } void VertexAttributePointer::set_value_type_UNSIGNED_INT_VEC2() { set_value_type(GL_UNSIGNED_INT_VEC2); } void VertexAttributePointer::set_value_type_UNSIGNED_INT_VEC3() { set_value_type(GL_UNSIGNED_INT_VEC3); } void VertexAttributePointer::set_value_type_UNSIGNED_INT_VEC4() { set_value_type(GL_UNSIGNED_INT_VEC4); } void VertexAttributePointer::set_value_type_UNSIGNED_INT() { set_value_type(GL_UNSIGNED_INT); } void VertexAttributePointer::set_value_type_FLOAT_VEC2() { set_value_type(GL_FLOAT_VEC2); } void VertexAttributePointer::set_value_type_FLOAT_VEC3() { set_value_type(GL_FLOAT_VEC3); } void VertexAttributePointer::set_value_type_FLOAT_VEC4() { set_value_type(GL_FLOAT_VEC4); } void VertexAttributePointer::set_value_type_FLOAT_MAT2() { set_value_type(GL_FLOAT_MAT2); } void VertexAttributePointer::set_value_type_FLOAT_MAT2x3() { set_value_type(GL_FLOAT_MAT2x3); } void VertexAttributePointer::set_value_type_FLOAT_MAT2x4() { set_value_type(GL_FLOAT_MAT2x4); } void VertexAttributePointer::set_value_type_FLOAT_MAT3() { set_value_type(GL_FLOAT_MAT3); } void VertexAttributePointer::set_value_type_FLOAT_MAT3x2() { set_value_type(GL_FLOAT_MAT3x2); } void VertexAttributePointer::set_value_type_FLOAT_MAT3x4() { set_value_type(GL_FLOAT_MAT3x4); } void VertexAttributePointer::set_value_type_FLOAT_MAT4() { set_value_type(GL_FLOAT_MAT4); } void VertexAttributePointer::set_value_type_FLOAT_MAT4x2() { set_value_type(GL_FLOAT_MAT4x2); } void VertexAttributePointer::set_value_type_FLOAT_MAT4x3() { set_value_type(GL_FLOAT_MAT4x3); } void VertexAttributePointer::set_value_type_FLOAT() { set_value_type(GL_FLOAT); } void VertexAttributePointer::set_value_type_DOUBLE_VEC2() { set_value_type(GL_DOUBLE_VEC2); } void VertexAttributePointer::set_value_type_DOUBLE_VEC3() { set_value_type(GL_DOUBLE_VEC3); } void VertexAttributePointer::set_value_type_DOUBLE_VEC4() { set_value_type(GL_DOUBLE_VEC4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT2() { set_value_type(GL_DOUBLE_MAT2); } void VertexAttributePointer::set_value_type_DOUBLE_MAT2x3() { set_value_type(GL_DOUBLE_MAT2x3); } void VertexAttributePointer::set_value_type_DOUBLE_MAT2x4() { set_value_type(GL_DOUBLE_MAT2x4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT3() { set_value_type(GL_DOUBLE_MAT3); } void VertexAttributePointer::set_value_type_DOUBLE_MAT3x2() { set_value_type(GL_DOUBLE_MAT3x2); } void VertexAttributePointer::set_value_type_DOUBLE_MAT3x4() { set_value_type(GL_DOUBLE_MAT3x4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT4() { set_value_type(GL_DOUBLE_MAT4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT4x2() { set_value_type(GL_DOUBLE_MAT4x2); } void VertexAttributePointer::set_value_type_DOUBLE_MAT4x3() { set_value_type(GL_DOUBLE_MAT4x3); } void VertexAttributePointer::set_value_type_DOUBLE() { set_value_type(GL_DOUBLE); } /// @} /// @{ -------------------------------------------------- SET NORMALIZED void VertexAttributePointer::set_normalized(bool b) { _pdata->normalized = b ? GL_TRUE : GL_FALSE; } /// @} /// @{ -------------------------------------------------- SET NAME void VertexAttributePointer::set_name(std::string name) { _pdata->name = name; } /// @} } // namespace bk
36.358566
113
0.623603
BenKoehler
d9edcbce7865b0e126ad3b005bc0448ce001ff11
7,233
cpp
C++
test/unit/type-analysis/DexTypeEnvironmentTest.cpp
agampe/redex
e49d6e26c10fedc7becf5b3ee2b76ea6f2610aae
[ "MIT" ]
null
null
null
test/unit/type-analysis/DexTypeEnvironmentTest.cpp
agampe/redex
e49d6e26c10fedc7becf5b3ee2b76ea6f2610aae
[ "MIT" ]
null
null
null
test/unit/type-analysis/DexTypeEnvironmentTest.cpp
agampe/redex
e49d6e26c10fedc7becf5b3ee2b76ea6f2610aae
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "DexTypeEnvironment.h" #include <boost/optional/optional_io.hpp> #include "Creators.h" #include "RedexTest.h" struct DexTypeEnvironmentTest : public RedexTest { public: /* * Ljava/lang/Object; * | * A * / \ * B C * \ * D * \ * E * * Ljava/lang/Object; * | * H * | * I */ DexTypeEnvironmentTest() { // Synthesizing Ljava/lang/Object; ClassCreator creator = ClassCreator(type::java_lang_Object()); creator.create(); m_type_a = DexType::make_type("A"); creator = ClassCreator(m_type_a); creator.set_super(type::java_lang_Object()); creator.create(); m_type_b = DexType::make_type("B"); creator = ClassCreator(m_type_b); creator.set_super(m_type_a); creator.create(); m_type_c = DexType::make_type("C"); creator = ClassCreator(m_type_c); creator.set_super(m_type_a); creator.create(); m_type_d = DexType::make_type("D"); creator = ClassCreator(m_type_d); creator.set_super(m_type_c); creator.create(); m_type_e = DexType::make_type("E"); creator = ClassCreator(m_type_e); creator.set_super(m_type_d); creator.create(); m_type_h = DexType::make_type("H"); creator = ClassCreator(m_type_h); creator.set_super(type::java_lang_Object()); creator.create(); m_type_i = DexType::make_type("I"); creator = ClassCreator(m_type_i); creator.set_super(m_type_h); creator.create(); } protected: DexType* m_type_a; DexType* m_type_b; DexType* m_type_c; DexType* m_type_d; DexType* m_type_e; DexType* m_type_h; DexType* m_type_i; }; TEST_F(DexTypeEnvironmentTest, BasicTest) { auto env = DexTypeEnvironment(); EXPECT_TRUE(env.is_top()); auto& reg_env = env.get_reg_environment(); EXPECT_TRUE(reg_env.is_top()); auto& field_env = env.get_field_environment(); EXPECT_TRUE(field_env.is_top()); } TEST_F(DexTypeEnvironmentTest, RegisterEnvTest) { auto env = DexTypeEnvironment(); reg_t v0 = 0; auto type = env.get(v0); EXPECT_TRUE(type.is_top()); env.set(v0, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(v0), DexTypeDomain(m_type_a)); reg_t v1 = 1; env.set(v1, DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(v1), DexTypeDomain(m_type_b)); auto a_join_b = DexTypeDomain(m_type_a); a_join_b.join_with(env.get(v1)); EXPECT_EQ(a_join_b, DexTypeDomain(m_type_a)); auto b_join_a = DexTypeDomain(m_type_b); b_join_a.join_with(env.get(v0)); EXPECT_EQ(b_join_a, DexTypeDomain(m_type_a)); } TEST_F(DexTypeEnvironmentTest, FieldEnvTest) { auto env = DexTypeEnvironment(); DexField* f1 = (DexField*)1; auto type = env.get(f1); EXPECT_TRUE(type.is_top()); env.set(f1, DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(f1), DexTypeDomain(m_type_b)); DexField* f2 = (DexField*)2; EXPECT_TRUE(env.get(f2).is_top()); env.set(f2, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(f2), DexTypeDomain(m_type_a)); auto a_join_b = env.get(f2); a_join_b.join_with(env.get(f1)); EXPECT_EQ(a_join_b, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(f1), DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(f2), DexTypeDomain(m_type_a)); auto b_join_a = env.get(f1); b_join_a.join_with(env.get(f2)); EXPECT_EQ(b_join_a, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(f1), DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(f2), DexTypeDomain(m_type_a)); } TEST_F(DexTypeEnvironmentTest, JoinWithTest) { auto domain_b = DexTypeDomain(m_type_b); auto domain_c = DexTypeDomain(m_type_c); domain_b.join_with(domain_c); EXPECT_EQ(domain_b, DexTypeDomain(m_type_a)); domain_b = DexTypeDomain(m_type_b); auto domain_d = DexTypeDomain(m_type_d); domain_b.join_with(domain_d); EXPECT_EQ(domain_b, DexTypeDomain(m_type_a)); domain_b = DexTypeDomain(m_type_b); auto domain_e = DexTypeDomain(m_type_e); domain_b.join_with(domain_e); EXPECT_EQ(domain_b, DexTypeDomain(m_type_a)); auto domain_a = DexTypeDomain(m_type_a); domain_e = DexTypeDomain(m_type_e); domain_a.join_with(domain_e); EXPECT_EQ(domain_a, DexTypeDomain(m_type_a)); auto top1 = DexTypeDomain::top(); auto top2 = DexTypeDomain::top(); top1.join_with(top2); EXPECT_TRUE(top1.is_top()); EXPECT_TRUE(top2.is_top()); domain_a = DexTypeDomain(m_type_a); auto domain_h = DexTypeDomain(m_type_h); domain_a.join_with(domain_h); EXPECT_EQ(domain_a, DexTypeDomain(type::java_lang_Object())); domain_b = DexTypeDomain(m_type_b); domain_h = DexTypeDomain(m_type_h); domain_b.join_with(domain_h); EXPECT_EQ(domain_b, DexTypeDomain(type::java_lang_Object())); domain_d = DexTypeDomain(m_type_d); domain_h = DexTypeDomain(m_type_h); domain_d.join_with(domain_h); EXPECT_EQ(domain_d, DexTypeDomain(type::java_lang_Object())); domain_e = DexTypeDomain(m_type_e); domain_h = DexTypeDomain(m_type_h); domain_e.join_with(domain_h); EXPECT_EQ(domain_e, DexTypeDomain(type::java_lang_Object())); domain_b = DexTypeDomain(m_type_b); auto domain_i = DexTypeDomain(m_type_i); domain_b.join_with(domain_i); EXPECT_TRUE(domain_b.get_type_domain().is_top()); EXPECT_FALSE(domain_i.get_type_domain().is_top()); } TEST_F(DexTypeEnvironmentTest, NullableDexTypeDomainTest) { auto null1 = DexTypeDomain::null(); EXPECT_FALSE(null1.is_bottom()); EXPECT_FALSE(null1.is_top()); EXPECT_TRUE(null1.get_type_domain().is_none()); auto type_a = DexTypeDomain(m_type_a); null1.join_with(type_a); EXPECT_FALSE(null1.is_null()); EXPECT_FALSE(null1.is_not_null()); EXPECT_TRUE(null1.is_nullable()); EXPECT_NE(null1, DexTypeDomain(m_type_a)); EXPECT_EQ(*null1.get_dex_type(), m_type_a); EXPECT_EQ(type_a, DexTypeDomain(m_type_a)); EXPECT_FALSE(null1.get_type_domain().is_none()); EXPECT_FALSE(type_a.get_type_domain().is_none()); type_a = DexTypeDomain(m_type_a); null1 = DexTypeDomain::null(); type_a.join_with(null1); EXPECT_FALSE(type_a.is_null()); EXPECT_FALSE(type_a.is_not_null()); EXPECT_TRUE(type_a.is_nullable()); EXPECT_NE(type_a, DexTypeDomain(m_type_a)); EXPECT_EQ(*type_a.get_dex_type(), m_type_a); EXPECT_EQ(null1, DexTypeDomain::null()); EXPECT_FALSE(type_a.get_type_domain().is_none()); EXPECT_TRUE(null1.get_type_domain().is_none()); auto top1 = DexTypeDomain::top(); auto top2 = DexTypeDomain::top(); top1.join_with(top2); EXPECT_TRUE(top1.is_top()); EXPECT_TRUE(top2.is_top()); EXPECT_FALSE(top1.get_type_domain().is_none()); EXPECT_FALSE(top2.get_type_domain().is_none()); top1 = DexTypeDomain::top(); auto bottom = DexTypeDomain::bottom(); top1.join_with(bottom); EXPECT_TRUE(top1.is_top()); EXPECT_TRUE(bottom.is_bottom()); EXPECT_FALSE(top1.get_type_domain().is_none()); EXPECT_FALSE(bottom.get_type_domain().is_none()); bottom = DexTypeDomain::bottom(); top1 = DexTypeDomain::top(); bottom.join_with(top1); EXPECT_TRUE(bottom.is_top()); EXPECT_TRUE(top1.is_top()); EXPECT_FALSE(bottom.get_type_domain().is_none()); EXPECT_FALSE(top1.get_type_domain().is_none()); }
28.932
66
0.7163
agampe